Skip to content

Commit fb0ddab

Browse files
authored
Don't box values that pass through std::move (#634)
1 parent 58318d6 commit fb0ddab

17 files changed

Lines changed: 323 additions & 52 deletions

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5444,11 +5444,7 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg,
54445444

54455445
// The rule takes the argument by value from an rvalue reference parameter,
54465446
// e.g., push_back(T &&), and so C++ moves it.
5447-
auto param_type = GetParamType(expr, ph_ctx.arg_idx);
5448-
bool moved = ph_ctx.access == TranslationRule::Access::kTake ||
5449-
(ph_ctx.access == TranslationRule::Access::kMove && param_type &&
5450-
(*param_type)->isRValueReferenceType());
5451-
if (moved && !clang::isa<clang::MaterializeTemporaryExpr>(arg)) {
5447+
if (MovesRuleArg(expr, ph_ctx.arg_idx, arg, ph_ctx.access)) {
54525448
auto *ref = clang::dyn_cast<clang::DeclRefExpr>(arg->IgnoreParenImpCasts());
54535449
auto *var = ref ? clang::dyn_cast<clang::VarDecl>(ref->getDecl()) : nullptr;
54545450
if (auto *record = arg->getType()->getAsCXXRecordDecl();

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,15 @@ bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor) {
612612
return ctor->isUserProvided() || NeedsDefaultedMoveConstructor(parent);
613613
}
614614

615+
bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg,
616+
TranslationRule::Access access) {
617+
auto param_type = GetParamType(expr, arg_idx);
618+
bool moved = access == TranslationRule::Access::kTake ||
619+
(access == TranslationRule::Access::kMove && param_type &&
620+
(*param_type)->isRValueReferenceType());
621+
return moved && !clang::isa<clang::MaterializeTemporaryExpr>(arg);
622+
}
623+
615624
static bool
616625
IsImplicitConvertingConstructor(const clang::CXXConstructorDecl *ctor) {
617626
return !ctor->isCopyOrMoveConstructor() && !ctor->isImplicit() &&

‎cpp2rust/converter/converter_lib.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include <unordered_set>
2121
#include <vector>
2222

23+
#include "converter/translation_rule.h"
2324
#include "logging.h"
2425

2526
namespace clang {
@@ -110,6 +111,9 @@ bool IsDefaultedMoveConstructor(const clang::CXXConstructorDecl *ctor);
110111

111112
bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor);
112113

114+
bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg,
115+
TranslationRule::Access access);
116+
113117
// Whether decl has a move constructor converted to a move_from method.
114118
bool HasMoveFromConstructor(const clang::RecordDecl *decl);
115119

‎cpp2rust/converter/models/boxed_vars.cpp‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,19 @@ class AddressTakenVisitor
324324
TraverseStmt(init);
325325
continue;
326326
}
327+
auto *record = arg->getType()->getAsRecordDecl();
328+
if (TranslationRule::AnyFragment(
329+
rule->body, [&](const TranslationRule::BodyFragment &fragment) {
330+
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(
331+
&fragment);
332+
return ph && ph->n == i &&
333+
((ph->access == TranslationRule::Access::kMove &&
334+
MovesFromArg(expr, i, all_args[i])) ||
335+
(record && HasMoveFromConstructor(record) &&
336+
MovesRuleArg(expr, i, all_args[i], ph->access)));
337+
})) {
338+
continue;
339+
}
327340
if (!rule->takesAddress(ctx_, i, arg) ||
328341
rule->takesTemporaryAddress(ctx_, expr, i, arg)) {
329342
AddValueUse(arg);
@@ -334,7 +347,7 @@ class AddressTakenVisitor
334347
// An element of an array or vector, or a field of a struct, is accessed
335348
// without making a pointer to it.
336349
void AddValueUse(const clang::Expr *expr, bool write = false) {
337-
expr = IgnoreNoOpCasts(expr->IgnoreParens());
350+
expr = IgnoreNoOpCasts(IgnoreTransparentStdCall(expr)->IgnoreParens());
338351
// The value of a conditional lvalue is the value of either operand; it is
339352
// written through a pointer to the operand.
340353
if (auto *cond = clang::dyn_cast<clang::ConditionalOperator>(expr)) {

‎tests/std/utilities/pairs/out/refcount/pairs.pair.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,12 @@ pub fn test_1() {
5454
})
5555
})
5656
);
57-
let values: Value<Vec<i32>> = Rc::new(RefCell::new(vec![7; 2_usize]));
57+
let mut values: Vec<i32> = vec![7; 2_usize];
5858
let copied: Value<(Value<Vec<i32>>, Value<i32>)> = Rc::new(RefCell::new((
59-
Rc::new(RefCell::new(({ (*values.borrow()).clone() }))),
59+
Rc::new(RefCell::new((values).clone())),
6060
Rc::new(RefCell::new(3)),
6161
)));
62-
assert!(({ ((*values.borrow()).len() == 2_usize) }));
62+
assert!((values.len() == 2_usize));
6363
assert!(
6464
({
6565
((*(*copied.borrow()).0.borrow()).len() == 2_usize)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// ADDITIONAL_COMPILE_FLAGS: -std=c++23
2+
#include <cassert>
3+
#include <utility>
4+
#include <vector>
5+
6+
// N4950 [forward]/9: std::move(t) returns
7+
// static_cast<remove_reference_t<T>&&>(t), so moving a scalar reads its value.
8+
namespace p9_move_scalar {
9+
void test() {
10+
int source = 1;
11+
int target = std::move(source);
12+
assert(target == 1);
13+
assert(source == 1);
14+
}
15+
} // namespace p9_move_scalar
16+
17+
// N4950 [forward]/9: moving a trivially copyable object copies its value.
18+
namespace p9_move_trivially_copyable {
19+
struct Point {
20+
int x;
21+
int y;
22+
};
23+
24+
void test() {
25+
Point source{1, 2};
26+
Point target = std::move(source);
27+
assert(target.x == 1 && target.y == 2);
28+
assert(source.x == 1 && source.y == 2);
29+
30+
Point assigned{0, 0};
31+
Point other{3, 4};
32+
assigned = std::move(other);
33+
assert(assigned.x == 3 && assigned.y == 4);
34+
assert(other.x == 3 && other.y == 4);
35+
36+
std::vector<Point> points;
37+
Point element{5, 6};
38+
points.push_back(std::move(element));
39+
assert(points[0].x == 5 && points[0].y == 6);
40+
assert(element.x == 5 && element.y == 6);
41+
}
42+
} // namespace p9_move_trivially_copyable
43+
44+
// N4950 [forward]/10: std::move(a) binds to the constructor A(A&&), which
45+
// moves the value from a.
46+
namespace p10_move_constructor {
47+
struct A {
48+
int value;
49+
A(int value) : value(value) {}
50+
A(A &&other) : value(other.value) { other.value = 0; }
51+
};
52+
53+
void test() {
54+
A source(1);
55+
A target = std::move(source);
56+
assert(target.value == 1);
57+
assert(source.value == 0);
58+
59+
std::vector<A> values;
60+
A element(2);
61+
values.push_back(std::move(element));
62+
assert(values[0].value == 2);
63+
assert(element.value == 0);
64+
}
65+
} // namespace p10_move_constructor
66+
67+
int main() {
68+
p9_move_scalar::test();
69+
p9_move_trivially_copyable::test();
70+
p10_move_constructor::test();
71+
return 0;
72+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
pub fn test_0() {
10+
let mut source: i32 = 1;
11+
let mut target: i32 = source;
12+
assert!((target == 1));
13+
assert!((source == 1));
14+
}
15+
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)]
16+
#[byte_size(8)]
17+
pub struct p9_move_trivially_copyable_Point {
18+
#[offset(0)]
19+
pub x: i32,
20+
#[offset(4)]
21+
pub y: i32,
22+
}
23+
pub fn test_1() {
24+
let mut source: p9_move_trivially_copyable_Point =
25+
p9_move_trivially_copyable_Point { x: 1, y: 2 };
26+
let mut target: p9_move_trivially_copyable_Point = (source).clone();
27+
assert!((target.x == 1) && (target.y == 2));
28+
assert!((source.x == 1) && (source.y == 2));
29+
let mut assigned: p9_move_trivially_copyable_Point =
30+
p9_move_trivially_copyable_Point { x: 0, y: 0 };
31+
let mut other: p9_move_trivially_copyable_Point =
32+
p9_move_trivially_copyable_Point { x: 3, y: 4 };
33+
assigned = (other).clone();
34+
assert!((assigned.x == 3) && (assigned.y == 4));
35+
assert!((other.x == 3) && (other.y == 4));
36+
let mut points: Vec<p9_move_trivially_copyable_Point> = Vec::new();
37+
let mut element: p9_move_trivially_copyable_Point =
38+
p9_move_trivially_copyable_Point { x: 5, y: 6 };
39+
{
40+
let __a1 = (element).clone();
41+
points.push(__a1)
42+
};
43+
assert!((points[0_usize].x == 5) && (points[0_usize].y == 6));
44+
assert!((element.x == 5) && (element.y == 6));
45+
}
46+
#[derive(Record, ByteRepr, FnPtrArg, MoveCtor, CppFrom, Default)]
47+
#[cpp_from(i32, new, value)]
48+
#[byte_size(4)]
49+
pub struct p10_move_constructor_A {
50+
#[offset(0)]
51+
pub value: i32,
52+
}
53+
impl p10_move_constructor_A {
54+
pub fn new(mut value: i32) -> Self {
55+
Self { value: value }
56+
}
57+
pub fn move_from(other: Ptr<p10_move_constructor_A>) -> Self {
58+
let __this: p10_move_constructor_A = Self {
59+
value: other.with(|__s| __s.value),
60+
};
61+
field!(other, value).write(0);
62+
__this
63+
}
64+
}
65+
pub fn test_2() {
66+
let source: Value<p10_move_constructor_A> =
67+
Rc::new(RefCell::new(p10_move_constructor_A::new({ 1 })));
68+
let mut target: p10_move_constructor_A =
69+
p10_move_constructor_A::move_from({ source.as_pointer() });
70+
assert!((target.value == 1));
71+
assert!(({ ({ (*source.borrow()).value } == 0) }));
72+
let mut values: Vec<p10_move_constructor_A> = Vec::new();
73+
let element: Value<p10_move_constructor_A> =
74+
Rc::new(RefCell::new(p10_move_constructor_A::new({ 2 })));
75+
{
76+
let __a1 = p10_move_constructor_A::move_from({ element.as_pointer() });
77+
values.push(__a1)
78+
};
79+
assert!((values[0_usize].value == 2));
80+
assert!(({ ({ (*element.borrow()).value } == 0) }));
81+
}
82+
pub fn main() {
83+
__cpp2rust_init_globals();
84+
std::process::exit(main_0());
85+
}
86+
fn main_0() -> i32 {
87+
({ test_0() });
88+
({ test_1() });
89+
({ test_2() });
90+
return 0;
91+
}
92+
pub fn __cpp2rust_init_globals() {}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
extern crate libc;
2+
use libc::*;
3+
extern crate libcc2rs;
4+
use libcc2rs::*;
5+
use std::collections::BTreeMap;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::{AsFd, FromRawFd, IntoRawFd};
8+
use std::rc::Rc;
9+
pub unsafe fn test_0() {
10+
let mut source: i32 = 1;
11+
let mut target: i32 = source;
12+
assert!(((target) == (1)));
13+
assert!(((source) == (1)));
14+
}
15+
#[repr(C)]
16+
#[derive(Copy, Clone, VaArg, FnPtrArg, Default)]
17+
pub struct p9_move_trivially_copyable_Point {
18+
pub x: i32,
19+
pub y: i32,
20+
}
21+
pub unsafe fn test_1() {
22+
let mut source: p9_move_trivially_copyable_Point =
23+
p9_move_trivially_copyable_Point { x: 1, y: 2 };
24+
let mut target: p9_move_trivially_copyable_Point = source;
25+
assert!(((target.x) == (1)) && ((target.y) == (2)));
26+
assert!(((source.x) == (1)) && ((source.y) == (2)));
27+
let mut assigned: p9_move_trivially_copyable_Point =
28+
p9_move_trivially_copyable_Point { x: 0, y: 0 };
29+
let mut other: p9_move_trivially_copyable_Point =
30+
p9_move_trivially_copyable_Point { x: 3, y: 4 };
31+
assigned = other;
32+
assert!(((assigned.x) == (3)) && ((assigned.y) == (4)));
33+
assert!(((other.x) == (3)) && ((other.y) == (4)));
34+
let mut points: Vec<p9_move_trivially_copyable_Point> = Vec::new();
35+
let mut element: p9_move_trivially_copyable_Point =
36+
p9_move_trivially_copyable_Point { x: 5, y: 6 };
37+
{
38+
let __a1 = element;
39+
points.push(__a1)
40+
};
41+
assert!(((points[(0_usize)].x) == (5)) && ((points[(0_usize)].y) == (6)));
42+
assert!(((element.x) == (5)) && ((element.y) == (6)));
43+
}
44+
#[repr(C)]
45+
#[derive(FnPtrArg, MoveCtorUnsafe, CppFromUnsafe, Default)]
46+
#[cpp_from(i32, new, value)]
47+
pub struct p10_move_constructor_A {
48+
pub value: i32,
49+
}
50+
impl p10_move_constructor_A {
51+
pub unsafe fn new(mut value: i32) -> Self {
52+
let mut this = Self { value: value };
53+
this
54+
}
55+
pub unsafe fn move_from(other: *mut p10_move_constructor_A) -> Self {
56+
let mut this = Self {
57+
value: (*other).value,
58+
};
59+
(*other).value = 0;
60+
this
61+
}
62+
}
63+
pub unsafe fn test_2() {
64+
let mut source: p10_move_constructor_A = p10_move_constructor_A::new({ 1 });
65+
let mut target: p10_move_constructor_A = p10_move_constructor_A::move_from({ &mut source });
66+
assert!(((target.value) == (1)));
67+
assert!(((source.value) == (0)));
68+
let mut values: Vec<p10_move_constructor_A> = Vec::new();
69+
let mut element: p10_move_constructor_A = p10_move_constructor_A::new({ 2 });
70+
{
71+
let __a1 = p10_move_constructor_A::move_from({ &mut element });
72+
values.push(__a1)
73+
};
74+
assert!(((values[(0_usize)].value) == (2)));
75+
assert!(((element.value) == (0)));
76+
}
77+
pub fn main() {
78+
unsafe {
79+
__cpp2rust_init_globals();
80+
std::process::exit(main_0() as i32);
81+
}
82+
}
83+
unsafe fn main_0() -> i32 {
84+
(unsafe { test_0() });
85+
(unsafe { test_1() });
86+
(unsafe { test_2() });
87+
return 0;
88+
}
89+
pub unsafe fn __cpp2rust_init_globals() {}

‎tests/unit/out/refcount/11_move.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ use std::io::{Read, Seek, Write};
77
use std::os::fd::AsFd;
88
use std::rc::{Rc, Weak};
99
pub fn change_0(n: Ptr<Option<Value<i32>>>) {
10-
let m: Value<Option<Value<i32>>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(20)))));
11-
n.write((*m.borrow_mut()).take());
12-
assert!(({ ((*m.borrow()).as_pointer()).is_null() }));
10+
let mut m: Option<Value<i32>> = Some(Rc::new(RefCell::new(20)));
11+
n.write(m.take());
12+
assert!((m.as_pointer()).is_null());
1313
}
1414
pub fn main() {
1515
__cpp2rust_init_globals();

‎tests/unit/out/refcount/alloc_array.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@ use std::io::{Read, Seek, Write};
77
use std::os::fd::AsFd;
88
use std::rc::{Rc, Weak};
99
pub fn All_0(arr: Ptr<Option<Value<Box<[i32]>>>>, mut N: i32, mut element: i32) {
10-
let all: Value<Option<Value<Box<[i32]>>>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(
10+
let mut all: Option<Value<Box<[i32]>>> = Some(Rc::new(RefCell::new(
1111
(0..(N as usize)).map(|_| 0_i32).collect::<Box<[_]>>(),
12-
)))));
12+
)));
1313
{
1414
let mut i: i32 = 0;
1515
'loop_: while (i < N) {
16-
(*all.borrow()).decay().offset((i as usize)).write(element);
16+
all.decay().offset((i as usize)).write(element);
1717
i.prefix_inc();
1818
}
1919
}
20-
arr.write((*all.borrow_mut()).take());
20+
arr.write(all.take());
2121
}
2222
pub fn Consume_1(mut arr: Option<Value<Box<[i32]>>>, mut N: i32) -> i32 {
2323
let mut sum: i32 = 0;

0 commit comments

Comments
 (0)