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