Skip to content

Commit 2722c2a

Browse files
authored
Rollup merge of #98078 - erikdesjardins:uncheckedsize, r=petrochenkov
Use unchecked mul to compute slice sizes This allows LLVM to realize that `slice.len() > 0` iff `slice.len() * size_of::<T>() > 0`, allowing a branch on the latter to be folded into the former when dropping vecs and boxed slices, in some cases. Fixes (partially) #96497
2 parents bb48051 + 50f6a9e commit 2722c2a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

compiler/rustc_codegen_ssa/src/glue.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,12 @@ pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
3939
// The info in this case is the length of the str, so the size is that
4040
// times the unit size.
4141
(
42-
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
42+
// All slice sizes must fit into `isize`, so this multiplication cannot (signed) wrap.
43+
// NOTE: ideally, we want the effects of both `unchecked_smul` and `unchecked_umul`
44+
// (resulting in `mul nsw nuw` in LLVM IR), since we know that the multiplication
45+
// cannot signed wrap, and that both operands are non-negative. But at the time of writing,
46+
// `BuilderMethods` can't do this, and it doesn't seem to enable any further optimizations.
47+
bx.unchecked_smul(info.unwrap(), bx.const_usize(unit.size.bytes())),
4348
bx.const_usize(unit.align.abi.bytes()),
4449
)
4550
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// This test case checks that LLVM is aware that computing the size of a slice cannot wrap.
2+
// The possibility of wrapping results in an additional branch when dropping boxed slices
3+
// in some situations, see https://github.com/rust-lang/rust/issues/96497#issuecomment-1112865218
4+
5+
// compile-flags: -O
6+
// min-llvm-version: 14.0
7+
8+
#![crate_type="lib"]
9+
10+
// CHECK-LABEL: @simple_size_of_nowrap
11+
#[no_mangle]
12+
pub fn simple_size_of_nowrap(x: &[u32]) -> usize {
13+
// Make sure the shift used to compute the size has a nowrap flag.
14+
15+
// CHECK: [[A:%.*]] = shl nsw {{.*}}, 2
16+
// CHECK-NEXT: ret {{.*}} [[A]]
17+
core::mem::size_of_val(x)
18+
}
19+
20+
// CHECK-LABEL: @drop_write
21+
#[no_mangle]
22+
pub fn drop_write(mut x: Box<[u32]>) {
23+
// Check that this write is optimized out.
24+
// This depends on the size calculation not wrapping,
25+
// since otherwise LLVM can't tell that the memory is always deallocated if the slice len > 0.
26+
27+
// CHECK-NOT: store i32 42
28+
x[1] = 42;
29+
}

0 commit comments

Comments
 (0)