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