Skip to content

Commit 8f4ada4

Browse files
Implement a SimplifyStaticSwitch MIR pass which
removes unnecessary switches on statically known discriminants.
1 parent c84d5e7 commit 8f4ada4

14 files changed

+1059
-27
lines changed

compiler/rustc_mir_transform/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ mod check_alignment;
101101
pub mod simplify;
102102
mod simplify_branches;
103103
mod simplify_comparison_integral;
104+
mod simplify_static_switch;
104105
mod sroa;
105106
mod uninhabited_enum_branching;
106107
mod unreachable_prop;
@@ -561,6 +562,8 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
561562
&simplify::SimplifyLocals::BeforeConstProp,
562563
&copy_prop::CopyProp,
563564
&ref_prop::ReferencePropagation,
565+
// Remove switches on a statically known discriminant, which can happen as a result of inlining.
566+
&simplify_static_switch::SimplifyStaticSwitch,
564567
// Perform `SeparateConstSwitch` after SSA-based analyses, as cloning blocks may
565568
// destroy the SSA property. It should still happen before const-propagation, so the
566569
// latter pass will leverage the created opportunities.
Lines changed: 320 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,320 @@
1+
use super::MirPass;
2+
3+
use rustc_data_structures::fx::FxHashMap;
4+
use rustc_middle::mir::visit::{PlaceContext, Visitor};
5+
use rustc_middle::mir::{
6+
AggregateKind, BasicBlock, Body, Local, Location, Operand, Place, Rvalue, StatementKind,
7+
TerminatorKind,
8+
};
9+
use rustc_middle::ty::TyCtxt;
10+
use rustc_mir_dataflow::impls::MaybeBorrowedLocals;
11+
use rustc_mir_dataflow::Analysis;
12+
use rustc_session::Session;
13+
14+
use super::simplify;
15+
use super::ssa::SsaLocals;
16+
17+
/// # Overview
18+
///
19+
/// This pass looks to optimize a pattern in MIR where variants of an aggregate
20+
/// are constructed in one or more blocks with the same successor and then that
21+
/// aggregate/discriminant is switched on in that successor block, in which case
22+
/// we can remove the switch on the discriminant because we statically know
23+
/// what target block will be taken for each variant.
24+
///
25+
/// Note that an aggregate which is returned from a function call or passed as
26+
/// an argument is not viable for this optimization because we do not statically
27+
/// know the discriminant/variant of the aggregate.
28+
///
29+
/// For example, the following CFG:
30+
/// ```text
31+
/// x = Foo::A(y); --- Foo::A ---> ...
32+
/// / \ /
33+
/// ... --> switch x
34+
/// \ / \
35+
/// x = Foo::B(y); --- Foo::B ---> ...
36+
/// ```
37+
/// would become:
38+
/// ```text
39+
/// x = Foo::A(y); --------- Foo::A ---> ...
40+
/// /
41+
/// ...
42+
/// \
43+
/// x = Foo::B(y); --------- Foo::B ---> ...
44+
/// ```
45+
///
46+
/// # Soundness
47+
///
48+
/// - If the discriminant being switched on is not SSA, or if the aggregate is
49+
/// mutated before the discriminant is assigned, the optimization cannot be
50+
/// applied because we no longer statically know what variant the aggregate
51+
/// could be, or what discriminant is being switched on.
52+
///
53+
/// - If the discriminant is borrowed before being switched on, or the aggregate
54+
/// is borrowed before the discriminant is assigned, we also cannot optimize due
55+
/// to the possibilty stated in the first paragraph.
56+
///
57+
/// - An aggregate being constructed has a known variant, and if it is not borrowed
58+
/// or mutated before being switched on, then it does not actually need a runtime
59+
/// switch on the discriminant (aka variant) of said aggregate.
60+
///
61+
pub struct SimplifyStaticSwitch;
62+
63+
impl<'tcx> MirPass<'tcx> for SimplifyStaticSwitch {
64+
fn is_enabled(&self, sess: &Session) -> bool {
65+
sess.mir_opt_level() >= 2
66+
}
67+
68+
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
69+
debug!("Running SimplifyStaticSwitch on {:?}", body.source.def_id());
70+
71+
let ssa_locals = SsaLocals::new(body);
72+
if simplify_static_switches(tcx, body, &ssa_locals) {
73+
simplify::remove_dead_blocks(tcx, body);
74+
}
75+
}
76+
}
77+
78+
#[instrument(level = "debug", skip_all, ret)]
79+
fn simplify_static_switches<'tcx>(
80+
tcx: TyCtxt<'tcx>,
81+
body: &mut Body<'tcx>,
82+
ssa_locals: &SsaLocals,
83+
) -> bool {
84+
let dominators = body.basic_blocks.dominators();
85+
let predecessors = body.basic_blocks.predecessors();
86+
let mut discriminants = FxHashMap::default();
87+
let mut static_switches = FxHashMap::default();
88+
let mut borrowed_locals =
89+
MaybeBorrowedLocals.into_engine(tcx, body).iterate_to_fixpoint().into_results_cursor(body);
90+
for (switched, rvalue, location) in ssa_locals.assignments(body) {
91+
let Rvalue::Discriminant(discr) = rvalue else {
92+
continue
93+
};
94+
95+
borrowed_locals.seek_after_primary_effect(location);
96+
// If `discr` was borrowed before its discriminant was assigned to `switched`,
97+
// or if it was borrowed in the assignment, we cannot optimize.
98+
if borrowed_locals.contains(discr.local) {
99+
debug!("The aggregate: {discr:?} was borrowed before its discriminant was read");
100+
continue;
101+
}
102+
103+
let Location { block, statement_index } = location;
104+
let mut finder = MutatedLocalFinder { local: discr.local, mutated: false };
105+
for (statement_index, statement) in body.basic_blocks[block]
106+
.statements
107+
.iter()
108+
.enumerate()
109+
.take_while(|&(index, _)| index != statement_index)
110+
{
111+
finder.visit_statement(statement, Location { block, statement_index });
112+
}
113+
114+
if finder.mutated {
115+
debug!("The aggregate: {discr:?} was mutated before its discriminant was read");
116+
continue;
117+
}
118+
119+
// If `switched` is borrowed by the time we actually switch on it, we also cannot optimize.
120+
borrowed_locals.seek_to_block_end(block);
121+
if borrowed_locals.contains(switched) {
122+
debug!("The local: {switched:?} was borrowed before being switched on");
123+
continue;
124+
}
125+
126+
discriminants.insert(
127+
switched,
128+
Discriminant {
129+
block,
130+
discr: discr.local,
131+
exclude: if ssa_locals.num_direct_uses(switched) == 1 {
132+
// If there is only one direct use of `switched` we do not need to keep
133+
// it around because the only use is in the switch.
134+
Some(statement_index)
135+
} else {
136+
None
137+
},
138+
},
139+
);
140+
}
141+
142+
if discriminants.is_empty() {
143+
debug!("No SSA locals were assigned a discriminant");
144+
return false;
145+
}
146+
147+
for (switched, Discriminant { discr, block, exclude }) in discriminants {
148+
let data = &body.basic_blocks[block];
149+
if data.is_cleanup {
150+
continue;
151+
}
152+
153+
let predecessors = &predecessors[block];
154+
if predecessors.is_empty() {
155+
continue;
156+
}
157+
158+
if predecessors.iter().any(|&pred| {
159+
// If we find a backedge from: `pred -> block`, this indicates that
160+
// `block` is a loop header. To avoid creating irreducible CFGs we do
161+
// not thread through loop headers.
162+
dominators.dominates(block, pred)
163+
}) {
164+
debug!("Unable to thread through loop header: {block:?}");
165+
continue;
166+
}
167+
168+
let terminator = data.terminator();
169+
let TerminatorKind::SwitchInt {
170+
discr: Operand::Copy(place) | Operand::Move(place),
171+
targets
172+
} = &terminator.kind else {
173+
continue
174+
};
175+
176+
if place.local != switched {
177+
continue;
178+
}
179+
180+
let mut finder = MutatedLocalFinder { local: discr, mutated: false };
181+
'preds: for &pred in predecessors {
182+
let data = &body.basic_blocks[pred];
183+
let terminator = data.terminator();
184+
let TerminatorKind::Goto { .. } = terminator.kind else {
185+
continue
186+
};
187+
188+
for (statement_index, statement) in data.statements.iter().enumerate().rev() {
189+
match statement.kind {
190+
StatementKind::SetDiscriminant { box place, variant_index: variant }
191+
| StatementKind::Assign(box (
192+
place,
193+
Rvalue::Aggregate(box AggregateKind::Adt(_, variant, ..), ..),
194+
)) if place.local == discr => {
195+
if finder.mutated {
196+
debug!(
197+
"The discriminant: {discr:?} was mutated in predecessor: {pred:?}"
198+
);
199+
// We can't optimize this predecessor, so try the next one.
200+
finder.mutated = false;
201+
202+
continue 'preds;
203+
}
204+
205+
let discr_ty = body.local_decls[discr].ty;
206+
if let Some(discr) = discr_ty.discriminant_for_variant(tcx, variant) {
207+
debug!(
208+
"{pred:?}: {place:?} = {discr_ty:?}::{variant:?}; goto -> {block:?}",
209+
);
210+
211+
let target = targets.target_for_value(discr.val);
212+
static_switches
213+
.entry(block)
214+
.and_modify(|static_switches: &mut &mut [StaticSwitch]| {
215+
if static_switches.iter_mut().all(|switch| {
216+
if switch.pred == pred {
217+
switch.target = target;
218+
false
219+
} else {
220+
true
221+
}
222+
}) {
223+
*static_switches =
224+
tcx.arena.alloc_from_iter(
225+
static_switches.iter().copied().chain([
226+
StaticSwitch { pred, target, exclude },
227+
]),
228+
);
229+
}
230+
})
231+
.or_insert_with(|| {
232+
tcx.arena.alloc([StaticSwitch { pred, target, exclude }])
233+
});
234+
}
235+
236+
continue 'preds;
237+
}
238+
_ if finder.mutated => {
239+
debug!("The discriminant: {discr:?} was mutated in predecessor: {pred:?}");
240+
// Note that the discriminant could have been mutated in one predecessor
241+
// but not the others, in which case only the predecessors which did not mutate
242+
// the discriminant can be optimized.
243+
finder.mutated = false;
244+
245+
continue 'preds;
246+
}
247+
_ => finder.visit_statement(statement, Location { block, statement_index }),
248+
}
249+
}
250+
}
251+
}
252+
253+
if static_switches.is_empty() {
254+
debug!("No static switches were found in the current body");
255+
return false;
256+
}
257+
258+
let basic_blocks = body.basic_blocks.as_mut();
259+
let num_switches: usize = static_switches.iter().map(|(_, switches)| switches.len()).sum();
260+
for (block, static_switches) in static_switches {
261+
for switch in static_switches {
262+
debug!("{block:?}: Removing static switch: {switch:?}");
263+
264+
// We use the SSA, to destroy the SSA.
265+
let data = {
266+
let (block, pred) = basic_blocks.pick2_mut(block, switch.pred);
267+
match switch.exclude {
268+
Some(exclude) => {
269+
pred.statements.extend(block.statements.iter().enumerate().filter_map(
270+
|(index, statement)| {
271+
if index == exclude { None } else { Some(statement.clone()) }
272+
},
273+
));
274+
}
275+
None => pred.statements.extend_from_slice(&block.statements),
276+
}
277+
pred
278+
};
279+
let terminator = data.terminator_mut();
280+
281+
// Make sure that we have not overwritten the terminator and it is still
282+
// a `goto -> block`.
283+
assert_eq!(terminator.kind, TerminatorKind::Goto { target: block });
284+
// Something to be noted is that, this creates an edge from: `pred -> target`,
285+
// and because we ensure that we do not thread through any loop headers, meaning
286+
// it is not part of a loop, this edge will only ever appear once in the CFG.
287+
terminator.kind = TerminatorKind::Goto { target: switch.target };
288+
}
289+
}
290+
291+
debug!("Removed {num_switches} static switches from: {:?}", body.source.def_id());
292+
true
293+
}
294+
295+
#[derive(Debug, Copy, Clone)]
296+
struct StaticSwitch {
297+
pred: BasicBlock,
298+
target: BasicBlock,
299+
exclude: Option<usize>,
300+
}
301+
302+
#[derive(Debug, Copy, Clone)]
303+
struct Discriminant {
304+
discr: Local,
305+
block: BasicBlock,
306+
exclude: Option<usize>,
307+
}
308+
309+
struct MutatedLocalFinder {
310+
local: Local,
311+
mutated: bool,
312+
}
313+
314+
impl<'tcx> Visitor<'tcx> for MutatedLocalFinder {
315+
fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _: Location) {
316+
if self.local == place.local && let PlaceContext::MutatingUse(..) = context {
317+
self.mutated = true;
318+
}
319+
}
320+
}

