1 //! A pass that promotes borrows of constant rvalues.
3 //! The rvalues considered constant are trees of temps,
4 //! each with exactly one initialization, and holding
5 //! a constant value with no interior mutability.
6 //! They are placed into a new MIR constant body in
7 //! `promoted` and the borrow rvalue is replaced with
8 //! a `Literal::Promoted` using the index into `promoted`
9 //! of that constant MIR.
11 //! This pass assumes that every use is dominated by an
12 //! initialization and can otherwise silence errors, if
13 //! move analysis runs after promotion on broken MIR.
15 use rustc::hir::def_id::DefId;
17 use rustc::mir::visit::{PlaceContext, MutatingUseContext, MutVisitor, Visitor};
18 use rustc::mir::traversal::ReversePostorder;
19 use rustc::ty::subst::InternalSubsts;
20 use rustc::ty::TyCtxt;
23 use rustc_index::vec::{IndexVec, Idx};
25 use std::{iter, mem, usize};
27 /// State of a temporary during collection and promotion.
28 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
30 /// No references to this temp.
32 /// One direct assignment and any number of direct uses.
33 /// A borrow of this temp is promotable if the assigned
34 /// value is qualified as constant.
39 /// Any other combination of assignments/uses.
41 /// This temp was part of an rvalue which got extracted
42 /// during promotion and needs cleanup.
47 pub fn is_promotable(&self) -> bool {
48 debug!("is_promotable: self={:?}", self);
49 if let TempState::Defined { .. } = *self {
57 /// A "root candidate" for promotion, which will become the
58 /// returned value in a promoted MIR, unless it's a subset
59 /// of a larger candidate.
62 /// Borrow of a constant temporary.
65 /// Promotion of the `x` in `[x; 32]`.
68 /// Currently applied to function calls where the callee has the unstable
69 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
70 /// intrinsic. The intrinsic requires the arguments are indeed constant and
71 /// the attribute currently provides the semantic requirement that arguments
73 Argument { bb: BasicBlock, index: usize },
76 struct TempCollector<'tcx> {
77 temps: IndexVec<Local, TempState>,
79 body: &'tcx Body<'tcx>,
82 impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> {
83 fn visit_local(&mut self,
85 context: PlaceContext,
87 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
88 // We're only interested in temporaries and the return place
89 match self.body.local_kind(index) {
91 | LocalKind::ReturnPointer
98 // Ignore drops, if the temp gets promoted,
99 // then it's constant and thus drop is noop.
100 // Non-uses are also irrelevent.
101 if context.is_drop() || !context.is_use() {
103 "visit_local: context.is_drop={:?} context.is_use={:?}",
104 context.is_drop(), context.is_use(),
109 let temp = &mut self.temps[index];
110 debug!("visit_local: temp={:?}", temp);
111 if *temp == TempState::Undefined {
113 PlaceContext::MutatingUse(MutatingUseContext::Store) |
114 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
115 *temp = TempState::Defined {
121 _ => { /* mark as unpromotable below */ }
123 } else if let TempState::Defined { ref mut uses, .. } = *temp {
124 // We always allow borrows, even mutable ones, as we need
125 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
126 let allowed_use = context.is_borrow() || context.is_nonmutating_use();
127 debug!("visit_local: allowed_use={:?}", allowed_use);
132 /* mark as unpromotable below */
134 *temp = TempState::Unpromotable;
137 fn visit_source_info(&mut self, source_info: &SourceInfo) {
138 self.span = source_info.span;
142 pub fn collect_temps(body: &Body<'_>,
143 rpo: &mut ReversePostorder<'_, '_>) -> IndexVec<Local, TempState> {
144 let mut collector = TempCollector {
145 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
149 for (bb, data) in rpo {
150 collector.visit_basic_block_data(bb, data);
155 struct Promoter<'a, 'tcx> {
157 source: &'a mut Body<'tcx>,
158 promoted: Body<'tcx>,
159 temps: &'a mut IndexVec<Local, TempState>,
161 /// If true, all nested temps are also kept in the
162 /// source MIR, not moved to the promoted MIR.
166 impl<'a, 'tcx> Promoter<'a, 'tcx> {
167 fn new_block(&mut self) -> BasicBlock {
168 let span = self.promoted.span;
169 self.promoted.basic_blocks_mut().push(BasicBlockData {
171 terminator: Some(Terminator {
172 source_info: SourceInfo {
174 scope: OUTERMOST_SOURCE_SCOPE
176 kind: TerminatorKind::Return
182 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
183 let last = self.promoted.basic_blocks().last().unwrap();
184 let data = &mut self.promoted[last];
185 data.statements.push(Statement {
186 source_info: SourceInfo {
188 scope: OUTERMOST_SOURCE_SCOPE
190 kind: StatementKind::Assign(box(Place::from(dest), rvalue))
194 /// Copies the initialization of this temp to the
195 /// promoted MIR, recursing through temps.
196 fn promote_temp(&mut self, temp: Local) -> Local {
197 let old_keep_original = self.keep_original;
198 let loc = match self.temps[temp] {
199 TempState::Defined { location, uses } if uses > 0 => {
201 self.keep_original = true;
206 span_bug!(self.promoted.span, "{:?} not promotable: {:?}",
210 if !self.keep_original {
211 self.temps[temp] = TempState::PromotedOut;
214 let no_stmts = self.source[loc.block].statements.len();
215 let new_temp = self.promoted.local_decls.push(
216 LocalDecl::new_temp(self.source.local_decls[temp].ty,
217 self.source.local_decls[temp].source_info.span));
219 debug!("promote({:?} @ {:?}/{:?}, {:?})",
220 temp, loc, no_stmts, self.keep_original);
222 // First, take the Rvalue or Call out of the source MIR,
223 // or duplicate it, depending on keep_original.
224 if loc.statement_index < no_stmts {
225 let (mut rvalue, source_info) = {
226 let statement = &mut self.source[loc.block].statements[loc.statement_index];
227 let rhs = match statement.kind {
228 StatementKind::Assign(box(_, ref mut rhs)) => rhs,
230 span_bug!(statement.source_info.span, "{:?} is not an assignment",
235 (if self.keep_original {
238 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
239 mem::replace(rhs, unit)
240 }, statement.source_info)
243 self.visit_rvalue(&mut rvalue, loc);
244 self.assign(new_temp, rvalue, source_info.span);
246 let terminator = if self.keep_original {
247 self.source[loc.block].terminator().clone()
249 let terminator = self.source[loc.block].terminator_mut();
250 let target = match terminator.kind {
251 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
253 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
257 source_info: terminator.source_info,
258 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto {
264 match terminator.kind {
265 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
266 self.visit_operand(&mut func, loc);
267 for arg in &mut args {
268 self.visit_operand(arg, loc);
271 let last = self.promoted.basic_blocks().last().unwrap();
272 let new_target = self.new_block();
274 *self.promoted[last].terminator_mut() = Terminator {
275 kind: TerminatorKind::Call {
280 (Place::from(new_temp), new_target)
288 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
293 self.keep_original = old_keep_original;
297 fn promote_candidate(
300 candidate: Candidate,
301 next_promoted_id: usize,
302 ) -> Option<Body<'tcx>> {
304 let promoted = &mut self.promoted;
305 let promoted_id = Promoted::new(next_promoted_id);
307 let mut promoted_place = |ty, span| {
308 promoted.span = span;
309 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
311 base: PlaceBase::Static(box Static {
313 StaticKind::Promoted(
315 InternalSubsts::identity_for_item(tcx, def_id),
323 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
325 Candidate::Ref(loc) => {
326 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
327 match statement.kind {
328 StatementKind::Assign(box(_, Rvalue::Ref(_, _, ref mut place))) => {
329 // Use the underlying local for this (necessarily interior) borrow.
330 let ty = place.base.ty(local_decls).ty;
331 let span = statement.source_info.span;
333 Operand::Move(Place {
336 promoted_place(ty, span).base,
344 Candidate::Repeat(loc) => {
345 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
346 match statement.kind {
347 StatementKind::Assign(box(_, Rvalue::Repeat(ref mut operand, _))) => {
348 let ty = operand.ty(local_decls, self.tcx);
349 let span = statement.source_info.span;
352 Operand::Copy(promoted_place(ty, span))
358 Candidate::Argument { bb, index } => {
359 let terminator = blocks[bb].terminator_mut();
360 match terminator.kind {
361 TerminatorKind::Call { ref mut args, .. } => {
362 let ty = args[index].ty(local_decls, self.tcx);
363 let span = terminator.source_info.span;
364 let operand = Operand::Copy(promoted_place(ty, span));
365 mem::replace(&mut args[index], operand)
367 // We expected a `TerminatorKind::Call` for which we'd like to promote an
368 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
369 // we are seeing a `Goto`. That means that the `promote_temps` method
370 // already promoted this call away entirely. This case occurs when calling
371 // a function requiring a constant argument and as that constant value
372 // providing a value whose computation contains another call to a function
373 // requiring a constant argument.
374 TerminatorKind::Goto { .. } => return None,
381 assert_eq!(self.new_block(), START_BLOCK);
382 self.visit_operand(&mut operand, Location {
383 block: BasicBlock::new(0),
384 statement_index: usize::MAX
387 let span = self.promoted.span;
388 self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
393 /// Replaces all temporaries with their promoted counterparts.
394 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
395 fn visit_local(&mut self,
399 if self.source.local_kind(*local) == LocalKind::Temp {
400 *local = self.promote_temp(*local);
405 pub fn promote_candidates<'tcx>(
407 body: &mut Body<'tcx>,
409 mut temps: IndexVec<Local, TempState>,
410 candidates: Vec<Candidate>,
411 ) -> IndexVec<Promoted, Body<'tcx>> {
412 // Visit candidates in reverse, in case they're nested.
413 debug!("promote_candidates({:?})", candidates);
415 let mut promotions = IndexVec::new();
417 for candidate in candidates.into_iter().rev() {
419 Candidate::Repeat(Location { block, statement_index }) |
420 Candidate::Ref(Location { block, statement_index }) => {
421 match body[block].statements[statement_index].kind {
422 StatementKind::Assign(box(Place {
423 base: PlaceBase::Local(local),
426 if temps[local] == TempState::PromotedOut {
434 Candidate::Argument { .. } => {}
438 // Declare return place local so that `mir::Body::new` doesn't complain.
439 let initial_locals = iter::once(
440 LocalDecl::new_return_place(tcx.types.never, body.span)
443 let promoter = Promoter {
446 // FIXME: maybe try to filter this to avoid blowing up
448 body.source_scopes.clone(),
449 body.source_scope_local_data.clone(),
464 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
465 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
466 promotions.push(promoted);
470 // Eliminate assignments to, and drops of promoted temps.
471 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
472 for block in body.basic_blocks_mut() {
473 block.statements.retain(|statement| {
474 match statement.kind {
475 StatementKind::Assign(box(Place {
476 base: PlaceBase::Local(index),
479 StatementKind::StorageLive(index) |
480 StatementKind::StorageDead(index) => {
486 let terminator = block.terminator_mut();
487 match terminator.kind {
488 TerminatorKind::Drop { location: Place {
489 base: PlaceBase::Local(index),
493 terminator.kind = TerminatorKind::Goto {