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