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