Skip to content

Commit a4d0fc3

Browse files
committed
Add SingleUseConsts mir-opt pass
1 parent d2fb97f commit a4d0fc3

File tree

31 files changed

+1004
-344
lines changed

31 files changed

+1004
-344
lines changed

Diff for: compiler/rustc_mir_transform/src/const_debuginfo.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ pub struct ConstDebugInfo;
1616

1717
impl<'tcx> MirPass<'tcx> for ConstDebugInfo {
1818
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
19-
sess.mir_opt_level() > 0
19+
// Disabled in favour of `SingleUseConsts`
20+
sess.mir_opt_level() > 2
2021
}
2122

2223
fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {

Diff for: compiler/rustc_mir_transform/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ mod check_alignment;
106106
pub mod simplify;
107107
mod simplify_branches;
108108
mod simplify_comparison_integral;
109+
mod single_use_consts;
109110
mod sroa;
110111
mod unreachable_enum_branching;
111112
mod unreachable_prop;
@@ -593,6 +594,7 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
593594
&gvn::GVN,
594595
&simplify::SimplifyLocals::AfterGVN,
595596
&dataflow_const_prop::DataflowConstProp,
597+
&single_use_consts::SingleUseConsts,
596598
&const_debuginfo::ConstDebugInfo,
597599
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
598600
&jump_threading::JumpThreading,
+195
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
use rustc_index::{bit_set::BitSet, IndexVec};
2+
use rustc_middle::bug;
3+
use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
4+
use rustc_middle::mir::*;
5+
use rustc_middle::ty::TyCtxt;
6+
7+
/// Various parts of MIR building introduce temporaries that are commonly not needed.
8+
///
9+
/// Notably, `if CONST` and `match CONST` end up being used-once temporaries, which
10+
/// obfuscates the structure for other passes and codegen, which would like to always
11+
/// be able to just see the constant directly.
12+
///
13+
/// At higher optimization levels fancier passes like GVN will take care of this
14+
/// in a more general fashion, but this handles the easy cases so can run in debug.
15+
///
16+
/// This only removes constants with a single-use because re-evaluating constants
17+
/// isn't always an improvement, especially for large ones.
18+
///
19+
/// It also removes *never*-used constants, since it had all the information
20+
/// needed to do that too, including updating the debug info.
21+
pub struct SingleUseConsts;
22+
23+
impl<'tcx> MirPass<'tcx> for SingleUseConsts {
24+
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
25+
sess.mir_opt_level() > 0
26+
}
27+
28+
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
29+
let mut finder = SingleUseConstsFinder {
30+
ineligible_locals: BitSet::new_empty(body.local_decls.len()),
31+
locations: IndexVec::new(),
32+
};
33+
34+
finder.ineligible_locals.insert_range(..=Local::from_usize(body.arg_count));
35+
36+
finder.visit_body(body);
37+
38+
for (local, locations) in finder.locations.iter_enumerated() {
39+
if finder.ineligible_locals.contains(local) {
40+
continue;
41+
}
42+
43+
let Some(init_loc) = locations.init_loc else {
44+
continue;
45+
};
46+
47+
// We're only changing an operand, not the terminator kinds or successors
48+
let basic_blocks = body.basic_blocks.as_mut_preserves_cfg();
49+
let init_statement =
50+
basic_blocks[init_loc.block].statements[init_loc.statement_index].replace_nop();
51+
let StatementKind::Assign(place_and_rvalue) = init_statement.kind else {
52+
bug!("No longer an assign?");
53+
};
54+
let (place, rvalue) = *place_and_rvalue;
55+
assert_eq!(place.as_local(), Some(local));
56+
let Rvalue::Use(operand) = rvalue else { bug!("No longer a use?") };
57+
58+
let mut replacer = LocalReplacer { tcx, local, operand: Some(operand) };
59+
60+
for var_debug_info in &mut body.var_debug_info {
61+
replacer.visit_var_debug_info(var_debug_info);
62+
}
63+
64+
let Some(use_loc) = locations.use_loc else { continue };
65+
66+
let use_block = &mut basic_blocks[use_loc.block];
67+
if let Some(use_statement) = use_block.statements.get_mut(use_loc.statement_index) {
68+
replacer.visit_statement(use_statement, use_loc);
69+
} else {
70+
replacer.visit_terminator(use_block.terminator_mut(), use_loc);
71+
}
72+
73+
if replacer.operand.is_some() {
74+
bug!(
75+
"operand wasn't used replacing local {local:?} with locations {locations:?} in body {body:#?}"
76+
);
77+
}
78+
}
79+
}
80+
}
81+
82+
#[derive(Copy, Clone, Debug)]
83+
struct LocationPair {
84+
init_loc: Option<Location>,
85+
use_loc: Option<Location>,
86+
}
87+
88+
impl LocationPair {
89+
fn new() -> Self {
90+
Self { init_loc: None, use_loc: None }
91+
}
92+
}
93+
94+
struct SingleUseConstsFinder {
95+
ineligible_locals: BitSet<Local>,
96+
locations: IndexVec<Local, LocationPair>,
97+
}
98+
99+
impl<'tcx> Visitor<'tcx> for SingleUseConstsFinder {
100+
fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
101+
if let Some(local) = place.as_local()
102+
&& let Rvalue::Use(operand) = rvalue
103+
&& let Operand::Constant(_) = operand
104+
{
105+
let locations = self.locations.ensure_contains_elem(local, LocationPair::new);
106+
if locations.init_loc.is_some() {
107+
self.ineligible_locals.insert(local);
108+
} else {
109+
locations.init_loc = Some(location);
110+
}
111+
} else {
112+
self.super_assign(place, rvalue, location);
113+
}
114+
}
115+
116+
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
117+
if let Some(place) = operand.place()
118+
&& let Some(local) = place.as_local()
119+
{
120+
let locations = self.locations.ensure_contains_elem(local, LocationPair::new);
121+
if locations.use_loc.is_some() {
122+
self.ineligible_locals.insert(local);
123+
} else {
124+
locations.use_loc = Some(location);
125+
}
126+
} else {
127+
self.super_operand(operand, location);
128+
}
129+
}
130+
131+
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
132+
match &statement.kind {
133+
// Storage markers are irrelevant to this.
134+
StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => {}
135+
_ => self.super_statement(statement, location),
136+
}
137+
}
138+
139+
fn visit_var_debug_info(&mut self, var_debug_info: &VarDebugInfo<'tcx>) {
140+
if let VarDebugInfoContents::Place(place) = &var_debug_info.value
141+
&& let Some(_local) = place.as_local()
142+
{
143+
// It's a simple one that we can easily update
144+
} else {
145+
self.super_var_debug_info(var_debug_info);
146+
}
147+
}
148+
149+
fn visit_local(&mut self, local: Local, _context: PlaceContext, _location: Location) {
150+
// If there's any path that gets here, rather than being understood elsewhere,
151+
// then we'd better not do anything with this local.
152+
self.ineligible_locals.insert(local);
153+
}
154+
}
155+
156+
struct LocalReplacer<'tcx> {
157+
tcx: TyCtxt<'tcx>,
158+
local: Local,
159+
operand: Option<Operand<'tcx>>,
160+
}
161+
162+
impl<'tcx> MutVisitor<'tcx> for LocalReplacer<'tcx> {
163+
fn tcx(&self) -> TyCtxt<'tcx> {
164+
self.tcx
165+
}
166+
167+
fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _location: Location) {
168+
if let Operand::Copy(place) | Operand::Move(place) = operand
169+
&& let Some(local) = place.as_local()
170+
&& local == self.local
171+
{
172+
*operand = self.operand.take().unwrap_or_else(|| {
173+
bug!("there was a second use of the operand");
174+
});
175+
}
176+
}
177+
178+
fn visit_var_debug_info(&mut self, var_debug_info: &mut VarDebugInfo<'tcx>) {
179+
if let VarDebugInfoContents::Place(place) = &var_debug_info.value
180+
&& let Some(local) = place.as_local()
181+
&& local == self.local
182+
{
183+
let const_op = self
184+
.operand
185+
.as_ref()
186+
.unwrap_or_else(|| {
187+
bug!("the operand was already stolen");
188+
})
189+
.constant()
190+
.unwrap()
191+
.clone();
192+
var_debug_info.value = VarDebugInfoContents::Const(const_op);
193+
}
194+
}
195+
}

