]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Auto merge of #54929 - csmoe:cfg_lint, r=petrochenkov
[rust.git] / src / librustc_mir / transform / promote_consts.rs
1 // Copyright 2016 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 pass that promotes borrows of constant rvalues.
12 //!
13 //! The rvalues considered constant are trees of temps,
14 //! each with exactly one initialization, and holding
15 //! a constant value with no interior mutability.
16 //! They are placed into a new MIR constant body in
17 //! `promoted` and the borrow rvalue is replaced with
18 //! a `Literal::Promoted` using the index into `promoted`
19 //! of that constant MIR.
20 //!
21 //! This pass assumes that every use is dominated by an
22 //! initialization and can otherwise silence errors, if
23 //! move analysis runs after promotion on broken MIR.
24
25 use rustc::mir::*;
26 use rustc::mir::visit::{PlaceContext, MutVisitor, Visitor};
27 use rustc::mir::traversal::ReversePostorder;
28 use rustc::ty::TyCtxt;
29 use syntax_pos::Span;
30
31 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
32
33 use std::{iter, mem, usize};
34
35 /// State of a temporary during collection and promotion.
36 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
37 pub enum TempState {
38     /// No references to this temp.
39     Undefined,
40     /// One direct assignment and any number of direct uses.
41     /// A borrow of this temp is promotable if the assigned
42     /// value is qualified as constant.
43     Defined {
44         location: Location,
45         uses: usize
46     },
47     /// Any other combination of assignments/uses.
48     Unpromotable,
49     /// This temp was part of an rvalue which got extracted
50     /// during promotion and needs cleanup.
51     PromotedOut
52 }
53
54 impl TempState {
55     pub fn is_promotable(&self) -> bool {
56         if let TempState::Defined { uses, .. } = *self {
57             uses > 0
58         } else {
59             false
60         }
61     }
62 }
63
64 /// A "root candidate" for promotion, which will become the
65 /// returned value in a promoted MIR, unless it's a subset
66 /// of a larger candidate.
67 #[derive(Debug)]
68 pub enum Candidate {
69     /// Borrow of a constant temporary.
70     Ref(Location),
71
72     /// Currently applied to function calls where the callee has the unstable
73     /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
74     /// intrinsic. The intrinsic requires the arguments are indeed constant and
75     /// the attribute currently provides the semantic requirement that arguments
76     /// must be constant.
77     Argument { bb: BasicBlock, index: usize },
78 }
79
80 struct TempCollector<'tcx> {
81     temps: IndexVec<Local, TempState>,
82     span: Span,
83     mir: &'tcx Mir<'tcx>,
84 }
85
86 impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
87     fn visit_local(&mut self,
88                    &index: &Local,
89                    context: PlaceContext<'tcx>,
90                    location: Location) {
91         // We're only interested in temporaries
92         if self.mir.local_kind(index) != LocalKind::Temp {
93             return;
94         }
95
96         // Ignore drops, if the temp gets promoted,
97         // then it's constant and thus drop is noop.
98         // Storage live ranges are also irrelevant.
99         if context.is_drop() || context.is_storage_marker() {
100             return;
101         }
102
103         let temp = &mut self.temps[index];
104         if *temp == TempState::Undefined {
105             match context {
106                 PlaceContext::Store |
107                 PlaceContext::AsmOutput |
108                 PlaceContext::Call => {
109                     *temp = TempState::Defined {
110                         location,
111                         uses: 0
112                     };
113                     return;
114                 }
115                 _ => { /* mark as unpromotable below */ }
116             }
117         } else if let TempState::Defined { ref mut uses, .. } = *temp {
118             // We always allow borrows, even mutable ones, as we need
119             // to promote mutable borrows of some ZSTs e.g. `&mut []`.
120             let allowed_use = match context {
121                 PlaceContext::Borrow {..} => true,
122                 _ => context.is_nonmutating_use()
123             };
124             if allowed_use {
125                 *uses += 1;
126                 return;
127             }
128             /* mark as unpromotable below */
129         }
130         *temp = TempState::Unpromotable;
131     }
132
133     fn visit_source_info(&mut self, source_info: &SourceInfo) {
134         self.span = source_info.span;
135     }
136 }
137
138 pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec<Local, TempState> {
139     let mut collector = TempCollector {
140         temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls),
141         span: mir.span,
142         mir,
143     };
144     for (bb, data) in rpo {
145         collector.visit_basic_block_data(bb, data);
146     }
147     collector.temps
148 }
149
150 struct Promoter<'a, 'tcx: 'a> {
151     tcx: TyCtxt<'a, 'tcx, 'tcx>,
152     source: &'a mut Mir<'tcx>,
153     promoted: Mir<'tcx>,
154     temps: &'a mut IndexVec<Local, TempState>,
155
156     /// If true, all nested temps are also kept in the
157     /// source MIR, not moved to the promoted MIR.
158     keep_original: bool
159 }
160
161 impl<'a, 'tcx> Promoter<'a, 'tcx> {
162     fn new_block(&mut self) -> BasicBlock {
163         let span = self.promoted.span;
164         self.promoted.basic_blocks_mut().push(BasicBlockData {
165             statements: vec![],
166             terminator: Some(Terminator {
167                 source_info: SourceInfo {
168                     span,
169                     scope: OUTERMOST_SOURCE_SCOPE
170                 },
171                 kind: TerminatorKind::Return
172             }),
173             is_cleanup: false
174         })
175     }
176
177     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
178         let last = self.promoted.basic_blocks().last().unwrap();
179         let data = &mut self.promoted[last];
180         data.statements.push(Statement {
181             source_info: SourceInfo {
182                 span,
183                 scope: OUTERMOST_SOURCE_SCOPE
184             },
185             kind: StatementKind::Assign(Place::Local(dest), box rvalue)
186         });
187     }
188
189     /// Copy the initialization of this temp to the
190     /// promoted MIR, recursing through temps.
191     fn promote_temp(&mut self, temp: Local) -> Local {
192         let old_keep_original = self.keep_original;
193         let loc = match self.temps[temp] {
194             TempState::Defined { location, uses } if uses > 0 => {
195                 if uses > 1 {
196                     self.keep_original = true;
197                 }
198                 location
199             }
200             state =>  {
201                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
202                           temp, state);
203             }
204         };
205         if !self.keep_original {
206             self.temps[temp] = TempState::PromotedOut;
207         }
208
209         let no_stmts = self.source[loc.block].statements.len();
210         let new_temp = self.promoted.local_decls.push(
211             LocalDecl::new_temp(self.source.local_decls[temp].ty,
212                                 self.source.local_decls[temp].source_info.span));
213
214         debug!("promote({:?} @ {:?}/{:?}, {:?})",
215                temp, loc, no_stmts, self.keep_original);
216
217         // First, take the Rvalue or Call out of the source MIR,
218         // or duplicate it, depending on keep_original.
219         if loc.statement_index < no_stmts {
220             let (rvalue, source_info) = {
221                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
222                 let rhs = match statement.kind {
223                     StatementKind::Assign(_, ref mut rhs) => rhs,
224                     _ => {
225                         span_bug!(statement.source_info.span, "{:?} is not an assignment",
226                                   statement);
227                     }
228                 };
229
230                 (if self.keep_original {
231                     rhs.clone()
232                 } else {
233                     let unit = box Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
234                     mem::replace(rhs, unit)
235                 }, statement.source_info)
236             };
237
238             let mut rvalue = *rvalue;
239             self.visit_rvalue(&mut rvalue, loc);
240             self.assign(new_temp, rvalue, source_info.span);
241         } else {
242             let terminator = if self.keep_original {
243                 self.source[loc.block].terminator().clone()
244             } else {
245                 let terminator = self.source[loc.block].terminator_mut();
246                 let target = match terminator.kind {
247                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
248                     ref kind => {
249                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
250                     }
251                 };
252                 Terminator {
253                     source_info: terminator.source_info,
254                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
255                         target,
256                     })
257                 }
258             };
259
260             match terminator.kind {
261                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
262                     self.visit_operand(&mut func, loc);
263                     for arg in &mut args {
264                         self.visit_operand(arg, loc);
265                     }
266
267                     let last = self.promoted.basic_blocks().last().unwrap();
268                     let new_target = self.new_block();
269
270                     *self.promoted[last].terminator_mut() = Terminator {
271                         kind: TerminatorKind::Call {
272                             func,
273                             args,
274                             cleanup: None,
275                             destination: Some((Place::Local(new_temp), new_target)),
276                             from_hir_call,
277                         },
278                         ..terminator
279                     };
280                 }
281                 ref kind => {
282                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
283                 }
284             };
285         };
286
287         self.keep_original = old_keep_original;
288         new_temp
289     }
290
291     fn promote_candidate(mut self, candidate: Candidate) {
292         let mut operand = {
293             let promoted = &mut self.promoted;
294             let promoted_id = Promoted::new(self.source.promoted.len());
295             let mut promoted_place = |ty, span| {
296                 promoted.span = span;
297                 promoted.local_decls[RETURN_PLACE] =
298                     LocalDecl::new_return_place(ty, span);
299                 Place::Promoted(box (promoted_id, ty))
300             };
301             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
302             match candidate {
303                 Candidate::Ref(loc) => {
304                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
305                     match statement.kind {
306                         StatementKind::Assign(_, box Rvalue::Ref(_, _, ref mut place)) => {
307                             // Find the underlying local for this (necessarily interior) borrow.
308                             // HACK(eddyb) using a recursive function because of mutable borrows.
309                             fn interior_base<'a, 'tcx>(place: &'a mut Place<'tcx>)
310                                                        -> &'a mut Place<'tcx> {
311                                 if let Place::Projection(ref mut proj) = *place {
312                                     assert_ne!(proj.elem, ProjectionElem::Deref);
313                                     return interior_base(&mut proj.base);
314                                 }
315                                 place
316                             }
317                             let place = interior_base(place);
318
319                             let ty = place.ty(local_decls, self.tcx).to_ty(self.tcx);
320                             let span = statement.source_info.span;
321
322                             Operand::Move(mem::replace(place, promoted_place(ty, span)))
323                         }
324                         _ => bug!()
325                     }
326                 }
327                 Candidate::Argument { bb, index } => {
328                     let terminator = blocks[bb].terminator_mut();
329                     match terminator.kind {
330                         TerminatorKind::Call { ref mut args, .. } => {
331                             let ty = args[index].ty(local_decls, self.tcx);
332                             let span = terminator.source_info.span;
333                             let operand = Operand::Copy(promoted_place(ty, span));
334                             mem::replace(&mut args[index], operand)
335                         }
336                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
337                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
338                         // we are seeing a `Goto`. That means that the `promote_temps` method
339                         // already promoted this call away entirely. This case occurs when calling
340                         // a function requiring a constant argument and as that constant value
341                         // providing a value whose computation contains another call to a function
342                         // requiring a constant argument.
343                         TerminatorKind::Goto { .. } => return,
344                         _ => bug!()
345                     }
346                 }
347             }
348         };
349
350         assert_eq!(self.new_block(), START_BLOCK);
351         self.visit_operand(&mut operand, Location {
352             block: BasicBlock::new(0),
353             statement_index: usize::MAX
354         });
355
356         let span = self.promoted.span;
357         self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
358         self.source.promoted.push(self.promoted);
359     }
360 }
361
362 /// Replaces all temporaries with their promoted counterparts.
363 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
364     fn visit_local(&mut self,
365                    local: &mut Local,
366                    _: PlaceContext<'tcx>,
367                    _: Location) {
368         if self.source.local_kind(*local) == LocalKind::Temp {
369             *local = self.promote_temp(*local);
370         }
371     }
372 }
373
374 pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>,
375                                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
376                                     mut temps: IndexVec<Local, TempState>,
377                                     candidates: Vec<Candidate>) {
378     // Visit candidates in reverse, in case they're nested.
379     debug!("promote_candidates({:?})", candidates);
380
381     for candidate in candidates.into_iter().rev() {
382         match candidate {
383             Candidate::Ref(Location { block, statement_index }) => {
384                 match mir[block].statements[statement_index].kind {
385                     StatementKind::Assign(Place::Local(local), _) => {
386                         if temps[local] == TempState::PromotedOut {
387                             // Already promoted.
388                             continue;
389                         }
390                     }
391                     _ => {}
392                 }
393             }
394             Candidate::Argument { .. } => {}
395         }
396
397
398         // Declare return place local so that `Mir::new` doesn't complain.
399         let initial_locals = iter::once(
400             LocalDecl::new_return_place(tcx.types.never, mir.span)
401         ).collect();
402
403         let promoter = Promoter {
404             promoted: Mir::new(
405                 IndexVec::new(),
406                 // FIXME: maybe try to filter this to avoid blowing up
407                 // memory usage?
408                 mir.source_scopes.clone(),
409                 mir.source_scope_local_data.clone(),
410                 IndexVec::new(),
411                 None,
412                 initial_locals,
413                 0,
414                 vec![],
415                 mir.span
416             ),
417             tcx,
418             source: mir,
419             temps: &mut temps,
420             keep_original: false
421         };
422         promoter.promote_candidate(candidate);
423     }
424
425     // Eliminate assignments to, and drops of promoted temps.
426     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
427     for block in mir.basic_blocks_mut() {
428         block.statements.retain(|statement| {
429             match statement.kind {
430                 StatementKind::Assign(Place::Local(index), _) |
431                 StatementKind::StorageLive(index) |
432                 StatementKind::StorageDead(index) => {
433                     !promoted(index)
434                 }
435                 _ => true
436             }
437         });
438         let terminator = block.terminator_mut();
439         match terminator.kind {
440             TerminatorKind::Drop { location: Place::Local(index), target, .. } => {
441                 if promoted(index) {
442                     terminator.kind = TerminatorKind::Goto {
443                         target,
444                     };
445                 }
446             }
447             _ => {}
448         }
449     }
450 }