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