Diff for: tests/mir-opt/building/match/sort_candidates.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ fn constant_eq(s: &str, b: bool) -> u32 {
55
// Check that we only test "a" once
66

77
// CHECK-LABEL: fn constant_eq(
8-
// CHECK: bb0: {
9-
// CHECK: [[a:_.*]] = const "a";
10-
// CHECK-NOT: {{_.*}} = const "a";
8+
// CHECK-NOT: const "a"
9+
// CHECK: {{_[0-9]+}} = const "a" as &[u8] (Transmute);
10+
// CHECK-NOT: const "a"
1111
match (s, b) {
1212
("a", _) if true => 1,
1313
("b", true) => 2,

Diff for: tests/mir-opt/dest-prop/union.main.DestinationPropagation.panic-abort.diff

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
bb0: {
1919
StorageLive(_1);
2020
StorageLive(_2);
21-
_2 = const 1_u32;
21+
nop;
2222
_1 = Un { us: const 1_u32 };
2323
StorageDead(_2);
2424
StorageLive(_3);

Diff for: tests/mir-opt/dest-prop/union.main.DestinationPropagation.panic-unwind.diff

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
bb0: {
1919
StorageLive(_1);
2020
StorageLive(_2);
21-
_2 = const 1_u32;
21+
nop;
2222
_1 = Un { us: const 1_u32 };
2323
StorageDead(_2);
2424
StorageLive(_3);

Diff for: tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
_3 = &_4;
3030
_2 = move _3 as &[T] (PointerCoercion(Unsize));
3131
StorageDead(_3);
32-
_5 = const 3_usize;
33-
_6 = const true;
32+
nop;
33+
nop;
3434
goto -> bb2;
3535
}
3636

Diff for: tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
_3 = &_4;
3030
_2 = move _3 as &[T] (PointerCoercion(Unsize));
3131
StorageDead(_3);
32-
_5 = const 3_usize;
33-
_6 = const true;
32+
nop;
33+
nop;
3434
goto -> bb2;
3535
}
3636

Diff for: tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff

+14-18
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,15 @@
2323
let mut _12: isize;
2424
let _13: std::alloc::AllocError;
2525
let mut _14: !;
26-
let _15: &str;
27-
let mut _16: &dyn std::fmt::Debug;
28-
let mut _17: &std::alloc::AllocError;
26+
let mut _15: &dyn std::fmt::Debug;
27+
let mut _16: &std::alloc::AllocError;
2928
scope 7 {
3029
}
3130
scope 8 {
3231
}
3332
}
3433
scope 9 (inlined NonNull::<[u8]>::as_ptr) {
35-
let mut _18: *const [u8];
34+
let mut _17: *const [u8];
3635
}
3736
}
3837
scope 3 (inlined #[track_caller] Option::<Layout>::unwrap) {
@@ -87,36 +86,33 @@
8786
StorageDead(_8);
8887
StorageDead(_7);
8988
StorageLive(_12);
90-
StorageLive(_15);
9189
_12 = discriminant(_6);
9290
switchInt(move _12) -> [0: bb6, 1: bb5, otherwise: bb1];
9391
}
9492

