]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir_transform/src/simplify.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_mir_transform / src / simplify.rs
CommitLineData
c30ab7b3 1//! A number of passes which remove various redundancies in the CFG.
3157f602 2//!
c30ab7b3
SL
3//! The `SimplifyCfg` pass gets rid of unnecessary blocks in the CFG, whereas the `SimplifyLocals`
4//! gets rid of all the unnecessary local variable declarations.
3157f602 5//!
c30ab7b3
SL
6//! The `SimplifyLocals` pass is kinda expensive and therefore not very suitable to be run often.
7//! Most of the passes should not care or be impacted in meaningful ways due to extra locals
94b46f34 8//! either, so running the pass once, right before codegen, should suffice.
c30ab7b3
SL
9//!
10//! On the other side of the spectrum, the `SimplifyCfg` pass is considerably cheap to run, thus
11//! one should run it after every pass which may modify CFG in significant ways. This pass must
12//! also be run before any analysis passes because it removes dead blocks, and some of these can be
13//! ill-typed.
14//!
15//! The cause of this typing issue is typeck allowing most blocks whose end is not reachable have
16//! an arbitrary return type, rather than having the usual () return type (as a note, typeck's
17//! notion of reachability is in fact slightly weaker than MIR CFG reachability - see #31617). A
18//! standard example of the situation is:
3157f602 19//!
3157f602
XL
20//! ```rust
21//! fn example() {
22//! let _a: char = { return; };
23//! }
24//! ```
25//!
c30ab7b3
SL
26//! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we
27//! naively generate still contains the `_a = ()` write in the unreachable block "after" the
28//! return.
3157f602 29
c295e0f8 30use crate::MirPass;
064997fb 31use rustc_data_structures::fx::FxHashSet;
e74abb32 32use rustc_index::vec::{Idx, IndexVec};
17df50a5 33use rustc_middle::mir::coverage::*;
ba9703b0
XL
34use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
35use rustc_middle::mir::*;
f9f354fc 36use rustc_middle::ty::TyCtxt;
3dfed10e 37use smallvec::SmallVec;
cdc7bbd5 38use std::convert::TryInto;
92a42be0 39
dfeec247
XL
40pub struct SimplifyCfg {
41 label: String,
42}
a7813a04 43
7cac9316
XL
44impl SimplifyCfg {
45 pub fn new(label: &str) -> Self {
46 SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
92a42be0 47 }
a7813a04
XL
48}
49
a2a8927a 50pub fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
dc9dc135 51 CfgSimplifier::new(body).simplify();
17df50a5 52 remove_dead_blocks(tcx, body);
cc61c64b
XL
53
54 // FIXME: Should probably be moved into some kind of pass manager
dc9dc135 55 body.basic_blocks_mut().raw.shrink_to_fit();
cc61c64b
XL
56}
57
e1599b0c 58impl<'tcx> MirPass<'tcx> for SimplifyCfg {
487cf647
FG
59 fn name(&self) -> &str {
60 &self.label
3157f602 61 }
3157f602 62
17df50a5 63 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
5869c6ff 64 debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body.source);
17df50a5 65 simplify_cfg(tcx, body);
a7813a04 66 }
3157f602
XL
67}
68
dc9dc135 69pub struct CfgSimplifier<'a, 'tcx> {
3157f602 70 basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
dfeec247 71 pred_count: IndexVec<BasicBlock, u32>,
a7813a04
XL
72}
73
dc9dc135 74impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
f9f354fc 75 pub fn new(body: &'a mut Body<'tcx>) -> Self {
f2b60f7d 76 let mut pred_count = IndexVec::from_elem(0u32, &body.basic_blocks);
a7813a04 77
3157f602
XL
78 // we can't use mir.predecessors() here because that counts
79 // dead blocks, which we don't want to.
c30ab7b3
SL
80 pred_count[START_BLOCK] = 1;
81
dc9dc135 82 for (_, data) in traversal::preorder(body) {
3157f602 83 if let Some(ref term) = data.terminator {
923072b8 84 for tgt in term.successors() {
3157f602
XL
85 pred_count[tgt] += 1;
86 }
a7813a04
XL
87 }
88 }
3157f602 89
dc9dc135 90 let basic_blocks = body.basic_blocks_mut();
3157f602 91
dfeec247 92 CfgSimplifier { basic_blocks, pred_count }
a7813a04
XL
93 }
94
8bb4bdeb 95 pub fn simplify(mut self) {
3b2f2976
XL
96 self.strip_nops();
97
ba9703b0
XL
98 // Vec of the blocks that should be merged. We store the indices here, instead of the
99 // statements itself to avoid moving the (relatively) large statements twice.
100 // We do not push the statements directly into the target block (`bb`) as that is slower
101 // due to additional reallocations
102 let mut merged_blocks = Vec::new();
3157f602
XL
103 loop {
104 let mut changed = false;
105
0731742a 106 for bb in self.basic_blocks.indices() {
3157f602 107 if self.pred_count[bb] == 0 {
dfeec247 108 continue;
a7813a04
XL
109 }
110
3157f602
XL
111 debug!("simplifying {:?}", bb);
112
dfeec247
XL
113 let mut terminator =
114 self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
3157f602
XL
115
116 for successor in terminator.successors_mut() {
117 self.collapse_goto_chain(successor, &mut changed);
a7813a04
XL
118 }
119
3157f602 120 let mut inner_changed = true;
ba9703b0 121 merged_blocks.clear();
3157f602
XL
122 while inner_changed {
123 inner_changed = false;
124 inner_changed |= self.simplify_branch(&mut terminator);
ba9703b0 125 inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
3157f602 126 changed |= inner_changed;
92a42be0 127 }
92a42be0 128
ba9703b0
XL
129 let statements_to_merge =
130 merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
131
132 if statements_to_merge > 0 {
133 let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
134 statements.reserve(statements_to_merge);
135 for &from in &merged_blocks {
136 statements.append(&mut self.basic_blocks[from].statements);
137 }
138 self.basic_blocks[bb].statements = statements;
139 }
140
141 self.basic_blocks[bb].terminator = Some(terminator);
a7813a04 142 }
92a42be0 143
dfeec247
XL
144 if !changed {
145 break;
146 }
a7813a04
XL
147 }
148 }
a7813a04 149
3dfed10e
XL
150 /// This function will return `None` if
151 /// * the block has statements
152 /// * the block has a terminator other than `goto`
153 /// * the block has no terminator (meaning some other part of the current optimization stole it)
154 fn take_terminator_if_simple_goto(&mut self, bb: BasicBlock) -> Option<Terminator<'tcx>> {
155 match self.basic_blocks[bb] {
3157f602
XL
156 BasicBlockData {
157 ref statements,
dfeec247
XL
158 terminator:
159 ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
160 ..
3157f602
XL
161 } if statements.is_empty() => terminator.take(),
162 // if `terminator` is None, this means we are in a loop. In that
163 // case, let all the loop collapse to its entry.
3dfed10e
XL
164 _ => None,
165 }
166 }
3157f602 167
3dfed10e
XL
168 /// Collapse a goto chain starting from `start`
169 fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
170 // Using `SmallVec` here, because in some logs on libcore oli-obk saw many single-element
171 // goto chains. We should probably benchmark different sizes.
172 let mut terminators: SmallVec<[_; 1]> = Default::default();
173 let mut current = *start;
174 while let Some(terminator) = self.take_terminator_if_simple_goto(current) {
5e7ed085
FG
175 let Terminator { kind: TerminatorKind::Goto { target }, .. } = terminator else {
176 unreachable!();
3dfed10e
XL
177 };
178 terminators.push((current, terminator));
179 current = target;
180 }
181 let last = current;
182 *start = last;
183 while let Some((current, mut terminator)) = terminators.pop() {
5e7ed085
FG
184 let Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } = terminator else {
185 unreachable!();
3dfed10e
XL
186 };
187 *changed |= *target != last;
188 *target = last;
189 debug!("collapsing goto chain from {:?} to {:?}", current, target);
190
191 if self.pred_count[current] == 1 {
192 // This is the last reference to current, so the pred-count to
193 // to target is moved into the current block.
194 self.pred_count[current] = 0;
195 } else {
196 self.pred_count[*target] += 1;
197 self.pred_count[current] -= 1;
92a42be0 198 }
3dfed10e 199 self.basic_blocks[current].terminator = Some(terminator);
c30ab7b3 200 }
3157f602 201 }
7453a54e 202
3157f602 203 // merge a block with 1 `goto` predecessor to its parent
dfeec247
XL
204 fn merge_successor(
205 &mut self,
ba9703b0 206 merged_blocks: &mut Vec<BasicBlock>,
dfeec247
XL
207 terminator: &mut Terminator<'tcx>,
208 ) -> bool {
3157f602 209 let target = match terminator.kind {
dfeec247
XL
210 TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
211 _ => return false,
3157f602
XL
212 };
213
214 debug!("merging block {:?} into {:?}", target, terminator);
215 *terminator = match self.basic_blocks[target].terminator.take() {
216 Some(terminator) => terminator,
217 None => {
218 // unreachable loop - this should not be possible, as we
219 // don't strand blocks, but handle it correctly.
dfeec247 220 return false;
3157f602
XL
221 }
222 };
ba9703b0
XL
223
224 merged_blocks.push(target);
3157f602 225 self.pred_count[target] = 0;
7453a54e 226
3157f602
XL
227 true
228 }
229
230 // turn a branch with all successors identical to a goto
231 fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
232 match terminator.kind {
dfeec247
XL
233 TerminatorKind::SwitchInt { .. } => {}
234 _ => return false,
3157f602
XL
235 };
236
237 let first_succ = {
923072b8
FG
238 if let Some(first_succ) = terminator.successors().next() {
239 if terminator.successors().all(|s| s == first_succ) {
83c7162d
XL
240 let count = terminator.successors().count();
241 self.pred_count[first_succ] -= (count - 1) as u32;
3157f602
XL
242 first_succ
243 } else {
dfeec247 244 return false;
92a42be0 245 }
3157f602 246 } else {
dfeec247 247 return false;
92a42be0 248 }
3157f602
XL
249 };
250
251 debug!("simplifying branch {:?}", terminator);
252 terminator.kind = TerminatorKind::Goto { target: first_succ };
253 true
254 }
8bb4bdeb
XL
255
256 fn strip_nops(&mut self) {
257 for blk in self.basic_blocks.iter_mut() {
1b1a35ee 258 blk.statements.retain(|stmt| !matches!(stmt.kind, StatementKind::Nop))
8bb4bdeb
XL
259 }
260 }
3157f602
XL
261}
262
a2a8927a 263pub fn remove_dead_blocks<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
5869c6ff 264 let reachable = traversal::reachable_as_bitset(body);
f2b60f7d 265 let num_blocks = body.basic_blocks.len();
5869c6ff
XL
266 if num_blocks == reachable.count() {
267 return;
3157f602
XL
268 }
269
064997fb
FG
270 let basic_blocks = body.basic_blocks.as_mut();
271 let source_scopes = &body.source_scopes;
dfeec247 272 let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
3157f602 273 let mut used_blocks = 0;
5869c6ff
XL
274 for alive_index in reachable.iter() {
275 let alive_index = alive_index.index();
3157f602
XL
276 replacements[alive_index] = BasicBlock::new(used_blocks);
277 if alive_index != used_blocks {
60c5eb7d
XL
278 // Swap the next alive block data with the current available slot. Since
279 // alive_index is non-decreasing this is a valid operation.
3157f602 280 basic_blocks.raw.swap(alive_index, used_blocks);
92a42be0 281 }
3157f602
XL
282 used_blocks += 1;
283 }
17df50a5
XL
284
285 if tcx.sess.instrument_coverage() {
064997fb 286 save_unreachable_coverage(basic_blocks, source_scopes, used_blocks);
17df50a5
XL
287 }
288
3157f602 289 basic_blocks.raw.truncate(used_blocks);
92a42be0 290
3157f602
XL
291 for block in basic_blocks {
292 for target in block.terminator_mut().successors_mut() {
293 *target = replacements[target.index()];
92a42be0 294 }
92a42be0
SL
295 }
296}
c30ab7b3 297
17df50a5
XL
298/// Some MIR transforms can determine at compile time that a sequences of
299/// statements will never be executed, so they can be dropped from the MIR.
300/// For example, an `if` or `else` block that is guaranteed to never be executed
301/// because its condition can be evaluated at compile time, such as by const
302/// evaluation: `if false { ... }`.
303///
304/// Those statements are bypassed by redirecting paths in the CFG around the
5099ac24 305/// `dead blocks`; but with `-C instrument-coverage`, the dead blocks usually
17df50a5
XL
306/// include `Coverage` statements representing the Rust source code regions to
307/// be counted at runtime. Without these `Coverage` statements, the regions are
308/// lost, and the Rust source code will show no coverage information.
309///
310/// What we want to show in a coverage report is the dead code with coverage
311/// counts of `0`. To do this, we need to save the code regions, by injecting
312/// `Unreachable` coverage statements. These are non-executable statements whose
313/// code regions are still recorded in the coverage map, representing regions
314/// with `0` executions.
064997fb
FG
315///
316/// If there are no live `Counter` `Coverage` statements remaining, we remove
317/// `Coverage` statements along with the dead blocks. Since at least one
318/// counter per function is required by LLVM (and necessary, to add the
319/// `function_hash` to the counter's call to the LLVM intrinsic
320/// `instrprof.increment()`).
321///
322/// The `generator::StateTransform` MIR pass and MIR inlining can create
323/// atypical conditions, where all live `Counter`s are dropped from the MIR.
324///
325/// With MIR inlining we can have coverage counters belonging to different
326/// instances in a single body, so the strategy described above is applied to
327/// coverage counters from each instance individually.
17df50a5
XL
328fn save_unreachable_coverage(
329 basic_blocks: &mut IndexVec<BasicBlock, BasicBlockData<'_>>,
064997fb 330 source_scopes: &IndexVec<SourceScope, SourceScopeData<'_>>,
17df50a5
XL
331 first_dead_block: usize,
332) {
064997fb
FG
333 // Identify instances that still have some live coverage counters left.
334 let mut live = FxHashSet::default();
335 for basic_block in &basic_blocks.raw[0..first_dead_block] {
336 for statement in &basic_block.statements {
337 let StatementKind::Coverage(coverage) = &statement.kind else { continue };
338 let CoverageKind::Counter { .. } = coverage.kind else { continue };
339 let instance = statement.source_info.scope.inlined_instance(source_scopes);
340 live.insert(instance);
341 }
342 }
343
344 for block in &mut basic_blocks.raw[..first_dead_block] {
345 for statement in &mut block.statements {
346 let StatementKind::Coverage(_) = &statement.kind else { continue };
347 let instance = statement.source_info.scope.inlined_instance(source_scopes);
348 if !live.contains(&instance) {
349 statement.make_nop();
17df50a5 350 }
064997fb
FG
351 }
352 }
353
354 if live.is_empty() {
17df50a5
XL
355 return;
356 }
357
064997fb
FG
358 // Retain coverage for instances that still have some live counters left.
359 let mut retained_coverage = Vec::new();
360 for dead_block in &basic_blocks.raw[first_dead_block..] {
361 for statement in &dead_block.statements {
362 let StatementKind::Coverage(coverage) = &statement.kind else { continue };
363 let Some(code_region) = &coverage.code_region else { continue };
364 let instance = statement.source_info.scope.inlined_instance(source_scopes);
365 if live.contains(&instance) {
366 retained_coverage.push((statement.source_info, code_region.clone()));
17df50a5
XL
367 }
368 }
369 }
370
371 let start_block = &mut basic_blocks[START_BLOCK];
064997fb
FG
372 start_block.statements.extend(retained_coverage.into_iter().map(
373 |(source_info, code_region)| Statement {
17df50a5 374 source_info,
94222f64 375 kind: StatementKind::Coverage(Box::new(Coverage {
17df50a5
XL
376 kind: CoverageKind::Unreachable,
377 code_region: Some(code_region),
94222f64 378 })),
064997fb
FG
379 },
380 ));
17df50a5
XL
381}
382
c30ab7b3
SL
383pub struct SimplifyLocals;
384
e1599b0c 385impl<'tcx> MirPass<'tcx> for SimplifyLocals {
a2a8927a
XL
386 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
387 sess.mir_opt_level() > 0
388 }
389
29967ef6
XL
390 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
391 trace!("running SimplifyLocals on {:?}", body.source);
6a06907d
XL
392 simplify_locals(body, tcx);
393 }
394}
ba9703b0 395
6a06907d
XL
396pub fn simplify_locals<'tcx>(body: &mut Body<'tcx>, tcx: TyCtxt<'tcx>) {
397 // First, we're going to get a count of *actual* uses for every `Local`.
cdc7bbd5 398 let mut used_locals = UsedLocals::new(body);
ba9703b0 399
6a06907d
XL
400 // Next, we're going to remove any `Local` with zero actual uses. When we remove those
401 // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals`
402 // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from
403 // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a
404 // fixedpoint where there are no more unused locals.
405 remove_unused_definitions(&mut used_locals, body);
ba9703b0 406
6a06907d 407 // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s.
cdc7bbd5 408 let map = make_local_map(&mut body.local_decls, &used_locals);
ba9703b0 409
6a06907d
XL
410 // Only bother running the `LocalUpdater` if we actually found locals to remove.
411 if map.iter().any(Option::is_none) {
412 // Update references to all vars and tmps now
413 let mut updater = LocalUpdater { map, tcx };
f2b60f7d 414 updater.visit_body_preserves_cfg(body);
ba9703b0 415
6a06907d 416 body.local_decls.shrink_to_fit();
c30ab7b3
SL
417 }
418}
419
420/// Construct the mapping while swapping out unused stuff out from the `vec`.
cdc7bbd5 421fn make_local_map<V>(
ba9703b0 422 local_decls: &mut IndexVec<Local, V>,
cdc7bbd5 423 used_locals: &UsedLocals,
8faf50e0 424) -> IndexVec<Local, Option<Local>> {
cdc7bbd5 425 let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*local_decls);
8faf50e0 426 let mut used = Local::new(0);
29967ef6
XL
427
428 for alive_index in local_decls.indices() {
cdc7bbd5
XL
429 // `is_used` treats the `RETURN_PLACE` and arguments as used.
430 if !used_locals.is_used(alive_index) {
431 continue;
432 }
433
434 map[alive_index] = Some(used);
435 if alive_index != used {
436 local_decls.swap(alive_index, used);
c30ab7b3 437 }
cdc7bbd5 438 used.increment_by(1);
c30ab7b3 439 }
ba9703b0 440 local_decls.truncate(used.index());
c30ab7b3
SL
441 map
442}
443
29967ef6 444/// Keeps track of used & unused locals.
cdc7bbd5 445struct UsedLocals {
29967ef6 446 increment: bool,
cdc7bbd5 447 arg_count: u32,
29967ef6 448 use_count: IndexVec<Local, u32>,
c30ab7b3
SL
449}
450
cdc7bbd5 451impl UsedLocals {
29967ef6 452 /// Determines which locals are used & unused in the given body.
cdc7bbd5 453 fn new(body: &Body<'_>) -> Self {
29967ef6
XL
454 let mut this = Self {
455 increment: true,
cdc7bbd5 456 arg_count: body.arg_count.try_into().unwrap(),
29967ef6
XL
457 use_count: IndexVec::from_elem(0, &body.local_decls),
458 };
459 this.visit_body(body);
460 this
ba9703b0 461 }
ba9703b0 462
29967ef6 463 /// Checks if local is used.
cdc7bbd5
XL
464 ///
465 /// Return place and arguments are always considered used.
29967ef6
XL
466 fn is_used(&self, local: Local) -> bool {
467 trace!("is_used({:?}): use_count: {:?}", local, self.use_count[local]);
cdc7bbd5 468 local.as_u32() <= self.arg_count || self.use_count[local] != 0
29967ef6 469 }
e74abb32 470
29967ef6 471 /// Updates the use counts to reflect the removal of given statement.
a2a8927a 472 fn statement_removed(&mut self, statement: &Statement<'_>) {
29967ef6 473 self.increment = false;
e74abb32 474
29967ef6
XL
475 // The location of the statement is irrelevant.
476 let location = Location { block: START_BLOCK, statement_index: 0 };
477 self.visit_statement(statement, location);
c30ab7b3 478 }
ba9703b0 479
29967ef6 480 /// Visits a left-hand side of an assignment.
a2a8927a 481 fn visit_lhs(&mut self, place: &Place<'_>, location: Location) {
29967ef6
XL
482 if place.is_indirect() {
483 // A use, not a definition.
484 self.visit_place(place, PlaceContext::MutatingUse(MutatingUseContext::Store), location);
485 } else {
cdc7bbd5
XL
486 // A definition. The base local itself is not visited, so this occurrence is not counted
487 // toward its use count. There might be other locals still, used in an indexing
488 // projection.
29967ef6 489 self.super_projection(
6a06907d 490 place.as_ref(),
29967ef6
XL
491 PlaceContext::MutatingUse(MutatingUseContext::Projection),
492 location,
493 );
494 }
ba9703b0
XL
495 }
496}
497
a2a8927a 498impl<'tcx> Visitor<'tcx> for UsedLocals {
29967ef6
XL
499 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
500 match statement.kind {
f2b60f7d 501 StatementKind::Intrinsic(..)
29967ef6
XL
502 | StatementKind::Retag(..)
503 | StatementKind::Coverage(..)
504 | StatementKind::FakeRead(..)
505 | StatementKind::AscribeUserType(..) => {
506 self.super_statement(statement, location);
ba9703b0 507 }
ba9703b0 508
29967ef6 509 StatementKind::Nop => {}
ba9703b0 510
29967ef6 511 StatementKind::StorageLive(_local) | StatementKind::StorageDead(_local) => {}
c30ab7b3 512
29967ef6 513 StatementKind::Assign(box (ref place, ref rvalue)) => {
923072b8
FG
514 if rvalue.is_safe_to_remove() {
515 self.visit_lhs(place, location);
516 self.visit_rvalue(rvalue, location);
517 } else {
518 self.super_statement(statement, location);
519 }
29967ef6 520 }
ba9703b0 521
04454e1e
FG
522 StatementKind::SetDiscriminant { ref place, variant_index: _ }
523 | StatementKind::Deinit(ref place) => {
29967ef6
XL
524 self.visit_lhs(place, location);
525 }
526 }
ba9703b0 527 }
ba9703b0 528
064997fb 529 fn visit_local(&mut self, local: Local, _ctx: PlaceContext, _location: Location) {
29967ef6 530 if self.increment {
064997fb 531 self.use_count[local] += 1;
29967ef6 532 } else {
064997fb
FG
533 assert_ne!(self.use_count[local], 0);
534 self.use_count[local] -= 1;
29967ef6 535 }
e74abb32 536 }
29967ef6 537}
e74abb32 538
29967ef6 539/// Removes unused definitions. Updates the used locals to reflect the changes made.
a2a8927a 540fn remove_unused_definitions(used_locals: &mut UsedLocals, body: &mut Body<'_>) {
29967ef6
XL
541 // The use counts are updated as we remove the statements. A local might become unused
542 // during the retain operation, leading to a temporary inconsistency (storage statements or
543 // definitions referencing the local might remain). For correctness it is crucial that this
544 // computation reaches a fixed point.
545
546 let mut modified = true;
547 while modified {
548 modified = false;
549
f2b60f7d 550 for data in body.basic_blocks.as_mut_preserves_cfg() {
29967ef6
XL
551 // Remove unnecessary StorageLive and StorageDead annotations.
552 data.statements.retain(|statement| {
553 let keep = match &statement.kind {
554 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
555 used_locals.is_used(*local)
556 }
557 StatementKind::Assign(box (place, _)) => used_locals.is_used(place.local),
ba9703b0 558
04454e1e
FG
559 StatementKind::SetDiscriminant { ref place, .. }
560 | StatementKind::Deinit(ref place) => used_locals.is_used(place.local),
29967ef6
XL
561 _ => true,
562 };
ba9703b0 563
29967ef6
XL
564 if !keep {
565 trace!("removing statement {:?}", statement);
566 modified = true;
567 used_locals.statement_removed(statement);
568 }
ba9703b0 569
29967ef6
XL
570 keep
571 });
572 }
c30ab7b3 573 }
ba9703b0 574}
e74abb32 575
ba9703b0
XL
576struct LocalUpdater<'tcx> {
577 map: IndexVec<Local, Option<Local>>,
578 tcx: TyCtxt<'tcx>,
579}
580
581impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
582 fn tcx(&self) -> TyCtxt<'tcx> {
583 self.tcx
c30ab7b3 584 }
e74abb32 585
ba9703b0
XL
586 fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
587 *l = self.map[*l].unwrap();
e74abb32 588 }
c30ab7b3 589}