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