]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/simplify.rs
Auto merge of #77692 - PankajChaudhary5:issue-76630, r=davidtwco
[rust.git] / compiler / rustc_mir / src / transform / 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::transform::MirPass;
31 use rustc_index::bit_set::BitSet;
32 use rustc_index::vec::{Idx, IndexVec};
33 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
34 use rustc_middle::mir::*;
35 use rustc_middle::ty::TyCtxt;
36 use smallvec::SmallVec;
37 use std::borrow::Cow;
38 use std::convert::TryInto;
39
40 pub struct SimplifyCfg {
41     label: String,
42 }
43
44 impl SimplifyCfg {
45     pub fn new(label: &str) -> Self {
46         SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
47     }
48 }
49
50 pub fn simplify_cfg(body: &mut Body<'_>) {
51     CfgSimplifier::new(body).simplify();
52     remove_dead_blocks(body);
53
54     // FIXME: Should probably be moved into some kind of pass manager
55     body.basic_blocks_mut().raw.shrink_to_fit();
56 }
57
58 impl<'tcx> MirPass<'tcx> for SimplifyCfg {
59     fn name(&self) -> Cow<'_, str> {
60         Cow::Borrowed(&self.label)
61     }
62
63     fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
64         debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body);
65         simplify_cfg(body);
66     }
67 }
68
69 pub struct CfgSimplifier<'a, 'tcx> {
70     basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
71     pred_count: IndexVec<BasicBlock, u32>,
72 }
73
74 impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
75     pub fn new(body: &'a mut Body<'tcx>) -> Self {
76         let mut pred_count = IndexVec::from_elem(0u32, body.basic_blocks());
77
78         // we can't use mir.predecessors() here because that counts
79         // dead blocks, which we don't want to.
80         pred_count[START_BLOCK] = 1;
81
82         for (_, data) in traversal::preorder(body) {
83             if let Some(ref term) = data.terminator {
84                 for &tgt in term.successors() {
85                     pred_count[tgt] += 1;
86                 }
87             }
88         }
89
90         let basic_blocks = body.basic_blocks_mut();
91
92         CfgSimplifier { basic_blocks, pred_count }
93     }
94
95     pub fn simplify(mut self) {
96         self.strip_nops();
97
98         let mut start = START_BLOCK;
99
100         // Vec of the blocks that should be merged. We store the indices here, instead of the
101         // statements itself to avoid moving the (relatively) large statements twice.
102         // We do not push the statements directly into the target block (`bb`) as that is slower
103         // due to additional reallocations
104         let mut merged_blocks = Vec::new();
105         loop {
106             let mut changed = false;
107
108             self.collapse_goto_chain(&mut start, &mut changed);
109
110             for bb in self.basic_blocks.indices() {
111                 if self.pred_count[bb] == 0 {
112                     continue;
113                 }
114
115                 debug!("simplifying {:?}", bb);
116
117                 let mut terminator =
118                     self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
119
120                 for successor in terminator.successors_mut() {
121                     self.collapse_goto_chain(successor, &mut changed);
122                 }
123
124                 let mut inner_changed = true;
125                 merged_blocks.clear();
126                 while inner_changed {
127                     inner_changed = false;
128                     inner_changed |= self.simplify_branch(&mut terminator);
129                     inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
130                     changed |= inner_changed;
131                 }
132
133                 let statements_to_merge =
134                     merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
135
136                 if statements_to_merge > 0 {
137                     let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
138                     statements.reserve(statements_to_merge);
139                     for &from in &merged_blocks {
140                         statements.append(&mut self.basic_blocks[from].statements);
141                     }
142                     self.basic_blocks[bb].statements = statements;
143                 }
144
145                 self.basic_blocks[bb].terminator = Some(terminator);
146             }
147
148             if !changed {
149                 break;
150             }
151         }
152
153         if start != START_BLOCK {
154             debug_assert!(self.pred_count[START_BLOCK] == 0);
155             self.basic_blocks.swap(START_BLOCK, start);
156             self.pred_count.swap(START_BLOCK, start);
157
158             // pred_count == 1 if the start block has no predecessor _blocks_.
159             if self.pred_count[START_BLOCK] > 1 {
160                 for (bb, data) in self.basic_blocks.iter_enumerated_mut() {
161                     if self.pred_count[bb] == 0 {
162                         continue;
163                     }
164
165                     for target in data.terminator_mut().successors_mut() {
166                         if *target == start {
167                             *target = START_BLOCK;
168                         }
169                     }
170                 }
171             }
172         }
173     }
174
175     /// This function will return `None` if
176     /// * the block has statements
177     /// * the block has a terminator other than `goto`
178     /// * the block has no terminator (meaning some other part of the current optimization stole it)
179     fn take_terminator_if_simple_goto(&mut self, bb: BasicBlock) -> Option<Terminator<'tcx>> {
180         match self.basic_blocks[bb] {
181             BasicBlockData {
182                 ref statements,
183                 terminator:
184                     ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
185                 ..
186             } if statements.is_empty() => terminator.take(),
187             // if `terminator` is None, this means we are in a loop. In that
188             // case, let all the loop collapse to its entry.
189             _ => None,
190         }
191     }
192
193     /// Collapse a goto chain starting from `start`
194     fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
195         // Using `SmallVec` here, because in some logs on libcore oli-obk saw many single-element
196         // goto chains. We should probably benchmark different sizes.
197         let mut terminators: SmallVec<[_; 1]> = Default::default();
198         let mut current = *start;
199         while let Some(terminator) = self.take_terminator_if_simple_goto(current) {
200             let target = match terminator {
201                 Terminator { kind: TerminatorKind::Goto { target }, .. } => target,
202                 _ => unreachable!(),
203             };
204             terminators.push((current, terminator));
205             current = target;
206         }
207         let last = current;
208         *start = last;
209         while let Some((current, mut terminator)) = terminators.pop() {
210             let target = match terminator {
211                 Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } => target,
212                 _ => unreachable!(),
213             };
214             *changed |= *target != last;
215             *target = last;
216             debug!("collapsing goto chain from {:?} to {:?}", current, target);
217
218             if self.pred_count[current] == 1 {
219                 // This is the last reference to current, so the pred-count to
220                 // to target is moved into the current block.
221                 self.pred_count[current] = 0;
222             } else {
223                 self.pred_count[*target] += 1;
224                 self.pred_count[current] -= 1;
225             }
226             self.basic_blocks[current].terminator = Some(terminator);
227         }
228     }
229
230     // merge a block with 1 `goto` predecessor to its parent
231     fn merge_successor(
232         &mut self,
233         merged_blocks: &mut Vec<BasicBlock>,
234         terminator: &mut Terminator<'tcx>,
235     ) -> bool {
236         let target = match terminator.kind {
237             TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
238             _ => return false,
239         };
240
241         debug!("merging block {:?} into {:?}", target, terminator);
242         *terminator = match self.basic_blocks[target].terminator.take() {
243             Some(terminator) => terminator,
244             None => {
245                 // unreachable loop - this should not be possible, as we
246                 // don't strand blocks, but handle it correctly.
247                 return false;
248             }
249         };
250
251         merged_blocks.push(target);
252         self.pred_count[target] = 0;
253
254         true
255     }
256
257     // turn a branch with all successors identical to a goto
258     fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
259         match terminator.kind {
260             TerminatorKind::SwitchInt { .. } => {}
261             _ => return false,
262         };
263
264         let first_succ = {
265             if let Some(&first_succ) = terminator.successors().next() {
266                 if terminator.successors().all(|s| *s == first_succ) {
267                     let count = terminator.successors().count();
268                     self.pred_count[first_succ] -= (count - 1) as u32;
269                     first_succ
270                 } else {
271                     return false;
272                 }
273             } else {
274                 return false;
275             }
276         };
277
278         debug!("simplifying branch {:?}", terminator);
279         terminator.kind = TerminatorKind::Goto { target: first_succ };
280         true
281     }
282
283     fn strip_nops(&mut self) {
284         for blk in self.basic_blocks.iter_mut() {
285             blk.statements.retain(|stmt| !matches!(stmt.kind, StatementKind::Nop))
286         }
287     }
288 }
289
290 pub fn remove_dead_blocks(body: &mut Body<'_>) {
291     let mut seen = BitSet::new_empty(body.basic_blocks().len());
292     for (bb, _) in traversal::preorder(body) {
293         seen.insert(bb.index());
294     }
295
296     let basic_blocks = body.basic_blocks_mut();
297
298     let num_blocks = basic_blocks.len();
299     let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
300     let mut used_blocks = 0;
301     for alive_index in seen.iter() {
302         replacements[alive_index] = BasicBlock::new(used_blocks);
303         if alive_index != used_blocks {
304             // Swap the next alive block data with the current available slot. Since
305             // alive_index is non-decreasing this is a valid operation.
306             basic_blocks.raw.swap(alive_index, used_blocks);
307         }
308         used_blocks += 1;
309     }
310     basic_blocks.raw.truncate(used_blocks);
311
312     for block in basic_blocks {
313         for target in block.terminator_mut().successors_mut() {
314             *target = replacements[target.index()];
315         }
316     }
317 }
318
319 pub struct SimplifyLocals;
320
321 impl<'tcx> MirPass<'tcx> for SimplifyLocals {
322     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
323         trace!("running SimplifyLocals on {:?}", body.source);
324
325         // First, we're going to get a count of *actual* uses for every `Local`.
326         let mut used_locals = UsedLocals::new(body);
327
328         // Next, we're going to remove any `Local` with zero actual uses. When we remove those
329         // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals`
330         // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from
331         // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a
332         // fixedpoint where there are no more unused locals.
333         remove_unused_definitions(&mut used_locals, body);
334
335         // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s.
336         let map = make_local_map(&mut body.local_decls, &used_locals);
337
338         // Only bother running the `LocalUpdater` if we actually found locals to remove.
339         if map.iter().any(Option::is_none) {
340             // Update references to all vars and tmps now
341             let mut updater = LocalUpdater { map, tcx };
342             updater.visit_body(body);
343
344             body.local_decls.shrink_to_fit();
345         }
346     }
347 }
348
349 /// Construct the mapping while swapping out unused stuff out from the `vec`.
350 fn make_local_map<V>(
351     local_decls: &mut IndexVec<Local, V>,
352     used_locals: &UsedLocals,
353 ) -> IndexVec<Local, Option<Local>> {
354     let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*local_decls);
355     let mut used = Local::new(0);
356
357     for alive_index in local_decls.indices() {
358         // `is_used` treats the `RETURN_PLACE` and arguments as used.
359         if !used_locals.is_used(alive_index) {
360             continue;
361         }
362
363         map[alive_index] = Some(used);
364         if alive_index != used {
365             local_decls.swap(alive_index, used);
366         }
367         used.increment_by(1);
368     }
369     local_decls.truncate(used.index());
370     map
371 }
372
373 /// Keeps track of used & unused locals.
374 struct UsedLocals {
375     increment: bool,
376     arg_count: u32,
377     use_count: IndexVec<Local, u32>,
378 }
379
380 impl UsedLocals {
381     /// Determines which locals are used & unused in the given body.
382     fn new(body: &Body<'_>) -> Self {
383         let mut this = Self {
384             increment: true,
385             arg_count: body.arg_count.try_into().unwrap(),
386             use_count: IndexVec::from_elem(0, &body.local_decls),
387         };
388         this.visit_body(body);
389         this
390     }
391
392     /// Checks if local is used.
393     ///
394     /// Return place and arguments are always considered used.
395     fn is_used(&self, local: Local) -> bool {
396         trace!("is_used({:?}): use_count: {:?}", local, self.use_count[local]);
397         local.as_u32() <= self.arg_count || self.use_count[local] != 0
398     }
399
400     /// Updates the use counts to reflect the removal of given statement.
401     fn statement_removed(&mut self, statement: &Statement<'tcx>) {
402         self.increment = false;
403
404         // The location of the statement is irrelevant.
405         let location = Location { block: START_BLOCK, statement_index: 0 };
406         self.visit_statement(statement, location);
407     }
408
409     /// Visits a left-hand side of an assignment.
410     fn visit_lhs(&mut self, place: &Place<'tcx>, location: Location) {
411         if place.is_indirect() {
412             // A use, not a definition.
413             self.visit_place(place, PlaceContext::MutatingUse(MutatingUseContext::Store), location);
414         } else {
415             // A definition. Although, it still might use other locals for indexing.
416             self.super_projection(
417                 place.local,
418                 &place.projection,
419                 PlaceContext::MutatingUse(MutatingUseContext::Projection),
420                 location,
421             );
422         }
423     }
424 }
425
426 impl Visitor<'_> for UsedLocals {
427     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
428         match statement.kind {
429             StatementKind::LlvmInlineAsm(..)
430             | StatementKind::Retag(..)
431             | StatementKind::Coverage(..)
432             | StatementKind::FakeRead(..)
433             | StatementKind::AscribeUserType(..) => {
434                 self.super_statement(statement, location);
435             }
436
437             StatementKind::Nop => {}
438
439             StatementKind::StorageLive(_local) | StatementKind::StorageDead(_local) => {}
440
441             StatementKind::Assign(box (ref place, ref rvalue)) => {
442                 self.visit_lhs(place, location);
443                 self.visit_rvalue(rvalue, location);
444             }
445
446             StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
447                 self.visit_lhs(place, location);
448             }
449         }
450     }
451
452     fn visit_local(&mut self, local: &Local, _ctx: PlaceContext, _location: Location) {
453         if self.increment {
454             self.use_count[*local] += 1;
455         } else {
456             assert_ne!(self.use_count[*local], 0);
457             self.use_count[*local] -= 1;
458         }
459     }
460 }
461
462 /// Removes unused definitions. Updates the used locals to reflect the changes made.
463 fn remove_unused_definitions<'a, 'tcx>(used_locals: &'a mut UsedLocals, body: &mut Body<'tcx>) {
464     // The use counts are updated as we remove the statements. A local might become unused
465     // during the retain operation, leading to a temporary inconsistency (storage statements or
466     // definitions referencing the local might remain). For correctness it is crucial that this
467     // computation reaches a fixed point.
468
469     let mut modified = true;
470     while modified {
471         modified = false;
472
473         for data in body.basic_blocks_mut() {
474             // Remove unnecessary StorageLive and StorageDead annotations.
475             data.statements.retain(|statement| {
476                 let keep = match &statement.kind {
477                     StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
478                         used_locals.is_used(*local)
479                     }
480                     StatementKind::Assign(box (place, _)) => used_locals.is_used(place.local),
481
482                     StatementKind::SetDiscriminant { ref place, .. } => {
483                         used_locals.is_used(place.local)
484                     }
485                     _ => true,
486                 };
487
488                 if !keep {
489                     trace!("removing statement {:?}", statement);
490                     modified = true;
491                     used_locals.statement_removed(statement);
492                 }
493
494                 keep
495             });
496         }
497     }
498 }
499
500 struct LocalUpdater<'tcx> {
501     map: IndexVec<Local, Option<Local>>,
502     tcx: TyCtxt<'tcx>,
503 }
504
505 impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
506     fn tcx(&self) -> TyCtxt<'tcx> {
507         self.tcx
508     }
509
510     fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
511         *l = self.map[*l].unwrap();
512     }
513 }