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