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