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