]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/simplify.rs
Auto merge of #46393 - kennytm:45861-step-2-3-make-tools-job-not-fail-fast, r=alexcri...
[rust.git] / src / librustc_mir / transform / simplify.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A number of passes which remove various redundancies in the CFG.
12 //!
13 //! The `SimplifyCfg` pass gets rid of unnecessary blocks in the CFG, whereas the `SimplifyLocals`
14 //! gets rid of all the unnecessary local variable declarations.
15 //!
16 //! The `SimplifyLocals` pass is kinda expensive and therefore not very suitable to be run often.
17 //! Most of the passes should not care or be impacted in meaningful ways due to extra locals
18 //! either, so running the pass once, right before translation, should suffice.
19 //!
20 //! On the other side of the spectrum, the `SimplifyCfg` pass is considerably cheap to run, thus
21 //! one should run it after every pass which may modify CFG in significant ways. This pass must
22 //! also be run before any analysis passes because it removes dead blocks, and some of these can be
23 //! ill-typed.
24 //!
25 //! The cause of this typing issue is typeck allowing most blocks whose end is not reachable have
26 //! an arbitrary return type, rather than having the usual () return type (as a note, typeck's
27 //! notion of reachability is in fact slightly weaker than MIR CFG reachability - see #31617). A
28 //! standard example of the situation is:
29 //!
30 //! ```rust
31 //!   fn example() {
32 //!       let _a: char = { return; };
33 //!   }
34 //! ```
35 //!
36 //! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we
37 //! naively generate still contains the `_a = ()` write in the unreachable block "after" the
38 //! return.
39
40 use rustc_data_structures::bitvec::BitVector;
41 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
42 use rustc::ty::TyCtxt;
43 use rustc::mir::*;
44 use rustc::mir::visit::{MutVisitor, Visitor, PlaceContext};
45 use std::borrow::Cow;
46 use transform::{MirPass, MirSource};
47
48 pub struct SimplifyCfg { label: String }
49
50 impl SimplifyCfg {
51     pub fn new(label: &str) -> Self {
52         SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
53     }
54 }
55
56 pub fn simplify_cfg(mir: &mut Mir) {
57     CfgSimplifier::new(mir).simplify();
58     remove_dead_blocks(mir);
59
60     // FIXME: Should probably be moved into some kind of pass manager
61     mir.basic_blocks_mut().raw.shrink_to_fit();
62 }
63
64 impl MirPass for SimplifyCfg {
65     fn name<'a>(&'a self) -> Cow<'a, str> {
66         Cow::Borrowed(&self.label)
67     }
68
69     fn run_pass<'a, 'tcx>(&self,
70                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
71                           _src: MirSource,
72                           mir: &mut Mir<'tcx>) {
73         debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, mir);
74         simplify_cfg(mir);
75     }
76 }
77
78 pub struct CfgSimplifier<'a, 'tcx: 'a> {
79     basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
80     pred_count: IndexVec<BasicBlock, u32>
81 }
82
83 impl<'a, 'tcx: 'a> CfgSimplifier<'a, 'tcx> {
84     pub fn new(mir: &'a mut Mir<'tcx>) -> Self {
85         let mut pred_count = IndexVec::from_elem(0u32, mir.basic_blocks());
86
87         // we can't use mir.predecessors() here because that counts
88         // dead blocks, which we don't want to.
89         pred_count[START_BLOCK] = 1;
90
91         for (_, data) in traversal::preorder(mir) {
92             if let Some(ref term) = data.terminator {
93                 for &tgt in term.successors().iter() {
94                     pred_count[tgt] += 1;
95                 }
96             }
97         }
98
99         let basic_blocks = mir.basic_blocks_mut();
100
101         CfgSimplifier {
102             basic_blocks,
103             pred_count,
104         }
105     }
106
107     pub fn simplify(mut self) {
108         self.strip_nops();
109
110         loop {
111             let mut changed = false;
112
113             for bb in (0..self.basic_blocks.len()).map(BasicBlock::new) {
114                 if self.pred_count[bb] == 0 {
115                     continue
116                 }
117
118                 debug!("simplifying {:?}", bb);
119
120                 let mut terminator = self.basic_blocks[bb].terminator.take()
121                     .expect("invalid terminator state");
122
123                 for successor in terminator.successors_mut() {
124                     self.collapse_goto_chain(successor, &mut changed);
125                 }
126
127                 let mut new_stmts = vec![];
128                 let mut inner_changed = true;
129                 while inner_changed {
130                     inner_changed = false;
131                     inner_changed |= self.simplify_branch(&mut terminator);
132                     inner_changed |= self.merge_successor(&mut new_stmts, &mut terminator);
133                     changed |= inner_changed;
134                 }
135
136                 self.basic_blocks[bb].statements.extend(new_stmts);
137                 self.basic_blocks[bb].terminator = Some(terminator);
138
139                 changed |= inner_changed;
140             }
141
142             if !changed { break }
143         }
144     }
145
146     // Collapse a goto chain starting from `start`
147     fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
148         let mut terminator = match self.basic_blocks[*start] {
149             BasicBlockData {
150                 ref statements,
151                 terminator: ref mut terminator @ Some(Terminator {
152                     kind: TerminatorKind::Goto { .. }, ..
153                 }), ..
154             } if statements.is_empty() => terminator.take(),
155             // if `terminator` is None, this means we are in a loop. In that
156             // case, let all the loop collapse to its entry.
157             _ => return
158         };
159
160         let target = match terminator {
161             Some(Terminator { kind: TerminatorKind::Goto { ref mut target }, .. }) => {
162                 self.collapse_goto_chain(target, changed);
163                 *target
164             }
165             _ => unreachable!()
166         };
167         self.basic_blocks[*start].terminator = terminator;
168
169         debug!("collapsing goto chain from {:?} to {:?}", *start, target);
170
171         *changed |= *start != target;
172
173         if self.pred_count[*start] == 1 {
174             // This is the last reference to *start, so the pred-count to
175             // to target is moved into the current block.
176             self.pred_count[*start] = 0;
177         } else {
178             self.pred_count[target] += 1;
179             self.pred_count[*start] -= 1;
180         }
181
182         *start = target;
183     }
184
185     // merge a block with 1 `goto` predecessor to its parent
186     fn merge_successor(&mut self,
187                        new_stmts: &mut Vec<Statement<'tcx>>,
188                        terminator: &mut Terminator<'tcx>)
189                        -> bool
190     {
191         let target = match terminator.kind {
192             TerminatorKind::Goto { target }
193                 if self.pred_count[target] == 1
194                 => target,
195             _ => return false
196         };
197
198         debug!("merging block {:?} into {:?}", target, terminator);
199         *terminator = match self.basic_blocks[target].terminator.take() {
200             Some(terminator) => terminator,
201             None => {
202                 // unreachable loop - this should not be possible, as we
203                 // don't strand blocks, but handle it correctly.
204                 return false
205             }
206         };
207         new_stmts.extend(self.basic_blocks[target].statements.drain(..));
208         self.pred_count[target] = 0;
209
210         true
211     }
212
213     // turn a branch with all successors identical to a goto
214     fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
215         match terminator.kind {
216             TerminatorKind::SwitchInt { .. } => {},
217             _ => return false
218         };
219
220         let first_succ = {
221             let successors = terminator.successors();
222             if let Some(&first_succ) = terminator.successors().get(0) {
223                 if successors.iter().all(|s| *s == first_succ) {
224                     self.pred_count[first_succ] -= (successors.len()-1) as u32;
225                     first_succ
226                 } else {
227                     return false
228                 }
229             } else {
230                 return false
231             }
232         };
233
234         debug!("simplifying branch {:?}", terminator);
235         terminator.kind = TerminatorKind::Goto { target: first_succ };
236         true
237     }
238
239     fn strip_nops(&mut self) {
240         for blk in self.basic_blocks.iter_mut() {
241             blk.statements.retain(|stmt| if let StatementKind::Nop = stmt.kind {
242                 false
243             } else {
244                 true
245             })
246         }
247     }
248 }
249
250 pub fn remove_dead_blocks(mir: &mut Mir) {
251     let mut seen = BitVector::new(mir.basic_blocks().len());
252     for (bb, _) in traversal::preorder(mir) {
253         seen.insert(bb.index());
254     }
255
256     let basic_blocks = mir.basic_blocks_mut();
257
258     let num_blocks = basic_blocks.len();
259     let mut replacements : Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
260     let mut used_blocks = 0;
261     for alive_index in seen.iter() {
262         replacements[alive_index] = BasicBlock::new(used_blocks);
263         if alive_index != used_blocks {
264             // Swap the next alive block data with the current available slot. Since alive_index is
265             // non-decreasing this is a valid operation.
266             basic_blocks.raw.swap(alive_index, used_blocks);
267         }
268         used_blocks += 1;
269     }
270     basic_blocks.raw.truncate(used_blocks);
271
272     for block in basic_blocks {
273         for target in block.terminator_mut().successors_mut() {
274             *target = replacements[target.index()];
275         }
276     }
277 }
278
279
280 pub struct SimplifyLocals;
281
282 impl MirPass for SimplifyLocals {
283     fn run_pass<'a, 'tcx>(&self,
284                           _: TyCtxt<'a, 'tcx, 'tcx>,
285                           _: MirSource,
286                           mir: &mut Mir<'tcx>) {
287         let mut marker = DeclMarker { locals: BitVector::new(mir.local_decls.len()) };
288         marker.visit_mir(mir);
289         // Return pointer and arguments are always live
290         marker.locals.insert(0);
291         for idx in mir.args_iter() {
292             marker.locals.insert(idx.index());
293         }
294         let map = make_local_map(&mut mir.local_decls, marker.locals);
295         // Update references to all vars and tmps now
296         LocalUpdater { map: map }.visit_mir(mir);
297         mir.local_decls.shrink_to_fit();
298     }
299 }
300
301 /// Construct the mapping while swapping out unused stuff out from the `vec`.
302 fn make_local_map<'tcx, I: Idx, V>(vec: &mut IndexVec<I, V>, mask: BitVector) -> Vec<usize> {
303     let mut map: Vec<usize> = ::std::iter::repeat(!0).take(vec.len()).collect();
304     let mut used = 0;
305     for alive_index in mask.iter() {
306         map[alive_index] = used;
307         if alive_index != used {
308             vec.swap(alive_index, used);
309         }
310         used += 1;
311     }
312     vec.truncate(used);
313     map
314 }
315
316 struct DeclMarker {
317     pub locals: BitVector,
318 }
319
320 impl<'tcx> Visitor<'tcx> for DeclMarker {
321     fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
322         // ignore these altogether, they get removed along with their otherwise unused decls.
323         if ctx != PlaceContext::StorageLive && ctx != PlaceContext::StorageDead {
324             self.locals.insert(local.index());
325         }
326     }
327 }
328
329 struct LocalUpdater {
330     map: Vec<usize>,
331 }
332
333 impl<'tcx> MutVisitor<'tcx> for LocalUpdater {
334     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
335         // Remove unnecessary StorageLive and StorageDead annotations.
336         data.statements.retain(|stmt| {
337             match stmt.kind {
338                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
339                     self.map[l.index()] != !0
340                 }
341                 _ => true
342             }
343         });
344         self.super_basic_block_data(block, data);
345     }
346     fn visit_local(&mut self, l: &mut Local, _: PlaceContext<'tcx>, _: Location) {
347         *l = Local::new(self.map[l.index()]);
348     }
349 }