Skip to content

Commit 09eee7b

Browse files
Keep mapped-call temporaries local to global initializers (#665)
Global initializers containing mapped calls such as `std::min(0, 0)` fail to compile in refcount output because temporary operands become ordinary Rust statics but use thread-local access. Unsafe output handles this literal-only call, but also fails nonconstant temporary initialization, including mixed-type conversions. `cpp2rust/converter/converter.cpp` now gives mapped-call arguments initializer-local storage through the enclosing full expression, including Rust-only cast temporaries. Enclosing calls share that storage for temporary arrays and records; hoisted bindings have unique names. Refcount global assignments bind right-hand sides before entering the thread-local closure, keeping temporary initialization outside it and preserving C++17's right-operand-first sequencing for same-type assignments. Still broken: - mixed-type compound-assignment sequencing, such as `i += (i = 10, std::max(1.5, 0.5))`, which still reads the left operand first; - constructor arguments and reference-member aggregates in global initializers, such as `S t(std::max(3, 4) + 1)` and `R rr{std::min(5, 6) + 0}`; - refcount rule closures in global initializers, such as `s.substr(std::min(1, 2), std::max(2, 3))`; - unsafe lifetime-extended static owners, such as `const int &r = read(std::min(4, 5));` with a value-returning `read`; - `std::max` over `std::string` temporaries, which needs nontrivial result copying; - pre-existing refcount dangling pointers for local `read(std::min(0, 1))`, `return read(std::max(2, 3))`, and the same pattern in a mem-initializer. --- Made by [Perfloop](https://app.perfloop.ai). Human sponsor: [Tomás Senart](https://github.com/tsenart). Signed-off-by: Perfloop Agent <agent@perfloop.ai>
1 parent a087427 commit 09eee7b

5 files changed

Lines changed: 549 additions & 2 deletions

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,13 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
596596
}
597597

598598
void Converter::ConvertVarDeclInitializer(clang::VarDecl *decl) {
599+
// Rust-only argument conversions can need temporaries even when Clang
600+
// supplies no ExprWithCleanups for the initializer.
601+
std::string declarations;
602+
ScopedValue scope(full_expression_temporaries_,
603+
in_const_initializer_ ? &declarations
604+
: full_expression_temporaries_);
605+
auto start = rs_code_->size();
599606
bool registers_destructor = NeedsStaticDestructor(decl);
600607
if (registers_destructor) {
601608
StrCat("{ let __static = ");
@@ -612,6 +619,10 @@ void Converter::ConvertVarDeclInitializer(clang::VarDecl *decl) {
612619
"; libcc2rs::register_static_destructor(|| {}); __static }}",
613620
StaticDestructorCall(decl)));
614621
}
622+
if (!declarations.empty()) {
623+
rs_code_->insert(start, "{ " + declarations);
624+
StrCat('}');
625+
}
615626
}
616627

