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