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