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