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