617628
void Converter::EmitHoistedInArmAssignment(clang::VarDecl *decl) {
@@ -2225,8 +2236,14 @@ void Converter::EmitHoistedArgs(CallInfo &info) {
22252236
StrCat(";");
22262237
break;
22272238
case Kind::Materialized: {
2239+
auto *declarations =
2240+
in_const_initializer_ ? full_expression_temporaries_ : nullptr;
2241+
if (declarations) {
2242+
// Other calls in the initializer may bind the same parameter.
2243+
ca.param_name = NewTempName();
2244+
}
22282245
auto [binding, ref] =
2229-
MaterializeTemp(ca.param_name, ca.param_type, ca.expr);
2246+
MaterializeTemp(ca.param_name, ca.param_type, ca.expr, declarations);
22302247
StrCat(binding);
22312248
ca.ref_temp_name = std::move(ref);
22322249
break;
@@ -5510,7 +5527,11 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg,
55105527
auto materialized = ph_ctx.materialize_ctx->GetOrMaterialize(
55115528
static_cast<unsigned>(ph_ctx.materialize_idx),
55125529
[this, arg](clang::QualType type) {
5513-
return MaterializeTemp(NewTempName(), type, arg);
5530+
// Call arguments live through the full expression, not as statics
5531+
// alongside the global whose initializer evaluates the call.
5532+
return MaterializeTemp(
5533+
NewTempName(), type, arg,
5534+
in_const_initializer_ ? full_expression_temporaries_ : nullptr);
55145535
});
55155536
// The temporary is initialized in a statement, which ends its borrows.
55165537
if (!materialized.empty()) {

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2486,6 +2486,12 @@ bool ConverterRefCount::EmitGlobalValueAssign(clang::Expr *lhs,
24862486
if (!var || !IsGlobalVar(var) || var->getType()->isReferenceType()) {
24872487
return false;
24882488
}
2489+
PushBrace brace(*this, in_const_initializer_);
2490+
if (in_const_initializer_) {
2491+
// Initialize full-expression temporaries outside the thread-local closure.
2492+
StrCat(keyword::kLet, "__rhs", token::kAssign, rhs, token::kSemiColon);
2493+
rhs = "__rhs";
2494+
}
24892495
StrCat(std::format("{}.with(|rc| *rc.borrow_mut() {} {})",
24902496
GetNamedDeclAsString(var), assign_operator, rhs));
24912497
return true;
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <algorithm>
2+
#include <cassert>
3+
#include <cstddef>
4+
5+
int read(const int &value) { return value; }
6+
7+
// The operands must survive until the returned reference has been consumed.
8+
int selected = read(std::min(0, 0));
9+
10+
int x = 0, y = 0;
11+
int assigned = (x = std::min(5, 6));
12+
int accumulated = (y += std::max(1, 2));
13+
int call_assigned = (x = read(5));
14+
15+
struct Item {
16+
int value;
17+
};
18+
19+
int read_array(const int (&value)[1]) { return value[0]; }
20+
int read_record(const Item &value) { return value.value; }
21+
22+
// Enclosing argument owners share the full expression, not the parameter name.
23+
int aggregate_selected =
24+
read_array({std::min(3, 4)}) + read_record({std::max(5, 6)});
25+
26+
// These C++ types agree, but their Rust mappings require a cast temporary.
27+
unsigned long left = 3;
28+
std::size_t right = 7;
29+
std::size_t mapped_selected = std::min<std::size_t>(left, right);
30+
31+
std::size_t get() {
32+
static std::size_t value = std::max<std::size_t>(left, right);
33+
return value;
34+
}
35+
36+
int main() {
37+
assert(selected == 0);
38+
assert(assigned == 5);
39+
assert(accumulated == 2);
40+
assert(call_assigned == 5);
41+
assert(aggregate_selected == 9);
42+
static int aggregate_static =
43+
read_array({std::max(7, 8)}) + read_record({std::min(9, 10)});
44+
assert(aggregate_static == 17);
45+
assert(mapped_selected == 3);
46+
assert(get() == 7);
47+
return 0;
48+
}
Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
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 read_0(value: Ptr<i32>) -> i32 {
10+
return (value.read());
11+
}
12+
thread_local!(
13+
pub static selected_1: Value<i32> = Rc::new(RefCell::new({
14+
let __tmp_0: Value<i32>;
15+
let __tmp_1: Value<i32>;
16+
({
17+
read_0(
18+
({
19+
__tmp_0 = Rc::new(RefCell::new(0));
20+
__tmp_1 = Rc::new(RefCell::new(0));
21+
if CppLess::less(&__tmp_0.as_pointer(), &__tmp_1.as_pointer()) {
22+
__tmp_0.as_pointer()
23+
} else {
24+
__tmp_1.as_pointer()
25+
}
26+
}),
27+
)
28+
})
29+
}));
30+
);
31+
thread_local!(
32+
pub static x_2: Value<i32> = Rc::new(RefCell::new(0));
33+
);
34+
thread_local!(
35+
pub static y_3: Value<i32> = Rc::new(RefCell::new(0));
36+
);
37+
thread_local!(
38+
pub static assigned_4: Value<i32> = Rc::new(RefCell::new({
39+
let __tmp_2: Value<i32>;
40+
let __tmp_3: Value<i32>;
41+
({
42+
{
43+
let __rhs = {
44+
__tmp_2 = Rc::new(RefCell::new(6));
45+
__tmp_3 = Rc::new(RefCell::new(5));
46+
(if CppLess::less(&__tmp_2.as_pointer(), &__tmp_3.as_pointer()) {
47+
__tmp_2.as_pointer()
48+
} else {
49+
__tmp_3.as_pointer()
50+
}
51+
.read())
52+
};
53+
x_2.with(|rc| *rc.borrow_mut() = __rhs)
54+
};
55+
x_2.with(|rc| *rc.borrow())
56+
})
57+
}));
58+
);
59+
thread_local!(
60+
pub static accumulated_5: Value<i32> = Rc::new(RefCell::new({
61+
let __tmp_4: Value<i32>;
62+
let __tmp_5: Value<i32>;
63+
({
64+
{
65+
let __rhs = {
66+
__tmp_4 = Rc::new(RefCell::new(1));
67+
__tmp_5 = Rc::new(RefCell::new(2));
68+
(if CppLess::less(&__tmp_4.as_pointer(), &__tmp_5.as_pointer()) {
69+
__tmp_5.as_pointer()
70+
} else {
71+
__tmp_4.as_pointer()
72+
}
73+
.read())
74+
};
75+
y_3.with(|rc| *rc.borrow_mut() += __rhs)
76+
};
77+
y_3.with(|rc| *rc.borrow())
78+
})
79+
}));
80+
);
81+
thread_local!(
82+
pub static call_assigned_6: Value<i32> = Rc::new(RefCell::new({
83+
let __tmp_6: Value<i32>;
84+
({
85+
{
86+
let __rhs = ({
87+
__tmp_6 = Rc::new(RefCell::new(5));
88+
read_0(__tmp_6.as_pointer())
89+
});
90+
x_2.with(|rc| *rc.borrow_mut() = __rhs)
91+
};
92+
x_2.with(|rc| *rc.borrow())
93+
})
94+
}));
95+
);
96+
#[derive(Copy, Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)]
97+
#[byte_size(4)]
98+
pub struct Item {
99+
#[offset(0)]
100+
pub value: i32,
101+
}
102+
pub fn read_array_7(value: Ptr<i32>) -> i32 {
103+
return (elem!(value, 0).read());
104+
}
105+
pub fn read_record_8(value: Ptr<Item>) -> i32 {
106+
return value.with(|__s| __s.value);
107+
}
108+
thread_local!(
109+
pub static aggregate_selected_9: Value<i32> = Rc::new(RefCell::new({
110+
let __tmp_8: Value<i32>;
111+
let __tmp_9: Value<i32>;
112+
let __tmp_7: Value<Box<[i32]>>;
113+
let __tmp_11: Value<i32>;
114+
let __tmp_12: Value<i32>;
115+
let __tmp_10: Value<Item>;
116+
(({
117+
__tmp_7 = Rc::new(RefCell::new(Box::new([{
118+
__tmp_8 = Rc::new(RefCell::new(4));
119+
__tmp_9 = Rc::new(RefCell::new(3));
120+
(if CppLess::less(&__tmp_8.as_pointer(), &__tmp_9.as_pointer()) {
121+
__tmp_8.as_pointer()
122+
} else {
123+
__tmp_9.as_pointer()
124+
}
125+
.read())
126+
}])));
127+
read_array_7(__tmp_7.decay())
128+
}) + ({
129+
__tmp_10 = Rc::new(RefCell::new(Item {
130+
value: {
131+
__tmp_11 = Rc::new(RefCell::new(5));
132+
__tmp_12 = Rc::new(RefCell::new(6));
133+
(if CppLess::less(&__tmp_11.as_pointer(), &__tmp_12.as_pointer()) {
134+
__tmp_12.as_pointer()
135+
} else {
136+
__tmp_11.as_pointer()
137+
}
138+
.read())
139+
},
140+
}));
141+
read_record_8(__tmp_10.as_pointer())
142+
}))
143+
}));
144+
);
145+
thread_local!(
146+
pub static left_10: Value<u64> = Rc::new(RefCell::new(3_u64));
147+
);
148+
thread_local!(
149+
pub static right_11: Value<usize> = Rc::new(RefCell::new(7_usize));
150+
);
151+
thread_local!(
152+
pub static mapped_selected_12: Value<usize> = {
153+
let __tmp_13: Value<u64>;
154+
Rc::new(RefCell::new(
155+
(({
156+
__tmp_13 = Rc::new(RefCell::new((right_11.with(|rc| *rc.borrow()) as u64)));
157+
(if CppLess::less(&__tmp_13.as_pointer(), &left_10.with(|v| v.as_pointer())) {
158+
__tmp_13.as_pointer()
159+
} else {
160+
left_10.with(|v| v.as_pointer())
161+
}
162+
.read())
163+
}) as usize),
164+
))
165+
};
166+
);
167+
pub fn get_13() -> usize {
168+
return value_14.with(|rc| *rc.borrow());
169+
}
170+
thread_local!(
171+
static value_14: Value<usize> = {
172+
let __tmp_14: Value<u64>;
173+
Rc::new(RefCell::new(
174+
(({
175+
__tmp_14 = Rc::new(RefCell::new((right_11.with(|rc| *rc.borrow()) as u64)));
176+
(if CppLess::less(&left_10.with(|v| v.as_pointer()), &__tmp_14.as_pointer()) {
177+
__tmp_14.as_pointer()
178+
} else {
179+
left_10.with(|v| v.as_pointer())
180+
}
181+
.read())
182+
}) as usize),
183+
))
184+
};
185+
);
186+
pub fn main() {
187+
__cpp2rust_init_globals();
188+
libcc2rs::cpp2rust_exit(main_0());
189+
}
190+
fn main_0() -> i32 {
191+
assert!((selected_1.with(|rc| *rc.borrow()) == 0));
192+
assert!((assigned_4.with(|rc| *rc.borrow()) == 5));
193+
assert!((accumulated_5.with(|rc| *rc.borrow()) == 2));
194+
assert!((call_assigned_6.with(|rc| *rc.borrow()) == 5));
195+
assert!((aggregate_selected_9.with(|rc| *rc.borrow()) == 9));
196+
assert!((aggregate_static_15.with(|rc| *rc.borrow()) == 17));
197+
assert!((mapped_selected_12.with(|rc| *rc.borrow()) == 3_usize));
198+
assert!((({ get_13() }) == 7_usize));
199+
return 0;
200+
}
201+
thread_local!(
202+
static aggregate_static_15: Value<i32> = Rc::new(RefCell::new({
203+
let __tmp_16: Value<i32>;
204+
let __tmp_17: Value<i32>;
205+
let __tmp_15: Value<Box<[i32]>>;
206+
let __tmp_19: Value<i32>;
207+
let __tmp_20: Value<i32>;
208+
let __tmp_18: Value<Item>;
209+
(({
210+
__tmp_15 = Rc::new(RefCell::new(Box::new([{
211+
__tmp_16 = Rc::new(RefCell::new(7));
212+
__tmp_17 = Rc::new(RefCell::new(8));
213+
(if CppLess::less(&__tmp_16.as_pointer(), &__tmp_17.as_pointer()) {
214+
__tmp_17.as_pointer()
215+
} else {
216+
__tmp_16.as_pointer()
217+
}
218+
.read())
219+
}])));
220+
read_array_7(__tmp_15.decay())
221+
}) + ({
222+
__tmp_18 = Rc::new(RefCell::new(Item {
223+
value: {
224+
__tmp_19 = Rc::new(RefCell::new(10));
225+
__tmp_20 = Rc::new(RefCell::new(9));
226+
(if CppLess::less(&__tmp_19.as_pointer(), &__tmp_20.as_pointer()) {
227+
__tmp_19.as_pointer()
228+
} else {
229+
__tmp_20.as_pointer()
230+
}
231+
.read())
232+
},
233+
}));
234+
read_record_8(__tmp_18.as_pointer())
235+
}))
236+
}));
237+
);
238+
pub fn __cpp2rust_init_globals() {
239+
let _ = selected_1.with(|_| ());
240+
let _ = x_2.with(|_| ());
241+
let _ = y_3.with(|_| ());
242+
let _ = assigned_4.with(|_| ());
243+
let _ = accumulated_5.with(|_| ());
244+
let _ = call_assigned_6.with(|_| ());
245+
let _ = aggregate_selected_9.with(|_| ());
246+
let _ = left_10.with(|_| ());
247+
let _ = right_11.with(|_| ());
248+
let _ = mapped_selected_12.with(|_| ());
249+
}

0 commit comments

Comments
 (0)