9593
bb5: {
96-
_15 = const "called `Result::unwrap()` on an `Err` value";
94+
StorageLive(_15);
9795
StorageLive(_16);
98-
StorageLive(_17);
99-
_17 = &_13;
100-
_16 = move _17 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
101-
StorageDead(_17);
102-
_14 = result::unwrap_failed(move _15, move _16) -> unwind unreachable;
96+
_16 = &_13;
97+
_15 = move _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
98+
StorageDead(_16);
99+
_14 = result::unwrap_failed(const "called `Result::unwrap()` on an `Err` value", move _15) -> unwind unreachable;
103100
}
104101

105102
bb6: {
106103
_5 = move ((_6 as Ok).0: std::ptr::NonNull<[u8]>);
107-
StorageDead(_15);
108104
StorageDead(_12);
109105
StorageDead(_6);
110-
- StorageLive(_18);
106+
- StorageLive(_17);
111107
+ nop;
112-
_18 = (_5.0: *const [u8]);
113-
- _4 = move _18 as *mut [u8] (PtrToPtr);
114-
- StorageDead(_18);
115-
+ _4 = _18 as *mut [u8] (PtrToPtr);
108+
_17 = (_5.0: *const [u8]);
109+
- _4 = move _17 as *mut [u8] (PtrToPtr);
110+
- StorageDead(_17);
111+
+ _4 = _17 as *mut [u8] (PtrToPtr);
116112
+ nop;
117113
StorageDead(_5);
118114
- _3 = move _4 as *mut u8 (PtrToPtr);
119-
+ _3 = _18 as *mut u8 (PtrToPtr);
115+
+ _3 = _17 as *mut u8 (PtrToPtr);
120116
StorageDead(_4);
121117
StorageDead(_3);
122118
- StorageDead(_1);

0 commit comments

Comments
 (0)