tests/mir-opt/separate_const_switch.identity.SeparateConstSwitch.diff

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -51,51 +51,44 @@
5151
StorageLive(_10);
5252
StorageLive(_11);
5353
_9 = discriminant(_1);
54-
switchInt(move _9) -> [0: bb7, 1: bb5, otherwise: bb6];
54+
switchInt(move _9) -> [0: bb5, 1: bb3, otherwise: bb4];
5555
}
5656

5757
bb1: {
58-
StorageDead(_11);
59-
StorageDead(_10);
60-
_5 = discriminant(_3);
61-
switchInt(move _5) -> [0: bb2, 1: bb4, otherwise: bb3];
62-
}
63-
64-
bb2: {
6558
_8 = ((_3 as Continue).0: i32);
6659
_0 = Result::<i32, i32>::Ok(_8);
6760
StorageDead(_3);
6861
return;
6962
}
7063

71-
bb3: {
72-
unreachable;
73-
}
74-
75-
bb4: {
64+
bb2: {
7665
_6 = ((_3 as Break).0: std::result::Result<std::convert::Infallible, i32>);
7766
_13 = ((_6 as Err).0: i32);
7867
_0 = Result::<i32, i32>::Err(move _13);
7968
StorageDead(_3);
8069
return;
8170
}
8271

83-
bb5: {
72+
bb3: {
8473
_11 = ((_1 as Err).0: i32);
8574
StorageLive(_12);
8675
_12 = Result::<Infallible, i32>::Err(move _11);
8776
_3 = ControlFlow::<Result<Infallible, i32>, i32>::Break(move _12);
8877
StorageDead(_12);
89-
goto -> bb1;
78+
StorageDead(_11);
79+
StorageDead(_10);
80+
goto -> bb2;
9081
}
9182

92-
bb6: {
83+
bb4: {
9384
unreachable;
9485
}
9586

96-
bb7: {
87+
bb5: {
9788
_10 = ((_1 as Ok).0: i32);
9889
_3 = ControlFlow::<Result<Infallible, i32>, i32>::Continue(move _10);
90+
StorageDead(_11);
91+
StorageDead(_10);
9992
goto -> bb1;
10093
}
10194
}

0 commit comments

Comments
 (0)