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