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