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