]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
Rollup merge of #76867 - poliorcetics:intra-doc-core-iter, r=jyn514
[rust.git] / compiler / rustc_middle / src / mir / mod.rs
1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4
5 use crate::mir::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{Allocation, ConstValue, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{Subst, SubstsRef};
13 use crate::ty::{
14     self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
15 };
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorKind, Namespace};
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::{self, GeneratorKind};
20 use rustc_target::abi::VariantIdx;
21
22 use polonius_engine::Atom;
23 pub use rustc_ast::Mutability;
24 use rustc_data_structures::fx::FxHashSet;
25 use rustc_data_structures::graph::dominators::{dominators, Dominators};
26 use rustc_data_structures::graph::{self, GraphSuccessors};
27 use rustc_index::bit_set::BitMatrix;
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_serialize::{Decodable, Encodable};
30 use rustc_span::symbol::Symbol;
31 use rustc_span::{Span, DUMMY_SP};
32 use rustc_target::abi;
33 use rustc_target::asm::InlineAsmRegOrRegClass;
34 use std::borrow::Cow;
35 use std::fmt::{self, Debug, Display, Formatter, Write};
36 use std::ops::{Index, IndexMut};
37 use std::slice;
38 use std::{iter, mem, option};
39
40 use self::predecessors::{PredecessorCache, Predecessors};
41 pub use self::query::*;
42
43 pub mod abstract_const;
44 pub mod coverage;
45 pub mod interpret;
46 pub mod mono;
47 mod predecessors;
48 mod query;
49 pub mod tcx;
50 pub mod terminator;
51 pub use terminator::*;
52 pub mod traversal;
53 mod type_foldable;
54 pub mod visit;
55
56 /// Types for locals
57 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
58
59 pub trait HasLocalDecls<'tcx> {
60     fn local_decls(&self) -> &LocalDecls<'tcx>;
61 }
62
63 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
64     fn local_decls(&self) -> &LocalDecls<'tcx> {
65         self
66     }
67 }
68
69 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
70     fn local_decls(&self) -> &LocalDecls<'tcx> {
71         &self.local_decls
72     }
73 }
74
75 /// The various "big phases" that MIR goes through.
76 ///
77 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
78 /// dialects forbid certain variants or values in certain phases.
79 ///
80 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
81 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
82 ///
83 /// Warning: ordering of variants is significant.
84 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
85 #[derive(HashStable)]
86 pub enum MirPhase {
87     Build = 0,
88     // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
89     // We used to have this for pre-miri MIR based const eval.
90     Const = 1,
91     /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
92     /// by creating a new MIR body per promoted element. After this phase (and thus the termination
93     /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
94     /// query.
95     ConstPromotion = 2,
96     /// After this phase
97     /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
98     /// * `DropAndReplace` is gone for good
99     /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
100     ///   means that the auto-generated drop glue will be invoked.
101     DropLowering = 3,
102     /// After this phase, generators are explicit state machines (no more `Yield`).
103     /// `AggregateKind::Generator` is gone for good.
104     GeneratorLowering = 4,
105     Optimization = 5,
106 }
107
108 impl MirPhase {
109     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
110     pub fn phase_index(&self) -> usize {
111         *self as usize
112     }
113 }
114
115 /// The lowered representation of a single function.
116 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
117 pub struct Body<'tcx> {
118     /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
119     /// that indexes into this vector.
120     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
121
122     /// Records how far through the "desugaring and optimization" process this particular
123     /// MIR has traversed. This is particularly useful when inlining, since in that context
124     /// we instantiate the promoted constants and add them to our promoted vector -- but those
125     /// promoted items have already been optimized, whereas ours have not. This field allows
126     /// us to see the difference and forego optimization on the inlined promoted items.
127     pub phase: MirPhase,
128
129     /// A list of source scopes; these are referenced by statements
130     /// and used for debuginfo. Indexed by a `SourceScope`.
131     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
132
133     /// The yield type of the function, if it is a generator.
134     pub yield_ty: Option<Ty<'tcx>>,
135
136     /// Generator drop glue.
137     pub generator_drop: Option<Box<Body<'tcx>>>,
138
139     /// The layout of a generator. Produced by the state transformation.
140     pub generator_layout: Option<GeneratorLayout<'tcx>>,
141
142     /// If this is a generator then record the type of source expression that caused this generator
143     /// to be created.
144     pub generator_kind: Option<GeneratorKind>,
145
146     /// Declarations of locals.
147     ///
148     /// The first local is the return value pointer, followed by `arg_count`
149     /// locals for the function arguments, followed by any user-declared
150     /// variables and temporaries.
151     pub local_decls: LocalDecls<'tcx>,
152
153     /// User type annotations.
154     pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
155
156     /// The number of arguments this function takes.
157     ///
158     /// Starting at local 1, `arg_count` locals will be provided by the caller
159     /// and can be assumed to be initialized.
160     ///
161     /// If this MIR was built for a constant, this will be 0.
162     pub arg_count: usize,
163
164     /// Mark an argument local (which must be a tuple) as getting passed as
165     /// its individual components at the LLVM level.
166     ///
167     /// This is used for the "rust-call" ABI.
168     pub spread_arg: Option<Local>,
169
170     /// Debug information pertaining to user variables, including captures.
171     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
172
173     /// A span representing this MIR, for error reporting.
174     pub span: Span,
175
176     /// Constants that are required to evaluate successfully for this MIR to be well-formed.
177     /// We hold in this field all the constants we are not able to evaluate yet.
178     pub required_consts: Vec<Constant<'tcx>>,
179
180     /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
181     /// we'd statically know that no thing with interior mutability will ever be available to the
182     /// user without some serious unsafe code.  Now this means that our promoted is actually
183     /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
184     /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
185     /// interior mutability. This flag just makes this situation very obvious where the previous
186     /// implementation without the flag hid this situation silently.
187     /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
188     pub ignore_interior_mut_in_const_validation: bool,
189
190     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
191     ///
192     /// Note that this does not actually mean that this body is not computable right now.
193     /// The repeat count in the following example is polymorphic, but can still be evaluated
194     /// without knowing anything about the type parameter `T`.
195     ///
196     /// ```rust
197     /// fn test<T>() {
198     ///     let _ = [0; std::mem::size_of::<*mut T>()];
199     /// }
200     /// ```
201     ///
202     /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
203     /// removed the last mention of all generic params. We do not want to rely on optimizations and
204     /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
205     pub is_polymorphic: bool,
206
207     predecessor_cache: PredecessorCache,
208 }
209
210 impl<'tcx> Body<'tcx> {
211     pub fn new(
212         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
213         source_scopes: IndexVec<SourceScope, SourceScopeData>,
214         local_decls: LocalDecls<'tcx>,
215         user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
216         arg_count: usize,
217         var_debug_info: Vec<VarDebugInfo<'tcx>>,
218         span: Span,
219         generator_kind: Option<GeneratorKind>,
220     ) -> Self {
221         // We need `arg_count` locals, and one for the return place.
222         assert!(
223             local_decls.len() > arg_count,
224             "expected at least {} locals, got {}",
225             arg_count + 1,
226             local_decls.len()
227         );
228
229         let mut body = Body {
230             phase: MirPhase::Build,
231             basic_blocks,
232             source_scopes,
233             yield_ty: None,
234             generator_drop: None,
235             generator_layout: None,
236             generator_kind,
237             local_decls,
238             user_type_annotations,
239             arg_count,
240             spread_arg: None,
241             var_debug_info,
242             span,
243             required_consts: Vec::new(),
244             ignore_interior_mut_in_const_validation: false,
245             is_polymorphic: false,
246             predecessor_cache: PredecessorCache::new(),
247         };
248         body.is_polymorphic = body.has_param_types_or_consts();
249         body
250     }
251
252     /// Returns a partially initialized MIR body containing only a list of basic blocks.
253     ///
254     /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
255     /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
256     /// crate.
257     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
258         let mut body = Body {
259             phase: MirPhase::Build,
260             basic_blocks,
261             source_scopes: IndexVec::new(),
262             yield_ty: None,
263             generator_drop: None,
264             generator_layout: None,
265             local_decls: IndexVec::new(),
266             user_type_annotations: IndexVec::new(),
267             arg_count: 0,
268             spread_arg: None,
269             span: DUMMY_SP,
270             required_consts: Vec::new(),
271             generator_kind: None,
272             var_debug_info: Vec::new(),
273             ignore_interior_mut_in_const_validation: false,
274             is_polymorphic: false,
275             predecessor_cache: PredecessorCache::new(),
276         };
277         body.is_polymorphic = body.has_param_types_or_consts();
278         body
279     }
280
281     #[inline]
282     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
283         &self.basic_blocks
284     }
285
286     #[inline]
287     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
288         // Because the user could mutate basic block terminators via this reference, we need to
289         // invalidate the predecessor cache.
290         //
291         // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
292         // invalidate the predecessor cache.
293         self.predecessor_cache.invalidate();
294         &mut self.basic_blocks
295     }
296
297     #[inline]
298     pub fn basic_blocks_and_local_decls_mut(
299         &mut self,
300     ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
301         self.predecessor_cache.invalidate();
302         (&mut self.basic_blocks, &mut self.local_decls)
303     }
304
305     #[inline]
306     pub fn basic_blocks_local_decls_mut_and_var_debug_info(
307         &mut self,
308     ) -> (
309         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
310         &mut LocalDecls<'tcx>,
311         &mut Vec<VarDebugInfo<'tcx>>,
312     ) {
313         self.predecessor_cache.invalidate();
314         (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
315     }
316
317     /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
318     /// `START_BLOCK`.
319     pub fn is_cfg_cyclic(&self) -> bool {
320         graph::is_cyclic(self)
321     }
322
323     #[inline]
324     pub fn local_kind(&self, local: Local) -> LocalKind {
325         let index = local.as_usize();
326         if index == 0 {
327             debug_assert!(
328                 self.local_decls[local].mutability == Mutability::Mut,
329                 "return place should be mutable"
330             );
331
332             LocalKind::ReturnPointer
333         } else if index < self.arg_count + 1 {
334             LocalKind::Arg
335         } else if self.local_decls[local].is_user_variable() {
336             LocalKind::Var
337         } else {
338             LocalKind::Temp
339         }
340     }
341
342     /// Returns an iterator over all temporaries.
343     #[inline]
344     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
345         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
346             let local = Local::new(index);
347             if self.local_decls[local].is_user_variable() { None } else { Some(local) }
348         })
349     }
350
351     /// Returns an iterator over all user-declared locals.
352     #[inline]
353     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
354         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
355             let local = Local::new(index);
356             self.local_decls[local].is_user_variable().then_some(local)
357         })
358     }
359
360     /// Returns an iterator over all user-declared mutable locals.
361     #[inline]
362     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
363         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
364             let local = Local::new(index);
365             let decl = &self.local_decls[local];
366             if decl.is_user_variable() && decl.mutability == Mutability::Mut {
367                 Some(local)
368             } else {
369                 None
370             }
371         })
372     }
373
374     /// Returns an iterator over all user-declared mutable arguments and locals.
375     #[inline]
376     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
377         (1..self.local_decls.len()).filter_map(move |index| {
378             let local = Local::new(index);
379             let decl = &self.local_decls[local];
380             if (decl.is_user_variable() || index < self.arg_count + 1)
381                 && decl.mutability == Mutability::Mut
382             {
383                 Some(local)
384             } else {
385                 None
386             }
387         })
388     }
389
390     /// Returns an iterator over all function arguments.
391     #[inline]
392     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
393         let arg_count = self.arg_count;
394         (1..arg_count + 1).map(Local::new)
395     }
396
397     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
398     /// locals that are neither arguments nor the return place).
399     #[inline]
400     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
401         let arg_count = self.arg_count;
402         let local_count = self.local_decls.len();
403         (arg_count + 1..local_count).map(Local::new)
404     }
405
406     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
407     /// invalidating statement indices in `Location`s.
408     pub fn make_statement_nop(&mut self, location: Location) {
409         let block = &mut self.basic_blocks[location.block];
410         debug_assert!(location.statement_index < block.statements.len());
411         block.statements[location.statement_index].make_nop()
412     }
413
414     /// Returns the source info associated with `location`.
415     pub fn source_info(&self, location: Location) -> &SourceInfo {
416         let block = &self[location.block];
417         let stmts = &block.statements;
418         let idx = location.statement_index;
419         if idx < stmts.len() {
420             &stmts[idx].source_info
421         } else {
422             assert_eq!(idx, stmts.len());
423             &block.terminator().source_info
424         }
425     }
426
427     /// Checks if `sub` is a sub scope of `sup`
428     pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
429         while sub != sup {
430             match self.source_scopes[sub].parent_scope {
431                 None => return false,
432                 Some(p) => sub = p,
433             }
434         }
435         true
436     }
437
438     /// Returns the return type; it always return first element from `local_decls` array.
439     #[inline]
440     pub fn return_ty(&self) -> Ty<'tcx> {
441         self.local_decls[RETURN_PLACE].ty
442     }
443
444     /// Gets the location of the terminator for the given block.
445     #[inline]
446     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
447         Location { block: bb, statement_index: self[bb].statements.len() }
448     }
449
450     #[inline]
451     pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
452         self.predecessor_cache.compute(&self.basic_blocks)
453     }
454
455     #[inline]
456     pub fn dominators(&self) -> Dominators<BasicBlock> {
457         dominators(self)
458     }
459 }
460
461 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
462 pub enum Safety {
463     Safe,
464     /// Unsafe because of a PushUnsafeBlock
465     BuiltinUnsafe,
466     /// Unsafe because of an unsafe fn
467     FnUnsafe,
468     /// Unsafe because of an `unsafe` block
469     ExplicitUnsafe(hir::HirId),
470 }
471
472 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
473     type Output = BasicBlockData<'tcx>;
474
475     #[inline]
476     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
477         &self.basic_blocks()[index]
478     }
479 }
480
481 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
482     #[inline]
483     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
484         &mut self.basic_blocks_mut()[index]
485     }
486 }
487
488 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
489 pub enum ClearCrossCrate<T> {
490     Clear,
491     Set(T),
492 }
493
494 impl<T> ClearCrossCrate<T> {
495     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
496         match self {
497             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
498             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
499         }
500     }
501
502     pub fn assert_crate_local(self) -> T {
503         match self {
504             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
505             ClearCrossCrate::Set(v) => v,
506         }
507     }
508 }
509
510 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
511 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
512
513 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
514     #[inline]
515     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
516         if E::CLEAR_CROSS_CRATE {
517             return Ok(());
518         }
519
520         match *self {
521             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
522             ClearCrossCrate::Set(ref val) => {
523                 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
524                 val.encode(e)
525             }
526         }
527     }
528 }
529 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
530     #[inline]
531     fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
532         if D::CLEAR_CROSS_CRATE {
533             return Ok(ClearCrossCrate::Clear);
534         }
535
536         let discr = u8::decode(d)?;
537
538         match discr {
539             TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
540             TAG_CLEAR_CROSS_CRATE_SET => {
541                 let val = T::decode(d)?;
542                 Ok(ClearCrossCrate::Set(val))
543             }
544             tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
545         }
546     }
547 }
548
549 /// Grouped information about the source code origin of a MIR entity.
550 /// Intended to be inspected by diagnostics and debuginfo.
551 /// Most passes can work with it as a whole, within a single function.
552 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
553 // `Hash`. Please ping @bjorn3 if removing them.
554 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
555 pub struct SourceInfo {
556     /// The source span for the AST pertaining to this MIR entity.
557     pub span: Span,
558
559     /// The source scope, keeping track of which bindings can be
560     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
561     pub scope: SourceScope,
562 }
563
564 impl SourceInfo {
565     #[inline]
566     pub fn outermost(span: Span) -> Self {
567         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
568     }
569 }
570
571 ///////////////////////////////////////////////////////////////////////////
572 // Borrow kinds
573
574 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
575 #[derive(HashStable)]
576 pub enum BorrowKind {
577     /// Data must be immutable and is aliasable.
578     Shared,
579
580     /// The immediately borrowed place must be immutable, but projections from
581     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
582     /// conflict with a mutable borrow of `a.b.c`.
583     ///
584     /// This is used when lowering matches: when matching on a place we want to
585     /// ensure that place have the same value from the start of the match until
586     /// an arm is selected. This prevents this code from compiling:
587     ///
588     ///     let mut x = &Some(0);
589     ///     match *x {
590     ///         None => (),
591     ///         Some(_) if { x = &None; false } => (),
592     ///         Some(_) => (),
593     ///     }
594     ///
595     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
596     /// should not prevent `if let None = x { ... }`, for example, because the
597     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
598     /// We can also report errors with this kind of borrow differently.
599     Shallow,
600
601     /// Data must be immutable but not aliasable. This kind of borrow
602     /// cannot currently be expressed by the user and is used only in
603     /// implicit closure bindings. It is needed when the closure is
604     /// borrowing or mutating a mutable referent, e.g.:
605     ///
606     ///     let x: &mut isize = ...;
607     ///     let y = || *x += 5;
608     ///
609     /// If we were to try to translate this closure into a more explicit
610     /// form, we'd encounter an error with the code as written:
611     ///
612     ///     struct Env { x: & &mut isize }
613     ///     let x: &mut isize = ...;
614     ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
615     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
616     ///
617     /// This is then illegal because you cannot mutate an `&mut` found
618     /// in an aliasable location. To solve, you'd have to translate with
619     /// an `&mut` borrow:
620     ///
621     ///     struct Env { x: & &mut isize }
622     ///     let x: &mut isize = ...;
623     ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
624     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
625     ///
626     /// Now the assignment to `**env.x` is legal, but creating a
627     /// mutable pointer to `x` is not because `x` is not mutable. We
628     /// could fix this by declaring `x` as `let mut x`. This is ok in
629     /// user code, if awkward, but extra weird for closures, since the
630     /// borrow is hidden.
631     ///
632     /// So we introduce a "unique imm" borrow -- the referent is
633     /// immutable, but not aliasable. This solves the problem. For
634     /// simplicity, we don't give users the way to express this
635     /// borrow, it's just used when translating closures.
636     Unique,
637
638     /// Data is mutable and not aliasable.
639     Mut {
640         /// `true` if this borrow arose from method-call auto-ref
641         /// (i.e., `adjustment::Adjust::Borrow`).
642         allow_two_phase_borrow: bool,
643     },
644 }
645
646 impl BorrowKind {
647     pub fn allows_two_phase_borrow(&self) -> bool {
648         match *self {
649             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
650             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
651         }
652     }
653 }
654
655 ///////////////////////////////////////////////////////////////////////////
656 // Variables and temps
657
658 rustc_index::newtype_index! {
659     pub struct Local {
660         derive [HashStable]
661         DEBUG_FORMAT = "_{}",
662         const RETURN_PLACE = 0,
663     }
664 }
665
666 impl Atom for Local {
667     fn index(self) -> usize {
668         Idx::index(self)
669     }
670 }
671
672 /// Classifies locals into categories. See `Body::local_kind`.
673 #[derive(PartialEq, Eq, Debug, HashStable)]
674 pub enum LocalKind {
675     /// User-declared variable binding.
676     Var,
677     /// Compiler-introduced temporary.
678     Temp,
679     /// Function argument.
680     Arg,
681     /// Location of function's return value.
682     ReturnPointer,
683 }
684
685 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
686 pub struct VarBindingForm<'tcx> {
687     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
688     pub binding_mode: ty::BindingMode,
689     /// If an explicit type was provided for this variable binding,
690     /// this holds the source Span of that type.
691     ///
692     /// NOTE: if you want to change this to a `HirId`, be wary that
693     /// doing so breaks incremental compilation (as of this writing),
694     /// while a `Span` does not cause our tests to fail.
695     pub opt_ty_info: Option<Span>,
696     /// Place of the RHS of the =, or the subject of the `match` where this
697     /// variable is initialized. None in the case of `let PATTERN;`.
698     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
699     /// (a) the right-hand side isn't evaluated as a place expression.
700     /// (b) it gives a way to separate this case from the remaining cases
701     ///     for diagnostics.
702     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
703     /// The span of the pattern in which this variable was bound.
704     pub pat_span: Span,
705 }
706
707 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
708 pub enum BindingForm<'tcx> {
709     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
710     Var(VarBindingForm<'tcx>),
711     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
712     ImplicitSelf(ImplicitSelfKind),
713     /// Reference used in a guard expression to ensure immutability.
714     RefForGuard,
715 }
716
717 /// Represents what type of implicit self a function has, if any.
718 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
719 pub enum ImplicitSelfKind {
720     /// Represents a `fn x(self);`.
721     Imm,
722     /// Represents a `fn x(mut self);`.
723     Mut,
724     /// Represents a `fn x(&self);`.
725     ImmRef,
726     /// Represents a `fn x(&mut self);`.
727     MutRef,
728     /// Represents when a function does not have a self argument or
729     /// when a function has a `self: X` argument.
730     None,
731 }
732
733 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
734
735 mod binding_form_impl {
736     use crate::ich::StableHashingContext;
737     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
738
739     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
740         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
741             use super::BindingForm::*;
742             ::std::mem::discriminant(self).hash_stable(hcx, hasher);
743
744             match self {
745                 Var(binding) => binding.hash_stable(hcx, hasher),
746                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
747                 RefForGuard => (),
748             }
749         }
750     }
751 }
752
753 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
754 /// created during evaluation of expressions in a block tail
755 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
756 ///
757 /// It is used to improve diagnostics when such temporaries are
758 /// involved in borrow_check errors, e.g., explanations of where the
759 /// temporaries come from, when their destructors are run, and/or how
760 /// one might revise the code to satisfy the borrow checker's rules.
761 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
762 pub struct BlockTailInfo {
763     /// If `true`, then the value resulting from evaluating this tail
764     /// expression is ignored by the block's expression context.
765     ///
766     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
767     /// but not e.g., `let _x = { ...; tail };`
768     pub tail_result_is_ignored: bool,
769
770     /// `Span` of the tail expression.
771     pub span: Span,
772 }
773
774 /// A MIR local.
775 ///
776 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
777 /// argument, or the return place.
778 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
779 pub struct LocalDecl<'tcx> {
780     /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
781     ///
782     /// Temporaries and the return place are always mutable.
783     pub mutability: Mutability,
784
785     // FIXME(matthewjasper) Don't store in this in `Body`
786     pub local_info: Option<Box<LocalInfo<'tcx>>>,
787
788     /// `true` if this is an internal local.
789     ///
790     /// These locals are not based on types in the source code and are only used
791     /// for a few desugarings at the moment.
792     ///
793     /// The generator transformation will sanity check the locals which are live
794     /// across a suspension point against the type components of the generator
795     /// which type checking knows are live across a suspension point. We need to
796     /// flag drop flags to avoid triggering this check as they are introduced
797     /// after typeck.
798     ///
799     /// Unsafety checking will also ignore dereferences of these locals,
800     /// so they can be used for raw pointers only used in a desugaring.
801     ///
802     /// This should be sound because the drop flags are fully algebraic, and
803     /// therefore don't affect the OIBIT or outlives properties of the
804     /// generator.
805     pub internal: bool,
806
807     /// If this local is a temporary and `is_block_tail` is `Some`,
808     /// then it is a temporary created for evaluation of some
809     /// subexpression of some block's tail expression (with no
810     /// intervening statement context).
811     // FIXME(matthewjasper) Don't store in this in `Body`
812     pub is_block_tail: Option<BlockTailInfo>,
813
814     /// The type of this local.
815     pub ty: Ty<'tcx>,
816
817     /// If the user manually ascribed a type to this variable,
818     /// e.g., via `let x: T`, then we carry that type here. The MIR
819     /// borrow checker needs this information since it can affect
820     /// region inference.
821     // FIXME(matthewjasper) Don't store in this in `Body`
822     pub user_ty: Option<Box<UserTypeProjections>>,
823
824     /// The *syntactic* (i.e., not visibility) source scope the local is defined
825     /// in. If the local was defined in a let-statement, this
826     /// is *within* the let-statement, rather than outside
827     /// of it.
828     ///
829     /// This is needed because the visibility source scope of locals within
830     /// a let-statement is weird.
831     ///
832     /// The reason is that we want the local to be *within* the let-statement
833     /// for lint purposes, but we want the local to be *after* the let-statement
834     /// for names-in-scope purposes.
835     ///
836     /// That's it, if we have a let-statement like the one in this
837     /// function:
838     ///
839     /// ```
840     /// fn foo(x: &str) {
841     ///     #[allow(unused_mut)]
842     ///     let mut x: u32 = { // <- one unused mut
843     ///         let mut y: u32 = x.parse().unwrap();
844     ///         y + 2
845     ///     };
846     ///     drop(x);
847     /// }
848     /// ```
849     ///
850     /// Then, from a lint point of view, the declaration of `x: u32`
851     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
852     /// lint scopes are the same as the AST/HIR nesting.
853     ///
854     /// However, from a name lookup point of view, the scopes look more like
855     /// as if the let-statements were `match` expressions:
856     ///
857     /// ```
858     /// fn foo(x: &str) {
859     ///     match {
860     ///         match x.parse().unwrap() {
861     ///             y => y + 2
862     ///         }
863     ///     } {
864     ///         x => drop(x)
865     ///     };
866     /// }
867     /// ```
868     ///
869     /// We care about the name-lookup scopes for debuginfo - if the
870     /// debuginfo instruction pointer is at the call to `x.parse()`, we
871     /// want `x` to refer to `x: &str`, but if it is at the call to
872     /// `drop(x)`, we want it to refer to `x: u32`.
873     ///
874     /// To allow both uses to work, we need to have more than a single scope
875     /// for a local. We have the `source_info.scope` represent the "syntactic"
876     /// lint scope (with a variable being under its let block) while the
877     /// `var_debug_info.source_info.scope` represents the "local variable"
878     /// scope (where the "rest" of a block is under all prior let-statements).
879     ///
880     /// The end result looks like this:
881     ///
882     /// ```text
883     /// ROOT SCOPE
884     ///  │{ argument x: &str }
885     ///  │
886     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
887     ///  │ │                         // in practice because I'm lazy.
888     ///  │ │
889     ///  │ │← x.source_info.scope
890     ///  │ │← `x.parse().unwrap()`
891     ///  │ │
892     ///  │ │ │← y.source_info.scope
893     ///  │ │
894     ///  │ │ │{ let y: u32 }
895     ///  │ │ │
896     ///  │ │ │← y.var_debug_info.source_info.scope
897     ///  │ │ │← `y + 2`
898     ///  │
899     ///  │ │{ let x: u32 }
900     ///  │ │← x.var_debug_info.source_info.scope
901     ///  │ │← `drop(x)` // This accesses `x: u32`.
902     /// ```
903     pub source_info: SourceInfo,
904 }
905
906 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
907 #[cfg(target_arch = "x86_64")]
908 static_assert_size!(LocalDecl<'_>, 56);
909
910 /// Extra information about a some locals that's used for diagnostics and for
911 /// classifying variables into local variables, statics, etc, which is needed e.g.
912 /// for unsafety checking.
913 ///
914 /// Not used for non-StaticRef temporaries, the return place, or anonymous
915 /// function parameters.
916 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
917 pub enum LocalInfo<'tcx> {
918     /// A user-defined local variable or function parameter
919     ///
920     /// The `BindingForm` is solely used for local diagnostics when generating
921     /// warnings/errors when compiling the current crate, and therefore it need
922     /// not be visible across crates.
923     User(ClearCrossCrate<BindingForm<'tcx>>),
924     /// A temporary created that references the static with the given `DefId`.
925     StaticRef { def_id: DefId, is_thread_local: bool },
926     /// A temporary created that references the const with the given `DefId`
927     ConstRef { def_id: DefId },
928 }
929
930 impl<'tcx> LocalDecl<'tcx> {
931     /// Returns `true` only if local is a binding that can itself be
932     /// made mutable via the addition of the `mut` keyword, namely
933     /// something like the occurrences of `x` in:
934     /// - `fn foo(x: Type) { ... }`,
935     /// - `let x = ...`,
936     /// - or `match ... { C(x) => ... }`
937     pub fn can_be_made_mutable(&self) -> bool {
938         match self.local_info {
939             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
940                 binding_mode: ty::BindingMode::BindByValue(_),
941                 opt_ty_info: _,
942                 opt_match_place: _,
943                 pat_span: _,
944             })))) => true,
945
946             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
947                 ImplicitSelfKind::Imm,
948             )))) => true,
949
950             _ => false,
951         }
952     }
953
954     /// Returns `true` if local is definitely not a `ref ident` or
955     /// `ref mut ident` binding. (Such bindings cannot be made into
956     /// mutable bindings, but the inverse does not necessarily hold).
957     pub fn is_nonref_binding(&self) -> bool {
958         match self.local_info {
959             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
960                 binding_mode: ty::BindingMode::BindByValue(_),
961                 opt_ty_info: _,
962                 opt_match_place: _,
963                 pat_span: _,
964             })))) => true,
965
966             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
967
968             _ => false,
969         }
970     }
971
972     /// Returns `true` if this variable is a named variable or function
973     /// parameter declared by the user.
974     #[inline]
975     pub fn is_user_variable(&self) -> bool {
976         match self.local_info {
977             Some(box LocalInfo::User(_)) => true,
978             _ => false,
979         }
980     }
981
982     /// Returns `true` if this is a reference to a variable bound in a `match`
983     /// expression that is used to access said variable for the guard of the
984     /// match arm.
985     pub fn is_ref_for_guard(&self) -> bool {
986         match self.local_info {
987             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
988             _ => false,
989         }
990     }
991
992     /// Returns `Some` if this is a reference to a static item that is used to
993     /// access that static
994     pub fn is_ref_to_static(&self) -> bool {
995         match self.local_info {
996             Some(box LocalInfo::StaticRef { .. }) => true,
997             _ => false,
998         }
999     }
1000
1001     /// Returns `Some` if this is a reference to a static item that is used to
1002     /// access that static
1003     pub fn is_ref_to_thread_local(&self) -> bool {
1004         match self.local_info {
1005             Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1006             _ => false,
1007         }
1008     }
1009
1010     /// Returns `true` is the local is from a compiler desugaring, e.g.,
1011     /// `__next` from a `for` loop.
1012     #[inline]
1013     pub fn from_compiler_desugaring(&self) -> bool {
1014         self.source_info.span.desugaring_kind().is_some()
1015     }
1016
1017     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1018     #[inline]
1019     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1020         Self::with_source_info(ty, SourceInfo::outermost(span))
1021     }
1022
1023     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1024     #[inline]
1025     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1026         LocalDecl {
1027             mutability: Mutability::Mut,
1028             local_info: None,
1029             internal: false,
1030             is_block_tail: None,
1031             ty,
1032             user_ty: None,
1033             source_info,
1034         }
1035     }
1036
1037     /// Converts `self` into same `LocalDecl` except tagged as internal.
1038     #[inline]
1039     pub fn internal(mut self) -> Self {
1040         self.internal = true;
1041         self
1042     }
1043
1044     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1045     #[inline]
1046     pub fn immutable(mut self) -> Self {
1047         self.mutability = Mutability::Not;
1048         self
1049     }
1050
1051     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1052     #[inline]
1053     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1054         assert!(self.is_block_tail.is_none());
1055         self.is_block_tail = Some(info);
1056         self
1057     }
1058 }
1059
1060 /// Debug information pertaining to a user variable.
1061 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1062 pub struct VarDebugInfo<'tcx> {
1063     pub name: Symbol,
1064
1065     /// Source info of the user variable, including the scope
1066     /// within which the variable is visible (to debuginfo)
1067     /// (see `LocalDecl`'s `source_info` field for more details).
1068     pub source_info: SourceInfo,
1069
1070     /// Where the data for this user variable is to be found.
1071     /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1072     /// based on a `Local`, not a `Static`, and contains no indexing.
1073     pub place: Place<'tcx>,
1074 }
1075
1076 ///////////////////////////////////////////////////////////////////////////
1077 // BasicBlock
1078
1079 rustc_index::newtype_index! {
1080     /// A node in the MIR [control-flow graph][CFG].
1081     ///
1082     /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1083     /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1084     /// as an edge in a graph between basic blocks.
1085     ///
1086     /// Basic blocks consist of a series of [statements][Statement], ending with a
1087     /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1088     /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1089     /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1090     /// needed because some analyses require that there are no critical edges in the CFG.
1091     ///
1092     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1093     ///
1094     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1095     /// [data-flow analyses]:
1096     ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1097     /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1098     /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1099     pub struct BasicBlock {
1100         derive [HashStable]
1101         DEBUG_FORMAT = "bb{}",
1102         const START_BLOCK = 0,
1103     }
1104 }
1105
1106 impl BasicBlock {
1107     pub fn start_location(self) -> Location {
1108         Location { block: self, statement_index: 0 }
1109     }
1110 }
1111
1112 ///////////////////////////////////////////////////////////////////////////
1113 // BasicBlockData and Terminator
1114
1115 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1116 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1117 pub struct BasicBlockData<'tcx> {
1118     /// List of statements in this block.
1119     pub statements: Vec<Statement<'tcx>>,
1120
1121     /// Terminator for this block.
1122     ///
1123     /// N.B., this should generally ONLY be `None` during construction.
1124     /// Therefore, you should generally access it via the
1125     /// `terminator()` or `terminator_mut()` methods. The only
1126     /// exception is that certain passes, such as `simplify_cfg`, swap
1127     /// out the terminator temporarily with `None` while they continue
1128     /// to recurse over the set of basic blocks.
1129     pub terminator: Option<Terminator<'tcx>>,
1130
1131     /// If true, this block lies on an unwind path. This is used
1132     /// during codegen where distinct kinds of basic blocks may be
1133     /// generated (particularly for MSVC cleanup). Unwind blocks must
1134     /// only branch to other unwind blocks.
1135     pub is_cleanup: bool,
1136 }
1137
1138 /// Information about an assertion failure.
1139 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1140 pub enum AssertKind<O> {
1141     BoundsCheck { len: O, index: O },
1142     Overflow(BinOp, O, O),
1143     OverflowNeg(O),
1144     DivisionByZero(O),
1145     RemainderByZero(O),
1146     ResumedAfterReturn(GeneratorKind),
1147     ResumedAfterPanic(GeneratorKind),
1148 }
1149
1150 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1151 pub enum InlineAsmOperand<'tcx> {
1152     In {
1153         reg: InlineAsmRegOrRegClass,
1154         value: Operand<'tcx>,
1155     },
1156     Out {
1157         reg: InlineAsmRegOrRegClass,
1158         late: bool,
1159         place: Option<Place<'tcx>>,
1160     },
1161     InOut {
1162         reg: InlineAsmRegOrRegClass,
1163         late: bool,
1164         in_value: Operand<'tcx>,
1165         out_place: Option<Place<'tcx>>,
1166     },
1167     Const {
1168         value: Operand<'tcx>,
1169     },
1170     SymFn {
1171         value: Box<Constant<'tcx>>,
1172     },
1173     SymStatic {
1174         def_id: DefId,
1175     },
1176 }
1177
1178 /// Type for MIR `Assert` terminator error messages.
1179 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1180
1181 pub type Successors<'a> =
1182     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1183 pub type SuccessorsMut<'a> =
1184     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1185
1186 impl<'tcx> BasicBlockData<'tcx> {
1187     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1188         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1189     }
1190
1191     /// Accessor for terminator.
1192     ///
1193     /// Terminator may not be None after construction of the basic block is complete. This accessor
1194     /// provides a convenience way to reach the terminator.
1195     pub fn terminator(&self) -> &Terminator<'tcx> {
1196         self.terminator.as_ref().expect("invalid terminator state")
1197     }
1198
1199     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1200         self.terminator.as_mut().expect("invalid terminator state")
1201     }
1202
1203     pub fn retain_statements<F>(&mut self, mut f: F)
1204     where
1205         F: FnMut(&mut Statement<'_>) -> bool,
1206     {
1207         for s in &mut self.statements {
1208             if !f(s) {
1209                 s.make_nop();
1210             }
1211         }
1212     }
1213
1214     pub fn expand_statements<F, I>(&mut self, mut f: F)
1215     where
1216         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1217         I: iter::TrustedLen<Item = Statement<'tcx>>,
1218     {
1219         // Gather all the iterators we'll need to splice in, and their positions.
1220         let mut splices: Vec<(usize, I)> = vec![];
1221         let mut extra_stmts = 0;
1222         for (i, s) in self.statements.iter_mut().enumerate() {
1223             if let Some(mut new_stmts) = f(s) {
1224                 if let Some(first) = new_stmts.next() {
1225                     // We can already store the first new statement.
1226                     *s = first;
1227
1228                     // Save the other statements for optimized splicing.
1229                     let remaining = new_stmts.size_hint().0;
1230                     if remaining > 0 {
1231                         splices.push((i + 1 + extra_stmts, new_stmts));
1232                         extra_stmts += remaining;
1233                     }
1234                 } else {
1235                     s.make_nop();
1236                 }
1237             }
1238         }
1239
1240         // Splice in the new statements, from the end of the block.
1241         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1242         // where a range of elements ("gap") is left uninitialized, with
1243         // splicing adding new elements to the end of that gap and moving
1244         // existing elements from before the gap to the end of the gap.
1245         // For now, this is safe code, emulating a gap but initializing it.
1246         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1247         self.statements.resize(
1248             gap.end,
1249             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1250         );
1251         for (splice_start, new_stmts) in splices.into_iter().rev() {
1252             let splice_end = splice_start + new_stmts.size_hint().0;
1253             while gap.end > splice_end {
1254                 gap.start -= 1;
1255                 gap.end -= 1;
1256                 self.statements.swap(gap.start, gap.end);
1257             }
1258             self.statements.splice(splice_start..splice_end, new_stmts);
1259             gap.end = splice_start;
1260         }
1261     }
1262
1263     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1264         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1265     }
1266 }
1267
1268 impl<O> AssertKind<O> {
1269     /// Getting a description does not require `O` to be printable, and does not
1270     /// require allocation.
1271     /// The caller is expected to handle `BoundsCheck` separately.
1272     pub fn description(&self) -> &'static str {
1273         use AssertKind::*;
1274         match self {
1275             Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1276             Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1277             Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1278             Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1279             Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1280             OverflowNeg(_) => "attempt to negate with overflow",
1281             Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1282             Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1283             Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1284             DivisionByZero(_) => "attempt to divide by zero",
1285             RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1286             ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1287             ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1288             ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1289             ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1290             BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1291         }
1292     }
1293
1294     /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1295     fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1296     where
1297         O: Debug,
1298     {
1299         use AssertKind::*;
1300         match self {
1301             BoundsCheck { ref len, ref index } => write!(
1302                 f,
1303                 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1304                 len, index
1305             ),
1306
1307             OverflowNeg(op) => {
1308                 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1309             }
1310             DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1311             RemainderByZero(op) => write!(
1312                 f,
1313                 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1314                 op
1315             ),
1316             Overflow(BinOp::Add, l, r) => write!(
1317                 f,
1318                 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1319                 l, r
1320             ),
1321             Overflow(BinOp::Sub, l, r) => write!(
1322                 f,
1323                 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1324                 l, r
1325             ),
1326             Overflow(BinOp::Mul, l, r) => write!(
1327                 f,
1328                 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1329                 l, r
1330             ),
1331             Overflow(BinOp::Div, l, r) => write!(
1332                 f,
1333                 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1334                 l, r
1335             ),
1336             Overflow(BinOp::Rem, l, r) => write!(
1337                 f,
1338                 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1339                 l, r
1340             ),
1341             Overflow(BinOp::Shr, _, r) => {
1342                 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1343             }
1344             Overflow(BinOp::Shl, _, r) => {
1345                 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1346             }
1347             _ => write!(f, "\"{}\"", self.description()),
1348         }
1349     }
1350 }
1351
1352 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1353     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1354         use AssertKind::*;
1355         match self {
1356             BoundsCheck { ref len, ref index } => {
1357                 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1358             }
1359             OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1360             DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1361             RemainderByZero(op) => {
1362                 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1363             }
1364             Overflow(BinOp::Add, l, r) => {
1365                 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1366             }
1367             Overflow(BinOp::Sub, l, r) => {
1368                 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1369             }
1370             Overflow(BinOp::Mul, l, r) => {
1371                 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1372             }
1373             Overflow(BinOp::Div, l, r) => {
1374                 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1375             }
1376             Overflow(BinOp::Rem, l, r) => write!(
1377                 f,
1378                 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1379                 l, r
1380             ),
1381             Overflow(BinOp::Shr, _, r) => {
1382                 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1383             }
1384             Overflow(BinOp::Shl, _, r) => {
1385                 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1386             }
1387             _ => write!(f, "{}", self.description()),
1388         }
1389     }
1390 }
1391
1392 ///////////////////////////////////////////////////////////////////////////
1393 // Statements
1394
1395 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1396 pub struct Statement<'tcx> {
1397     pub source_info: SourceInfo,
1398     pub kind: StatementKind<'tcx>,
1399 }
1400
1401 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1402 #[cfg(target_arch = "x86_64")]
1403 static_assert_size!(Statement<'_>, 32);
1404
1405 impl Statement<'_> {
1406     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1407     /// invalidating statement indices in `Location`s.
1408     pub fn make_nop(&mut self) {
1409         self.kind = StatementKind::Nop
1410     }
1411
1412     /// Changes a statement to a nop and returns the original statement.
1413     pub fn replace_nop(&mut self) -> Self {
1414         Statement {
1415             source_info: self.source_info,
1416             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1417         }
1418     }
1419 }
1420
1421 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1422 pub enum StatementKind<'tcx> {
1423     /// Write the RHS Rvalue to the LHS Place.
1424     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1425
1426     /// This represents all the reading that a pattern match may do
1427     /// (e.g., inspecting constants and discriminant values), and the
1428     /// kind of pattern it comes from. This is in order to adapt potential
1429     /// error messages to these specific patterns.
1430     ///
1431     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1432     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1433     FakeRead(FakeReadCause, Box<Place<'tcx>>),
1434
1435     /// Write the discriminant for a variant to the enum Place.
1436     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1437
1438     /// Start a live range for the storage of the local.
1439     StorageLive(Local),
1440
1441     /// End the current live range for the storage of the local.
1442     StorageDead(Local),
1443
1444     /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1445     /// of `StatementKind` low.
1446     LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1447
1448     /// Retag references in the given place, ensuring they got fresh tags. This is
1449     /// part of the Stacked Borrows model. These statements are currently only interpreted
1450     /// by miri and only generated when "-Z mir-emit-retag" is passed.
1451     /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1452     /// for more details.
1453     Retag(RetagKind, Box<Place<'tcx>>),
1454
1455     /// Encodes a user's type ascription. These need to be preserved
1456     /// intact so that NLL can respect them. For example:
1457     ///
1458     ///     let a: T = y;
1459     ///
1460     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1461     /// to the user-given type `T`. The effect depends on the specified variance:
1462     ///
1463     /// - `Covariant` -- requires that `T_y <: T`
1464     /// - `Contravariant` -- requires that `T_y :> T`
1465     /// - `Invariant` -- requires that `T_y == T`
1466     /// - `Bivariant` -- no effect
1467     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1468
1469     /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1470     /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1471     /// map into the binary. The `Counter` kind also generates executable code, to increment a
1472     /// counter varible at runtime, each time the code region is executed.
1473     Coverage(Box<Coverage>),
1474
1475     /// No-op. Useful for deleting instructions without affecting statement indices.
1476     Nop,
1477 }
1478
1479 impl<'tcx> StatementKind<'tcx> {
1480     pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1481         match self {
1482             StatementKind::Assign(x) => Some(x),
1483             _ => None,
1484         }
1485     }
1486 }
1487
1488 /// Describes what kind of retag is to be performed.
1489 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1490 pub enum RetagKind {
1491     /// The initial retag when entering a function.
1492     FnEntry,
1493     /// Retag preparing for a two-phase borrow.
1494     TwoPhase,
1495     /// Retagging raw pointers.
1496     Raw,
1497     /// A "normal" retag.
1498     Default,
1499 }
1500
1501 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1502 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1503 pub enum FakeReadCause {
1504     /// Inject a fake read of the borrowed input at the end of each guards
1505     /// code.
1506     ///
1507     /// This should ensure that you cannot change the variant for an enum while
1508     /// you are in the midst of matching on it.
1509     ForMatchGuard,
1510
1511     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1512     /// generate a read of x to check that it is initialized and safe.
1513     ForMatchedPlace,
1514
1515     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1516     /// in a match guard to ensure that it's value hasn't change by the time
1517     /// we create the OutsideGuard version.
1518     ForGuardBinding,
1519
1520     /// Officially, the semantics of
1521     ///
1522     /// `let pattern = <expr>;`
1523     ///
1524     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1525     /// into the pattern.
1526     ///
1527     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1528     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1529     /// but in some cases it can affect the borrow checker, as in #53695.
1530     /// Therefore, we insert a "fake read" here to ensure that we get
1531     /// appropriate errors.
1532     ForLet,
1533
1534     /// If we have an index expression like
1535     ///
1536     /// (*x)[1][{ x = y; 4}]
1537     ///
1538     /// then the first bounds check is invalidated when we evaluate the second
1539     /// index expression. Thus we create a fake borrow of `x` across the second
1540     /// indexer, which will cause a borrow check error.
1541     ForIndex,
1542 }
1543
1544 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1545 pub struct LlvmInlineAsm<'tcx> {
1546     pub asm: hir::LlvmInlineAsmInner,
1547     pub outputs: Box<[Place<'tcx>]>,
1548     pub inputs: Box<[(Span, Operand<'tcx>)]>,
1549 }
1550
1551 impl Debug for Statement<'_> {
1552     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1553         use self::StatementKind::*;
1554         match self.kind {
1555             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1556             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1557             Retag(ref kind, ref place) => write!(
1558                 fmt,
1559                 "Retag({}{:?})",
1560                 match kind {
1561                     RetagKind::FnEntry => "[fn entry] ",
1562                     RetagKind::TwoPhase => "[2phase] ",
1563                     RetagKind::Raw => "[raw] ",
1564                     RetagKind::Default => "",
1565                 },
1566                 place,
1567             ),
1568             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1569             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1570             SetDiscriminant { ref place, variant_index } => {
1571                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1572             }
1573             LlvmInlineAsm(ref asm) => {
1574                 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1575             }
1576             AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1577                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1578             }
1579             Coverage(box ref coverage) => {
1580                 let rgn = &coverage.code_region;
1581                 match coverage.kind {
1582                     CoverageKind::Counter { id, .. } => {
1583                         write!(fmt, "Coverage::Counter({:?}) for {:?}", id.index(), rgn)
1584                     }
1585                     CoverageKind::Expression { id, lhs, op, rhs } => write!(
1586                         fmt,
1587                         "Coverage::Expression({:?}) = {} {} {} for {:?}",
1588                         id.index(),
1589                         lhs.index(),
1590                         if op == coverage::Op::Add { "+" } else { "-" },
1591                         rhs.index(),
1592                         rgn
1593                     ),
1594                     CoverageKind::Unreachable => write!(fmt, "Coverage::Unreachable for {:?}", rgn),
1595                 }
1596             }
1597             Nop => write!(fmt, "nop"),
1598         }
1599     }
1600 }
1601
1602 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1603 pub struct Coverage {
1604     pub kind: CoverageKind,
1605     pub code_region: CodeRegion,
1606 }
1607
1608 ///////////////////////////////////////////////////////////////////////////
1609 // Places
1610
1611 /// A path to a value; something that can be evaluated without
1612 /// changing or disturbing program state.
1613 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1614 pub struct Place<'tcx> {
1615     pub local: Local,
1616
1617     /// projection out of a place (access a field, deref a pointer, etc)
1618     pub projection: &'tcx List<PlaceElem<'tcx>>,
1619 }
1620
1621 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1622 #[derive(TyEncodable, TyDecodable, HashStable)]
1623 pub enum ProjectionElem<V, T> {
1624     Deref,
1625     Field(Field, T),
1626     Index(V),
1627
1628     /// These indices are generated by slice patterns. Easiest to explain
1629     /// by example:
1630     ///
1631     /// ```
1632     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1633     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1634     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1635     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1636     /// ```
1637     ConstantIndex {
1638         /// index or -index (in Python terms), depending on from_end
1639         offset: u64,
1640         /// The thing being indexed must be at least this long. For arrays this
1641         /// is always the exact length.
1642         min_length: u64,
1643         /// Counting backwards from end? This is always false when indexing an
1644         /// array.
1645         from_end: bool,
1646     },
1647
1648     /// These indices are generated by slice patterns.
1649     ///
1650     /// If `from_end` is true `slice[from..slice.len() - to]`.
1651     /// Otherwise `array[from..to]`.
1652     Subslice {
1653         from: u64,
1654         to: u64,
1655         /// Whether `to` counts from the start or end of the array/slice.
1656         /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1657         /// For `ProjectionKind`, this can also be `true` for arrays.
1658         from_end: bool,
1659     },
1660
1661     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1662     /// this for ADTs with more than one variant. It may be better to
1663     /// just introduce it always, or always for enums.
1664     ///
1665     /// The included Symbol is the name of the variant, used for printing MIR.
1666     Downcast(Option<Symbol>, VariantIdx),
1667 }
1668
1669 impl<V, T> ProjectionElem<V, T> {
1670     /// Returns `true` if the target of this projection may refer to a different region of memory
1671     /// than the base.
1672     fn is_indirect(&self) -> bool {
1673         match self {
1674             Self::Deref => true,
1675
1676             Self::Field(_, _)
1677             | Self::Index(_)
1678             | Self::ConstantIndex { .. }
1679             | Self::Subslice { .. }
1680             | Self::Downcast(_, _) => false,
1681         }
1682     }
1683 }
1684
1685 /// Alias for projections as they appear in places, where the base is a place
1686 /// and the index is a local.
1687 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1688
1689 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1690 #[cfg(target_arch = "x86_64")]
1691 static_assert_size!(PlaceElem<'_>, 24);
1692
1693 /// Alias for projections as they appear in `UserTypeProjection`, where we
1694 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1695 pub type ProjectionKind = ProjectionElem<(), ()>;
1696
1697 rustc_index::newtype_index! {
1698     pub struct Field {
1699         derive [HashStable]
1700         DEBUG_FORMAT = "field[{}]"
1701     }
1702 }
1703
1704 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1705 pub struct PlaceRef<'tcx> {
1706     pub local: Local,
1707     pub projection: &'tcx [PlaceElem<'tcx>],
1708 }
1709
1710 impl<'tcx> Place<'tcx> {
1711     // FIXME change this to a const fn by also making List::empty a const fn.
1712     pub fn return_place() -> Place<'tcx> {
1713         Place { local: RETURN_PLACE, projection: List::empty() }
1714     }
1715
1716     /// Returns `true` if this `Place` contains a `Deref` projection.
1717     ///
1718     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1719     /// same region of memory as its base.
1720     pub fn is_indirect(&self) -> bool {
1721         self.projection.iter().any(|elem| elem.is_indirect())
1722     }
1723
1724     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1725     /// a single deref of a local.
1726     //
1727     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1728     pub fn local_or_deref_local(&self) -> Option<Local> {
1729         match self.as_ref() {
1730             PlaceRef { local, projection: [] }
1731             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1732             _ => None,
1733         }
1734     }
1735
1736     /// If this place represents a local variable like `_X` with no
1737     /// projections, return `Some(_X)`.
1738     pub fn as_local(&self) -> Option<Local> {
1739         self.as_ref().as_local()
1740     }
1741
1742     pub fn as_ref(&self) -> PlaceRef<'tcx> {
1743         PlaceRef { local: self.local, projection: &self.projection }
1744     }
1745 }
1746
1747 impl From<Local> for Place<'_> {
1748     fn from(local: Local) -> Self {
1749         Place { local, projection: List::empty() }
1750     }
1751 }
1752
1753 impl<'tcx> PlaceRef<'tcx> {
1754     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1755     /// a single deref of a local.
1756     //
1757     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1758     pub fn local_or_deref_local(&self) -> Option<Local> {
1759         match *self {
1760             PlaceRef { local, projection: [] }
1761             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1762             _ => None,
1763         }
1764     }
1765
1766     /// If this place represents a local variable like `_X` with no
1767     /// projections, return `Some(_X)`.
1768     pub fn as_local(&self) -> Option<Local> {
1769         match *self {
1770             PlaceRef { local, projection: [] } => Some(local),
1771             _ => None,
1772         }
1773     }
1774 }
1775
1776 impl Debug for Place<'_> {
1777     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1778         for elem in self.projection.iter().rev() {
1779             match elem {
1780                 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1781                     write!(fmt, "(").unwrap();
1782                 }
1783                 ProjectionElem::Deref => {
1784                     write!(fmt, "(*").unwrap();
1785                 }
1786                 ProjectionElem::Index(_)
1787                 | ProjectionElem::ConstantIndex { .. }
1788                 | ProjectionElem::Subslice { .. } => {}
1789             }
1790         }
1791
1792         write!(fmt, "{:?}", self.local)?;
1793
1794         for elem in self.projection.iter() {
1795             match elem {
1796                 ProjectionElem::Downcast(Some(name), _index) => {
1797                     write!(fmt, " as {})", name)?;
1798                 }
1799                 ProjectionElem::Downcast(None, index) => {
1800                     write!(fmt, " as variant#{:?})", index)?;
1801                 }
1802                 ProjectionElem::Deref => {
1803                     write!(fmt, ")")?;
1804                 }
1805                 ProjectionElem::Field(field, ty) => {
1806                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1807                 }
1808                 ProjectionElem::Index(ref index) => {
1809                     write!(fmt, "[{:?}]", index)?;
1810                 }
1811                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1812                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1813                 }
1814                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1815                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1816                 }
1817                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1818                     write!(fmt, "[{:?}:]", from)?;
1819                 }
1820                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1821                     write!(fmt, "[:-{:?}]", to)?;
1822                 }
1823                 ProjectionElem::Subslice { from, to, from_end: true } => {
1824                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
1825                 }
1826                 ProjectionElem::Subslice { from, to, from_end: false } => {
1827                     write!(fmt, "[{:?}..{:?}]", from, to)?;
1828                 }
1829             }
1830         }
1831
1832         Ok(())
1833     }
1834 }
1835
1836 ///////////////////////////////////////////////////////////////////////////
1837 // Scopes
1838
1839 rustc_index::newtype_index! {
1840     pub struct SourceScope {
1841         derive [HashStable]
1842         DEBUG_FORMAT = "scope[{}]",
1843         const OUTERMOST_SOURCE_SCOPE = 0,
1844     }
1845 }
1846
1847 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1848 pub struct SourceScopeData {
1849     pub span: Span,
1850     pub parent_scope: Option<SourceScope>,
1851
1852     /// Crate-local information for this source scope, that can't (and
1853     /// needn't) be tracked across crates.
1854     pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1855 }
1856
1857 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1858 pub struct SourceScopeLocalData {
1859     /// An `HirId` with lint levels equivalent to this scope's lint levels.
1860     pub lint_root: hir::HirId,
1861     /// The unsafe block that contains this node.
1862     pub safety: Safety,
1863 }
1864
1865 ///////////////////////////////////////////////////////////////////////////
1866 // Operands
1867
1868 /// These are values that can appear inside an rvalue. They are intentionally
1869 /// limited to prevent rvalues from being nested in one another.
1870 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1871 pub enum Operand<'tcx> {
1872     /// Copy: The value must be available for use afterwards.
1873     ///
1874     /// This implies that the type of the place must be `Copy`; this is true
1875     /// by construction during build, but also checked by the MIR type checker.
1876     Copy(Place<'tcx>),
1877
1878     /// Move: The value (including old borrows of it) will not be used again.
1879     ///
1880     /// Safe for values of all types (modulo future developments towards `?Move`).
1881     /// Correct usage patterns are enforced by the borrow checker for safe code.
1882     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1883     Move(Place<'tcx>),
1884
1885     /// Synthesizes a constant value.
1886     Constant(Box<Constant<'tcx>>),
1887 }
1888
1889 impl<'tcx> Debug for Operand<'tcx> {
1890     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1891         use self::Operand::*;
1892         match *self {
1893             Constant(ref a) => write!(fmt, "{:?}", a),
1894             Copy(ref place) => write!(fmt, "{:?}", place),
1895             Move(ref place) => write!(fmt, "move {:?}", place),
1896         }
1897     }
1898 }
1899
1900 impl<'tcx> Operand<'tcx> {
1901     /// Convenience helper to make a constant that refers to the fn
1902     /// with given `DefId` and substs. Since this is used to synthesize
1903     /// MIR, assumes `user_ty` is None.
1904     pub fn function_handle(
1905         tcx: TyCtxt<'tcx>,
1906         def_id: DefId,
1907         substs: SubstsRef<'tcx>,
1908         span: Span,
1909     ) -> Self {
1910         let ty = tcx.type_of(def_id).subst(tcx, substs);
1911         Operand::Constant(box Constant {
1912             span,
1913             user_ty: None,
1914             literal: ty::Const::zero_sized(tcx, ty),
1915         })
1916     }
1917
1918     pub fn is_move(&self) -> bool {
1919         matches!(self, Operand::Move(..))
1920     }
1921
1922     /// Convenience helper to make a literal-like constant from a given scalar value.
1923     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1924     pub fn const_from_scalar(
1925         tcx: TyCtxt<'tcx>,
1926         ty: Ty<'tcx>,
1927         val: Scalar,
1928         span: Span,
1929     ) -> Operand<'tcx> {
1930         debug_assert!({
1931             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1932             let type_size = tcx
1933                 .layout_of(param_env_and_ty)
1934                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1935                 .size;
1936             let scalar_size = abi::Size::from_bytes(match val {
1937                 Scalar::Raw { size, .. } => size,
1938                 _ => panic!("Invalid scalar type {:?}", val),
1939             });
1940             scalar_size == type_size
1941         });
1942         Operand::Constant(box Constant {
1943             span,
1944             user_ty: None,
1945             literal: ty::Const::from_scalar(tcx, val, ty),
1946         })
1947     }
1948
1949     /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1950     /// wraps a constant literal value. Panics if this is not the case.
1951     pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1952         match operand {
1953             Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1954                 Some(scalar) => scalar,
1955                 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1956             },
1957             _ => panic!("{:?}: Constant expected", operand),
1958         }
1959     }
1960
1961     /// Convenience helper to make a literal-like constant from a given `&str` slice.
1962     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1963     pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1964         let tcx = tcx;
1965         let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1966         let allocation = tcx.intern_const_alloc(allocation);
1967         let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1968         let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1969         Operand::Constant(box Constant {
1970             span,
1971             user_ty: None,
1972             literal: ty::Const::from_value(tcx, const_val, ty),
1973         })
1974     }
1975
1976     /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1977     /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1978     pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1979         match operand {
1980             Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1981                 Some(const_value) => const_value,
1982                 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1983             },
1984             _ => panic!("{:?}: Constant expected", operand),
1985         }
1986     }
1987
1988     pub fn to_copy(&self) -> Self {
1989         match *self {
1990             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1991             Operand::Move(place) => Operand::Copy(place),
1992         }
1993     }
1994
1995     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1996     /// constant.
1997     pub fn place(&self) -> Option<Place<'tcx>> {
1998         match self {
1999             Operand::Copy(place) | Operand::Move(place) => Some(*place),
2000             Operand::Constant(_) => None,
2001         }
2002     }
2003
2004     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2005     /// place.
2006     pub fn constant(&self) -> Option<&Constant<'tcx>> {
2007         match self {
2008             Operand::Constant(x) => Some(&**x),
2009             Operand::Copy(_) | Operand::Move(_) => None,
2010         }
2011     }
2012 }
2013
2014 ///////////////////////////////////////////////////////////////////////////
2015 /// Rvalues
2016
2017 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
2018 pub enum Rvalue<'tcx> {
2019     /// x (either a move or copy, depending on type of x)
2020     Use(Operand<'tcx>),
2021
2022     /// [x; 32]
2023     Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2024
2025     /// &x or &mut x
2026     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2027
2028     /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2029     /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2030     /// static.
2031     ThreadLocalRef(DefId),
2032
2033     /// Create a raw pointer to the given place
2034     /// Can be generated by raw address of expressions (`&raw const x`),
2035     /// or when casting a reference to a raw pointer.
2036     AddressOf(Mutability, Place<'tcx>),
2037
2038     /// length of a `[X]` or `[X;n]` value
2039     Len(Place<'tcx>),
2040
2041     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2042
2043     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2044     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2045
2046     NullaryOp(NullOp, Ty<'tcx>),
2047     UnaryOp(UnOp, Operand<'tcx>),
2048
2049     /// Read the discriminant of an ADT.
2050     ///
2051     /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2052     /// be defined to return, say, a 0) if ADT is not an enum.
2053     Discriminant(Place<'tcx>),
2054
2055     /// Creates an aggregate value, like a tuple or struct. This is
2056     /// only needed because we want to distinguish `dest = Foo { x:
2057     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2058     /// that `Foo` has a destructor. These rvalues can be optimized
2059     /// away after type-checking and before lowering.
2060     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2061 }
2062
2063 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2064 pub enum CastKind {
2065     Misc,
2066     Pointer(PointerCast),
2067 }
2068
2069 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2070 pub enum AggregateKind<'tcx> {
2071     /// The type is of the element
2072     Array(Ty<'tcx>),
2073     Tuple,
2074
2075     /// The second field is the variant index. It's equal to 0 for struct
2076     /// and union expressions. The fourth field is
2077     /// active field number and is present only for union expressions
2078     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2079     /// active field index would identity the field `c`
2080     Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2081
2082     Closure(DefId, SubstsRef<'tcx>),
2083     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2084 }
2085
2086 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2087 pub enum BinOp {
2088     /// The `+` operator (addition)
2089     Add,
2090     /// The `-` operator (subtraction)
2091     Sub,
2092     /// The `*` operator (multiplication)
2093     Mul,
2094     /// The `/` operator (division)
2095     Div,
2096     /// The `%` operator (modulus)
2097     Rem,
2098     /// The `^` operator (bitwise xor)
2099     BitXor,
2100     /// The `&` operator (bitwise and)
2101     BitAnd,
2102     /// The `|` operator (bitwise or)
2103     BitOr,
2104     /// The `<<` operator (shift left)
2105     Shl,
2106     /// The `>>` operator (shift right)
2107     Shr,
2108     /// The `==` operator (equality)
2109     Eq,
2110     /// The `<` operator (less than)
2111     Lt,
2112     /// The `<=` operator (less than or equal to)
2113     Le,
2114     /// The `!=` operator (not equal to)
2115     Ne,
2116     /// The `>=` operator (greater than or equal to)
2117     Ge,
2118     /// The `>` operator (greater than)
2119     Gt,
2120     /// The `ptr.offset` operator
2121     Offset,
2122 }
2123
2124 impl BinOp {
2125     pub fn is_checkable(self) -> bool {
2126         use self::BinOp::*;
2127         match self {
2128             Add | Sub | Mul | Shl | Shr => true,
2129             _ => false,
2130         }
2131     }
2132 }
2133
2134 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2135 pub enum NullOp {
2136     /// Returns the size of a value of that type
2137     SizeOf,
2138     /// Creates a new uninitialized box for a value of that type
2139     Box,
2140 }
2141
2142 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2143 pub enum UnOp {
2144     /// The `!` operator for logical inversion
2145     Not,
2146     /// The `-` operator for negation
2147     Neg,
2148 }
2149
2150 impl<'tcx> Debug for Rvalue<'tcx> {
2151     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2152         use self::Rvalue::*;
2153
2154         match *self {
2155             Use(ref place) => write!(fmt, "{:?}", place),
2156             Repeat(ref a, ref b) => {
2157                 write!(fmt, "[{:?}; ", a)?;
2158                 pretty_print_const(b, fmt, false)?;
2159                 write!(fmt, "]")
2160             }
2161             Len(ref a) => write!(fmt, "Len({:?})", a),
2162             Cast(ref kind, ref place, ref ty) => {
2163                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2164             }
2165             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2166             CheckedBinaryOp(ref op, ref a, ref b) => {
2167                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2168             }
2169             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2170             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2171             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2172             ThreadLocalRef(did) => ty::tls::with(|tcx| {
2173                 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2174                 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2175             }),
2176             Ref(region, borrow_kind, ref place) => {
2177                 let kind_str = match borrow_kind {
2178                     BorrowKind::Shared => "",
2179                     BorrowKind::Shallow => "shallow ",
2180                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2181                 };
2182
2183                 // When printing regions, add trailing space if necessary.
2184                 let print_region = ty::tls::with(|tcx| {
2185                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2186                 });
2187                 let region = if print_region {
2188                     let mut region = region.to_string();
2189                     if !region.is_empty() {
2190                         region.push(' ');
2191                     }
2192                     region
2193                 } else {
2194                     // Do not even print 'static
2195                     String::new()
2196                 };
2197                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2198             }
2199
2200             AddressOf(mutability, ref place) => {
2201                 let kind_str = match mutability {
2202                     Mutability::Mut => "mut",
2203                     Mutability::Not => "const",
2204                 };
2205
2206                 write!(fmt, "&raw {} {:?}", kind_str, place)
2207             }
2208
2209             Aggregate(ref kind, ref places) => {
2210                 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2211                     let mut tuple_fmt = fmt.debug_tuple(name);
2212                     for place in places {
2213                         tuple_fmt.field(place);
2214                     }
2215                     tuple_fmt.finish()
2216                 };
2217
2218                 match **kind {
2219                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2220
2221                     AggregateKind::Tuple => {
2222                         if places.is_empty() {
2223                             write!(fmt, "()")
2224                         } else {
2225                             fmt_tuple(fmt, "")
2226                         }
2227                     }
2228
2229                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2230                         let variant_def = &adt_def.variants[variant];
2231
2232                         let name = ty::tls::with(|tcx| {
2233                             let mut name = String::new();
2234                             let substs = tcx.lift(&substs).expect("could not lift for printing");
2235                             FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2236                                 .print_def_path(variant_def.def_id, substs)?;
2237                             Ok(name)
2238                         })?;
2239
2240                         match variant_def.ctor_kind {
2241                             CtorKind::Const => fmt.write_str(&name),
2242                             CtorKind::Fn => fmt_tuple(fmt, &name),
2243                             CtorKind::Fictive => {
2244                                 let mut struct_fmt = fmt.debug_struct(&name);
2245                                 for (field, place) in variant_def.fields.iter().zip(places) {
2246                                     struct_fmt.field(&field.ident.as_str(), place);
2247                                 }
2248                                 struct_fmt.finish()
2249                             }
2250                         }
2251                     }
2252
2253                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2254                         if let Some(def_id) = def_id.as_local() {
2255                             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2256                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2257                                 let substs = tcx.lift(&substs).unwrap();
2258                                 format!(
2259                                     "[closure@{}]",
2260                                     tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2261                                 )
2262                             } else {
2263                                 let span = tcx.hir().span(hir_id);
2264                                 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2265                             };
2266                             let mut struct_fmt = fmt.debug_struct(&name);
2267
2268                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2269                                 for (&var_id, place) in upvars.keys().zip(places) {
2270                                     let var_name = tcx.hir().name(var_id);
2271                                     struct_fmt.field(&var_name.as_str(), place);
2272                                 }
2273                             }
2274
2275                             struct_fmt.finish()
2276                         } else {
2277                             write!(fmt, "[closure]")
2278                         }
2279                     }),
2280
2281                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2282                         if let Some(def_id) = def_id.as_local() {
2283                             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2284                             let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2285                             let mut struct_fmt = fmt.debug_struct(&name);
2286
2287                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2288                                 for (&var_id, place) in upvars.keys().zip(places) {
2289                                     let var_name = tcx.hir().name(var_id);
2290                                     struct_fmt.field(&var_name.as_str(), place);
2291                                 }
2292                             }
2293
2294                             struct_fmt.finish()
2295                         } else {
2296                             write!(fmt, "[generator]")
2297                         }
2298                     }),
2299                 }
2300             }
2301         }
2302     }
2303 }
2304
2305 ///////////////////////////////////////////////////////////////////////////
2306 /// Constants
2307 ///
2308 /// Two constants are equal if they are the same constant. Note that
2309 /// this does not necessarily mean that they are `==` in Rust. In
2310 /// particular, one must be wary of `NaN`!
2311
2312 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2313 pub struct Constant<'tcx> {
2314     pub span: Span,
2315
2316     /// Optional user-given type: for something like
2317     /// `collect::<Vec<_>>`, this would be present and would
2318     /// indicate that `Vec<_>` was explicitly specified.
2319     ///
2320     /// Needed for NLL to impose user-given type constraints.
2321     pub user_ty: Option<UserTypeAnnotationIndex>,
2322
2323     pub literal: &'tcx ty::Const<'tcx>,
2324 }
2325
2326 impl Constant<'tcx> {
2327     pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2328         match self.literal.val.try_to_scalar() {
2329             Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2330                 GlobalAlloc::Static(def_id) => {
2331                     assert!(!tcx.is_thread_local_static(def_id));
2332                     Some(def_id)
2333                 }
2334                 _ => None,
2335             },
2336             _ => None,
2337         }
2338     }
2339 }
2340
2341 /// A collection of projections into user types.
2342 ///
2343 /// They are projections because a binding can occur a part of a
2344 /// parent pattern that has been ascribed a type.
2345 ///
2346 /// Its a collection because there can be multiple type ascriptions on
2347 /// the path from the root of the pattern down to the binding itself.
2348 ///
2349 /// An example:
2350 ///
2351 /// ```rust
2352 /// struct S<'a>((i32, &'a str), String);
2353 /// let S((_, w): (i32, &'static str), _): S = ...;
2354 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2355 /// //  ---------------------------------  ^ (2)
2356 /// ```
2357 ///
2358 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2359 /// ascribed the type `(i32, &'static str)`.
2360 ///
2361 /// The highlights labelled `(2)` show the whole pattern being
2362 /// ascribed the type `S`.
2363 ///
2364 /// In this example, when we descend to `w`, we will have built up the
2365 /// following two projected types:
2366 ///
2367 ///   * base: `S`,                   projection: `(base.0).1`
2368 ///   * base: `(i32, &'static str)`, projection: `base.1`
2369 ///
2370 /// The first will lead to the constraint `w: &'1 str` (for some
2371 /// inferred region `'1`). The second will lead to the constraint `w:
2372 /// &'static str`.
2373 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2374 pub struct UserTypeProjections {
2375     pub contents: Vec<(UserTypeProjection, Span)>,
2376 }
2377
2378 impl<'tcx> UserTypeProjections {
2379     pub fn none() -> Self {
2380         UserTypeProjections { contents: vec![] }
2381     }
2382
2383     pub fn is_empty(&self) -> bool {
2384         self.contents.is_empty()
2385     }
2386
2387     pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2388         UserTypeProjections { contents: projs.collect() }
2389     }
2390
2391     pub fn projections_and_spans(
2392         &self,
2393     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2394         self.contents.iter()
2395     }
2396
2397     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2398         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2399     }
2400
2401     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2402         self.contents.push((user_ty.clone(), span));
2403         self
2404     }
2405
2406     fn map_projections(
2407         mut self,
2408         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2409     ) -> Self {
2410         self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2411         self
2412     }
2413
2414     pub fn index(self) -> Self {
2415         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2416     }
2417
2418     pub fn subslice(self, from: u64, to: u64) -> Self {
2419         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2420     }
2421
2422     pub fn deref(self) -> Self {
2423         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2424     }
2425
2426     pub fn leaf(self, field: Field) -> Self {
2427         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2428     }
2429
2430     pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2431         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2432     }
2433 }
2434
2435 /// Encodes the effect of a user-supplied type annotation on the
2436 /// subcomponents of a pattern. The effect is determined by applying the
2437 /// given list of proejctions to some underlying base type. Often,
2438 /// the projection element list `projs` is empty, in which case this
2439 /// directly encodes a type in `base`. But in the case of complex patterns with
2440 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2441 /// in which case the `projs` vector is used.
2442 ///
2443 /// Examples:
2444 ///
2445 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2446 ///
2447 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2448 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2449 ///   determined by finding the type of the `.0` field from `T`.
2450 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2451 pub struct UserTypeProjection {
2452     pub base: UserTypeAnnotationIndex,
2453     pub projs: Vec<ProjectionKind>,
2454 }
2455
2456 impl Copy for ProjectionKind {}
2457
2458 impl UserTypeProjection {
2459     pub(crate) fn index(mut self) -> Self {
2460         self.projs.push(ProjectionElem::Index(()));
2461         self
2462     }
2463
2464     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2465         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2466         self
2467     }
2468
2469     pub(crate) fn deref(mut self) -> Self {
2470         self.projs.push(ProjectionElem::Deref);
2471         self
2472     }
2473
2474     pub(crate) fn leaf(mut self, field: Field) -> Self {
2475         self.projs.push(ProjectionElem::Field(field, ()));
2476         self
2477     }
2478
2479     pub(crate) fn variant(
2480         mut self,
2481         adt_def: &AdtDef,
2482         variant_index: VariantIdx,
2483         field: Field,
2484     ) -> Self {
2485         self.projs.push(ProjectionElem::Downcast(
2486             Some(adt_def.variants[variant_index].ident.name),
2487             variant_index,
2488         ));
2489         self.projs.push(ProjectionElem::Field(field, ()));
2490         self
2491     }
2492 }
2493
2494 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2495
2496 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2497     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2498         use crate::mir::ProjectionElem::*;
2499
2500         let base = self.base.fold_with(folder);
2501         let projs: Vec<_> = self
2502             .projs
2503             .iter()
2504             .map(|&elem| match elem {
2505                 Deref => Deref,
2506                 Field(f, ()) => Field(f, ()),
2507                 Index(()) => Index(()),
2508                 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2509                 ConstantIndex { offset, min_length, from_end } => {
2510                     ConstantIndex { offset, min_length, from_end }
2511                 }
2512                 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2513             })
2514             .collect();
2515
2516         UserTypeProjection { base, projs }
2517     }
2518
2519     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2520         self.base.visit_with(visitor)
2521         // Note: there's nothing in `self.proj` to visit.
2522     }
2523 }
2524
2525 rustc_index::newtype_index! {
2526     pub struct Promoted {
2527         derive [HashStable]
2528         DEBUG_FORMAT = "promoted[{}]"
2529     }
2530 }
2531
2532 impl<'tcx> Debug for Constant<'tcx> {
2533     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2534         write!(fmt, "{}", self)
2535     }
2536 }
2537
2538 impl<'tcx> Display for Constant<'tcx> {
2539     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2540         match self.literal.ty.kind() {
2541             ty::FnDef(..) => {}
2542             _ => write!(fmt, "const ")?,
2543         }
2544         pretty_print_const(self.literal, fmt, true)
2545     }
2546 }
2547
2548 fn pretty_print_const(
2549     c: &ty::Const<'tcx>,
2550     fmt: &mut Formatter<'_>,
2551     print_types: bool,
2552 ) -> fmt::Result {
2553     use crate::ty::print::PrettyPrinter;
2554     ty::tls::with(|tcx| {
2555         let literal = tcx.lift(&c).unwrap();
2556         let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2557         cx.print_alloc_ids = true;
2558         cx.pretty_print_const(literal, print_types)?;
2559         Ok(())
2560     })
2561 }
2562
2563 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2564     type Node = BasicBlock;
2565 }
2566
2567 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2568     #[inline]
2569     fn num_nodes(&self) -> usize {
2570         self.basic_blocks.len()
2571     }
2572 }
2573
2574 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2575     #[inline]
2576     fn start_node(&self) -> Self::Node {
2577         START_BLOCK
2578     }
2579 }
2580
2581 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2582     #[inline]
2583     fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2584         self.basic_blocks[node].terminator().successors().cloned()
2585     }
2586 }
2587
2588 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2589     type Item = BasicBlock;
2590     type Iter = iter::Cloned<Successors<'b>>;
2591 }
2592
2593 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2594     type Item = BasicBlock;
2595     type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2596 }
2597
2598 impl graph::WithPredecessors for Body<'tcx> {
2599     #[inline]
2600     fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2601         self.predecessors()[node].clone().into_iter()
2602     }
2603 }
2604
2605 /// `Location` represents the position of the start of the statement; or, if
2606 /// `statement_index` equals the number of statements, then the start of the
2607 /// terminator.
2608 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2609 pub struct Location {
2610     /// The block that the location is within.
2611     pub block: BasicBlock,
2612
2613     pub statement_index: usize,
2614 }
2615
2616 impl fmt::Debug for Location {
2617     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2618         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2619     }
2620 }
2621
2622 impl Location {
2623     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2624
2625     /// Returns the location immediately after this one within the enclosing block.
2626     ///
2627     /// Note that if this location represents a terminator, then the
2628     /// resulting location would be out of bounds and invalid.
2629     pub fn successor_within_block(&self) -> Location {
2630         Location { block: self.block, statement_index: self.statement_index + 1 }
2631     }
2632
2633     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2634     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2635         // If we are in the same block as the other location and are an earlier statement
2636         // then we are a predecessor of `other`.
2637         if self.block == other.block && self.statement_index < other.statement_index {
2638             return true;
2639         }
2640
2641         let predecessors = body.predecessors();
2642
2643         // If we're in another block, then we want to check that block is a predecessor of `other`.
2644         let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2645         let mut visited = FxHashSet::default();
2646
2647         while let Some(block) = queue.pop() {
2648             // If we haven't visited this block before, then make sure we visit it's predecessors.
2649             if visited.insert(block) {
2650                 queue.extend(predecessors[block].iter().cloned());
2651             } else {
2652                 continue;
2653             }
2654
2655             // If we found the block that `self` is in, then we are a predecessor of `other` (since
2656             // we found that block by looking at the predecessors of `other`).
2657             if self.block == block {
2658                 return true;
2659             }
2660         }
2661
2662         false
2663     }
2664
2665     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2666         if self.block == other.block {
2667             self.statement_index <= other.statement_index
2668         } else {
2669             dominators.is_dominated_by(other.block, self.block)
2670         }
2671     }
2672 }