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