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.
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.
11 //! A pass that promotes borrows of constant rvalues.
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.
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.
26 use rustc::mir::visit::{PlaceContext, MutVisitor, Visitor};
27 use rustc::mir::traversal::ReversePostorder;
28 use rustc::ty::TyCtxt;
31 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
33 use std::{iter, mem, usize};
35 /// State of a temporary during collection and promotion.
36 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
38 /// No references to this temp.
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.
47 /// Any other combination of assignments/uses.
49 /// This temp was part of an rvalue which got extracted
50 /// during promotion and needs cleanup.
55 pub fn is_promotable(&self) -> bool {
56 if let TempState::Defined { uses, .. } = *self {
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.
69 /// Borrow of a constant temporary.
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
77 Argument { bb: BasicBlock, index: usize },
80 struct TempCollector<'tcx> {
81 temps: IndexVec<Local, TempState>,
86 impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
87 fn visit_local(&mut self,
89 context: PlaceContext<'tcx>,
91 // We're only interested in temporaries
92 if self.mir.local_kind(index) != LocalKind::Temp {
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() {
103 let temp = &mut self.temps[index];
104 if *temp == TempState::Undefined {
106 PlaceContext::Store |
107 PlaceContext::AsmOutput |
108 PlaceContext::Call => {
109 *temp = TempState::Defined {
115 _ => { /* mark as unpromotable below */ }
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()
128 /* mark as unpromotable below */
130 *temp = TempState::Unpromotable;
133 fn visit_source_info(&mut self, source_info: &SourceInfo) {
134 self.span = source_info.span;
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),
144 for (bb, data) in rpo {
145 collector.visit_basic_block_data(bb, data);
150 struct Promoter<'a, 'tcx: 'a> {
151 tcx: TyCtxt<'a, 'tcx, 'tcx>,
152 source: &'a mut Mir<'tcx>,
154 temps: &'a mut IndexVec<Local, TempState>,
156 /// If true, all nested temps are also kept in the
157 /// source MIR, not moved to the promoted MIR.
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 {
166 terminator: Some(Terminator {
167 source_info: SourceInfo {
169 scope: OUTERMOST_SOURCE_SCOPE
171 kind: TerminatorKind::Return
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 {
183 scope: OUTERMOST_SOURCE_SCOPE
185 kind: StatementKind::Assign(Place::Local(dest), rvalue)
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 => {
196 self.keep_original = true;
201 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
205 if !self.keep_original {
206 self.temps[temp] = TempState::PromotedOut;
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));
214 debug!("promote({:?} @ {:?}/{:?}, {:?})",
215 temp, loc, no_stmts, self.keep_original);
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 (mut 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,
225 span_bug!(statement.source_info.span, "{:?} is not an assignment",
230 (if self.keep_original {
233 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
234 mem::replace(rhs, unit)
235 }, statement.source_info)
238 self.visit_rvalue(&mut rvalue, loc);
239 self.assign(new_temp, rvalue, source_info.span);
241 let terminator = if self.keep_original {
242 self.source[loc.block].terminator().clone()
244 let terminator = self.source[loc.block].terminator_mut();
245 let target = match terminator.kind {
246 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
248 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
252 source_info: terminator.source_info,
253 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
259 match terminator.kind {
260 TerminatorKind::Call { mut func, mut args, .. } => {
261 self.visit_operand(&mut func, loc);
262 for arg in &mut args {
263 self.visit_operand(arg, loc);
266 let last = self.promoted.basic_blocks().last().unwrap();
267 let new_target = self.new_block();
269 *self.promoted[last].terminator_mut() = Terminator {
270 kind: TerminatorKind::Call {
274 destination: Some((Place::Local(new_temp), new_target))
280 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
285 self.keep_original = old_keep_original;
289 fn promote_candidate(mut self, candidate: Candidate) {
291 let promoted = &mut self.promoted;
292 let promoted_id = Promoted::new(self.source.promoted.len());
293 let mut promoted_place = |ty, span| {
294 promoted.span = span;
295 promoted.local_decls[RETURN_PLACE] =
296 LocalDecl::new_return_place(ty, span);
297 Place::Promoted(box (promoted_id, ty))
299 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
301 Candidate::Ref(loc) => {
302 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
303 match statement.kind {
304 StatementKind::Assign(_, Rvalue::Ref(_, _, ref mut place)) => {
305 // Find the underlying local for this (necessarilly interior) borrow.
306 // HACK(eddyb) using a recursive function because of mutable borrows.
307 fn interior_base<'a, 'tcx>(place: &'a mut Place<'tcx>)
308 -> &'a mut Place<'tcx> {
309 if let Place::Projection(ref mut proj) = *place {
310 assert_ne!(proj.elem, ProjectionElem::Deref);
311 return interior_base(&mut proj.base);
315 let place = interior_base(place);
317 let ty = place.ty(local_decls, self.tcx).to_ty(self.tcx);
318 let span = statement.source_info.span;
320 Operand::Move(mem::replace(place, promoted_place(ty, span)))
325 Candidate::Argument { bb, index } => {
326 let terminator = blocks[bb].terminator_mut();
327 match terminator.kind {
328 TerminatorKind::Call { ref mut args, .. } => {
329 let ty = args[index].ty(local_decls, self.tcx);
330 let span = terminator.source_info.span;
331 let operand = Operand::Copy(promoted_place(ty, span));
332 mem::replace(&mut args[index], operand)
340 assert_eq!(self.new_block(), START_BLOCK);
341 self.visit_operand(&mut operand, Location {
342 block: BasicBlock::new(0),
343 statement_index: usize::MAX
346 let span = self.promoted.span;
347 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
348 self.source.promoted.push(self.promoted);
352 /// Replaces all temporaries with their promoted counterparts.
353 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
354 fn visit_local(&mut self,
356 _: PlaceContext<'tcx>,
358 if self.source.local_kind(*local) == LocalKind::Temp {
359 *local = self.promote_temp(*local);
364 pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>,
365 tcx: TyCtxt<'a, 'tcx, 'tcx>,
366 mut temps: IndexVec<Local, TempState>,
367 candidates: Vec<Candidate>) {
368 // Visit candidates in reverse, in case they're nested.
369 debug!("promote_candidates({:?})", candidates);
371 for candidate in candidates.into_iter().rev() {
373 Candidate::Ref(Location { block, statement_index }) => {
374 match mir[block].statements[statement_index].kind {
375 StatementKind::Assign(Place::Local(local), _) => {
376 if temps[local] == TempState::PromotedOut {
384 Candidate::Argument { .. } => {}
388 // Declare return place local so that `Mir::new` doesn't complain.
389 let initial_locals = iter::once(
390 LocalDecl::new_return_place(tcx.types.never, mir.span)
393 let mut promoter = Promoter {
396 // FIXME: maybe try to filter this to avoid blowing up
398 mir.source_scopes.clone(),
399 mir.source_scope_local_data.clone(),
412 promoter.promote_candidate(candidate);
415 // Eliminate assignments to, and drops of promoted temps.
416 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
417 for block in mir.basic_blocks_mut() {
418 block.statements.retain(|statement| {
419 match statement.kind {
420 StatementKind::Assign(Place::Local(index), _) |
421 StatementKind::StorageLive(index) |
422 StatementKind::StorageDead(index) => {
428 let terminator = block.terminator_mut();
429 match terminator.kind {
430 TerminatorKind::Drop { location: Place::Local(index), target, .. } => {
432 terminator.kind = TerminatorKind::Goto {