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