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