]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Rollup merge of #60952 - dtolnay:heap, r=Amanieu
[rust.git] / src / librustc / mir / mod.rs
1 // ignore-tidy-filelength
2
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
4 //!
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
6
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, InlineAsm as HirInlineAsm};
10 use crate::mir::interpret::{ConstValue, InterpError, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_data_structures::graph::dominators::{dominators, Dominators};
16 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
17 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
18 use rustc_data_structures::sync::Lrc;
19 use rustc_data_structures::sync::MappedReadGuard;
20 use rustc_macros::HashStable;
21 use crate::rustc_serialize::{self as serialize};
22 use smallvec::SmallVec;
23 use std::borrow::Cow;
24 use std::fmt::{self, Debug, Formatter, Write};
25 use std::iter::FusedIterator;
26 use std::ops::{Index, IndexMut};
27 use std::slice;
28 use std::vec::IntoIter;
29 use std::{iter, mem, option, u32};
30 use syntax::ast::{self, Name};
31 use syntax::symbol::{InternedString, Symbol};
32 use syntax_pos::{Span, DUMMY_SP};
33 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
34 use crate::ty::subst::{Subst, SubstsRef};
35 use crate::ty::layout::VariantIdx;
36 use crate::ty::{
37     self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
38     UserTypeAnnotationIndex,
39 };
40 use crate::ty::print::{FmtPrinter, Printer};
41 use crate::ty::adjustment::{PointerCast};
42
43 pub use crate::mir::interpret::AssertMessage;
44
45 mod cache;
46 pub mod interpret;
47 pub mod mono;
48 pub mod tcx;
49 pub mod traversal;
50 pub mod visit;
51
52 /// Types for locals
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
54
55 pub trait HasLocalDecls<'tcx> {
56     fn local_decls(&self) -> &LocalDecls<'tcx>;
57 }
58
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60     fn local_decls(&self) -> &LocalDecls<'tcx> {
61         self
62     }
63 }
64
65 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
66     fn local_decls(&self) -> &LocalDecls<'tcx> {
67         &self.local_decls
68     }
69 }
70
71 /// The various "big phases" that MIR goes through.
72 ///
73 /// Warning: ordering of variants is significant
74 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
75 pub enum MirPhase {
76     Build = 0,
77     Const = 1,
78     Validated = 2,
79     Optimized = 3,
80 }
81
82 impl MirPhase {
83     /// Gets the index of the current MirPhase within the set of all MirPhases.
84     pub fn phase_index(&self) -> usize {
85         *self as usize
86     }
87 }
88
89 /// Lowered representation of a single function.
90 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
91 pub struct Mir<'tcx> {
92     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
93     /// that indexes into this vector.
94     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
95
96     /// Records how far through the "desugaring and optimization" process this particular
97     /// MIR has traversed. This is particularly useful when inlining, since in that context
98     /// we instantiate the promoted constants and add them to our promoted vector -- but those
99     /// promoted items have already been optimized, whereas ours have not. This field allows
100     /// us to see the difference and forego optimization on the inlined promoted items.
101     pub phase: MirPhase,
102
103     /// List of source scopes; these are referenced by statements
104     /// and used for debuginfo. Indexed by a `SourceScope`.
105     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
106
107     /// Crate-local information for each source scope, that can't (and
108     /// needn't) be tracked across crates.
109     pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
110
111     /// Rvalues promoted from this function, such as borrows of constants.
112     /// Each of them is the Mir of a constant with the fn's type parameters
113     /// in scope, but a separate set of locals.
114     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
115
116     /// Yields type of the function, if it is a generator.
117     pub yield_ty: Option<Ty<'tcx>>,
118
119     /// Generator drop glue
120     pub generator_drop: Option<Box<Mir<'tcx>>>,
121
122     /// The layout of a generator. Produced by the state transformation.
123     pub generator_layout: Option<GeneratorLayout<'tcx>>,
124
125     /// Declarations of locals.
126     ///
127     /// The first local is the return value pointer, followed by `arg_count`
128     /// locals for the function arguments, followed by any user-declared
129     /// variables and temporaries.
130     pub local_decls: LocalDecls<'tcx>,
131
132     /// User type annotations
133     pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
134
135     /// Number of arguments this function takes.
136     ///
137     /// Starting at local 1, `arg_count` locals will be provided by the caller
138     /// and can be assumed to be initialized.
139     ///
140     /// If this MIR was built for a constant, this will be 0.
141     pub arg_count: usize,
142
143     /// Mark an argument local (which must be a tuple) as getting passed as
144     /// its individual components at the LLVM level.
145     ///
146     /// This is used for the "rust-call" ABI.
147     pub spread_arg: Option<Local>,
148
149     /// Names and capture modes of all the closure upvars, assuming
150     /// the first argument is either the closure or a reference to it.
151     // NOTE(eddyb) This is *strictly* a temporary hack for codegen
152     // debuginfo generation, and will be removed at some point.
153     // Do **NOT** use it for anything else, upvar information should not be
154     // in the MIR, please rely on local crate HIR or other side-channels.
155     pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
156
157     /// Mark this MIR of a const context other than const functions as having converted a `&&` or
158     /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
159     /// this conversion from happening and use short circuiting, we will cause the following code
160     /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
161     ///
162     /// List of places where control flow was destroyed. Used for error reporting.
163     pub control_flow_destroyed: Vec<(Span, String)>,
164
165     /// A span representing this MIR, for error reporting
166     pub span: Span,
167
168     /// A cache for various calculations
169     cache: cache::Cache,
170 }
171
172 impl<'tcx> Mir<'tcx> {
173     pub fn new(
174         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
175         source_scopes: IndexVec<SourceScope, SourceScopeData>,
176         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
177         promoted: IndexVec<Promoted, Mir<'tcx>>,
178         yield_ty: Option<Ty<'tcx>>,
179         local_decls: LocalDecls<'tcx>,
180         user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
181         arg_count: usize,
182         __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
183         span: Span,
184         control_flow_destroyed: Vec<(Span, String)>,
185     ) -> Self {
186         // We need `arg_count` locals, and one for the return place
187         assert!(
188             local_decls.len() >= arg_count + 1,
189             "expected at least {} locals, got {}",
190             arg_count + 1,
191             local_decls.len()
192         );
193
194         Mir {
195             phase: MirPhase::Build,
196             basic_blocks,
197             source_scopes,
198             source_scope_local_data,
199             promoted,
200             yield_ty,
201             generator_drop: None,
202             generator_layout: None,
203             local_decls,
204             user_type_annotations,
205             arg_count,
206             __upvar_debuginfo_codegen_only_do_not_use,
207             spread_arg: None,
208             span,
209             cache: cache::Cache::new(),
210             control_flow_destroyed,
211         }
212     }
213
214     #[inline]
215     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
216         &self.basic_blocks
217     }
218
219     #[inline]
220     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
221         self.cache.invalidate();
222         &mut self.basic_blocks
223     }
224
225     #[inline]
226     pub fn basic_blocks_and_local_decls_mut(
227         &mut self,
228     ) -> (
229         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
230         &mut LocalDecls<'tcx>,
231     ) {
232         self.cache.invalidate();
233         (&mut self.basic_blocks, &mut self.local_decls)
234     }
235
236     #[inline]
237     pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
238         self.cache.predecessors(self)
239     }
240
241     #[inline]
242     pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
243         MappedReadGuard::map(self.predecessors(), |p| &p[bb])
244     }
245
246     #[inline]
247     pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
248         let if_zero_locations = if loc.statement_index == 0 {
249             let predecessor_blocks = self.predecessors_for(loc.block);
250             let num_predecessor_blocks = predecessor_blocks.len();
251             Some(
252                 (0..num_predecessor_blocks)
253                     .map(move |i| predecessor_blocks[i])
254                     .map(move |bb| self.terminator_loc(bb)),
255             )
256         } else {
257             None
258         };
259
260         let if_not_zero_locations = if loc.statement_index == 0 {
261             None
262         } else {
263             Some(Location {
264                 block: loc.block,
265                 statement_index: loc.statement_index - 1,
266             })
267         };
268
269         if_zero_locations
270             .into_iter()
271             .flatten()
272             .chain(if_not_zero_locations)
273     }
274
275     #[inline]
276     pub fn dominators(&self) -> Dominators<BasicBlock> {
277         dominators(self)
278     }
279
280     #[inline]
281     pub fn local_kind(&self, local: Local) -> LocalKind {
282         let index = local.as_usize();
283         if index == 0 {
284             debug_assert!(
285                 self.local_decls[local].mutability == Mutability::Mut,
286                 "return place should be mutable"
287             );
288
289             LocalKind::ReturnPointer
290         } else if index < self.arg_count + 1 {
291             LocalKind::Arg
292         } else if self.local_decls[local].name.is_some() {
293             LocalKind::Var
294         } else {
295             LocalKind::Temp
296         }
297     }
298
299     /// Returns an iterator over all temporaries.
300     #[inline]
301     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
302         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
303             let local = Local::new(index);
304             if self.local_decls[local].is_user_variable.is_some() {
305                 None
306             } else {
307                 Some(local)
308             }
309         })
310     }
311
312     /// Returns an iterator over all user-declared locals.
313     #[inline]
314     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
315         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
316             let local = Local::new(index);
317             if self.local_decls[local].is_user_variable.is_some() {
318                 Some(local)
319             } else {
320                 None
321             }
322         })
323     }
324
325     /// Returns an iterator over all user-declared mutable locals.
326     #[inline]
327     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
328         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
329             let local = Local::new(index);
330             let decl = &self.local_decls[local];
331             if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
332                 Some(local)
333             } else {
334                 None
335             }
336         })
337     }
338
339     /// Returns an iterator over all user-declared mutable arguments and locals.
340     #[inline]
341     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
342         (1..self.local_decls.len()).filter_map(move |index| {
343             let local = Local::new(index);
344             let decl = &self.local_decls[local];
345             if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
346                 && decl.mutability == Mutability::Mut
347             {
348                 Some(local)
349             } else {
350                 None
351             }
352         })
353     }
354
355     /// Returns an iterator over all function arguments.
356     #[inline]
357     pub fn args_iter(&self) -> impl Iterator<Item = Local> {
358         let arg_count = self.arg_count;
359         (1..=arg_count).map(Local::new)
360     }
361
362     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
363     /// locals that are neither arguments nor the return place).
364     #[inline]
365     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
366         let arg_count = self.arg_count;
367         let local_count = self.local_decls.len();
368         (arg_count + 1..local_count).map(Local::new)
369     }
370
371     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
372     /// invalidating statement indices in `Location`s.
373     pub fn make_statement_nop(&mut self, location: Location) {
374         let block = &mut self[location.block];
375         debug_assert!(location.statement_index < block.statements.len());
376         block.statements[location.statement_index].make_nop()
377     }
378
379     /// Returns the source info associated with `location`.
380     pub fn source_info(&self, location: Location) -> &SourceInfo {
381         let block = &self[location.block];
382         let stmts = &block.statements;
383         let idx = location.statement_index;
384         if idx < stmts.len() {
385             &stmts[idx].source_info
386         } else {
387             assert_eq!(idx, stmts.len());
388             &block.terminator().source_info
389         }
390     }
391
392     /// Checks if `sub` is a sub scope of `sup`
393     pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
394         while sub != sup {
395             match self.source_scopes[sub].parent_scope {
396                 None => return false,
397                 Some(p) => sub = p,
398             }
399         }
400         true
401     }
402
403     /// Returns the return type, it always return first element from `local_decls` array
404     pub fn return_ty(&self) -> Ty<'tcx> {
405         self.local_decls[RETURN_PLACE].ty
406     }
407
408     /// Gets the location of the terminator for the given block
409     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
410         Location {
411             block: bb,
412             statement_index: self[bb].statements.len(),
413         }
414     }
415 }
416
417 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
418 pub enum Safety {
419     Safe,
420     /// Unsafe because of a PushUnsafeBlock
421     BuiltinUnsafe,
422     /// Unsafe because of an unsafe fn
423     FnUnsafe,
424     /// Unsafe because of an `unsafe` block
425     ExplicitUnsafe(hir::HirId),
426 }
427
428 impl_stable_hash_for!(struct Mir<'tcx> {
429     phase,
430     basic_blocks,
431     source_scopes,
432     source_scope_local_data,
433     promoted,
434     yield_ty,
435     generator_drop,
436     generator_layout,
437     local_decls,
438     user_type_annotations,
439     arg_count,
440     __upvar_debuginfo_codegen_only_do_not_use,
441     spread_arg,
442     control_flow_destroyed,
443     span,
444     cache
445 });
446
447 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
448     type Output = BasicBlockData<'tcx>;
449
450     #[inline]
451     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
452         &self.basic_blocks()[index]
453     }
454 }
455
456 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
457     #[inline]
458     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
459         &mut self.basic_blocks_mut()[index]
460     }
461 }
462
463 #[derive(Copy, Clone, Debug, HashStable)]
464 pub enum ClearCrossCrate<T> {
465     Clear,
466     Set(T),
467 }
468
469 impl<T> ClearCrossCrate<T> {
470     pub fn assert_crate_local(self) -> T {
471         match self {
472             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
473             ClearCrossCrate::Set(v) => v,
474         }
475     }
476 }
477
478 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
479 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
480
481 /// Grouped information about the source code origin of a MIR entity.
482 /// Intended to be inspected by diagnostics and debuginfo.
483 /// Most passes can work with it as a whole, within a single function.
484 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
485 pub struct SourceInfo {
486     /// Source span for the AST pertaining to this MIR entity.
487     pub span: Span,
488
489     /// The source scope, keeping track of which bindings can be
490     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
491     pub scope: SourceScope,
492 }
493
494 ///////////////////////////////////////////////////////////////////////////
495 // Mutability and borrow kinds
496
497 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
498 pub enum Mutability {
499     Mut,
500     Not,
501 }
502
503 impl From<Mutability> for hir::Mutability {
504     fn from(m: Mutability) -> Self {
505         match m {
506             Mutability::Mut => hir::MutMutable,
507             Mutability::Not => hir::MutImmutable,
508         }
509     }
510 }
511
512 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd,
513          Ord, RustcEncodable, RustcDecodable, HashStable)]
514 pub enum BorrowKind {
515     /// Data must be immutable and is aliasable.
516     Shared,
517
518     /// The immediately borrowed place must be immutable, but projections from
519     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
520     /// conflict with a mutable borrow of `a.b.c`.
521     ///
522     /// This is used when lowering matches: when matching on a place we want to
523     /// ensure that place have the same value from the start of the match until
524     /// an arm is selected. This prevents this code from compiling:
525     ///
526     ///     let mut x = &Some(0);
527     ///     match *x {
528     ///         None => (),
529     ///         Some(_) if { x = &None; false } => (),
530     ///         Some(_) => (),
531     ///     }
532     ///
533     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
534     /// should not prevent `if let None = x { ... }`, for example, because the
535     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
536     /// We can also report errors with this kind of borrow differently.
537     Shallow,
538
539     /// Data must be immutable but not aliasable. This kind of borrow
540     /// cannot currently be expressed by the user and is used only in
541     /// implicit closure bindings. It is needed when the closure is
542     /// borrowing or mutating a mutable referent, e.g.:
543     ///
544     ///     let x: &mut isize = ...;
545     ///     let y = || *x += 5;
546     ///
547     /// If we were to try to translate this closure into a more explicit
548     /// form, we'd encounter an error with the code as written:
549     ///
550     ///     struct Env { x: & &mut isize }
551     ///     let x: &mut isize = ...;
552     ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
553     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
554     ///
555     /// This is then illegal because you cannot mutate an `&mut` found
556     /// in an aliasable location. To solve, you'd have to translate with
557     /// an `&mut` borrow:
558     ///
559     ///     struct Env { x: & &mut isize }
560     ///     let x: &mut isize = ...;
561     ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
562     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
563     ///
564     /// Now the assignment to `**env.x` is legal, but creating a
565     /// mutable pointer to `x` is not because `x` is not mutable. We
566     /// could fix this by declaring `x` as `let mut x`. This is ok in
567     /// user code, if awkward, but extra weird for closures, since the
568     /// borrow is hidden.
569     ///
570     /// So we introduce a "unique imm" borrow -- the referent is
571     /// immutable, but not aliasable. This solves the problem. For
572     /// simplicity, we don't give users the way to express this
573     /// borrow, it's just used when translating closures.
574     Unique,
575
576     /// Data is mutable and not aliasable.
577     Mut {
578         /// `true` if this borrow arose from method-call auto-ref
579         /// (i.e., `adjustment::Adjust::Borrow`).
580         allow_two_phase_borrow: bool,
581     },
582 }
583
584 impl BorrowKind {
585     pub fn allows_two_phase_borrow(&self) -> bool {
586         match *self {
587             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
588             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
589         }
590     }
591 }
592
593 ///////////////////////////////////////////////////////////////////////////
594 // Variables and temps
595
596 newtype_index! {
597     pub struct Local {
598         derive [HashStable]
599         DEBUG_FORMAT = "_{}",
600         const RETURN_PLACE = 0,
601     }
602 }
603
604 /// Classifies locals into categories. See `Mir::local_kind`.
605 #[derive(PartialEq, Eq, Debug, HashStable)]
606 pub enum LocalKind {
607     /// User-declared variable binding
608     Var,
609     /// Compiler-introduced temporary
610     Temp,
611     /// Function argument
612     Arg,
613     /// Location of function's return value
614     ReturnPointer,
615 }
616
617 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
618 pub struct VarBindingForm<'tcx> {
619     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
620     pub binding_mode: ty::BindingMode,
621     /// If an explicit type was provided for this variable binding,
622     /// this holds the source Span of that type.
623     ///
624     /// NOTE: if you want to change this to a `HirId`, be wary that
625     /// doing so breaks incremental compilation (as of this writing),
626     /// while a `Span` does not cause our tests to fail.
627     pub opt_ty_info: Option<Span>,
628     /// Place of the RHS of the =, or the subject of the `match` where this
629     /// variable is initialized. None in the case of `let PATTERN;`.
630     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
631     /// (a) the right-hand side isn't evaluated as a place expression.
632     /// (b) it gives a way to separate this case from the remaining cases
633     ///     for diagnostics.
634     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
635     /// Span of the pattern in which this variable was bound.
636     pub pat_span: Span,
637 }
638
639 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
640 pub enum BindingForm<'tcx> {
641     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
642     Var(VarBindingForm<'tcx>),
643     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
644     ImplicitSelf(ImplicitSelfKind),
645     /// Reference used in a guard expression to ensure immutability.
646     RefForGuard,
647 }
648
649 /// Represents what type of implicit self a function has, if any.
650 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
651 pub enum ImplicitSelfKind {
652     /// Represents a `fn x(self);`.
653     Imm,
654     /// Represents a `fn x(mut self);`.
655     Mut,
656     /// Represents a `fn x(&self);`.
657     ImmRef,
658     /// Represents a `fn x(&mut self);`.
659     MutRef,
660     /// Represents when a function does not have a self argument or
661     /// when a function has a `self: X` argument.
662     None
663 }
664
665 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
666
667 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
668     binding_mode,
669     opt_ty_info,
670     opt_match_place,
671     pat_span
672 });
673
674 impl_stable_hash_for!(enum self::ImplicitSelfKind {
675     Imm,
676     Mut,
677     ImmRef,
678     MutRef,
679     None
680 });
681
682 impl_stable_hash_for!(enum self::MirPhase {
683     Build,
684     Const,
685     Validated,
686     Optimized,
687 });
688
689 mod binding_form_impl {
690     use crate::ich::StableHashingContext;
691     use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
692
693     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
694         fn hash_stable<W: StableHasherResult>(
695             &self,
696             hcx: &mut StableHashingContext<'a>,
697             hasher: &mut StableHasher<W>,
698         ) {
699             use super::BindingForm::*;
700             ::std::mem::discriminant(self).hash_stable(hcx, hasher);
701
702             match self {
703                 Var(binding) => binding.hash_stable(hcx, hasher),
704                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
705                 RefForGuard => (),
706             }
707         }
708     }
709 }
710
711 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
712 /// created during evaluation of expressions in a block tail
713 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
714 ///
715 /// It is used to improve diagnostics when such temporaries are
716 /// involved in borrow_check errors, e.g., explanations of where the
717 /// temporaries come from, when their destructors are run, and/or how
718 /// one might revise the code to satisfy the borrow checker's rules.
719 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
720 pub struct BlockTailInfo {
721     /// If `true`, then the value resulting from evaluating this tail
722     /// expression is ignored by the block's expression context.
723     ///
724     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
725     /// but not e.g., `let _x = { ...; tail };`
726     pub tail_result_is_ignored: bool,
727 }
728
729 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
730
731 /// A MIR local.
732 ///
733 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
734 /// argument, or the return place.
735 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
736 pub struct LocalDecl<'tcx> {
737     /// `let mut x` vs `let x`.
738     ///
739     /// Temporaries and the return place are always mutable.
740     pub mutability: Mutability,
741
742     /// Some(binding_mode) if this corresponds to a user-declared local variable.
743     ///
744     /// This is solely used for local diagnostics when generating
745     /// warnings/errors when compiling the current crate, and
746     /// therefore it need not be visible across crates. pnkfelix
747     /// currently hypothesized we *need* to wrap this in a
748     /// `ClearCrossCrate` as long as it carries as `HirId`.
749     pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
750
751     /// `true` if this is an internal local.
752     ///
753     /// These locals are not based on types in the source code and are only used
754     /// for a few desugarings at the moment.
755     ///
756     /// The generator transformation will sanity check the locals which are live
757     /// across a suspension point against the type components of the generator
758     /// which type checking knows are live across a suspension point. We need to
759     /// flag drop flags to avoid triggering this check as they are introduced
760     /// after typeck.
761     ///
762     /// Unsafety checking will also ignore dereferences of these locals,
763     /// so they can be used for raw pointers only used in a desugaring.
764     ///
765     /// This should be sound because the drop flags are fully algebraic, and
766     /// therefore don't affect the OIBIT or outlives properties of the
767     /// generator.
768     pub internal: bool,
769
770     /// If this local is a temporary and `is_block_tail` is `Some`,
771     /// then it is a temporary created for evaluation of some
772     /// subexpression of some block's tail expression (with no
773     /// intervening statement context).
774     pub is_block_tail: Option<BlockTailInfo>,
775
776     /// Type of this local.
777     pub ty: Ty<'tcx>,
778
779     /// If the user manually ascribed a type to this variable,
780     /// e.g., via `let x: T`, then we carry that type here. The MIR
781     /// borrow checker needs this information since it can affect
782     /// region inference.
783     pub user_ty: UserTypeProjections,
784
785     /// Name of the local, used in debuginfo and pretty-printing.
786     ///
787     /// Note that function arguments can also have this set to `Some(_)`
788     /// to generate better debuginfo.
789     pub name: Option<Name>,
790
791     /// The *syntactic* (i.e., not visibility) source scope the local is defined
792     /// in. If the local was defined in a let-statement, this
793     /// is *within* the let-statement, rather than outside
794     /// of it.
795     ///
796     /// This is needed because the visibility source scope of locals within
797     /// a let-statement is weird.
798     ///
799     /// The reason is that we want the local to be *within* the let-statement
800     /// for lint purposes, but we want the local to be *after* the let-statement
801     /// for names-in-scope purposes.
802     ///
803     /// That's it, if we have a let-statement like the one in this
804     /// function:
805     ///
806     /// ```
807     /// fn foo(x: &str) {
808     ///     #[allow(unused_mut)]
809     ///     let mut x: u32 = { // <- one unused mut
810     ///         let mut y: u32 = x.parse().unwrap();
811     ///         y + 2
812     ///     };
813     ///     drop(x);
814     /// }
815     /// ```
816     ///
817     /// Then, from a lint point of view, the declaration of `x: u32`
818     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
819     /// lint scopes are the same as the AST/HIR nesting.
820     ///
821     /// However, from a name lookup point of view, the scopes look more like
822     /// as if the let-statements were `match` expressions:
823     ///
824     /// ```
825     /// fn foo(x: &str) {
826     ///     match {
827     ///         match x.parse().unwrap() {
828     ///             y => y + 2
829     ///         }
830     ///     } {
831     ///         x => drop(x)
832     ///     };
833     /// }
834     /// ```
835     ///
836     /// We care about the name-lookup scopes for debuginfo - if the
837     /// debuginfo instruction pointer is at the call to `x.parse()`, we
838     /// want `x` to refer to `x: &str`, but if it is at the call to
839     /// `drop(x)`, we want it to refer to `x: u32`.
840     ///
841     /// To allow both uses to work, we need to have more than a single scope
842     /// for a local. We have the `source_info.scope` represent the
843     /// "syntactic" lint scope (with a variable being under its let
844     /// block) while the `visibility_scope` represents the "local variable"
845     /// scope (where the "rest" of a block is under all prior let-statements).
846     ///
847     /// The end result looks like this:
848     ///
849     /// ```text
850     /// ROOT SCOPE
851     ///  │{ argument x: &str }
852     ///  │
853     ///  │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
854     ///  │ │                        // in practice because I'm lazy.
855     ///  │ │
856     ///  │ │← x.source_info.scope
857     ///  │ │← `x.parse().unwrap()`
858     ///  │ │
859     ///  │ │ │← y.source_info.scope
860     ///  │ │
861     ///  │ │ │{ let y: u32 }
862     ///  │ │ │
863     ///  │ │ │← y.visibility_scope
864     ///  │ │ │← `y + 2`
865     ///  │
866     ///  │ │{ let x: u32 }
867     ///  │ │← x.visibility_scope
868     ///  │ │← `drop(x)` // this accesses `x: u32`
869     /// ```
870     pub source_info: SourceInfo,
871
872     /// Source scope within which the local is visible (for debuginfo)
873     /// (see `source_info` for more details).
874     pub visibility_scope: SourceScope,
875 }
876
877 impl<'tcx> LocalDecl<'tcx> {
878     /// Returns `true` only if local is a binding that can itself be
879     /// made mutable via the addition of the `mut` keyword, namely
880     /// something like the occurrences of `x` in:
881     /// - `fn foo(x: Type) { ... }`,
882     /// - `let x = ...`,
883     /// - or `match ... { C(x) => ... }`
884     pub fn can_be_made_mutable(&self) -> bool {
885         match self.is_user_variable {
886             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
887                 binding_mode: ty::BindingMode::BindByValue(_),
888                 opt_ty_info: _,
889                 opt_match_place: _,
890                 pat_span: _,
891             }))) => true,
892
893             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
894                 => true,
895
896             _ => false,
897         }
898     }
899
900     /// Returns `true` if local is definitely not a `ref ident` or
901     /// `ref mut ident` binding. (Such bindings cannot be made into
902     /// mutable bindings, but the inverse does not necessarily hold).
903     pub fn is_nonref_binding(&self) -> bool {
904         match self.is_user_variable {
905             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
906                 binding_mode: ty::BindingMode::BindByValue(_),
907                 opt_ty_info: _,
908                 opt_match_place: _,
909                 pat_span: _,
910             }))) => true,
911
912             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
913
914             _ => false,
915         }
916     }
917
918     /// Creates a new `LocalDecl` for a temporary.
919     #[inline]
920     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
921         Self::new_local(ty, Mutability::Mut, false, span)
922     }
923
924     /// Converts `self` into same `LocalDecl` except tagged as immutable.
925     #[inline]
926     pub fn immutable(mut self) -> Self {
927         self.mutability = Mutability::Not;
928         self
929     }
930
931     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
932     #[inline]
933     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
934         assert!(self.is_block_tail.is_none());
935         self.is_block_tail = Some(info);
936         self
937     }
938
939     /// Creates a new `LocalDecl` for a internal temporary.
940     #[inline]
941     pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
942         Self::new_local(ty, Mutability::Mut, true, span)
943     }
944
945     #[inline]
946     fn new_local(
947         ty: Ty<'tcx>,
948         mutability: Mutability,
949         internal: bool,
950         span: Span,
951     ) -> Self {
952         LocalDecl {
953             mutability,
954             ty,
955             user_ty: UserTypeProjections::none(),
956             name: None,
957             source_info: SourceInfo {
958                 span,
959                 scope: OUTERMOST_SOURCE_SCOPE,
960             },
961             visibility_scope: OUTERMOST_SOURCE_SCOPE,
962             internal,
963             is_user_variable: None,
964             is_block_tail: None,
965         }
966     }
967
968     /// Builds a `LocalDecl` for the return place.
969     ///
970     /// This must be inserted into the `local_decls` list as the first local.
971     #[inline]
972     pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
973         LocalDecl {
974             mutability: Mutability::Mut,
975             ty: return_ty,
976             user_ty: UserTypeProjections::none(),
977             source_info: SourceInfo {
978                 span,
979                 scope: OUTERMOST_SOURCE_SCOPE,
980             },
981             visibility_scope: OUTERMOST_SOURCE_SCOPE,
982             internal: false,
983             is_block_tail: None,
984             name: None, // FIXME maybe we do want some name here?
985             is_user_variable: None,
986         }
987     }
988 }
989
990 /// A closure capture, with its name and mode.
991 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
992 pub struct UpvarDebuginfo {
993     pub debug_name: Name,
994
995     /// If true, the capture is behind a reference.
996     pub by_ref: bool,
997 }
998
999 ///////////////////////////////////////////////////////////////////////////
1000 // BasicBlock
1001
1002 newtype_index! {
1003     pub struct BasicBlock {
1004         derive [HashStable]
1005         DEBUG_FORMAT = "bb{}",
1006         const START_BLOCK = 0,
1007     }
1008 }
1009
1010 impl BasicBlock {
1011     pub fn start_location(self) -> Location {
1012         Location {
1013             block: self,
1014             statement_index: 0,
1015         }
1016     }
1017 }
1018
1019 ///////////////////////////////////////////////////////////////////////////
1020 // BasicBlockData and Terminator
1021
1022 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1023 pub struct BasicBlockData<'tcx> {
1024     /// List of statements in this block.
1025     pub statements: Vec<Statement<'tcx>>,
1026
1027     /// Terminator for this block.
1028     ///
1029     /// N.B., this should generally ONLY be `None` during construction.
1030     /// Therefore, you should generally access it via the
1031     /// `terminator()` or `terminator_mut()` methods. The only
1032     /// exception is that certain passes, such as `simplify_cfg`, swap
1033     /// out the terminator temporarily with `None` while they continue
1034     /// to recurse over the set of basic blocks.
1035     pub terminator: Option<Terminator<'tcx>>,
1036
1037     /// If true, this block lies on an unwind path. This is used
1038     /// during codegen where distinct kinds of basic blocks may be
1039     /// generated (particularly for MSVC cleanup). Unwind blocks must
1040     /// only branch to other unwind blocks.
1041     pub is_cleanup: bool,
1042 }
1043
1044 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1045 pub struct Terminator<'tcx> {
1046     pub source_info: SourceInfo,
1047     pub kind: TerminatorKind<'tcx>,
1048 }
1049
1050 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1051 pub enum TerminatorKind<'tcx> {
1052     /// block should have one successor in the graph; we jump there
1053     Goto { target: BasicBlock },
1054
1055     /// operand evaluates to an integer; jump depending on its value
1056     /// to one of the targets, and otherwise fallback to `otherwise`
1057     SwitchInt {
1058         /// discriminant value being tested
1059         discr: Operand<'tcx>,
1060
1061         /// type of value being tested
1062         switch_ty: Ty<'tcx>,
1063
1064         /// Possible values. The locations to branch to in each case
1065         /// are found in the corresponding indices from the `targets` vector.
1066         values: Cow<'tcx, [u128]>,
1067
1068         /// Possible branch sites. The last element of this vector is used
1069         /// for the otherwise branch, so targets.len() == values.len() + 1
1070         /// should hold.
1071         // This invariant is quite non-obvious and also could be improved.
1072         // One way to make this invariant is to have something like this instead:
1073         //
1074         // branches: Vec<(ConstInt, BasicBlock)>,
1075         // otherwise: Option<BasicBlock> // exhaustive if None
1076         //
1077         // However we’ve decided to keep this as-is until we figure a case
1078         // where some other approach seems to be strictly better than other.
1079         targets: Vec<BasicBlock>,
1080     },
1081
1082     /// Indicates that the landing pad is finished and unwinding should
1083     /// continue. Emitted by build::scope::diverge_cleanup.
1084     Resume,
1085
1086     /// Indicates that the landing pad is finished and that the process
1087     /// should abort. Used to prevent unwinding for foreign items.
1088     Abort,
1089
1090     /// Indicates a normal return. The return place should have
1091     /// been filled in by now. This should occur at most once.
1092     Return,
1093
1094     /// Indicates a terminator that can never be reached.
1095     Unreachable,
1096
1097     /// Drop the Place
1098     Drop {
1099         location: Place<'tcx>,
1100         target: BasicBlock,
1101         unwind: Option<BasicBlock>,
1102     },
1103
1104     /// Drop the Place and assign the new value over it. This ensures
1105     /// that the assignment to `P` occurs *even if* the destructor for
1106     /// place unwinds. Its semantics are best explained by the
1107     /// elaboration:
1108     ///
1109     /// ```
1110     /// BB0 {
1111     ///   DropAndReplace(P <- V, goto BB1, unwind BB2)
1112     /// }
1113     /// ```
1114     ///
1115     /// becomes
1116     ///
1117     /// ```
1118     /// BB0 {
1119     ///   Drop(P, goto BB1, unwind BB2)
1120     /// }
1121     /// BB1 {
1122     ///   // P is now uninitialized
1123     ///   P <- V
1124     /// }
1125     /// BB2 {
1126     ///   // P is now uninitialized -- its dtor panicked
1127     ///   P <- V
1128     /// }
1129     /// ```
1130     DropAndReplace {
1131         location: Place<'tcx>,
1132         value: Operand<'tcx>,
1133         target: BasicBlock,
1134         unwind: Option<BasicBlock>,
1135     },
1136
1137     /// Block ends with a call of a converging function
1138     Call {
1139         /// The function that’s being called
1140         func: Operand<'tcx>,
1141         /// Arguments the function is called with.
1142         /// These are owned by the callee, which is free to modify them.
1143         /// This allows the memory occupied by "by-value" arguments to be
1144         /// reused across function calls without duplicating the contents.
1145         args: Vec<Operand<'tcx>>,
1146         /// Destination for the return value. If some, the call is converging.
1147         destination: Option<(Place<'tcx>, BasicBlock)>,
1148         /// Cleanups to be done if the call unwinds.
1149         cleanup: Option<BasicBlock>,
1150         /// Whether this is from a call in HIR, rather than from an overloaded
1151         /// operator. True for overloaded function call.
1152         from_hir_call: bool,
1153     },
1154
1155     /// Jump to the target if the condition has the expected value,
1156     /// otherwise panic with a message and a cleanup target.
1157     Assert {
1158         cond: Operand<'tcx>,
1159         expected: bool,
1160         msg: AssertMessage<'tcx>,
1161         target: BasicBlock,
1162         cleanup: Option<BasicBlock>,
1163     },
1164
1165     /// A suspend point
1166     Yield {
1167         /// The value to return
1168         value: Operand<'tcx>,
1169         /// Where to resume to
1170         resume: BasicBlock,
1171         /// Cleanup to be done if the generator is dropped at this suspend point
1172         drop: Option<BasicBlock>,
1173     },
1174
1175     /// Indicates the end of the dropping of a generator
1176     GeneratorDrop,
1177
1178     /// A block where control flow only ever takes one real path, but borrowck
1179     /// needs to be more conservative.
1180     FalseEdges {
1181         /// The target normal control flow will take
1182         real_target: BasicBlock,
1183         /// The list of blocks control flow could conceptually take, but won't
1184         /// in practice
1185         imaginary_targets: Vec<BasicBlock>,
1186     },
1187     /// A terminator for blocks that only take one path in reality, but where we
1188     /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1189     /// This can arise in infinite loops with no function calls for example.
1190     FalseUnwind {
1191         /// The target normal control flow will take
1192         real_target: BasicBlock,
1193         /// The imaginary cleanup block link. This particular path will never be taken
1194         /// in practice, but in order to avoid fragility we want to always
1195         /// consider it in borrowck. We don't want to accept programs which
1196         /// pass borrowck only when panic=abort or some assertions are disabled
1197         /// due to release vs. debug mode builds. This needs to be an Option because
1198         /// of the remove_noop_landing_pads and no_landing_pads passes
1199         unwind: Option<BasicBlock>,
1200     },
1201 }
1202
1203 pub type Successors<'a> =
1204     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1205 pub type SuccessorsMut<'a> =
1206     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1207
1208 impl<'tcx> Terminator<'tcx> {
1209     pub fn successors(&self) -> Successors<'_> {
1210         self.kind.successors()
1211     }
1212
1213     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1214         self.kind.successors_mut()
1215     }
1216
1217     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1218         self.kind.unwind()
1219     }
1220
1221     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1222         self.kind.unwind_mut()
1223     }
1224 }
1225
1226 impl<'tcx> TerminatorKind<'tcx> {
1227     pub fn if_<'a, 'gcx>(
1228         tcx: TyCtxt<'a, 'gcx, 'tcx>,
1229         cond: Operand<'tcx>,
1230         t: BasicBlock,
1231         f: BasicBlock,
1232     ) -> TerminatorKind<'tcx> {
1233         static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1234         TerminatorKind::SwitchInt {
1235             discr: cond,
1236             switch_ty: tcx.types.bool,
1237             values: From::from(BOOL_SWITCH_FALSE),
1238             targets: vec![f, t],
1239         }
1240     }
1241
1242     pub fn successors(&self) -> Successors<'_> {
1243         use self::TerminatorKind::*;
1244         match *self {
1245             Resume
1246             | Abort
1247             | GeneratorDrop
1248             | Return
1249             | Unreachable
1250             | Call {
1251                 destination: None,
1252                 cleanup: None,
1253                 ..
1254             } => None.into_iter().chain(&[]),
1255             Goto { target: ref t }
1256             | Call {
1257                 destination: None,
1258                 cleanup: Some(ref t),
1259                 ..
1260             }
1261             | Call {
1262                 destination: Some((_, ref t)),
1263                 cleanup: None,
1264                 ..
1265             }
1266             | Yield {
1267                 resume: ref t,
1268                 drop: None,
1269                 ..
1270             }
1271             | DropAndReplace {
1272                 target: ref t,
1273                 unwind: None,
1274                 ..
1275             }
1276             | Drop {
1277                 target: ref t,
1278                 unwind: None,
1279                 ..
1280             }
1281             | Assert {
1282                 target: ref t,
1283                 cleanup: None,
1284                 ..
1285             }
1286             | FalseUnwind {
1287                 real_target: ref t,
1288                 unwind: None,
1289             } => Some(t).into_iter().chain(&[]),
1290             Call {
1291                 destination: Some((_, ref t)),
1292                 cleanup: Some(ref u),
1293                 ..
1294             }
1295             | Yield {
1296                 resume: ref t,
1297                 drop: Some(ref u),
1298                 ..
1299             }
1300             | DropAndReplace {
1301                 target: ref t,
1302                 unwind: Some(ref u),
1303                 ..
1304             }
1305             | Drop {
1306                 target: ref t,
1307                 unwind: Some(ref u),
1308                 ..
1309             }
1310             | Assert {
1311                 target: ref t,
1312                 cleanup: Some(ref u),
1313                 ..
1314             }
1315             | FalseUnwind {
1316                 real_target: ref t,
1317                 unwind: Some(ref u),
1318             } => Some(t).into_iter().chain(slice::from_ref(u)),
1319             SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1320             FalseEdges {
1321                 ref real_target,
1322                 ref imaginary_targets,
1323             } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1324         }
1325     }
1326
1327     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1328         use self::TerminatorKind::*;
1329         match *self {
1330             Resume
1331             | Abort
1332             | GeneratorDrop
1333             | Return
1334             | Unreachable
1335             | Call {
1336                 destination: None,
1337                 cleanup: None,
1338                 ..
1339             } => None.into_iter().chain(&mut []),
1340             Goto { target: ref mut t }
1341             | Call {
1342                 destination: None,
1343                 cleanup: Some(ref mut t),
1344                 ..
1345             }
1346             | Call {
1347                 destination: Some((_, ref mut t)),
1348                 cleanup: None,
1349                 ..
1350             }
1351             | Yield {
1352                 resume: ref mut t,
1353                 drop: None,
1354                 ..
1355             }
1356             | DropAndReplace {
1357                 target: ref mut t,
1358                 unwind: None,
1359                 ..
1360             }
1361             | Drop {
1362                 target: ref mut t,
1363                 unwind: None,
1364                 ..
1365             }
1366             | Assert {
1367                 target: ref mut t,
1368                 cleanup: None,
1369                 ..
1370             }
1371             | FalseUnwind {
1372                 real_target: ref mut t,
1373                 unwind: None,
1374             } => Some(t).into_iter().chain(&mut []),
1375             Call {
1376                 destination: Some((_, ref mut t)),
1377                 cleanup: Some(ref mut u),
1378                 ..
1379             }
1380             | Yield {
1381                 resume: ref mut t,
1382                 drop: Some(ref mut u),
1383                 ..
1384             }
1385             | DropAndReplace {
1386                 target: ref mut t,
1387                 unwind: Some(ref mut u),
1388                 ..
1389             }
1390             | Drop {
1391                 target: ref mut t,
1392                 unwind: Some(ref mut u),
1393                 ..
1394             }
1395             | Assert {
1396                 target: ref mut t,
1397                 cleanup: Some(ref mut u),
1398                 ..
1399             }
1400             | FalseUnwind {
1401                 real_target: ref mut t,
1402                 unwind: Some(ref mut u),
1403             } => Some(t).into_iter().chain(slice::from_mut(u)),
1404             SwitchInt {
1405                 ref mut targets, ..
1406             } => None.into_iter().chain(&mut targets[..]),
1407             FalseEdges {
1408                 ref mut real_target,
1409                 ref mut imaginary_targets,
1410             } => Some(real_target)
1411                 .into_iter()
1412                 .chain(&mut imaginary_targets[..]),
1413         }
1414     }
1415
1416     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1417         match *self {
1418             TerminatorKind::Goto { .. }
1419             | TerminatorKind::Resume
1420             | TerminatorKind::Abort
1421             | TerminatorKind::Return
1422             | TerminatorKind::Unreachable
1423             | TerminatorKind::GeneratorDrop
1424             | TerminatorKind::Yield { .. }
1425             | TerminatorKind::SwitchInt { .. }
1426             | TerminatorKind::FalseEdges { .. } => None,
1427             TerminatorKind::Call {
1428                 cleanup: ref unwind,
1429                 ..
1430             }
1431             | TerminatorKind::Assert {
1432                 cleanup: ref unwind,
1433                 ..
1434             }
1435             | TerminatorKind::DropAndReplace { ref unwind, .. }
1436             | TerminatorKind::Drop { ref unwind, .. }
1437             | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1438         }
1439     }
1440
1441     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1442         match *self {
1443             TerminatorKind::Goto { .. }
1444             | TerminatorKind::Resume
1445             | TerminatorKind::Abort
1446             | TerminatorKind::Return
1447             | TerminatorKind::Unreachable
1448             | TerminatorKind::GeneratorDrop
1449             | TerminatorKind::Yield { .. }
1450             | TerminatorKind::SwitchInt { .. }
1451             | TerminatorKind::FalseEdges { .. } => None,
1452             TerminatorKind::Call {
1453                 cleanup: ref mut unwind,
1454                 ..
1455             }
1456             | TerminatorKind::Assert {
1457                 cleanup: ref mut unwind,
1458                 ..
1459             }
1460             | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1461             | TerminatorKind::Drop { ref mut unwind, .. }
1462             | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1463         }
1464     }
1465 }
1466
1467 impl<'tcx> BasicBlockData<'tcx> {
1468     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1469         BasicBlockData {
1470             statements: vec![],
1471             terminator,
1472             is_cleanup: false,
1473         }
1474     }
1475
1476     /// Accessor for terminator.
1477     ///
1478     /// Terminator may not be None after construction of the basic block is complete. This accessor
1479     /// provides a convenience way to reach the terminator.
1480     pub fn terminator(&self) -> &Terminator<'tcx> {
1481         self.terminator.as_ref().expect("invalid terminator state")
1482     }
1483
1484     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1485         self.terminator.as_mut().expect("invalid terminator state")
1486     }
1487
1488     pub fn retain_statements<F>(&mut self, mut f: F)
1489     where
1490         F: FnMut(&mut Statement<'_>) -> bool,
1491     {
1492         for s in &mut self.statements {
1493             if !f(s) {
1494                 s.make_nop();
1495             }
1496         }
1497     }
1498
1499     pub fn expand_statements<F, I>(&mut self, mut f: F)
1500     where
1501         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1502         I: iter::TrustedLen<Item = Statement<'tcx>>,
1503     {
1504         // Gather all the iterators we'll need to splice in, and their positions.
1505         let mut splices: Vec<(usize, I)> = vec![];
1506         let mut extra_stmts = 0;
1507         for (i, s) in self.statements.iter_mut().enumerate() {
1508             if let Some(mut new_stmts) = f(s) {
1509                 if let Some(first) = new_stmts.next() {
1510                     // We can already store the first new statement.
1511                     *s = first;
1512
1513                     // Save the other statements for optimized splicing.
1514                     let remaining = new_stmts.size_hint().0;
1515                     if remaining > 0 {
1516                         splices.push((i + 1 + extra_stmts, new_stmts));
1517                         extra_stmts += remaining;
1518                     }
1519                 } else {
1520                     s.make_nop();
1521                 }
1522             }
1523         }
1524
1525         // Splice in the new statements, from the end of the block.
1526         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1527         // where a range of elements ("gap") is left uninitialized, with
1528         // splicing adding new elements to the end of that gap and moving
1529         // existing elements from before the gap to the end of the gap.
1530         // For now, this is safe code, emulating a gap but initializing it.
1531         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1532         self.statements.resize(
1533             gap.end,
1534             Statement {
1535                 source_info: SourceInfo {
1536                     span: DUMMY_SP,
1537                     scope: OUTERMOST_SOURCE_SCOPE,
1538                 },
1539                 kind: StatementKind::Nop,
1540             },
1541         );
1542         for (splice_start, new_stmts) in splices.into_iter().rev() {
1543             let splice_end = splice_start + new_stmts.size_hint().0;
1544             while gap.end > splice_end {
1545                 gap.start -= 1;
1546                 gap.end -= 1;
1547                 self.statements.swap(gap.start, gap.end);
1548             }
1549             self.statements.splice(splice_start..splice_end, new_stmts);
1550             gap.end = splice_start;
1551         }
1552     }
1553
1554     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1555         if index < self.statements.len() {
1556             &self.statements[index]
1557         } else {
1558             &self.terminator
1559         }
1560     }
1561 }
1562
1563 impl<'tcx> Debug for TerminatorKind<'tcx> {
1564     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1565         self.fmt_head(fmt)?;
1566         let successor_count = self.successors().count();
1567         let labels = self.fmt_successor_labels();
1568         assert_eq!(successor_count, labels.len());
1569
1570         match successor_count {
1571             0 => Ok(()),
1572
1573             1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1574
1575             _ => {
1576                 write!(fmt, " -> [")?;
1577                 for (i, target) in self.successors().enumerate() {
1578                     if i > 0 {
1579                         write!(fmt, ", ")?;
1580                     }
1581                     write!(fmt, "{}: {:?}", labels[i], target)?;
1582                 }
1583                 write!(fmt, "]")
1584             }
1585         }
1586     }
1587 }
1588
1589 impl<'tcx> TerminatorKind<'tcx> {
1590     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1591     /// successor basic block, if any. The only information not included is the list of possible
1592     /// successors, which may be rendered differently between the text and the graphviz format.
1593     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1594         use self::TerminatorKind::*;
1595         match *self {
1596             Goto { .. } => write!(fmt, "goto"),
1597             SwitchInt {
1598                 discr: ref place, ..
1599             } => write!(fmt, "switchInt({:?})", place),
1600             Return => write!(fmt, "return"),
1601             GeneratorDrop => write!(fmt, "generator_drop"),
1602             Resume => write!(fmt, "resume"),
1603             Abort => write!(fmt, "abort"),
1604             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1605             Unreachable => write!(fmt, "unreachable"),
1606             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1607             DropAndReplace {
1608                 ref location,
1609                 ref value,
1610                 ..
1611             } => write!(fmt, "replace({:?} <- {:?})", location, value),
1612             Call {
1613                 ref func,
1614                 ref args,
1615                 ref destination,
1616                 ..
1617             } => {
1618                 if let Some((ref destination, _)) = *destination {
1619                     write!(fmt, "{:?} = ", destination)?;
1620                 }
1621                 write!(fmt, "{:?}(", func)?;
1622                 for (index, arg) in args.iter().enumerate() {
1623                     if index > 0 {
1624                         write!(fmt, ", ")?;
1625                     }
1626                     write!(fmt, "{:?}", arg)?;
1627                 }
1628                 write!(fmt, ")")
1629             }
1630             Assert {
1631                 ref cond,
1632                 expected,
1633                 ref msg,
1634                 ..
1635             } => {
1636                 write!(fmt, "assert(")?;
1637                 if !expected {
1638                     write!(fmt, "!")?;
1639                 }
1640                 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1641             }
1642             FalseEdges { .. } => write!(fmt, "falseEdges"),
1643             FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1644         }
1645     }
1646
1647     /// Returns the list of labels for the edges to the successor basic blocks.
1648     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1649         use self::TerminatorKind::*;
1650         match *self {
1651             Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1652             Goto { .. } => vec!["".into()],
1653             SwitchInt {
1654                 ref values,
1655                 switch_ty,
1656                 ..
1657             } => {
1658                 let size = ty::tls::with(|tcx| {
1659                     let param_env = ty::ParamEnv::empty();
1660                     let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1661                     tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1662                 });
1663                 values
1664                     .iter()
1665                     .map(|&u| {
1666                         let mut s = String::new();
1667                         let c = ty::Const {
1668                             val: ConstValue::Scalar(
1669                                 Scalar::Bits {
1670                                     bits: u,
1671                                     size: size.bytes() as u8,
1672                                 }.into(),
1673                             ),
1674                             ty: switch_ty,
1675                         };
1676                         fmt_const_val(&mut s, c).unwrap();
1677                         s.into()
1678                     }).chain(iter::once("otherwise".into()))
1679                     .collect()
1680             }
1681             Call {
1682                 destination: Some(_),
1683                 cleanup: Some(_),
1684                 ..
1685             } => vec!["return".into(), "unwind".into()],
1686             Call {
1687                 destination: Some(_),
1688                 cleanup: None,
1689                 ..
1690             } => vec!["return".into()],
1691             Call {
1692                 destination: None,
1693                 cleanup: Some(_),
1694                 ..
1695             } => vec!["unwind".into()],
1696             Call {
1697                 destination: None,
1698                 cleanup: None,
1699                 ..
1700             } => vec![],
1701             Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1702             Yield { drop: None, .. } => vec!["resume".into()],
1703             DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1704                 vec!["return".into()]
1705             }
1706             DropAndReplace {
1707                 unwind: Some(_), ..
1708             }
1709             | Drop {
1710                 unwind: Some(_), ..
1711             } => vec!["return".into(), "unwind".into()],
1712             Assert { cleanup: None, .. } => vec!["".into()],
1713             Assert { .. } => vec!["success".into(), "unwind".into()],
1714             FalseEdges {
1715                 ref imaginary_targets,
1716                 ..
1717             } => {
1718                 let mut l = vec!["real".into()];
1719                 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1720                 l
1721             }
1722             FalseUnwind {
1723                 unwind: Some(_), ..
1724             } => vec!["real".into(), "cleanup".into()],
1725             FalseUnwind { unwind: None, .. } => vec!["real".into()],
1726         }
1727     }
1728 }
1729
1730 ///////////////////////////////////////////////////////////////////////////
1731 // Statements
1732
1733 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1734 pub struct Statement<'tcx> {
1735     pub source_info: SourceInfo,
1736     pub kind: StatementKind<'tcx>,
1737 }
1738
1739 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1740 #[cfg(target_arch = "x86_64")]
1741 static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Statement<'_>>() == 56);
1742
1743 impl<'tcx> Statement<'tcx> {
1744     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1745     /// invalidating statement indices in `Location`s.
1746     pub fn make_nop(&mut self) {
1747         self.kind = StatementKind::Nop
1748     }
1749
1750     /// Changes a statement to a nop and returns the original statement.
1751     pub fn replace_nop(&mut self) -> Self {
1752         Statement {
1753             source_info: self.source_info,
1754             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1755         }
1756     }
1757 }
1758
1759 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1760 pub enum StatementKind<'tcx> {
1761     /// Write the RHS Rvalue to the LHS Place.
1762     Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1763
1764     /// This represents all the reading that a pattern match may do
1765     /// (e.g., inspecting constants and discriminant values), and the
1766     /// kind of pattern it comes from. This is in order to adapt potential
1767     /// error messages to these specific patterns.
1768     ///
1769     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1770     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1771     FakeRead(FakeReadCause, Place<'tcx>),
1772
1773     /// Write the discriminant for a variant to the enum Place.
1774     SetDiscriminant {
1775         place: Place<'tcx>,
1776         variant_index: VariantIdx,
1777     },
1778
1779     /// Start a live range for the storage of the local.
1780     StorageLive(Local),
1781
1782     /// End the current live range for the storage of the local.
1783     StorageDead(Local),
1784
1785     /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1786     /// of `StatementKind` low.
1787     InlineAsm(Box<InlineAsm<'tcx>>),
1788
1789     /// Retag references in the given place, ensuring they got fresh tags. This is
1790     /// part of the Stacked Borrows model. These statements are currently only interpreted
1791     /// by miri and only generated when "-Z mir-emit-retag" is passed.
1792     /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1793     /// for more details.
1794     Retag(RetagKind, Place<'tcx>),
1795
1796     /// Encodes a user's type ascription. These need to be preserved
1797     /// intact so that NLL can respect them. For example:
1798     ///
1799     ///     let a: T = y;
1800     ///
1801     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1802     /// to the user-given type `T`. The effect depends on the specified variance:
1803     ///
1804     /// - `Covariant` -- requires that `T_y <: T`
1805     /// - `Contravariant` -- requires that `T_y :> T`
1806     /// - `Invariant` -- requires that `T_y == T`
1807     /// - `Bivariant` -- no effect
1808     AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1809
1810     /// No-op. Useful for deleting instructions without affecting statement indices.
1811     Nop,
1812 }
1813
1814 /// `RetagKind` describes what kind of retag is to be performed.
1815 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1816 pub enum RetagKind {
1817     /// The initial retag when entering a function
1818     FnEntry,
1819     /// Retag preparing for a two-phase borrow
1820     TwoPhase,
1821     /// Retagging raw pointers
1822     Raw,
1823     /// A "normal" retag
1824     Default,
1825 }
1826
1827 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1828 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1829 pub enum FakeReadCause {
1830     /// Inject a fake read of the borrowed input at the end of each guards
1831     /// code.
1832     ///
1833     /// This should ensure that you cannot change the variant for an enum while
1834     /// you are in the midst of matching on it.
1835     ForMatchGuard,
1836
1837     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1838     /// generate a read of x to check that it is initialized and safe.
1839     ForMatchedPlace,
1840
1841     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1842     /// in a match guard to ensure that it's value hasn't change by the time
1843     /// we create the OutsideGuard version.
1844     ForGuardBinding,
1845
1846     /// Officially, the semantics of
1847     ///
1848     /// `let pattern = <expr>;`
1849     ///
1850     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1851     /// into the pattern.
1852     ///
1853     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1854     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1855     /// but in some cases it can affect the borrow checker, as in #53695.
1856     /// Therefore, we insert a "fake read" here to ensure that we get
1857     /// appropriate errors.
1858     ForLet,
1859 }
1860
1861 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1862 pub struct InlineAsm<'tcx> {
1863     pub asm: HirInlineAsm,
1864     pub outputs: Box<[Place<'tcx>]>,
1865     pub inputs: Box<[(Span, Operand<'tcx>)]>,
1866 }
1867
1868 impl<'tcx> Debug for Statement<'tcx> {
1869     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1870         use self::StatementKind::*;
1871         match self.kind {
1872             Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1873             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1874             Retag(ref kind, ref place) =>
1875                 write!(fmt, "Retag({}{:?})",
1876                     match kind {
1877                         RetagKind::FnEntry => "[fn entry] ",
1878                         RetagKind::TwoPhase => "[2phase] ",
1879                         RetagKind::Raw => "[raw] ",
1880                         RetagKind::Default => "",
1881                     },
1882                     place,
1883                 ),
1884             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1885             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1886             SetDiscriminant {
1887                 ref place,
1888                 variant_index,
1889             } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1890             InlineAsm(ref asm) =>
1891                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs),
1892             AscribeUserType(ref place, ref variance, ref c_ty) => {
1893                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1894             }
1895             Nop => write!(fmt, "nop"),
1896         }
1897     }
1898 }
1899
1900 ///////////////////////////////////////////////////////////////////////////
1901 // Places
1902
1903 /// A path to a value; something that can be evaluated without
1904 /// changing or disturbing program state.
1905 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1906 pub enum Place<'tcx> {
1907     Base(PlaceBase<'tcx>),
1908
1909     /// projection out of a place (access a field, deref a pointer, etc)
1910     Projection(Box<PlaceProjection<'tcx>>),
1911 }
1912
1913 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1914 pub enum PlaceBase<'tcx> {
1915     /// local variable
1916     Local(Local),
1917
1918     /// static or static mut variable
1919     Static(Box<Static<'tcx>>),
1920 }
1921
1922 /// We store the normalized type to avoid requiring normalization when reading MIR
1923 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1924 pub struct Static<'tcx> {
1925     pub ty: Ty<'tcx>,
1926     pub kind: StaticKind,
1927 }
1928
1929 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable)]
1930 pub enum StaticKind {
1931     Promoted(Promoted),
1932     Static(DefId),
1933 }
1934
1935 impl_stable_hash_for!(struct Static<'tcx> {
1936     ty,
1937     kind
1938 });
1939
1940 /// The `Projection` data structure defines things of the form `B.x`
1941 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1942 /// shared between `Constant` and `Place`. See the aliases
1943 /// `PlaceProjection` etc below.
1944 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1945          Hash, RustcEncodable, RustcDecodable, HashStable)]
1946 pub struct Projection<B, V, T> {
1947     pub base: B,
1948     pub elem: ProjectionElem<V, T>,
1949 }
1950
1951 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1952          Hash, RustcEncodable, RustcDecodable, HashStable)]
1953 pub enum ProjectionElem<V, T> {
1954     Deref,
1955     Field(Field, T),
1956     Index(V),
1957
1958     /// These indices are generated by slice patterns. Easiest to explain
1959     /// by example:
1960     ///
1961     /// ```
1962     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1963     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1964     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1965     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1966     /// ```
1967     ConstantIndex {
1968         /// index or -index (in Python terms), depending on from_end
1969         offset: u32,
1970         /// thing being indexed must be at least this long
1971         min_length: u32,
1972         /// counting backwards from end?
1973         from_end: bool,
1974     },
1975
1976     /// These indices are generated by slice patterns.
1977     ///
1978     /// slice[from:-to] in Python terms.
1979     Subslice {
1980         from: u32,
1981         to: u32,
1982     },
1983
1984     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1985     /// this for ADTs with more than one variant. It may be better to
1986     /// just introduce it always, or always for enums.
1987     ///
1988     /// The included Symbol is the name of the variant, used for printing MIR.
1989     Downcast(Option<Symbol>, VariantIdx),
1990 }
1991
1992 /// Alias for projections as they appear in places, where the base is a place
1993 /// and the index is a local.
1994 pub type PlaceProjection<'tcx> = Projection<Place<'tcx>, Local, Ty<'tcx>>;
1995
1996 /// Alias for projections as they appear in places, where the base is a place
1997 /// and the index is a local.
1998 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1999
2000 // at least on 64 bit systems, `PlaceElem` should not be larger than two pointers
2001 static_assert!(PROJECTION_ELEM_IS_2_PTRS_LARGE:
2002     mem::size_of::<PlaceElem<'_>>() <= 16
2003 );
2004
2005 /// Alias for projections as they appear in `UserTypeProjection`, where we
2006 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
2007 pub type ProjectionKind = ProjectionElem<(), ()>;
2008
2009 newtype_index! {
2010     pub struct Field {
2011         derive [HashStable]
2012         DEBUG_FORMAT = "field[{}]"
2013     }
2014 }
2015
2016 impl<'tcx> Place<'tcx> {
2017     pub const RETURN_PLACE: Place<'tcx> = Place::Base(PlaceBase::Local(RETURN_PLACE));
2018
2019     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2020         self.elem(ProjectionElem::Field(f, ty))
2021     }
2022
2023     pub fn deref(self) -> Place<'tcx> {
2024         self.elem(ProjectionElem::Deref)
2025     }
2026
2027     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2028         self.elem(ProjectionElem::Downcast(
2029             Some(adt_def.variants[variant_index].ident.name),
2030             variant_index))
2031     }
2032
2033     pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
2034         self.elem(ProjectionElem::Downcast(None, variant_index))
2035     }
2036
2037     pub fn index(self, index: Local) -> Place<'tcx> {
2038         self.elem(ProjectionElem::Index(index))
2039     }
2040
2041     pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2042         Place::Projection(Box::new(PlaceProjection { base: self, elem }))
2043     }
2044
2045     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2046     /// a single deref of a local.
2047     //
2048     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2049     pub fn local(&self) -> Option<Local> {
2050         match self {
2051             Place::Base(PlaceBase::Local(local)) |
2052             Place::Projection(box Projection {
2053                 base: Place::Base(PlaceBase::Local(local)),
2054                 elem: ProjectionElem::Deref,
2055             }) => Some(*local),
2056             _ => None,
2057         }
2058     }
2059
2060     /// Finds the innermost `Local` from this `Place`.
2061     pub fn base_local(&self) -> Option<Local> {
2062         let mut place = self;
2063         loop {
2064             match place {
2065                 Place::Projection(proj) => place = &proj.base,
2066                 Place::Base(PlaceBase::Static(_)) => return None,
2067                 Place::Base(PlaceBase::Local(local)) => return Some(*local),
2068             }
2069         }
2070     }
2071
2072     /// Recursively "iterates" over place components, generating a `PlaceBase` and
2073     /// `PlaceProjections` list and invoking `op` with a `PlaceProjectionsIter`.
2074     pub fn iterate<R>(
2075         &self,
2076         op: impl FnOnce(&PlaceBase<'tcx>, PlaceProjectionsIter<'_, 'tcx>) -> R,
2077     ) -> R {
2078         self.iterate2(&PlaceProjections::Empty, op)
2079     }
2080
2081     fn iterate2<R>(
2082         &self,
2083         next: &PlaceProjections<'_, 'tcx>,
2084         op: impl FnOnce(&PlaceBase<'tcx>, PlaceProjectionsIter<'_, 'tcx>) -> R,
2085     ) -> R {
2086         match self {
2087             Place::Projection(interior) => interior.base.iterate2(
2088                 &PlaceProjections::List {
2089                     projection: interior,
2090                     next,
2091                 },
2092                 op,
2093             ),
2094
2095             Place::Base(base) => op(base, next.iter()),
2096         }
2097     }
2098 }
2099
2100 /// A linked list of projections running up the stack; begins with the
2101 /// innermost projection and extends to the outermost (e.g., `a.b.c`
2102 /// would have the place `b` with a "next" pointer to `b.c`).
2103 /// Created by `Place::iterate`.
2104 ///
2105 /// N.B., this particular impl strategy is not the most obvious. It was
2106 /// chosen because it makes a measurable difference to NLL
2107 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
2108 pub enum PlaceProjections<'p, 'tcx: 'p> {
2109     Empty,
2110
2111     List {
2112         projection: &'p PlaceProjection<'tcx>,
2113         next: &'p PlaceProjections<'p, 'tcx>,
2114     }
2115 }
2116
2117 impl<'p, 'tcx> PlaceProjections<'p, 'tcx> {
2118     fn iter(&self) -> PlaceProjectionsIter<'_, 'tcx> {
2119         PlaceProjectionsIter { value: self }
2120     }
2121 }
2122
2123 impl<'p, 'tcx> IntoIterator for &'p PlaceProjections<'p, 'tcx> {
2124     type Item = &'p PlaceProjection<'tcx>;
2125     type IntoIter = PlaceProjectionsIter<'p, 'tcx>;
2126
2127     /// Converts a list of `PlaceProjection` components into an iterator;
2128     /// this iterator yields up a never-ending stream of `Option<&Place>`.
2129     /// These begin with the "innermost" projection and then with each
2130     /// projection therefrom. So given a place like `a.b.c` it would
2131     /// yield up:
2132     ///
2133     /// ```notrust
2134     /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2135     /// ```
2136     fn into_iter(self) -> Self::IntoIter {
2137         self.iter()
2138     }
2139 }
2140
2141 /// Iterator over components; see `PlaceProjections::iter` for more
2142 /// information.
2143 ///
2144 /// N.B., this is not a *true* Rust iterator -- the code above just
2145 /// manually invokes `next`. This is because we (sometimes) want to
2146 /// keep executing even after `None` has been returned.
2147 pub struct PlaceProjectionsIter<'p, 'tcx: 'p> {
2148     pub value: &'p PlaceProjections<'p, 'tcx>,
2149 }
2150
2151 impl<'p, 'tcx> Iterator for PlaceProjectionsIter<'p, 'tcx> {
2152     type Item = &'p PlaceProjection<'tcx>;
2153
2154     fn next(&mut self) -> Option<Self::Item> {
2155         if let &PlaceProjections::List { projection, next } = self.value {
2156             self.value = next;
2157             Some(projection)
2158         } else {
2159             None
2160         }
2161     }
2162 }
2163
2164 impl<'p, 'tcx> FusedIterator for PlaceProjectionsIter<'p, 'tcx> {}
2165
2166 impl<'tcx> Debug for Place<'tcx> {
2167     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2168         self.iterate(|_place_base, place_projections| {
2169             // FIXME: remove this collect once we have migrated to slices
2170             let projs_vec: Vec<_> = place_projections.collect();
2171             for projection in projs_vec.iter().rev() {
2172                 match projection.elem {
2173                     ProjectionElem::Downcast(_, _) |
2174                     ProjectionElem::Field(_, _) => {
2175                         write!(fmt, "(").unwrap();
2176                     }
2177                     ProjectionElem::Deref => {
2178                         write!(fmt, "(*").unwrap();
2179                     }
2180                     ProjectionElem::Index(_) |
2181                     ProjectionElem::ConstantIndex { .. } |
2182                     ProjectionElem::Subslice { .. } => {}
2183                 }
2184             }
2185         });
2186
2187         self.iterate(|place_base, place_projections| {
2188             match place_base {
2189                 PlaceBase::Local(id) => {
2190                     write!(fmt, "{:?}", id)?;
2191                 }
2192                 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2193                     write!(
2194                         fmt,
2195                         "({}: {:?})",
2196                         ty::tls::with(|tcx| tcx.def_path_str(*def_id)),
2197                         ty
2198                     )?;
2199                 },
2200                 PlaceBase::Static(
2201                     box self::Static { ty, kind: StaticKind::Promoted(promoted) }
2202                 ) => {
2203                     write!(
2204                         fmt,
2205                         "({:?}: {:?})",
2206                         promoted,
2207                         ty
2208                     )?;
2209                 },
2210             }
2211
2212             for projection in place_projections {
2213                 match projection.elem {
2214                     ProjectionElem::Downcast(Some(name), _index) => {
2215                         write!(fmt, " as {})", name)?;
2216                     }
2217                     ProjectionElem::Downcast(None, index) => {
2218                         write!(fmt, " as variant#{:?})", index)?;
2219                     }
2220                     ProjectionElem::Deref => {
2221                         write!(fmt, ")")?;
2222                     }
2223                     ProjectionElem::Field(field, ty) => {
2224                         write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2225                     }
2226                     ProjectionElem::Index(ref index) => {
2227                         write!(fmt, "[{:?}]", index)?;
2228                     }
2229                     ProjectionElem::ConstantIndex {
2230                         offset,
2231                         min_length,
2232                         from_end: false,
2233                     } => {
2234                         write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2235                     }
2236                     ProjectionElem::ConstantIndex {
2237                         offset,
2238                         min_length,
2239                         from_end: true,
2240                     } => {
2241                         write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2242                     }
2243                     ProjectionElem::Subslice { from, to } if to == 0 => {
2244                         write!(fmt, "[{:?}:]", from)?;
2245                     }
2246                     ProjectionElem::Subslice { from, to } if from == 0 => {
2247                         write!(fmt, "[:-{:?}]", to)?;
2248                     }
2249                     ProjectionElem::Subslice { from, to } => {
2250                         write!(fmt, "[{:?}:-{:?}]", from, to)?;
2251                     }
2252                 }
2253             }
2254
2255             Ok(())
2256         })
2257     }
2258 }
2259
2260 ///////////////////////////////////////////////////////////////////////////
2261 // Scopes
2262
2263 newtype_index! {
2264     pub struct SourceScope {
2265         derive [HashStable]
2266         DEBUG_FORMAT = "scope[{}]",
2267         const OUTERMOST_SOURCE_SCOPE = 0,
2268     }
2269 }
2270
2271 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2272 pub struct SourceScopeData {
2273     pub span: Span,
2274     pub parent_scope: Option<SourceScope>,
2275 }
2276
2277 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2278 pub struct SourceScopeLocalData {
2279     /// A HirId with lint levels equivalent to this scope's lint levels.
2280     pub lint_root: hir::HirId,
2281     /// The unsafe block that contains this node.
2282     pub safety: Safety,
2283 }
2284
2285 ///////////////////////////////////////////////////////////////////////////
2286 // Operands
2287
2288 /// These are values that can appear inside an rvalue. They are intentionally
2289 /// limited to prevent rvalues from being nested in one another.
2290 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2291 pub enum Operand<'tcx> {
2292     /// Copy: The value must be available for use afterwards.
2293     ///
2294     /// This implies that the type of the place must be `Copy`; this is true
2295     /// by construction during build, but also checked by the MIR type checker.
2296     Copy(Place<'tcx>),
2297
2298     /// Move: The value (including old borrows of it) will not be used again.
2299     ///
2300     /// Safe for values of all types (modulo future developments towards `?Move`).
2301     /// Correct usage patterns are enforced by the borrow checker for safe code.
2302     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2303     Move(Place<'tcx>),
2304
2305     /// Synthesizes a constant value.
2306     Constant(Box<Constant<'tcx>>),
2307 }
2308
2309 impl<'tcx> Debug for Operand<'tcx> {
2310     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2311         use self::Operand::*;
2312         match *self {
2313             Constant(ref a) => write!(fmt, "{:?}", a),
2314             Copy(ref place) => write!(fmt, "{:?}", place),
2315             Move(ref place) => write!(fmt, "move {:?}", place),
2316         }
2317     }
2318 }
2319
2320 impl<'tcx> Operand<'tcx> {
2321     /// Convenience helper to make a constant that refers to the fn
2322     /// with given `DefId` and substs. Since this is used to synthesize
2323     /// MIR, assumes `user_ty` is None.
2324     pub fn function_handle<'a>(
2325         tcx: TyCtxt<'a, 'tcx, 'tcx>,
2326         def_id: DefId,
2327         substs: SubstsRef<'tcx>,
2328         span: Span,
2329     ) -> Self {
2330         let ty = tcx.type_of(def_id).subst(tcx, substs);
2331         Operand::Constant(box Constant {
2332             span,
2333             ty,
2334             user_ty: None,
2335             literal: tcx.mk_const(
2336                 ty::Const::zero_sized(ty),
2337             ),
2338         })
2339     }
2340
2341     pub fn to_copy(&self) -> Self {
2342         match *self {
2343             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2344             Operand::Move(ref place) => Operand::Copy(place.clone()),
2345         }
2346     }
2347 }
2348
2349 ///////////////////////////////////////////////////////////////////////////
2350 /// Rvalues
2351
2352 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2353 pub enum Rvalue<'tcx> {
2354     /// x (either a move or copy, depending on type of x)
2355     Use(Operand<'tcx>),
2356
2357     /// [x; 32]
2358     Repeat(Operand<'tcx>, u64),
2359
2360     /// &x or &mut x
2361     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2362
2363     /// length of a [X] or [X;n] value
2364     Len(Place<'tcx>),
2365
2366     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2367
2368     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2369     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2370
2371     NullaryOp(NullOp, Ty<'tcx>),
2372     UnaryOp(UnOp, Operand<'tcx>),
2373
2374     /// Read the discriminant of an ADT.
2375     ///
2376     /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2377     /// be defined to return, say, a 0) if ADT is not an enum.
2378     Discriminant(Place<'tcx>),
2379
2380     /// Creates an aggregate value, like a tuple or struct. This is
2381     /// only needed because we want to distinguish `dest = Foo { x:
2382     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2383     /// that `Foo` has a destructor. These rvalues can be optimized
2384     /// away after type-checking and before lowering.
2385     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2386 }
2387
2388
2389 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2390 pub enum CastKind {
2391     Misc,
2392     Pointer(PointerCast),
2393 }
2394
2395 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2396 pub enum AggregateKind<'tcx> {
2397     /// The type is of the element
2398     Array(Ty<'tcx>),
2399     Tuple,
2400
2401     /// The second field is the variant index. It's equal to 0 for struct
2402     /// and union expressions. The fourth field is
2403     /// active field number and is present only for union expressions
2404     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2405     /// active field index would identity the field `c`
2406     Adt(
2407         &'tcx AdtDef,
2408         VariantIdx,
2409         SubstsRef<'tcx>,
2410         Option<UserTypeAnnotationIndex>,
2411         Option<usize>,
2412     ),
2413
2414     Closure(DefId, ClosureSubsts<'tcx>),
2415     Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2416 }
2417
2418 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2419 pub enum BinOp {
2420     /// The `+` operator (addition)
2421     Add,
2422     /// The `-` operator (subtraction)
2423     Sub,
2424     /// The `*` operator (multiplication)
2425     Mul,
2426     /// The `/` operator (division)
2427     Div,
2428     /// The `%` operator (modulus)
2429     Rem,
2430     /// The `^` operator (bitwise xor)
2431     BitXor,
2432     /// The `&` operator (bitwise and)
2433     BitAnd,
2434     /// The `|` operator (bitwise or)
2435     BitOr,
2436     /// The `<<` operator (shift left)
2437     Shl,
2438     /// The `>>` operator (shift right)
2439     Shr,
2440     /// The `==` operator (equality)
2441     Eq,
2442     /// The `<` operator (less than)
2443     Lt,
2444     /// The `<=` operator (less than or equal to)
2445     Le,
2446     /// The `!=` operator (not equal to)
2447     Ne,
2448     /// The `>=` operator (greater than or equal to)
2449     Ge,
2450     /// The `>` operator (greater than)
2451     Gt,
2452     /// The `ptr.offset` operator
2453     Offset,
2454 }
2455
2456 impl BinOp {
2457     pub fn is_checkable(self) -> bool {
2458         use self::BinOp::*;
2459         match self {
2460             Add | Sub | Mul | Shl | Shr => true,
2461             _ => false,
2462         }
2463     }
2464 }
2465
2466 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2467 pub enum NullOp {
2468     /// Returns the size of a value of that type
2469     SizeOf,
2470     /// Creates a new uninitialized box for a value of that type
2471     Box,
2472 }
2473
2474 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2475 pub enum UnOp {
2476     /// The `!` operator for logical inversion
2477     Not,
2478     /// The `-` operator for negation
2479     Neg,
2480 }
2481
2482 impl<'tcx> Debug for Rvalue<'tcx> {
2483     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2484         use self::Rvalue::*;
2485
2486         match *self {
2487             Use(ref place) => write!(fmt, "{:?}", place),
2488             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2489             Len(ref a) => write!(fmt, "Len({:?})", a),
2490             Cast(ref kind, ref place, ref ty) => {
2491                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2492             }
2493             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2494             CheckedBinaryOp(ref op, ref a, ref b) => {
2495                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2496             }
2497             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2498             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2499             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2500             Ref(region, borrow_kind, ref place) => {
2501                 let kind_str = match borrow_kind {
2502                     BorrowKind::Shared => "",
2503                     BorrowKind::Shallow => "shallow ",
2504                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2505                 };
2506
2507                 // When printing regions, add trailing space if necessary.
2508                 let print_region = ty::tls::with(|tcx| {
2509                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2510                 });
2511                 let region = if print_region {
2512                     let mut region = region.to_string();
2513                     if region.len() > 0 {
2514                         region.push(' ');
2515                     }
2516                     region
2517                 } else {
2518                     // Do not even print 'static
2519                     String::new()
2520                 };
2521                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2522             }
2523
2524             Aggregate(ref kind, ref places) => {
2525                 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2526                     let mut tuple_fmt = fmt.debug_tuple("");
2527                     for place in places {
2528                         tuple_fmt.field(place);
2529                     }
2530                     tuple_fmt.finish()
2531                 }
2532
2533                 match **kind {
2534                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2535
2536                     AggregateKind::Tuple => match places.len() {
2537                         0 => write!(fmt, "()"),
2538                         1 => write!(fmt, "({:?},)", places[0]),
2539                         _ => fmt_tuple(fmt, places),
2540                     },
2541
2542                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2543                         let variant_def = &adt_def.variants[variant];
2544
2545                         let f = &mut *fmt;
2546                         ty::tls::with(|tcx| {
2547                             let substs = tcx.lift(&substs).expect("could not lift for printing");
2548                             FmtPrinter::new(tcx, f, Namespace::ValueNS)
2549                                 .print_def_path(variant_def.def_id, substs)?;
2550                             Ok(())
2551                         })?;
2552
2553                         match variant_def.ctor_kind {
2554                             CtorKind::Const => Ok(()),
2555                             CtorKind::Fn => fmt_tuple(fmt, places),
2556                             CtorKind::Fictive => {
2557                                 let mut struct_fmt = fmt.debug_struct("");
2558                                 for (field, place) in variant_def.fields.iter().zip(places) {
2559                                     struct_fmt.field(&field.ident.as_str(), place);
2560                                 }
2561                                 struct_fmt.finish()
2562                             }
2563                         }
2564                     }
2565
2566                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2567                         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2568                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2569                                 format!("[closure@{:?}]", hir_id)
2570                             } else {
2571                                 format!("[closure@{:?}]", tcx.hir().span_by_hir_id(hir_id))
2572                             };
2573                             let mut struct_fmt = fmt.debug_struct(&name);
2574
2575                             if let Some(upvars) = tcx.upvars(def_id) {
2576                                 for (upvar, place) in upvars.iter().zip(places) {
2577                                     let var_name = tcx.hir().name_by_hir_id(upvar.var_id());
2578                                     struct_fmt.field(&var_name.as_str(), place);
2579                                 }
2580                             }
2581
2582                             struct_fmt.finish()
2583                         } else {
2584                             write!(fmt, "[closure]")
2585                         }
2586                     }),
2587
2588                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2589                         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2590                             let name = format!("[generator@{:?}]",
2591                                                tcx.hir().span_by_hir_id(hir_id));
2592                             let mut struct_fmt = fmt.debug_struct(&name);
2593
2594                             if let Some(upvars) = tcx.upvars(def_id) {
2595                                 for (upvar, place) in upvars.iter().zip(places) {
2596                                     let var_name = tcx.hir().name_by_hir_id(upvar.var_id());
2597                                     struct_fmt.field(&var_name.as_str(), place);
2598                                 }
2599                             }
2600
2601                             struct_fmt.finish()
2602                         } else {
2603                             write!(fmt, "[generator]")
2604                         }
2605                     }),
2606                 }
2607             }
2608         }
2609     }
2610 }
2611
2612 ///////////////////////////////////////////////////////////////////////////
2613 /// Constants
2614 ///
2615 /// Two constants are equal if they are the same constant. Note that
2616 /// this does not necessarily mean that they are "==" in Rust -- in
2617 /// particular one must be wary of `NaN`!
2618
2619 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2620 pub struct Constant<'tcx> {
2621     pub span: Span,
2622     pub ty: Ty<'tcx>,
2623
2624     /// Optional user-given type: for something like
2625     /// `collect::<Vec<_>>`, this would be present and would
2626     /// indicate that `Vec<_>` was explicitly specified.
2627     ///
2628     /// Needed for NLL to impose user-given type constraints.
2629     pub user_ty: Option<UserTypeAnnotationIndex>,
2630
2631     pub literal: &'tcx ty::Const<'tcx>,
2632 }
2633
2634 /// A collection of projections into user types.
2635 ///
2636 /// They are projections because a binding can occur a part of a
2637 /// parent pattern that has been ascribed a type.
2638 ///
2639 /// Its a collection because there can be multiple type ascriptions on
2640 /// the path from the root of the pattern down to the binding itself.
2641 ///
2642 /// An example:
2643 ///
2644 /// ```rust
2645 /// struct S<'a>((i32, &'a str), String);
2646 /// let S((_, w): (i32, &'static str), _): S = ...;
2647 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2648 /// //  ---------------------------------  ^ (2)
2649 /// ```
2650 ///
2651 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2652 /// ascribed the type `(i32, &'static str)`.
2653 ///
2654 /// The highlights labelled `(2)` show the whole pattern being
2655 /// ascribed the type `S`.
2656 ///
2657 /// In this example, when we descend to `w`, we will have built up the
2658 /// following two projected types:
2659 ///
2660 ///   * base: `S`,                   projection: `(base.0).1`
2661 ///   * base: `(i32, &'static str)`, projection: `base.1`
2662 ///
2663 /// The first will lead to the constraint `w: &'1 str` (for some
2664 /// inferred region `'1`). The second will lead to the constraint `w:
2665 /// &'static str`.
2666 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2667 pub struct UserTypeProjections {
2668     pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2669 }
2670
2671 BraceStructTypeFoldableImpl! {
2672     impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2673         contents
2674     }
2675 }
2676
2677 impl<'tcx> UserTypeProjections {
2678     pub fn none() -> Self {
2679         UserTypeProjections { contents: vec![] }
2680     }
2681
2682     pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection, Span)>) -> Self {
2683         UserTypeProjections { contents: projs.collect() }
2684     }
2685
2686     pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection, Span)> {
2687         self.contents.iter()
2688     }
2689
2690     pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection> {
2691         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2692     }
2693
2694     pub fn push_projection(
2695         mut self,
2696         user_ty: &UserTypeProjection,
2697         span: Span,
2698     ) -> Self {
2699         self.contents.push((user_ty.clone(), span));
2700         self
2701     }
2702
2703     fn map_projections(
2704         mut self,
2705         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection
2706     ) -> Self {
2707         self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2708         self
2709     }
2710
2711     pub fn index(self) -> Self {
2712         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2713     }
2714
2715     pub fn subslice(self, from: u32, to: u32) -> Self {
2716         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2717     }
2718
2719     pub fn deref(self) -> Self {
2720         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2721     }
2722
2723     pub fn leaf(self, field: Field) -> Self {
2724         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2725     }
2726
2727     pub fn variant(
2728         self,
2729         adt_def: &'tcx AdtDef,
2730         variant_index: VariantIdx,
2731         field: Field,
2732     ) -> Self {
2733         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2734     }
2735 }
2736
2737 /// Encodes the effect of a user-supplied type annotation on the
2738 /// subcomponents of a pattern. The effect is determined by applying the
2739 /// given list of proejctions to some underlying base type. Often,
2740 /// the projection element list `projs` is empty, in which case this
2741 /// directly encodes a type in `base`. But in the case of complex patterns with
2742 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2743 /// in which case the `projs` vector is used.
2744 ///
2745 /// Examples:
2746 ///
2747 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2748 ///
2749 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2750 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2751 ///   determined by finding the type of the `.0` field from `T`.
2752 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2753 pub struct UserTypeProjection {
2754     pub base: UserTypeAnnotationIndex,
2755     pub projs: Vec<ProjectionElem<(), ()>>,
2756 }
2757
2758 impl Copy for ProjectionKind { }
2759
2760 impl UserTypeProjection {
2761     pub(crate) fn index(mut self) -> Self {
2762         self.projs.push(ProjectionElem::Index(()));
2763         self
2764     }
2765
2766     pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2767         self.projs.push(ProjectionElem::Subslice { from, to });
2768         self
2769     }
2770
2771     pub(crate) fn deref(mut self) -> Self {
2772         self.projs.push(ProjectionElem::Deref);
2773         self
2774     }
2775
2776     pub(crate) fn leaf(mut self, field: Field) -> Self {
2777         self.projs.push(ProjectionElem::Field(field, ()));
2778         self
2779     }
2780
2781     pub(crate) fn variant(
2782         mut self,
2783         adt_def: &'tcx AdtDef,
2784         variant_index: VariantIdx,
2785         field: Field,
2786     ) -> Self {
2787         self.projs.push(ProjectionElem::Downcast(
2788             Some(adt_def.variants[variant_index].ident.name),
2789             variant_index));
2790         self.projs.push(ProjectionElem::Field(field, ()));
2791         self
2792     }
2793 }
2794
2795 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2796
2797 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2798     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2799         use crate::mir::ProjectionElem::*;
2800
2801         let base = self.base.fold_with(folder);
2802         let projs: Vec<_> = self.projs
2803             .iter()
2804             .map(|elem| {
2805                 match elem {
2806                     Deref => Deref,
2807                     Field(f, ()) => Field(f.clone(), ()),
2808                     Index(()) => Index(()),
2809                     elem => elem.clone(),
2810                 }})
2811             .collect();
2812
2813         UserTypeProjection { base, projs }
2814     }
2815
2816     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2817         self.base.visit_with(visitor)
2818         // Note: there's nothing in `self.proj` to visit.
2819     }
2820 }
2821
2822 newtype_index! {
2823     pub struct Promoted {
2824         derive [HashStable]
2825         DEBUG_FORMAT = "promoted[{}]"
2826     }
2827 }
2828
2829 impl<'tcx> Debug for Constant<'tcx> {
2830     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2831         write!(fmt, "const ")?;
2832         fmt_const_val(fmt, *self.literal)
2833     }
2834 }
2835 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2836 pub fn fmt_const_val(f: &mut impl Write, const_val: ty::Const<'_>) -> fmt::Result {
2837     use crate::ty::TyKind::*;
2838     let value = const_val.val;
2839     let ty = const_val.ty;
2840     // print some primitives
2841     if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2842         match ty.sty {
2843             Bool if bits == 0 => return write!(f, "false"),
2844             Bool if bits == 1 => return write!(f, "true"),
2845             Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2846             Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2847             Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2848             Int(i) => {
2849                 let bit_width = ty::tls::with(|tcx| {
2850                     let ty = tcx.lift_to_global(&ty).unwrap();
2851                     tcx.layout_of(ty::ParamEnv::empty().and(ty))
2852                         .unwrap()
2853                         .size
2854                         .bits()
2855                 });
2856                 let shift = 128 - bit_width;
2857                 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2858             }
2859             Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2860             _ => {}
2861         }
2862     }
2863     // print function definitions
2864     if let FnDef(did, _) = ty.sty {
2865         return write!(f, "{}", def_path_str(did));
2866     }
2867     // print string literals
2868     if let ConstValue::Slice(ptr, len) = value {
2869         if let Scalar::Ptr(ptr) = ptr {
2870             if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2871                 return ty::tls::with(|tcx| {
2872                     let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2873                     if let Some(interpret::AllocKind::Memory(alloc)) = alloc {
2874                         assert_eq!(len as usize as u64, len);
2875                         let slice =
2876                             &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2877                         let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2878                         write!(f, "{:?}", s)
2879                     } else {
2880                         write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2881                     }
2882                 });
2883             }
2884         }
2885     }
2886     // just raw dump everything else
2887     write!(f, "{:?} : {}", value, ty)
2888 }
2889
2890 fn def_path_str(def_id: DefId) -> String {
2891     ty::tls::with(|tcx| tcx.def_path_str(def_id))
2892 }
2893
2894 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2895     type Node = BasicBlock;
2896 }
2897
2898 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2899     fn num_nodes(&self) -> usize {
2900         self.basic_blocks.len()
2901     }
2902 }
2903
2904 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2905     fn start_node(&self) -> Self::Node {
2906         START_BLOCK
2907     }
2908 }
2909
2910 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2911     fn predecessors<'graph>(
2912         &'graph self,
2913         node: Self::Node,
2914     ) -> <Self as GraphPredecessors<'graph>>::Iter {
2915         self.predecessors_for(node).clone().into_iter()
2916     }
2917 }
2918
2919 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2920     fn successors<'graph>(
2921         &'graph self,
2922         node: Self::Node,
2923     ) -> <Self as GraphSuccessors<'graph>>::Iter {
2924         self.basic_blocks[node].terminator().successors().cloned()
2925     }
2926 }
2927
2928 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2929     type Item = BasicBlock;
2930     type Iter = IntoIter<BasicBlock>;
2931 }
2932
2933 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2934     type Item = BasicBlock;
2935     type Iter = iter::Cloned<Successors<'b>>;
2936 }
2937
2938 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2939 pub struct Location {
2940     /// the location is within this block
2941     pub block: BasicBlock,
2942
2943     /// the location is the start of the statement; or, if `statement_index`
2944     /// == num-statements, then the start of the terminator.
2945     pub statement_index: usize,
2946 }
2947
2948 impl fmt::Debug for Location {
2949     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2950         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2951     }
2952 }
2953
2954 impl Location {
2955     pub const START: Location = Location {
2956         block: START_BLOCK,
2957         statement_index: 0,
2958     };
2959
2960     /// Returns the location immediately after this one within the enclosing block.
2961     ///
2962     /// Note that if this location represents a terminator, then the
2963     /// resulting location would be out of bounds and invalid.
2964     pub fn successor_within_block(&self) -> Location {
2965         Location {
2966             block: self.block,
2967             statement_index: self.statement_index + 1,
2968         }
2969     }
2970
2971     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2972     pub fn is_predecessor_of<'tcx>(&self, other: Location, mir: &Mir<'tcx>) -> bool {
2973         // If we are in the same block as the other location and are an earlier statement
2974         // then we are a predecessor of `other`.
2975         if self.block == other.block && self.statement_index < other.statement_index {
2976             return true;
2977         }
2978
2979         // If we're in another block, then we want to check that block is a predecessor of `other`.
2980         let mut queue: Vec<BasicBlock> = mir.predecessors_for(other.block).clone();
2981         let mut visited = FxHashSet::default();
2982
2983         while let Some(block) = queue.pop() {
2984             // If we haven't visited this block before, then make sure we visit it's predecessors.
2985             if visited.insert(block) {
2986                 queue.append(&mut mir.predecessors_for(block).clone());
2987             } else {
2988                 continue;
2989             }
2990
2991             // If we found the block that `self` is in, then we are a predecessor of `other` (since
2992             // we found that block by looking at the predecessors of `other`).
2993             if self.block == block {
2994                 return true;
2995             }
2996         }
2997
2998         false
2999     }
3000
3001     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3002         if self.block == other.block {
3003             self.statement_index <= other.statement_index
3004         } else {
3005             dominators.is_dominated_by(other.block, self.block)
3006         }
3007     }
3008 }
3009
3010 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
3011 pub enum UnsafetyViolationKind {
3012     General,
3013     /// Permitted in const fn and regular fns.
3014     GeneralAndConstFn,
3015     ExternStatic(hir::HirId),
3016     BorrowPacked(hir::HirId),
3017 }
3018
3019 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
3020 pub struct UnsafetyViolation {
3021     pub source_info: SourceInfo,
3022     pub description: InternedString,
3023     pub details: InternedString,
3024     pub kind: UnsafetyViolationKind,
3025 }
3026
3027 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
3028 pub struct UnsafetyCheckResult {
3029     /// Violations that are propagated *upwards* from this function
3030     pub violations: Lrc<[UnsafetyViolation]>,
3031     /// unsafe blocks in this function, along with whether they are used. This is
3032     /// used for the "unused_unsafe" lint.
3033     pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
3034 }
3035
3036 newtype_index! {
3037     pub struct GeneratorSavedLocal {
3038         derive [HashStable]
3039         DEBUG_FORMAT = "_{}",
3040     }
3041 }
3042
3043 /// The layout of generator state
3044 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3045 pub struct GeneratorLayout<'tcx> {
3046     /// The type of every local stored inside the generator.
3047     pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
3048
3049     /// Which of the above fields are in each variant. Note that one field may
3050     /// be stored in multiple variants.
3051     pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
3052
3053     /// Names and scopes of all the stored generator locals.
3054     /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
3055     /// debuginfo generation, and will be removed at some point.
3056     /// Do **NOT** use it for anything else, local information should not be
3057     /// in the MIR, please rely on local crate HIR or other side-channels.
3058     pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
3059 }
3060
3061 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3062 pub struct BorrowCheckResult<'gcx> {
3063     pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
3064     pub used_mut_upvars: SmallVec<[Field; 8]>,
3065 }
3066
3067 /// After we borrow check a closure, we are left with various
3068 /// requirements that we have inferred between the free regions that
3069 /// appear in the closure's signature or on its field types. These
3070 /// requirements are then verified and proved by the closure's
3071 /// creating function. This struct encodes those requirements.
3072 ///
3073 /// The requirements are listed as being between various
3074 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
3075 /// vids refer to the free regions that appear in the closure (or
3076 /// generator's) type, in order of appearance. (This numbering is
3077 /// actually defined by the `UniversalRegions` struct in the NLL
3078 /// region checker. See for example
3079 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
3080 /// regions in the closure's type "as if" they were erased, so their
3081 /// precise identity is not important, only their position.
3082 ///
3083 /// Example: If type check produces a closure with the closure substs:
3084 ///
3085 /// ```text
3086 /// ClosureSubsts = [
3087 ///     i8,                                  // the "closure kind"
3088 ///     for<'x> fn(&'a &'x u32) -> &'x u32,  // the "closure signature"
3089 ///     &'a String,                          // some upvar
3090 /// ]
3091 /// ```
3092 ///
3093 /// here, there is one unique free region (`'a`) but it appears
3094 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
3095 ///
3096 /// ```text
3097 /// ClosureSubsts = [
3098 ///     i8,                                  // the "closure kind"
3099 ///     for<'x> fn(&'1 &'x u32) -> &'x u32,  // the "closure signature"
3100 ///     &'2 String,                          // some upvar
3101 /// ]
3102 /// ```
3103 ///
3104 /// Now the code might impose a requirement like `'1: '2`. When an
3105 /// instance of the closure is created, the corresponding free regions
3106 /// can be extracted from its type and constrained to have the given
3107 /// outlives relationship.
3108 ///
3109 /// In some cases, we have to record outlives requirements between
3110 /// types and regions as well. In that case, if those types include
3111 /// any regions, those regions are recorded as `ReClosureBound`
3112 /// instances assigned one of these same indices. Those regions will
3113 /// be substituted away by the creator. We use `ReClosureBound` in
3114 /// that case because the regions must be allocated in the global
3115 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
3116 /// internally within the rest of the NLL code).
3117 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3118 pub struct ClosureRegionRequirements<'gcx> {
3119     /// The number of external regions defined on the closure. In our
3120     /// example above, it would be 3 -- one for `'static`, then `'1`
3121     /// and `'2`. This is just used for a sanity check later on, to
3122     /// make sure that the number of regions we see at the callsite
3123     /// matches.
3124     pub num_external_vids: usize,
3125
3126     /// Requirements between the various free regions defined in
3127     /// indices.
3128     pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
3129 }
3130
3131 /// Indicates an outlives constraint between a type or between two
3132 /// free-regions declared on the closure.
3133 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3134 pub struct ClosureOutlivesRequirement<'tcx> {
3135     // This region or type ...
3136     pub subject: ClosureOutlivesSubject<'tcx>,
3137
3138     // ... must outlive this one.
3139     pub outlived_free_region: ty::RegionVid,
3140
3141     // If not, report an error here ...
3142     pub blame_span: Span,
3143
3144     // ... due to this reason.
3145     pub category: ConstraintCategory,
3146 }
3147
3148 /// Outlives constraints can be categorized to determine whether and why they
3149 /// are interesting (for error reporting). Order of variants indicates sort
3150 /// order of the category, thereby influencing diagnostic output.
3151 ///
3152 /// See also [rustc_mir::borrow_check::nll::constraints]
3153 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
3154          Hash, RustcEncodable, RustcDecodable, HashStable)]
3155 pub enum ConstraintCategory {
3156     Return,
3157     Yield,
3158     UseAsConst,
3159     UseAsStatic,
3160     TypeAnnotation,
3161     Cast,
3162
3163     /// A constraint that came from checking the body of a closure.
3164     ///
3165     /// We try to get the category that the closure used when reporting this.
3166     ClosureBounds,
3167     CallArgument,
3168     CopyBound,
3169     SizedBound,
3170     Assignment,
3171     OpaqueType,
3172
3173     /// A "boring" constraint (caused by the given location) is one that
3174     /// the user probably doesn't want to see described in diagnostics,
3175     /// because it is kind of an artifact of the type system setup.
3176     /// Example: `x = Foo { field: y }` technically creates
3177     /// intermediate regions representing the "type of `Foo { field: y
3178     /// }`", and data flows from `y` into those variables, but they
3179     /// are not very interesting. The assignment into `x` on the other
3180     /// hand might be.
3181     Boring,
3182     // Boring and applicable everywhere.
3183     BoringNoLocation,
3184
3185     /// A constraint that doesn't correspond to anything the user sees.
3186     Internal,
3187 }
3188
3189 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
3190 /// that must outlive some region.
3191 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3192 pub enum ClosureOutlivesSubject<'tcx> {
3193     /// Subject is a type, typically a type parameter, but could also
3194     /// be a projection. Indicates a requirement like `T: 'a` being
3195     /// passed to the caller, where the type here is `T`.
3196     ///
3197     /// The type here is guaranteed not to contain any free regions at
3198     /// present.
3199     Ty(Ty<'tcx>),
3200
3201     /// Subject is a free region from the closure. Indicates a requirement
3202     /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3203     Region(ty::RegionVid),
3204 }
3205
3206 /*
3207  * TypeFoldable implementations for MIR types
3208  */
3209
3210 CloneTypeFoldableAndLiftImpls! {
3211     BlockTailInfo,
3212     MirPhase,
3213     Mutability,
3214     SourceInfo,
3215     UpvarDebuginfo,
3216     FakeReadCause,
3217     RetagKind,
3218     SourceScope,
3219     SourceScopeData,
3220     SourceScopeLocalData,
3221     UserTypeAnnotationIndex,
3222 }
3223
3224 BraceStructTypeFoldableImpl! {
3225     impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
3226         phase,
3227         basic_blocks,
3228         source_scopes,
3229         source_scope_local_data,
3230         promoted,
3231         yield_ty,
3232         generator_drop,
3233         generator_layout,
3234         local_decls,
3235         user_type_annotations,
3236         arg_count,
3237         __upvar_debuginfo_codegen_only_do_not_use,
3238         spread_arg,
3239         control_flow_destroyed,
3240         span,
3241         cache,
3242     }
3243 }
3244
3245 BraceStructTypeFoldableImpl! {
3246     impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3247         field_tys,
3248         variant_fields,
3249         __local_debuginfo_codegen_only_do_not_use,
3250     }
3251 }
3252
3253 BraceStructTypeFoldableImpl! {
3254     impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3255         mutability,
3256         is_user_variable,
3257         internal,
3258         ty,
3259         user_ty,
3260         name,
3261         source_info,
3262         is_block_tail,
3263         visibility_scope,
3264     }
3265 }
3266
3267 BraceStructTypeFoldableImpl! {
3268     impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3269         statements,
3270         terminator,
3271         is_cleanup,
3272     }
3273 }
3274
3275 BraceStructTypeFoldableImpl! {
3276     impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3277         source_info, kind
3278     }
3279 }
3280
3281 EnumTypeFoldableImpl! {
3282     impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3283         (StatementKind::Assign)(a, b),
3284         (StatementKind::FakeRead)(cause, place),
3285         (StatementKind::SetDiscriminant) { place, variant_index },
3286         (StatementKind::StorageLive)(a),
3287         (StatementKind::StorageDead)(a),
3288         (StatementKind::InlineAsm)(a),
3289         (StatementKind::Retag)(kind, place),
3290         (StatementKind::AscribeUserType)(a, v, b),
3291         (StatementKind::Nop),
3292     }
3293 }
3294
3295 BraceStructTypeFoldableImpl! {
3296     impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3297         asm,
3298         outputs,
3299         inputs,
3300     }
3301 }
3302
3303 EnumTypeFoldableImpl! {
3304     impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3305         (ClearCrossCrate::Clear),
3306         (ClearCrossCrate::Set)(a),
3307     } where T: TypeFoldable<'tcx>
3308 }
3309
3310 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3311     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3312         use crate::mir::TerminatorKind::*;
3313
3314         let kind = match self.kind {
3315             Goto { target } => Goto { target },
3316             SwitchInt {
3317                 ref discr,
3318                 switch_ty,
3319                 ref values,
3320                 ref targets,
3321             } => SwitchInt {
3322                 discr: discr.fold_with(folder),
3323                 switch_ty: switch_ty.fold_with(folder),
3324                 values: values.clone(),
3325                 targets: targets.clone(),
3326             },
3327             Drop {
3328                 ref location,
3329                 target,
3330                 unwind,
3331             } => Drop {
3332                 location: location.fold_with(folder),
3333                 target,
3334                 unwind,
3335             },
3336             DropAndReplace {
3337                 ref location,
3338                 ref value,
3339                 target,
3340                 unwind,
3341             } => DropAndReplace {
3342                 location: location.fold_with(folder),
3343                 value: value.fold_with(folder),
3344                 target,
3345                 unwind,
3346             },
3347             Yield {
3348                 ref value,
3349                 resume,
3350                 drop,
3351             } => Yield {
3352                 value: value.fold_with(folder),
3353                 resume: resume,
3354                 drop: drop,
3355             },
3356             Call {
3357                 ref func,
3358                 ref args,
3359                 ref destination,
3360                 cleanup,
3361                 from_hir_call,
3362             } => {
3363                 let dest = destination
3364                     .as_ref()
3365                     .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3366
3367                 Call {
3368                     func: func.fold_with(folder),
3369                     args: args.fold_with(folder),
3370                     destination: dest,
3371                     cleanup,
3372                     from_hir_call,
3373                 }
3374             }
3375             Assert {
3376                 ref cond,
3377                 expected,
3378                 ref msg,
3379                 target,
3380                 cleanup,
3381             } => {
3382                 let msg = if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3383                     InterpError::BoundsCheck {
3384                         len: len.fold_with(folder),
3385                         index: index.fold_with(folder),
3386                     }
3387                 } else {
3388                     msg.clone()
3389                 };
3390                 Assert {
3391                     cond: cond.fold_with(folder),
3392                     expected,
3393                     msg,
3394                     target,
3395                     cleanup,
3396                 }
3397             }
3398             GeneratorDrop => GeneratorDrop,
3399             Resume => Resume,
3400             Abort => Abort,
3401             Return => Return,
3402             Unreachable => Unreachable,
3403             FalseEdges {
3404                 real_target,
3405                 ref imaginary_targets,
3406             } => FalseEdges {
3407                 real_target,
3408                 imaginary_targets: imaginary_targets.clone(),
3409             },
3410             FalseUnwind {
3411                 real_target,
3412                 unwind,
3413             } => FalseUnwind {
3414                 real_target,
3415                 unwind,
3416             },
3417         };
3418         Terminator {
3419             source_info: self.source_info,
3420             kind,
3421         }
3422     }
3423
3424     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3425         use crate::mir::TerminatorKind::*;
3426
3427         match self.kind {
3428             SwitchInt {
3429                 ref discr,
3430                 switch_ty,
3431                 ..
3432             } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3433             Drop { ref location, .. } => location.visit_with(visitor),
3434             DropAndReplace {
3435                 ref location,
3436                 ref value,
3437                 ..
3438             } => location.visit_with(visitor) || value.visit_with(visitor),
3439             Yield { ref value, .. } => value.visit_with(visitor),
3440             Call {
3441                 ref func,
3442                 ref args,
3443                 ref destination,
3444                 ..
3445             } => {
3446                 let dest = if let Some((ref loc, _)) = *destination {
3447                     loc.visit_with(visitor)
3448                 } else {
3449                     false
3450                 };
3451                 dest || func.visit_with(visitor) || args.visit_with(visitor)
3452             }
3453             Assert {
3454                 ref cond, ref msg, ..
3455             } => {
3456                 if cond.visit_with(visitor) {
3457                     if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3458                         len.visit_with(visitor) || index.visit_with(visitor)
3459                     } else {
3460                         false
3461                     }
3462                 } else {
3463                     false
3464                 }
3465             }
3466             Goto { .. }
3467             | Resume
3468             | Abort
3469             | Return
3470             | GeneratorDrop
3471             | Unreachable
3472             | FalseEdges { .. }
3473             | FalseUnwind { .. } => false,
3474         }
3475     }
3476 }
3477
3478 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3479     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3480         match self {
3481             &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3482             _ => self.clone(),
3483         }
3484     }
3485
3486     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3487         if let &Place::Projection(ref p) = self {
3488             p.visit_with(visitor)
3489         } else {
3490             false
3491         }
3492     }
3493 }
3494
3495 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3496     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3497         use crate::mir::Rvalue::*;
3498         match *self {
3499             Use(ref op) => Use(op.fold_with(folder)),
3500             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3501             Ref(region, bk, ref place) => {
3502                 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3503             }
3504             Len(ref place) => Len(place.fold_with(folder)),
3505             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3506             BinaryOp(op, ref rhs, ref lhs) => {
3507                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3508             }
3509             CheckedBinaryOp(op, ref rhs, ref lhs) => {
3510                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3511             }
3512             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3513             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3514             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3515             Aggregate(ref kind, ref fields) => {
3516                 let kind = box match **kind {
3517                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3518                     AggregateKind::Tuple => AggregateKind::Tuple,
3519                     AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3520                         def,
3521                         v,
3522                         substs.fold_with(folder),
3523                         user_ty.fold_with(folder),
3524                         n,
3525                     ),
3526                     AggregateKind::Closure(id, substs) => {
3527                         AggregateKind::Closure(id, substs.fold_with(folder))
3528                     }
3529                     AggregateKind::Generator(id, substs, movablity) => {
3530                         AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3531                     }
3532                 };
3533                 Aggregate(kind, fields.fold_with(folder))
3534             }
3535         }
3536     }
3537
3538     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3539         use crate::mir::Rvalue::*;
3540         match *self {
3541             Use(ref op) => op.visit_with(visitor),
3542             Repeat(ref op, _) => op.visit_with(visitor),
3543             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3544             Len(ref place) => place.visit_with(visitor),
3545             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3546             BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3547                 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3548             }
3549             UnaryOp(_, ref val) => val.visit_with(visitor),
3550             Discriminant(ref place) => place.visit_with(visitor),
3551             NullaryOp(_, ty) => ty.visit_with(visitor),
3552             Aggregate(ref kind, ref fields) => {
3553                 (match **kind {
3554                     AggregateKind::Array(ty) => ty.visit_with(visitor),
3555                     AggregateKind::Tuple => false,
3556                     AggregateKind::Adt(_, _, substs, user_ty, _) => {
3557                         substs.visit_with(visitor) || user_ty.visit_with(visitor)
3558                     }
3559                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3560                     AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3561                 }) || fields.visit_with(visitor)
3562             }
3563         }
3564     }
3565 }
3566
3567 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3568     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3569         match *self {
3570             Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3571             Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3572             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3573         }
3574     }
3575
3576     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3577         match *self {
3578             Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3579             Operand::Constant(ref c) => c.visit_with(visitor),
3580         }
3581     }
3582 }
3583
3584 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<B, V, T>
3585 where
3586     B: TypeFoldable<'tcx>,
3587     V: TypeFoldable<'tcx>,
3588     T: TypeFoldable<'tcx>,
3589 {
3590     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3591         use crate::mir::ProjectionElem::*;
3592
3593         let base = self.base.fold_with(folder);
3594         let elem = match self.elem {
3595             Deref => Deref,
3596             Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3597             Index(ref v) => Index(v.fold_with(folder)),
3598             ref elem => elem.clone(),
3599         };
3600
3601         Projection { base, elem }
3602     }
3603
3604     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3605         use crate::mir::ProjectionElem::*;
3606
3607         self.base.visit_with(visitor) || match self.elem {
3608             Field(_, ref ty) => ty.visit_with(visitor),
3609             Index(ref v) => v.visit_with(visitor),
3610             _ => false,
3611         }
3612     }
3613 }
3614
3615 impl<'tcx> TypeFoldable<'tcx> for Field {
3616     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3617         *self
3618     }
3619     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3620         false
3621     }
3622 }
3623
3624 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3625     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3626         *self
3627     }
3628     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3629         false
3630     }
3631 }
3632
3633 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3634     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3635         Constant {
3636             span: self.span.clone(),
3637             ty: self.ty.fold_with(folder),
3638             user_ty: self.user_ty.fold_with(folder),
3639             literal: self.literal.fold_with(folder),
3640         }
3641     }
3642     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3643         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
3644     }
3645 }