Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6371,9 +6371,18 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,

// Bindings in a global initializer are local to the expansion too.
clang::DeclContext *binding_context = curr_function_;
if (!binding_context && tgt_ir->usesInit()) {
binding_context = clang::BlockDecl::Create(
ctx_, ctx_.getTranslationUnitDecl(), expr->getExprLoc());
if (!binding_context) {
auto unused_bind = bind;
TranslationRule::AnyFragment(tgt_ir->body, [&](const auto &frag) {
if (auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&frag)) {
unused_bind[ph->n] = false;
}
return false;
});
if (tgt_ir->usesInit() || llvm::is_contained(unused_bind, true)) {
binding_context = clang::BlockDecl::Create(
ctx_, ctx_.getTranslationUnitDecl(), expr->getExprLoc());
}
}

for (size_t i = 0; binding_context && i < all_args.size(); ++i) {
Expand Down
27 changes: 26 additions & 1 deletion cpp2rust/converter/translation_rule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ ExprRule::argsToBind(clang::ASTContext &ctx, const clang::Expr *expr,
bool right_to_left = op && op->isAssignmentOp();
std::vector<bool> bind(args.size());
bool bind_rest = false;
bool bind_before_unused = false;
unsigned next_first = position;
bool init_args = usesInit();
auto num_args =
Expand All @@ -377,16 +378,40 @@ ExprRule::argsToBind(clang::ASTContext &ctx, const clang::Expr *expr,
continue;
}
if (arg->HasSideEffects(ctx)) {
if (uses[i] == 0) {
// A constexpr constructor need not have runtime side effects.
clang::Expr::EvalResult result;
if (!arg->isValueDependent() && arg->EvaluateAsRValue(result, ctx) &&
!result.HasSideEffects && !result.HasUndefinedBehavior) {
continue;
}
// Match Clang's folding of constant builtins, which can ignore an
// unused operand. Evaluate in runtime, not constant, context.
auto *call = clang::dyn_cast<clang::CallExpr>(expr);
clang::Expr::EvalResult call_result;
if (call && call->getBuiltinCallee() && call->isPRValue() &&
!call->isValueDependent() &&
call->EvaluateAsRValue(call_result, ctx) &&
!call_result.HasSideEffects &&
(call_result.Val.isInt() || call_result.Val.isFloat())) {
continue;
}
}
bind_before_unused |= uses[i] == 0;
// A temporary that a reference parameter is bound to would be
// materialized before the call, out of order.
bind_rest |=
uses[i] > 1 ||
uses[i] != 1 ||
(i < params.size() && takesTemporaryAddress(ctx, expr, i, arg)) ||
(uses[i] == 1 && first[i] > next_first);
bind[i] = bind_rest;
if (uses[i] == 1) {
next_first = std::min(next_first, first[i]);
}
} else if (bind_before_unused && uses[i] != 0) {
// Capture earlier values and places before an omitted operand changes
// what they would read or select.
bind[i] = true;
} else if (uses[i] > 1 && arg->isPRValue() && !arg->isEvaluatable(ctx) &&
!clang::isa<clang::DeclRefExpr>(arg->IgnoreParenLValueCasts())) {
// A value computed from others is not computed again, nor before the
Expand Down
62 changes: 62 additions & 0 deletions tests/unit/mapped_unused_args.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// ADDITIONAL_COMPILE_FLAGS: -std=c++17

#include <array>
#include <cstdio>

int bump(int *calls, int delta) {
*calls += delta;
return *calls;
}

std::array<int, 1> &pick(std::array<int, 1> &a, int *calls) {
++*calls;
return a;
}

int global_calls = 0;
std::array<int, 1> global_array{};
std::array<int, 1> &global_pick() {
++global_calls;
return global_array;
}
auto global_size = global_pick().size();

std::array<int, 3> make_array(int *calls) {
++*calls;
return {1, 2, 3};
}

const char *tag(int *calls) {
++*calls;
return "";
}

__attribute__((pure)) constexpr int read_calls(int *calls) {
return __builtin_is_constant_evaluated() ? 1 : *calls;
}

int main() {
auto size = global_size;
std::printf("global n=%zu calls=%d\n", size, global_calls);
std::array<int, 1> a{};
int calls = 0;
auto n = pick(a, &calls).size();
std::printf("array n=%zu calls=%d\n", n, calls);

calls = 0;
auto result = __builtin_expect(bump(&calls, 1), bump(&calls, 2));
std::printf("order value=%ld calls=%d\n", result, calls);
calls = 0;
n = make_array(&calls).size();
std::printf("temporary n=%zu calls=%d\n", n, calls);
calls = 0;
auto nan = __builtin_nanf(tag(&calls));
std::printf("pointer nan=%d calls=%d\n", nan != nan, calls);
calls = 2;
result = __builtin_expect(read_calls(&calls), bump(&calls, 2));
std::printf("snapshot value=%ld state=%d\n", result, calls);
calls = 0;
result = __builtin_expect(1, ++calls);
std::printf("pure n=%zu value=%ld folded=%ld calls=%d\n", a.size(),
__builtin_expect(10, 1), result, calls);
}
122 changes: 122 additions & 0 deletions tests/unit/out/refcount/mapped_unused_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
extern crate libcc2rs;
use libcc2rs::*;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
pub fn bump_0(mut calls: Ptr<i32>, mut delta: i32) -> i32 {
{
calls.with_mut(|__v| *__v = *__v + delta)
};
return (calls.read());
}
pub fn pick_1(a: Ptr<Box<[i32]>>, mut calls: Ptr<i32>) -> Ptr<Box<[i32]>> {
calls.with_mut(|__v| {
__v.prefix_inc();
});
return (a).clone();
}
thread_local!(
pub static global_calls_2: Value<i32> = Rc::new(RefCell::new(0));
);
thread_local!(
pub static global_array_3: Value<Box<[i32]>> =
Rc::new(RefCell::new(Box::<[i32]>::from(std::array::from_fn::<
_,
1,
_,
>(|_| 0_i32))));
);
pub fn global_pick_4() -> Ptr<Box<[i32]>> {
(*global_calls_2.with(Value::clone).borrow_mut()).prefix_inc();
return global_array_3.with(|v| v.as_pointer());
}
thread_local!(
pub static global_size_5: Value<usize> =
Rc::new(RefCell::new(match (({ global_pick_4() }),) {
(__tmp_0,) => 1,
}));
);
pub fn make_array_6(mut calls: Ptr<i32>) -> Box<[i32]> {
calls.with_mut(|__v| {
__v.prefix_inc();
});
return Box::<[i32]>::from([1, 2, 3]);
}
pub fn tag_7(mut calls: Ptr<i32>) -> Ptr<i8> {
calls.with_mut(|__v| {
__v.prefix_inc();
});
return Ptr::<i8>::from_string_literal(b"");
}
pub fn read_calls_8(mut calls: Ptr<i32>) -> i32 {
return if false { 1 } else { (calls.read()) };
}
pub fn main() {
__cpp2rust_init_globals();
libcc2rs::cpp2rust_exit(main_0());
}
fn main_0() -> i32 {
let mut size: usize = global_size_5.with(|rc| *rc.borrow());
printf!(
b"global n=%zu calls=%d\n",
size,
global_calls_2.with(|rc| *rc.borrow())
);
let a: Value<Box<[i32]>> = Rc::new(RefCell::new(Box::<[i32]>::from(std::array::from_fn::<
_,
1,
_,
>(|_| 0_i32))));
let calls: Value<i32> = Rc::new(RefCell::new(0));
let mut n: usize = match (({ pick_1(a.as_pointer(), (calls.as_pointer())) }),) {
(__tmp_1,) => 1,
};
printf!(b"array n=%zu calls=%d\n", n, (*calls.borrow()));
(*calls.borrow_mut()) = 0;
let mut result: i64 = {
let mut __tmp_2 = { (({ bump_0((calls.as_pointer()), 1) }) as i64) };
let mut __tmp_3 = { (({ bump_0((calls.as_pointer()), 2) }) as i64) };
__tmp_2
};
printf!(b"order value=%ld calls=%d\n", result, (*calls.borrow()));
(*calls.borrow_mut()) = 0;
n = match (Rc::new(RefCell::new(({ make_array_6((calls.as_pointer())) }))).as_pointer(),) {
(__tmp_4,) => 3,
};
printf!(b"temporary n=%zu calls=%d\n", n, (*calls.borrow()));
(*calls.borrow_mut()) = 0;
let mut nan: f32 = {
let mut __tmp_5 = { ({ tag_7((calls.as_pointer())) }) };
f32::NAN
};
printf!(
b"pointer nan=%d calls=%d\n",
((nan != nan) as i32),
(*calls.borrow())
);
(*calls.borrow_mut()) = 2;
result = {
let mut __tmp_6 = { (({ read_calls_8((calls.as_pointer())) }) as i64) };
let mut __tmp_7 = { (({ bump_0((calls.as_pointer()), 2) }) as i64) };
__tmp_6
};
printf!(b"snapshot value=%ld state=%d\n", result, (*calls.borrow()));
(*calls.borrow_mut()) = 0;
result = 1_i64;
printf!(
b"pure n=%zu value=%ld folded=%ld calls=%d\n",
1,
10_i64,
result,
(*calls.borrow())
);
0
}
pub fn __cpp2rust_init_globals() {
let _ = global_calls_2.with(|_| ());
let _ = global_array_3.with(|_| ());
let _ = global_size_5.with(|_| ());
}
134 changes: 134 additions & 0 deletions tests/unit/out/unsafe/mapped_unused_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
extern crate libc;
use libc::*;
extern crate libcc2rs;
use libcc2rs::*;
use std::collections::BTreeMap;
use std::io::{Read, Seek, Write};
use std::os::fd::{AsFd, FromRawFd, IntoRawFd};
use std::rc::Rc;
pub unsafe fn bump_0(mut calls: *mut i32, mut delta: i32) -> i32 {
(*calls) += delta;
return (*calls);
}
pub unsafe fn pick_1(a: *mut [i32; 1], mut calls: *mut i32) -> *mut [i32; 1] {
(*calls).prefix_inc();
return a;
}
pub static mut global_calls_2: std::cell::LazyCell<i32> = std::cell::LazyCell::new(|| unsafe { 0 });
pub static mut global_array_3: std::cell::LazyCell<[i32; 1]> =
std::cell::LazyCell::new(|| unsafe { std::array::from_fn::<_, 1, _>(|_| 0_i32) });
pub unsafe fn global_pick_4() -> *mut [i32; 1] {
(*std::cell::LazyCell::force_mut(&mut *&raw mut global_calls_2)).prefix_inc();
return &mut (*std::cell::LazyCell::force_mut(&mut *&raw mut global_array_3));
}
pub static mut global_size_5: std::cell::LazyCell<usize> = std::cell::LazyCell::new(|| unsafe {
match (((unsafe { global_pick_4() }) as *const [i32; 1]),) {
(__tmp_0,) => 1,
}
});
pub unsafe fn make_array_6(mut calls: *mut i32) -> [i32; 3] {
(*calls).prefix_inc();
return [1, 2, 3];
}
pub unsafe fn tag_7(mut calls: *mut i32) -> *const libc::c_char {
(*calls).prefix_inc();
return c"".as_ptr();
}
pub unsafe fn read_calls_8(mut calls: *mut i32) -> i32 {
return if false { 1 } else { (*calls) };
}
pub fn main() {
unsafe {
__cpp2rust_init_globals();
libcc2rs::cpp2rust_exit(main_0() as i32);
}
}
unsafe fn main_0() -> i32 {
let mut size: usize = (*std::cell::LazyCell::force_mut(&mut *&raw mut global_size_5));
(unsafe {
libc::printf(
c"global n=%zu calls=%d\n".as_ptr() as *const libc::c_char,
(size),
(*std::cell::LazyCell::force_mut(&mut *&raw mut global_calls_2)),
)
});
let mut a: [i32; 1] = std::array::from_fn::<_, 1, _>(|_| 0_i32);
let mut calls: i32 = 0;
let mut n: usize =
match (((unsafe { pick_1(&mut a, (&mut calls as *mut i32)) }) as *const [i32; 1]),) {
(__tmp_1,) => 1,
};
(unsafe {
libc::printf(
c"array n=%zu calls=%d\n".as_ptr() as *const libc::c_char,
(n),
(calls),
)
});
calls = 0;
let mut result: i64 = {
let mut __tmp_2 = { ((unsafe { bump_0((&mut calls as *mut i32), 1) }) as i64) };
let mut __tmp_3 = { ((unsafe { bump_0((&mut calls as *mut i32), 2) }) as i64) };
__tmp_2
};
(unsafe {
libc::printf(
c"order value=%ld calls=%d\n".as_ptr() as *const libc::c_char,
(result),
(calls),
)
});
calls = 0;
n = match ((&mut (unsafe { make_array_6((&mut calls as *mut i32)) }) as *const [i32; 3]),) {
(__tmp_4,) => 3,
};
(unsafe {
libc::printf(
c"temporary n=%zu calls=%d\n".as_ptr() as *const libc::c_char,
(n),
(calls),
)
});
calls = 0;
let mut nan: f32 = {
let mut __tmp_5 = { (unsafe { tag_7((&mut calls as *mut i32)) }) };
f32::NAN
};
(unsafe {
libc::printf(
c"pointer nan=%d calls=%d\n".as_ptr() as *const libc::c_char,
(((nan) != (nan)) as i32),
(calls),
)
});
calls = 2;
result = {
let mut __tmp_6 = { ((unsafe { read_calls_8((&mut calls as *mut i32)) }) as i64) };
let mut __tmp_7 = { ((unsafe { bump_0((&mut calls as *mut i32), 2) }) as i64) };
__tmp_6
};
(unsafe {
libc::printf(
c"snapshot value=%ld state=%d\n".as_ptr() as *const libc::c_char,
(result),
(calls),
)
});
calls = 0;
result = 1_i64;
(unsafe {
libc::printf(
c"pure n=%zu value=%ld folded=%ld calls=%d\n".as_ptr() as *const libc::c_char,
(1),
(10_i64),
(result),
(calls),
)
});
0
}
pub unsafe fn __cpp2rust_init_globals() {
std::cell::LazyCell::force(&*&raw const global_calls_2);
std::cell::LazyCell::force(&*&raw const global_array_3);
std::cell::LazyCell::force(&*&raw const global_size_5);
}
Loading