]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
f410865a6cd7f37e1b21ab72db5925a92e8bb9c5
[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 README](README.md) for details.
12
13 use graphviz::IntoCow;
14 use middle::const_val::ConstVal;
15 use middle::region;
16 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
17 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
18 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
19 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
20 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
21 use rustc_serialize as serialize;
22 use hir::def::CtorKind;
23 use hir::def_id::DefId;
24 use mir::visit::MirVisitable;
25 use ty::subst::{Subst, Substs};
26 use ty::{self, AdtDef, ClosureSubsts, Region, Ty, TyCtxt, GeneratorInterior};
27 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
28 use util::ppaux;
29 use std::slice;
30 use hir::{self, InlineAsm};
31 use std::ascii;
32 use std::borrow::{Cow};
33 use std::cell::Ref;
34 use std::fmt::{self, Debug, Formatter, Write};
35 use std::{iter, u32};
36 use std::ops::{Index, IndexMut};
37 use std::rc::Rc;
38 use std::vec::IntoIter;
39 use syntax::ast::{self, Name};
40 use syntax::symbol::InternedString;
41 use syntax_pos::Span;
42
43 mod cache;
44 pub mod tcx;
45 pub mod visit;
46 pub mod traversal;
47 pub mod interpret;
48 pub mod mono;
49
50 /// Types for locals
51 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
52
53 pub trait HasLocalDecls<'tcx> {
54     fn local_decls(&self) -> &LocalDecls<'tcx>;
55 }
56
57 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
58     fn local_decls(&self) -> &LocalDecls<'tcx> {
59         self
60     }
61 }
62
63 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
64     fn local_decls(&self) -> &LocalDecls<'tcx> {
65         &self.local_decls
66     }
67 }
68
69 /// Lowered representation of a single function.
70 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
71 pub struct Mir<'tcx> {
72     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
73     /// that indexes into this vector.
74     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
75
76     /// List of visibility (lexical) scopes; these are referenced by statements
77     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
78     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
79
80     /// Crate-local information for each visibility scope, that can't (and
81     /// needn't) be tracked across crates.
82     pub visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope, VisibilityScopeInfo>>,
83
84     /// Rvalues promoted from this function, such as borrows of constants.
85     /// Each of them is the Mir of a constant with the fn's type parameters
86     /// in scope, but a separate set of locals.
87     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
88
89     /// Yield type of the function, if it is a generator.
90     pub yield_ty: Option<Ty<'tcx>>,
91
92     /// Generator drop glue
93     pub generator_drop: Option<Box<Mir<'tcx>>>,
94
95     /// The layout of a generator. Produced by the state transformation.
96     pub generator_layout: Option<GeneratorLayout<'tcx>>,
97
98     /// Declarations of locals.
99     ///
100     /// The first local is the return value pointer, followed by `arg_count`
101     /// locals for the function arguments, followed by any user-declared
102     /// variables and temporaries.
103     pub local_decls: LocalDecls<'tcx>,
104
105     /// Number of arguments this function takes.
106     ///
107     /// Starting at local 1, `arg_count` locals will be provided by the caller
108     /// and can be assumed to be initialized.
109     ///
110     /// If this MIR was built for a constant, this will be 0.
111     pub arg_count: usize,
112
113     /// Names and capture modes of all the closure upvars, assuming
114     /// the first argument is either the closure or a reference to it.
115     pub upvar_decls: Vec<UpvarDecl>,
116
117     /// Mark an argument local (which must be a tuple) as getting passed as
118     /// its individual components at the LLVM level.
119     ///
120     /// This is used for the "rust-call" ABI.
121     pub spread_arg: Option<Local>,
122
123     /// A span representing this MIR, for error reporting
124     pub span: Span,
125
126     /// A cache for various calculations
127     cache: cache::Cache
128 }
129
130 /// where execution begins
131 pub const START_BLOCK: BasicBlock = BasicBlock(0);
132
133 impl<'tcx> Mir<'tcx> {
134     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
135                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
136                visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope,
137                                                                VisibilityScopeInfo>>,
138                promoted: IndexVec<Promoted, Mir<'tcx>>,
139                yield_ty: Option<Ty<'tcx>>,
140                local_decls: IndexVec<Local, LocalDecl<'tcx>>,
141                arg_count: usize,
142                upvar_decls: Vec<UpvarDecl>,
143                span: Span) -> Self
144     {
145         // We need `arg_count` locals, and one for the return place
146         assert!(local_decls.len() >= arg_count + 1,
147             "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
148
149         Mir {
150             basic_blocks,
151             visibility_scopes,
152             visibility_scope_info,
153             promoted,
154             yield_ty,
155             generator_drop: None,
156             generator_layout: None,
157             local_decls,
158             arg_count,
159             upvar_decls,
160             spread_arg: None,
161             span,
162             cache: cache::Cache::new()
163         }
164     }
165
166     #[inline]
167     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
168         &self.basic_blocks
169     }
170
171     #[inline]
172     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
173         self.cache.invalidate();
174         &mut self.basic_blocks
175     }
176
177     #[inline]
178     pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
179         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
180         &mut LocalDecls<'tcx>,
181     ) {
182         self.cache.invalidate();
183         (&mut self.basic_blocks, &mut self.local_decls)
184     }
185
186     #[inline]
187     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
188         self.cache.predecessors(self)
189     }
190
191     #[inline]
192     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
193         Ref::map(self.predecessors(), |p| &p[bb])
194     }
195
196     #[inline]
197     pub fn dominators(&self) -> Dominators<BasicBlock> {
198         dominators(self)
199     }
200
201     #[inline]
202     pub fn local_kind(&self, local: Local) -> LocalKind {
203         let index = local.0 as usize;
204         if index == 0 {
205             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
206                           "return place should be mutable");
207
208             LocalKind::ReturnPointer
209         } else if index < self.arg_count + 1 {
210             LocalKind::Arg
211         } else if self.local_decls[local].name.is_some() {
212             LocalKind::Var
213         } else {
214             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
215                           "temp should be mutable");
216
217             LocalKind::Temp
218         }
219     }
220
221     /// Returns an iterator over all temporaries.
222     #[inline]
223     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
224         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
225             let local = Local::new(index);
226             if self.local_decls[local].is_user_variable {
227                 None
228             } else {
229                 Some(local)
230             }
231         })
232     }
233
234     /// Returns an iterator over all user-declared locals.
235     #[inline]
236     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
237         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
238             let local = Local::new(index);
239             if self.local_decls[local].is_user_variable {
240                 Some(local)
241             } else {
242                 None
243             }
244         })
245     }
246
247     /// Returns an iterator over all function arguments.
248     #[inline]
249     pub fn args_iter(&self) -> impl Iterator<Item=Local> {
250         let arg_count = self.arg_count;
251         (1..arg_count+1).map(Local::new)
252     }
253
254     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
255     /// locals that are neither arguments nor the return place).
256     #[inline]
257     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
258         let arg_count = self.arg_count;
259         let local_count = self.local_decls.len();
260         (arg_count+1..local_count).map(Local::new)
261     }
262
263     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
264     /// invalidating statement indices in `Location`s.
265     pub fn make_statement_nop(&mut self, location: Location) {
266         let block = &mut self[location.block];
267         debug_assert!(location.statement_index < block.statements.len());
268         block.statements[location.statement_index].make_nop()
269     }
270
271     /// Returns the source info associated with `location`.
272     pub fn source_info(&self, location: Location) -> &SourceInfo {
273         let block = &self[location.block];
274         let stmts = &block.statements;
275         let idx = location.statement_index;
276         if idx < stmts.len() {
277             &stmts[idx].source_info
278         } else {
279             assert!(idx == stmts.len());
280             &block.terminator().source_info
281         }
282     }
283
284     /// Return the return type, it always return first element from `local_decls` array
285     pub fn return_ty(&self) -> Ty<'tcx> {
286         self.local_decls[RETURN_PLACE].ty
287     }
288 }
289
290 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
291 pub struct VisibilityScopeInfo {
292     /// A NodeId with lint levels equivalent to this scope's lint levels.
293     pub lint_root: ast::NodeId,
294     /// The unsafe block that contains this node.
295     pub safety: Safety,
296 }
297
298 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
299 pub enum Safety {
300     Safe,
301     /// Unsafe because of a PushUnsafeBlock
302     BuiltinUnsafe,
303     /// Unsafe because of an unsafe fn
304     FnUnsafe,
305     /// Unsafe because of an `unsafe` block
306     ExplicitUnsafe(ast::NodeId)
307 }
308
309 impl_stable_hash_for!(struct Mir<'tcx> {
310     basic_blocks,
311     visibility_scopes,
312     visibility_scope_info,
313     promoted,
314     yield_ty,
315     generator_drop,
316     generator_layout,
317     local_decls,
318     arg_count,
319     upvar_decls,
320     spread_arg,
321     span,
322     cache
323 });
324
325 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
326     type Output = BasicBlockData<'tcx>;
327
328     #[inline]
329     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
330         &self.basic_blocks()[index]
331     }
332 }
333
334 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
335     #[inline]
336     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
337         &mut self.basic_blocks_mut()[index]
338     }
339 }
340
341 #[derive(Clone, Debug)]
342 pub enum ClearCrossCrate<T> {
343     Clear,
344     Set(T)
345 }
346
347 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
348 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
349
350 /// Grouped information about the source code origin of a MIR entity.
351 /// Intended to be inspected by diagnostics and debuginfo.
352 /// Most passes can work with it as a whole, within a single function.
353 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
354 pub struct SourceInfo {
355     /// Source span for the AST pertaining to this MIR entity.
356     pub span: Span,
357
358     /// The lexical visibility scope, i.e. which bindings can be seen.
359     pub scope: VisibilityScope
360 }
361
362 ///////////////////////////////////////////////////////////////////////////
363 // Mutability and borrow kinds
364
365 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
366 pub enum Mutability {
367     Mut,
368     Not,
369 }
370
371 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
372 pub enum BorrowKind {
373     /// Data must be immutable and is aliasable.
374     Shared,
375
376     /// Data must be immutable but not aliasable.  This kind of borrow
377     /// cannot currently be expressed by the user and is used only in
378     /// implicit closure bindings. It is needed when you the closure
379     /// is borrowing or mutating a mutable referent, e.g.:
380     ///
381     ///    let x: &mut isize = ...;
382     ///    let y = || *x += 5;
383     ///
384     /// If we were to try to translate this closure into a more explicit
385     /// form, we'd encounter an error with the code as written:
386     ///
387     ///    struct Env { x: & &mut isize }
388     ///    let x: &mut isize = ...;
389     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
390     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
391     ///
392     /// This is then illegal because you cannot mutate a `&mut` found
393     /// in an aliasable location. To solve, you'd have to translate with
394     /// an `&mut` borrow:
395     ///
396     ///    struct Env { x: & &mut isize }
397     ///    let x: &mut isize = ...;
398     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
399     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
400     ///
401     /// Now the assignment to `**env.x` is legal, but creating a
402     /// mutable pointer to `x` is not because `x` is not mutable. We
403     /// could fix this by declaring `x` as `let mut x`. This is ok in
404     /// user code, if awkward, but extra weird for closures, since the
405     /// borrow is hidden.
406     ///
407     /// So we introduce a "unique imm" borrow -- the referent is
408     /// immutable, but not aliasable. This solves the problem. For
409     /// simplicity, we don't give users the way to express this
410     /// borrow, it's just used when translating closures.
411     Unique,
412
413     /// Data is mutable and not aliasable.
414     Mut,
415 }
416
417 ///////////////////////////////////////////////////////////////////////////
418 // Variables and temps
419
420 newtype_index!(Local
421     {
422         DEBUG_FORMAT = "_{}",
423         const RETURN_PLACE = 0,
424     });
425
426 /// Classifies locals into categories. See `Mir::local_kind`.
427 #[derive(PartialEq, Eq, Debug)]
428 pub enum LocalKind {
429     /// User-declared variable binding
430     Var,
431     /// Compiler-introduced temporary
432     Temp,
433     /// Function argument
434     Arg,
435     /// Location of function's return value
436     ReturnPointer,
437 }
438
439 /// A MIR local.
440 ///
441 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
442 /// argument, or the return place.
443 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
444 pub struct LocalDecl<'tcx> {
445     /// `let mut x` vs `let x`.
446     ///
447     /// Temporaries and the return place are always mutable.
448     pub mutability: Mutability,
449
450     /// True if this corresponds to a user-declared local variable.
451     pub is_user_variable: bool,
452
453     /// True if this is an internal local
454     ///
455     /// These locals are not based on types in the source code and are only used
456     /// for a few desugarings at the moment.
457     ///
458     /// The generator transformation will sanity check the locals which are live
459     /// across a suspension point against the type components of the generator
460     /// which type checking knows are live across a suspension point. We need to
461     /// flag drop flags to avoid triggering this check as they are introduced
462     /// after typeck.
463     ///
464     /// Unsafety checking will also ignore dereferences of these locals,
465     /// so they can be used for raw pointers only used in a desugaring.
466     ///
467     /// This should be sound because the drop flags are fully algebraic, and
468     /// therefore don't affect the OIBIT or outlives properties of the
469     /// generator.
470     pub internal: bool,
471
472     /// Type of this local.
473     pub ty: Ty<'tcx>,
474
475     /// Name of the local, used in debuginfo and pretty-printing.
476     ///
477     /// Note that function arguments can also have this set to `Some(_)`
478     /// to generate better debuginfo.
479     pub name: Option<Name>,
480
481     /// Source info of the local.
482     pub source_info: SourceInfo,
483
484     /// The *lexical* visibility scope the local is defined
485     /// in. If the local was defined in a let-statement, this
486     /// is *within* the let-statement, rather than outside
487     /// of it.
488     pub lexical_scope: VisibilityScope,
489 }
490
491 impl<'tcx> LocalDecl<'tcx> {
492     /// Create a new `LocalDecl` for a temporary.
493     #[inline]
494     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
495         LocalDecl {
496             mutability: Mutability::Mut,
497             ty,
498             name: None,
499             source_info: SourceInfo {
500                 span,
501                 scope: ARGUMENT_VISIBILITY_SCOPE
502             },
503             lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
504             internal: false,
505             is_user_variable: false
506         }
507     }
508
509     /// Create a new `LocalDecl` for a internal temporary.
510     #[inline]
511     pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
512         LocalDecl {
513             mutability: Mutability::Mut,
514             ty,
515             name: None,
516             source_info: SourceInfo {
517                 span,
518                 scope: ARGUMENT_VISIBILITY_SCOPE
519             },
520             lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
521             internal: true,
522             is_user_variable: false
523         }
524     }
525
526     /// Builds a `LocalDecl` for the return place.
527     ///
528     /// This must be inserted into the `local_decls` list as the first local.
529     #[inline]
530     pub fn new_return_place(return_ty: Ty, span: Span) -> LocalDecl {
531         LocalDecl {
532             mutability: Mutability::Mut,
533             ty: return_ty,
534             source_info: SourceInfo {
535                 span,
536                 scope: ARGUMENT_VISIBILITY_SCOPE
537             },
538             lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
539             internal: false,
540             name: None,     // FIXME maybe we do want some name here?
541             is_user_variable: false
542         }
543     }
544 }
545
546 /// A closure capture, with its name and mode.
547 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
548 pub struct UpvarDecl {
549     pub debug_name: Name,
550
551     /// If true, the capture is behind a reference.
552     pub by_ref: bool,
553
554     pub mutability: Mutability,
555 }
556
557 ///////////////////////////////////////////////////////////////////////////
558 // BasicBlock
559
560 newtype_index!(BasicBlock { DEBUG_FORMAT = "bb{}" });
561
562 impl BasicBlock {
563     pub fn start_location(self) -> Location {
564         Location {
565             block: self,
566             statement_index: 0,
567         }
568     }
569 }
570
571 ///////////////////////////////////////////////////////////////////////////
572 // BasicBlockData and Terminator
573
574 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
575 pub struct BasicBlockData<'tcx> {
576     /// List of statements in this block.
577     pub statements: Vec<Statement<'tcx>>,
578
579     /// Terminator for this block.
580     ///
581     /// NB. This should generally ONLY be `None` during construction.
582     /// Therefore, you should generally access it via the
583     /// `terminator()` or `terminator_mut()` methods. The only
584     /// exception is that certain passes, such as `simplify_cfg`, swap
585     /// out the terminator temporarily with `None` while they continue
586     /// to recurse over the set of basic blocks.
587     pub terminator: Option<Terminator<'tcx>>,
588
589     /// If true, this block lies on an unwind path. This is used
590     /// during trans where distinct kinds of basic blocks may be
591     /// generated (particularly for MSVC cleanup). Unwind blocks must
592     /// only branch to other unwind blocks.
593     pub is_cleanup: bool,
594 }
595
596 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
597 pub struct Terminator<'tcx> {
598     pub source_info: SourceInfo,
599     pub kind: TerminatorKind<'tcx>
600 }
601
602 #[derive(Clone, RustcEncodable, RustcDecodable)]
603 pub enum TerminatorKind<'tcx> {
604     /// block should have one successor in the graph; we jump there
605     Goto {
606         target: BasicBlock,
607     },
608
609     /// operand evaluates to an integer; jump depending on its value
610     /// to one of the targets, and otherwise fallback to `otherwise`
611     SwitchInt {
612         /// discriminant value being tested
613         discr: Operand<'tcx>,
614
615         /// type of value being tested
616         switch_ty: Ty<'tcx>,
617
618         /// Possible values. The locations to branch to in each case
619         /// are found in the corresponding indices from the `targets` vector.
620         values: Cow<'tcx, [ConstInt]>,
621
622         /// Possible branch sites. The last element of this vector is used
623         /// for the otherwise branch, so targets.len() == values.len() + 1
624         /// should hold.
625         // This invariant is quite non-obvious and also could be improved.
626         // One way to make this invariant is to have something like this instead:
627         //
628         // branches: Vec<(ConstInt, BasicBlock)>,
629         // otherwise: Option<BasicBlock> // exhaustive if None
630         //
631         // However we’ve decided to keep this as-is until we figure a case
632         // where some other approach seems to be strictly better than other.
633         targets: Vec<BasicBlock>,
634     },
635
636     /// Indicates that the landing pad is finished and unwinding should
637     /// continue. Emitted by build::scope::diverge_cleanup.
638     Resume,
639
640     /// Indicates a normal return. The return place should have
641     /// been filled in by now. This should occur at most once.
642     Return,
643
644     /// Indicates a terminator that can never be reached.
645     Unreachable,
646
647     /// Drop the Place
648     Drop {
649         location: Place<'tcx>,
650         target: BasicBlock,
651         unwind: Option<BasicBlock>
652     },
653
654     /// Drop the Place and assign the new value over it. This ensures
655     /// that the assignment to LV occurs *even if* the destructor for
656     /// place unwinds. Its semantics are best explained by by the
657     /// elaboration:
658     ///
659     /// ```
660     /// BB0 {
661     ///   DropAndReplace(LV <- RV, goto BB1, unwind BB2)
662     /// }
663     /// ```
664     ///
665     /// becomes
666     ///
667     /// ```
668     /// BB0 {
669     ///   Drop(LV, goto BB1, unwind BB2)
670     /// }
671     /// BB1 {
672     ///   // LV is now unitialized
673     ///   LV <- RV
674     /// }
675     /// BB2 {
676     ///   // LV is now unitialized -- its dtor panicked
677     ///   LV <- RV
678     /// }
679     /// ```
680     DropAndReplace {
681         location: Place<'tcx>,
682         value: Operand<'tcx>,
683         target: BasicBlock,
684         unwind: Option<BasicBlock>,
685     },
686
687     /// Block ends with a call of a converging function
688     Call {
689         /// The function that’s being called
690         func: Operand<'tcx>,
691         /// Arguments the function is called with.
692         /// These are owned by the callee, which is free to modify them.
693         /// This allows the memory occupied by "by-value" arguments to be
694         /// reused across function calls without duplicating the contents.
695         args: Vec<Operand<'tcx>>,
696         /// Destination for the return value. If some, the call is converging.
697         destination: Option<(Place<'tcx>, BasicBlock)>,
698         /// Cleanups to be done if the call unwinds.
699         cleanup: Option<BasicBlock>
700     },
701
702     /// Jump to the target if the condition has the expected value,
703     /// otherwise panic with a message and a cleanup target.
704     Assert {
705         cond: Operand<'tcx>,
706         expected: bool,
707         msg: AssertMessage<'tcx>,
708         target: BasicBlock,
709         cleanup: Option<BasicBlock>
710     },
711
712     /// A suspend point
713     Yield {
714         /// The value to return
715         value: Operand<'tcx>,
716         /// Where to resume to
717         resume: BasicBlock,
718         /// Cleanup to be done if the generator is dropped at this suspend point
719         drop: Option<BasicBlock>,
720     },
721
722     /// Indicates the end of the dropping of a generator
723     GeneratorDrop,
724
725     FalseEdges {
726         real_target: BasicBlock,
727         imaginary_targets: Vec<BasicBlock>
728     },
729 }
730
731 impl<'tcx> Terminator<'tcx> {
732     pub fn successors(&self) -> Cow<[BasicBlock]> {
733         self.kind.successors()
734     }
735
736     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
737         self.kind.successors_mut()
738     }
739
740     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
741         self.kind.unwind_mut()
742     }
743 }
744
745 impl<'tcx> TerminatorKind<'tcx> {
746     pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
747                          t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
748         static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
749         TerminatorKind::SwitchInt {
750             discr: cond,
751             switch_ty: tcx.types.bool,
752             values: From::from(BOOL_SWITCH_FALSE),
753             targets: vec![f, t],
754         }
755     }
756
757     pub fn successors(&self) -> Cow<[BasicBlock]> {
758         use self::TerminatorKind::*;
759         match *self {
760             Goto { target: ref b } => slice::from_ref(b).into_cow(),
761             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
762             Resume | GeneratorDrop => (&[]).into_cow(),
763             Return => (&[]).into_cow(),
764             Unreachable => (&[]).into_cow(),
765             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
766             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
767                 slice::from_ref(t).into_cow(),
768             Call { destination: None, cleanup: Some(ref c), .. } => slice::from_ref(c).into_cow(),
769             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
770             Yield { resume: t, drop: Some(c), .. } => vec![t, c].into_cow(),
771             Yield { resume: ref t, drop: None, .. } => slice::from_ref(t).into_cow(),
772             DropAndReplace { target, unwind: Some(unwind), .. } |
773             Drop { target, unwind: Some(unwind), .. } => {
774                 vec![target, unwind].into_cow()
775             }
776             DropAndReplace { ref target, unwind: None, .. } |
777             Drop { ref target, unwind: None, .. } => {
778                 slice::from_ref(target).into_cow()
779             }
780             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
781             Assert { ref target, .. } => slice::from_ref(target).into_cow(),
782             FalseEdges { ref real_target, ref imaginary_targets } => {
783                 let mut s = vec![*real_target];
784                 s.extend_from_slice(imaginary_targets);
785                 s.into_cow()
786             }
787         }
788     }
789
790     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
791     // `Vec<&mut BasicBlock>` would look like in the first place.
792     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
793         use self::TerminatorKind::*;
794         match *self {
795             Goto { target: ref mut b } => vec![b],
796             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
797             Resume | GeneratorDrop => Vec::new(),
798             Return => Vec::new(),
799             Unreachable => Vec::new(),
800             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
801             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
802             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
803             Call { destination: None, cleanup: None, .. } => vec![],
804             Yield { resume: ref mut t, drop: Some(ref mut c), .. } => vec![t, c],
805             Yield { resume: ref mut t, drop: None, .. } => vec![t],
806             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
807             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
808             DropAndReplace { ref mut target, unwind: None, .. } |
809             Drop { ref mut target, unwind: None, .. } => {
810                 vec![target]
811             }
812             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
813             Assert { ref mut target, .. } => vec![target],
814             FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
815                 let mut s = vec![real_target];
816                 s.extend(imaginary_targets.iter_mut());
817                 s
818             }
819         }
820     }
821
822     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
823         match *self {
824             TerminatorKind::Goto { .. } |
825             TerminatorKind::Resume |
826             TerminatorKind::Return |
827             TerminatorKind::Unreachable |
828             TerminatorKind::GeneratorDrop |
829             TerminatorKind::Yield { .. } |
830             TerminatorKind::SwitchInt { .. } |
831             TerminatorKind::FalseEdges { .. } => {
832                 None
833             },
834             TerminatorKind::Call { cleanup: ref mut unwind, .. } |
835             TerminatorKind::Assert { cleanup: ref mut unwind, .. } |
836             TerminatorKind::DropAndReplace { ref mut unwind, .. } |
837             TerminatorKind::Drop { ref mut unwind, .. } => {
838                 Some(unwind)
839             }
840         }
841     }
842 }
843
844 impl<'tcx> BasicBlockData<'tcx> {
845     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
846         BasicBlockData {
847             statements: vec![],
848             terminator,
849             is_cleanup: false,
850         }
851     }
852
853     /// Accessor for terminator.
854     ///
855     /// Terminator may not be None after construction of the basic block is complete. This accessor
856     /// provides a convenience way to reach the terminator.
857     pub fn terminator(&self) -> &Terminator<'tcx> {
858         self.terminator.as_ref().expect("invalid terminator state")
859     }
860
861     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
862         self.terminator.as_mut().expect("invalid terminator state")
863     }
864
865     pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
866         for s in &mut self.statements {
867             if !f(s) {
868                 s.kind = StatementKind::Nop;
869             }
870         }
871     }
872
873     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
874         if index < self.statements.len() {
875             &self.statements[index]
876         } else {
877             &self.terminator
878         }
879     }
880 }
881
882 impl<'tcx> Debug for TerminatorKind<'tcx> {
883     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
884         self.fmt_head(fmt)?;
885         let successors = self.successors();
886         let labels = self.fmt_successor_labels();
887         assert_eq!(successors.len(), labels.len());
888
889         match successors.len() {
890             0 => Ok(()),
891
892             1 => write!(fmt, " -> {:?}", successors[0]),
893
894             _ => {
895                 write!(fmt, " -> [")?;
896                 for (i, target) in successors.iter().enumerate() {
897                     if i > 0 {
898                         write!(fmt, ", ")?;
899                     }
900                     write!(fmt, "{}: {:?}", labels[i], target)?;
901                 }
902                 write!(fmt, "]")
903             }
904
905         }
906     }
907 }
908
909 impl<'tcx> TerminatorKind<'tcx> {
910     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
911     /// successor basic block, if any. The only information not included is the list of possible
912     /// successors, which may be rendered differently between the text and the graphviz format.
913     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
914         use self::TerminatorKind::*;
915         match *self {
916             Goto { .. } => write!(fmt, "goto"),
917             SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
918             Return => write!(fmt, "return"),
919             GeneratorDrop => write!(fmt, "generator_drop"),
920             Resume => write!(fmt, "resume"),
921             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
922             Unreachable => write!(fmt, "unreachable"),
923             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
924             DropAndReplace { ref location, ref value, .. } =>
925                 write!(fmt, "replace({:?} <- {:?})", location, value),
926             Call { ref func, ref args, ref destination, .. } => {
927                 if let Some((ref destination, _)) = *destination {
928                     write!(fmt, "{:?} = ", destination)?;
929                 }
930                 write!(fmt, "{:?}(", func)?;
931                 for (index, arg) in args.iter().enumerate() {
932                     if index > 0 {
933                         write!(fmt, ", ")?;
934                     }
935                     write!(fmt, "{:?}", arg)?;
936                 }
937                 write!(fmt, ")")
938             }
939             Assert { ref cond, expected, ref msg, .. } => {
940                 write!(fmt, "assert(")?;
941                 if !expected {
942                     write!(fmt, "!")?;
943                 }
944                 write!(fmt, "{:?}, ", cond)?;
945
946                 match *msg {
947                     AssertMessage::BoundsCheck { ref len, ref index } => {
948                         write!(fmt, "{:?}, {:?}, {:?}",
949                                "index out of bounds: the len is {} but the index is {}",
950                                len, index)?;
951                     }
952                     AssertMessage::Math(ref err) => {
953                         write!(fmt, "{:?}", err.description())?;
954                     }
955                     AssertMessage::GeneratorResumedAfterReturn => {
956                         write!(fmt, "{:?}", "generator resumed after completion")?;
957                     }
958                     AssertMessage::GeneratorResumedAfterPanic => {
959                         write!(fmt, "{:?}", "generator resumed after panicking")?;
960                     }
961                 }
962
963                 write!(fmt, ")")
964             },
965             FalseEdges { .. } => write!(fmt, "falseEdges")
966         }
967     }
968
969     /// Return the list of labels for the edges to the successor basic blocks.
970     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
971         use self::TerminatorKind::*;
972         match *self {
973             Return | Resume | Unreachable | GeneratorDrop => vec![],
974             Goto { .. } => vec!["".into()],
975             SwitchInt { ref values, .. } => {
976                 values.iter()
977                       .map(|const_val| {
978                           let mut buf = String::new();
979                           fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
980                           buf.into()
981                       })
982                       .chain(iter::once(String::from("otherwise").into()))
983                       .collect()
984             }
985             Call { destination: Some(_), cleanup: Some(_), .. } =>
986                 vec!["return".into_cow(), "unwind".into_cow()],
987             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
988             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
989             Call { destination: None, cleanup: None, .. } => vec![],
990             Yield { drop: Some(_), .. } =>
991                 vec!["resume".into_cow(), "drop".into_cow()],
992             Yield { drop: None, .. } => vec!["resume".into_cow()],
993             DropAndReplace { unwind: None, .. } |
994             Drop { unwind: None, .. } => vec!["return".into_cow()],
995             DropAndReplace { unwind: Some(_), .. } |
996             Drop { unwind: Some(_), .. } => {
997                 vec!["return".into_cow(), "unwind".into_cow()]
998             }
999             Assert { cleanup: None, .. } => vec!["".into()],
1000             Assert { .. } =>
1001                 vec!["success".into_cow(), "unwind".into_cow()],
1002             FalseEdges { ref imaginary_targets, .. } => {
1003                 let mut l = vec!["real".into()];
1004                 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1005                 l
1006             }
1007         }
1008     }
1009 }
1010
1011 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1012 pub enum AssertMessage<'tcx> {
1013     BoundsCheck {
1014         len: Operand<'tcx>,
1015         index: Operand<'tcx>
1016     },
1017     Math(ConstMathErr),
1018     GeneratorResumedAfterReturn,
1019     GeneratorResumedAfterPanic,
1020 }
1021
1022 ///////////////////////////////////////////////////////////////////////////
1023 // Statements
1024
1025 #[derive(Clone, RustcEncodable, RustcDecodable)]
1026 pub struct Statement<'tcx> {
1027     pub source_info: SourceInfo,
1028     pub kind: StatementKind<'tcx>,
1029 }
1030
1031 impl<'tcx> Statement<'tcx> {
1032     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1033     /// invalidating statement indices in `Location`s.
1034     pub fn make_nop(&mut self) {
1035         self.kind = StatementKind::Nop
1036     }
1037 }
1038
1039 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1040 pub enum StatementKind<'tcx> {
1041     /// Write the RHS Rvalue to the LHS Place.
1042     Assign(Place<'tcx>, Rvalue<'tcx>),
1043
1044     /// Write the discriminant for a variant to the enum Place.
1045     SetDiscriminant { place: Place<'tcx>, variant_index: usize },
1046
1047     /// Start a live range for the storage of the local.
1048     StorageLive(Local),
1049
1050     /// End the current live range for the storage of the local.
1051     StorageDead(Local),
1052
1053     /// Execute a piece of inline Assembly.
1054     InlineAsm {
1055         asm: Box<InlineAsm>,
1056         outputs: Vec<Place<'tcx>>,
1057         inputs: Vec<Operand<'tcx>>
1058     },
1059
1060     /// Assert the given places to be valid inhabitants of their type.  These statements are
1061     /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1062     /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1063     Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1064
1065     /// Mark one terminating point of a region scope (i.e. static region).
1066     /// (The starting point(s) arise implicitly from borrows.)
1067     EndRegion(region::Scope),
1068
1069     /// No-op. Useful for deleting instructions without affecting statement indices.
1070     Nop,
1071 }
1072
1073 /// The `ValidationOp` describes what happens with each of the operands of a
1074 /// `Validate` statement.
1075 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1076 pub enum ValidationOp {
1077     /// Recursively traverse the place following the type and validate that all type
1078     /// invariants are maintained.  Furthermore, acquire exclusive/read-only access to the
1079     /// memory reachable from the place.
1080     Acquire,
1081     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1082     /// access.
1083     Release,
1084     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1085     /// access *until* the given region ends.  Then, access will be recovered.
1086     Suspend(region::Scope),
1087 }
1088
1089 impl Debug for ValidationOp {
1090     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1091         use self::ValidationOp::*;
1092         match *self {
1093             Acquire => write!(fmt, "Acquire"),
1094             Release => write!(fmt, "Release"),
1095             // (reuse lifetime rendering policy from ppaux.)
1096             Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1097         }
1098     }
1099 }
1100
1101 // This is generic so that it can be reused by miri
1102 #[derive(Clone, RustcEncodable, RustcDecodable)]
1103 pub struct ValidationOperand<'tcx, T> {
1104     pub place: T,
1105     pub ty: Ty<'tcx>,
1106     pub re: Option<region::Scope>,
1107     pub mutbl: hir::Mutability,
1108 }
1109
1110 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1111     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1112         write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1113         if let Some(ce) = self.re {
1114             // (reuse lifetime rendering policy from ppaux.)
1115             write!(fmt, "/{}", ty::ReScope(ce))?;
1116         }
1117         if let hir::MutImmutable = self.mutbl {
1118             write!(fmt, " (imm)")?;
1119         }
1120         Ok(())
1121     }
1122 }
1123
1124 impl<'tcx> Debug for Statement<'tcx> {
1125     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1126         use self::StatementKind::*;
1127         match self.kind {
1128             Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1129             // (reuse lifetime rendering policy from ppaux.)
1130             EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1131             Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1132             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1133             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1134             SetDiscriminant { ref place, variant_index } => {
1135                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1136             },
1137             InlineAsm { ref asm, ref outputs, ref inputs } => {
1138                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1139             },
1140             Nop => write!(fmt, "nop"),
1141         }
1142     }
1143 }
1144
1145 ///////////////////////////////////////////////////////////////////////////
1146 // Places
1147
1148 /// A path to a value; something that can be evaluated without
1149 /// changing or disturbing program state.
1150 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1151 pub enum Place<'tcx> {
1152     /// local variable
1153     Local(Local),
1154
1155     /// static or static mut variable
1156     Static(Box<Static<'tcx>>),
1157
1158     /// projection out of a place (access a field, deref a pointer, etc)
1159     Projection(Box<PlaceProjection<'tcx>>),
1160 }
1161
1162 /// The def-id of a static, along with its normalized type (which is
1163 /// stored to avoid requiring normalization when reading MIR).
1164 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1165 pub struct Static<'tcx> {
1166     pub def_id: DefId,
1167     pub ty: Ty<'tcx>,
1168 }
1169
1170 impl_stable_hash_for!(struct Static<'tcx> {
1171     def_id,
1172     ty
1173 });
1174
1175 /// The `Projection` data structure defines things of the form `B.x`
1176 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1177 /// shared between `Constant` and `Place`. See the aliases
1178 /// `PlaceProjection` etc below.
1179 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1180 pub struct Projection<'tcx, B, V, T> {
1181     pub base: B,
1182     pub elem: ProjectionElem<'tcx, V, T>,
1183 }
1184
1185 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1186 pub enum ProjectionElem<'tcx, V, T> {
1187     Deref,
1188     Field(Field, T),
1189     Index(V),
1190
1191     /// These indices are generated by slice patterns. Easiest to explain
1192     /// by example:
1193     ///
1194     /// ```
1195     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1196     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1197     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1198     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1199     /// ```
1200     ConstantIndex {
1201         /// index or -index (in Python terms), depending on from_end
1202         offset: u32,
1203         /// thing being indexed must be at least this long
1204         min_length: u32,
1205         /// counting backwards from end?
1206         from_end: bool,
1207     },
1208
1209     /// These indices are generated by slice patterns.
1210     ///
1211     /// slice[from:-to] in Python terms.
1212     Subslice {
1213         from: u32,
1214         to: u32,
1215     },
1216
1217     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1218     /// this for ADTs with more than one variant. It may be better to
1219     /// just introduce it always, or always for enums.
1220     Downcast(&'tcx AdtDef, usize),
1221 }
1222
1223 /// Alias for projections as they appear in places, where the base is a place
1224 /// and the index is a local.
1225 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1226
1227 /// Alias for projections as they appear in places, where the base is a place
1228 /// and the index is a local.
1229 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1230
1231 newtype_index!(Field { DEBUG_FORMAT = "field[{}]" });
1232
1233 impl<'tcx> Place<'tcx> {
1234     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1235         self.elem(ProjectionElem::Field(f, ty))
1236     }
1237
1238     pub fn deref(self) -> Place<'tcx> {
1239         self.elem(ProjectionElem::Deref)
1240     }
1241
1242     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1243         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1244     }
1245
1246     pub fn index(self, index: Local) -> Place<'tcx> {
1247         self.elem(ProjectionElem::Index(index))
1248     }
1249
1250     pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1251         Place::Projection(Box::new(PlaceProjection {
1252             base: self,
1253             elem,
1254         }))
1255     }
1256 }
1257
1258 impl<'tcx> Debug for Place<'tcx> {
1259     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1260         use self::Place::*;
1261
1262         match *self {
1263             Local(id) => write!(fmt, "{:?}", id),
1264             Static(box self::Static { def_id, ty }) =>
1265                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
1266             Projection(ref data) =>
1267                 match data.elem {
1268                     ProjectionElem::Downcast(ref adt_def, index) =>
1269                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
1270                     ProjectionElem::Deref =>
1271                         write!(fmt, "(*{:?})", data.base),
1272                     ProjectionElem::Field(field, ty) =>
1273                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
1274                     ProjectionElem::Index(ref index) =>
1275                         write!(fmt, "{:?}[{:?}]", data.base, index),
1276                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
1277                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
1278                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
1279                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
1280                     ProjectionElem::Subslice { from, to } if to == 0 =>
1281                         write!(fmt, "{:?}[{:?}:]", data.base, from),
1282                     ProjectionElem::Subslice { from, to } if from == 0 =>
1283                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
1284                     ProjectionElem::Subslice { from, to } =>
1285                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
1286                                from, to),
1287
1288                 },
1289         }
1290     }
1291 }
1292
1293 ///////////////////////////////////////////////////////////////////////////
1294 // Scopes
1295
1296 newtype_index!(VisibilityScope
1297     {
1298         DEBUG_FORMAT = "scope[{}]",
1299         const ARGUMENT_VISIBILITY_SCOPE = 0,
1300     });
1301
1302 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1303 pub struct VisibilityScopeData {
1304     pub span: Span,
1305     pub parent_scope: Option<VisibilityScope>,
1306 }
1307
1308 ///////////////////////////////////////////////////////////////////////////
1309 // Operands
1310
1311 /// These are values that can appear inside an rvalue (or an index
1312 /// place). They are intentionally limited to prevent rvalues from
1313 /// being nested in one another.
1314 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1315 pub enum Operand<'tcx> {
1316     /// Copy: The value must be available for use afterwards.
1317     ///
1318     /// This implies that the type of the place must be `Copy`; this is true
1319     /// by construction during build, but also checked by the MIR type checker.
1320     Copy(Place<'tcx>),
1321     /// Move: The value (including old borrows of it) will not be used again.
1322     ///
1323     /// Safe for values of all types (modulo future developments towards `?Move`).
1324     /// Correct usage patterns are enforced by the borrow checker for safe code.
1325     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1326     Move(Place<'tcx>),
1327     Constant(Box<Constant<'tcx>>),
1328 }
1329
1330 impl<'tcx> Debug for Operand<'tcx> {
1331     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1332         use self::Operand::*;
1333         match *self {
1334             Constant(ref a) => write!(fmt, "{:?}", a),
1335             Copy(ref place) => write!(fmt, "{:?}", place),
1336             Move(ref place) => write!(fmt, "move {:?}", place),
1337         }
1338     }
1339 }
1340
1341 impl<'tcx> Operand<'tcx> {
1342     pub fn function_handle<'a>(
1343         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1344         def_id: DefId,
1345         substs: &'tcx Substs<'tcx>,
1346         span: Span,
1347     ) -> Self {
1348         let ty = tcx.type_of(def_id).subst(tcx, substs);
1349         Operand::Constant(box Constant {
1350             span,
1351             ty,
1352             literal: Literal::Value {
1353                 value: tcx.mk_const(ty::Const {
1354                     val: ConstVal::Function(def_id, substs),
1355                     ty
1356                 })
1357             },
1358         })
1359     }
1360
1361     pub fn to_copy(&self) -> Self {
1362         match *self {
1363             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1364             Operand::Move(ref place) => Operand::Copy(place.clone())
1365         }
1366     }
1367 }
1368
1369 ///////////////////////////////////////////////////////////////////////////
1370 /// Rvalues
1371
1372 #[derive(Clone, RustcEncodable, RustcDecodable)]
1373 pub enum Rvalue<'tcx> {
1374     /// x (either a move or copy, depending on type of x)
1375     Use(Operand<'tcx>),
1376
1377     /// [x; 32]
1378     Repeat(Operand<'tcx>, ConstUsize),
1379
1380     /// &x or &mut x
1381     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1382
1383     /// length of a [X] or [X;n] value
1384     Len(Place<'tcx>),
1385
1386     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1387
1388     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1389     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1390
1391     NullaryOp(NullOp, Ty<'tcx>),
1392     UnaryOp(UnOp, Operand<'tcx>),
1393
1394     /// Read the discriminant of an ADT.
1395     ///
1396     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1397     /// be defined to return, say, a 0) if ADT is not an enum.
1398     Discriminant(Place<'tcx>),
1399
1400     /// Create an aggregate value, like a tuple or struct.  This is
1401     /// only needed because we want to distinguish `dest = Foo { x:
1402     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1403     /// that `Foo` has a destructor. These rvalues can be optimized
1404     /// away after type-checking and before lowering.
1405     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1406 }
1407
1408 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1409 pub enum CastKind {
1410     Misc,
1411
1412     /// Convert unique, zero-sized type for a fn to fn()
1413     ReifyFnPointer,
1414
1415     /// Convert non capturing closure to fn()
1416     ClosureFnPointer,
1417
1418     /// Convert safe fn() to unsafe fn()
1419     UnsafeFnPointer,
1420
1421     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1422     /// trans must figure out the details once full monomorphization
1423     /// is known. For example, this could be used to cast from a
1424     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1425     /// (presuming `T: Trait`).
1426     Unsize,
1427 }
1428
1429 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1430 pub enum AggregateKind<'tcx> {
1431     /// The type is of the element
1432     Array(Ty<'tcx>),
1433     Tuple,
1434
1435     /// The second field is variant number (discriminant), it's equal
1436     /// to 0 for struct and union expressions. The fourth field is
1437     /// active field number and is present only for union expressions
1438     /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
1439     /// active field index would identity the field `c`
1440     Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1441
1442     Closure(DefId, ClosureSubsts<'tcx>),
1443     Generator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
1444 }
1445
1446 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1447 pub enum BinOp {
1448     /// The `+` operator (addition)
1449     Add,
1450     /// The `-` operator (subtraction)
1451     Sub,
1452     /// The `*` operator (multiplication)
1453     Mul,
1454     /// The `/` operator (division)
1455     Div,
1456     /// The `%` operator (modulus)
1457     Rem,
1458     /// The `^` operator (bitwise xor)
1459     BitXor,
1460     /// The `&` operator (bitwise and)
1461     BitAnd,
1462     /// The `|` operator (bitwise or)
1463     BitOr,
1464     /// The `<<` operator (shift left)
1465     Shl,
1466     /// The `>>` operator (shift right)
1467     Shr,
1468     /// The `==` operator (equality)
1469     Eq,
1470     /// The `<` operator (less than)
1471     Lt,
1472     /// The `<=` operator (less than or equal to)
1473     Le,
1474     /// The `!=` operator (not equal to)
1475     Ne,
1476     /// The `>=` operator (greater than or equal to)
1477     Ge,
1478     /// The `>` operator (greater than)
1479     Gt,
1480     /// The `ptr.offset` operator
1481     Offset,
1482 }
1483
1484 impl BinOp {
1485     pub fn is_checkable(self) -> bool {
1486         use self::BinOp::*;
1487         match self {
1488             Add | Sub | Mul | Shl | Shr => true,
1489             _ => false
1490         }
1491     }
1492 }
1493
1494 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1495 pub enum NullOp {
1496     /// Return the size of a value of that type
1497     SizeOf,
1498     /// Create a new uninitialized box for a value of that type
1499     Box,
1500 }
1501
1502 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1503 pub enum UnOp {
1504     /// The `!` operator for logical inversion
1505     Not,
1506     /// The `-` operator for negation
1507     Neg,
1508 }
1509
1510 impl<'tcx> Debug for Rvalue<'tcx> {
1511     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1512         use self::Rvalue::*;
1513
1514         match *self {
1515             Use(ref place) => write!(fmt, "{:?}", place),
1516             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1517             Len(ref a) => write!(fmt, "Len({:?})", a),
1518             Cast(ref kind, ref place, ref ty) => {
1519                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
1520             }
1521             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1522             CheckedBinaryOp(ref op, ref a, ref b) => {
1523                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1524             }
1525             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1526             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
1527             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1528             Ref(region, borrow_kind, ref place) => {
1529                 let kind_str = match borrow_kind {
1530                     BorrowKind::Shared => "",
1531                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1532                 };
1533
1534                 // When printing regions, add trailing space if necessary.
1535                 let region = if ppaux::verbose() || ppaux::identify_regions() {
1536                     let mut region = format!("{}", region);
1537                     if region.len() > 0 { region.push(' '); }
1538                     region
1539                 } else {
1540                     // Do not even print 'static
1541                     "".to_owned()
1542                 };
1543                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
1544             }
1545
1546             Aggregate(ref kind, ref places) => {
1547                 fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
1548                     let mut tuple_fmt = fmt.debug_tuple("");
1549                     for place in places {
1550                         tuple_fmt.field(place);
1551                     }
1552                     tuple_fmt.finish()
1553                 }
1554
1555                 match **kind {
1556                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
1557
1558                     AggregateKind::Tuple => {
1559                         match places.len() {
1560                             0 => write!(fmt, "()"),
1561                             1 => write!(fmt, "({:?},)", places[0]),
1562                             _ => fmt_tuple(fmt, places),
1563                         }
1564                     }
1565
1566                     AggregateKind::Adt(adt_def, variant, substs, _) => {
1567                         let variant_def = &adt_def.variants[variant];
1568
1569                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1570
1571                         match variant_def.ctor_kind {
1572                             CtorKind::Const => Ok(()),
1573                             CtorKind::Fn => fmt_tuple(fmt, places),
1574                             CtorKind::Fictive => {
1575                                 let mut struct_fmt = fmt.debug_struct("");
1576                                 for (field, place) in variant_def.fields.iter().zip(places) {
1577                                     struct_fmt.field(&field.name.as_str(), place);
1578                                 }
1579                                 struct_fmt.finish()
1580                             }
1581                         }
1582                     }
1583
1584                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1585                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1586                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1587                                 format!("[closure@{:?}]", node_id)
1588                             } else {
1589                                 format!("[closure@{:?}]", tcx.hir.span(node_id))
1590                             };
1591                             let mut struct_fmt = fmt.debug_struct(&name);
1592
1593                             tcx.with_freevars(node_id, |freevars| {
1594                                 for (freevar, place) in freevars.iter().zip(places) {
1595                                     let var_name = tcx.hir.name(freevar.var_id());
1596                                     struct_fmt.field(&var_name.as_str(), place);
1597                                 }
1598                             });
1599
1600                             struct_fmt.finish()
1601                         } else {
1602                             write!(fmt, "[closure]")
1603                         }
1604                     }),
1605
1606                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
1607                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1608                             let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
1609                             let mut struct_fmt = fmt.debug_struct(&name);
1610
1611                             tcx.with_freevars(node_id, |freevars| {
1612                                 for (freevar, place) in freevars.iter().zip(places) {
1613                                     let var_name = tcx.hir.name(freevar.var_id());
1614                                     struct_fmt.field(&var_name.as_str(), place);
1615                                 }
1616                                 struct_fmt.field("$state", &places[freevars.len()]);
1617                                 for i in (freevars.len() + 1)..places.len() {
1618                                     struct_fmt.field(&format!("${}", i - freevars.len() - 1),
1619                                                      &places[i]);
1620                                 }
1621                             });
1622
1623                             struct_fmt.finish()
1624                         } else {
1625                             write!(fmt, "[generator]")
1626                         }
1627                     }),
1628                 }
1629             }
1630         }
1631     }
1632 }
1633
1634 ///////////////////////////////////////////////////////////////////////////
1635 /// Constants
1636 ///
1637 /// Two constants are equal if they are the same constant. Note that
1638 /// this does not necessarily mean that they are "==" in Rust -- in
1639 /// particular one must be wary of `NaN`!
1640
1641 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1642 pub struct Constant<'tcx> {
1643     pub span: Span,
1644     pub ty: Ty<'tcx>,
1645     pub literal: Literal<'tcx>,
1646 }
1647
1648 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
1649
1650
1651 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1652 pub enum Literal<'tcx> {
1653     Value {
1654         value: &'tcx ty::Const<'tcx>,
1655     },
1656     Promoted {
1657         // Index into the `promoted` vector of `Mir`.
1658         index: Promoted
1659     },
1660 }
1661
1662 impl<'tcx> Debug for Constant<'tcx> {
1663     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1664         write!(fmt, "{:?}", self.literal)
1665     }
1666 }
1667
1668 impl<'tcx> Debug for Literal<'tcx> {
1669     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1670         use self::Literal::*;
1671         match *self {
1672             Value { value } => {
1673                 write!(fmt, "const ")?;
1674                 fmt_const_val(fmt, &value.val)
1675             }
1676             Promoted { index } => {
1677                 write!(fmt, "{:?}", index)
1678             }
1679         }
1680     }
1681 }
1682
1683 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1684 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1685     use middle::const_val::ConstVal::*;
1686     match *const_val {
1687         Float(f) => write!(fmt, "{:?}", f),
1688         Integral(n) => write!(fmt, "{}", n),
1689         Str(s) => write!(fmt, "{:?}", s),
1690         ByteStr(bytes) => {
1691             let escaped: String = bytes.data
1692                 .iter()
1693                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1694                 .collect();
1695             write!(fmt, "b\"{}\"", escaped)
1696         }
1697         Bool(b) => write!(fmt, "{:?}", b),
1698         Char(c) => write!(fmt, "{:?}", c),
1699         Variant(def_id) |
1700         Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1701         Aggregate(_) => bug!("`ConstVal::{:?}` should not be in MIR", const_val),
1702         Unevaluated(..) => write!(fmt, "{:?}", const_val)
1703     }
1704 }
1705
1706 fn item_path_str(def_id: DefId) -> String {
1707     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1708 }
1709
1710 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1711
1712     type Node = BasicBlock;
1713
1714     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1715
1716     fn start_node(&self) -> Self::Node { START_BLOCK }
1717
1718     fn predecessors<'graph>(&'graph self, node: Self::Node)
1719                             -> <Self as GraphPredecessors<'graph>>::Iter
1720     {
1721         self.predecessors_for(node).clone().into_iter()
1722     }
1723     fn successors<'graph>(&'graph self, node: Self::Node)
1724                           -> <Self as GraphSuccessors<'graph>>::Iter
1725     {
1726         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1727     }
1728 }
1729
1730 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1731     type Item = BasicBlock;
1732     type Iter = IntoIter<BasicBlock>;
1733 }
1734
1735 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1736     type Item = BasicBlock;
1737     type Iter = IntoIter<BasicBlock>;
1738 }
1739
1740 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1741 pub struct Location {
1742     /// the location is within this block
1743     pub block: BasicBlock,
1744
1745     /// the location is the start of the this statement; or, if `statement_index`
1746     /// == num-statements, then the start of the terminator.
1747     pub statement_index: usize,
1748 }
1749
1750 impl fmt::Debug for Location {
1751     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1752         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1753     }
1754 }
1755
1756 impl Location {
1757     /// Returns the location immediately after this one within the enclosing block.
1758     ///
1759     /// Note that if this location represents a terminator, then the
1760     /// resulting location would be out of bounds and invalid.
1761     pub fn successor_within_block(&self) -> Location {
1762         Location { block: self.block, statement_index: self.statement_index + 1 }
1763     }
1764
1765     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1766         if self.block == other.block {
1767             self.statement_index <= other.statement_index
1768         } else {
1769             dominators.is_dominated_by(other.block, self.block)
1770         }
1771     }
1772 }
1773
1774 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1775 pub enum UnsafetyViolationKind {
1776     General,
1777     ExternStatic(ast::NodeId),
1778     BorrowPacked(ast::NodeId),
1779 }
1780
1781 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1782 pub struct UnsafetyViolation {
1783     pub source_info: SourceInfo,
1784     pub description: InternedString,
1785     pub kind: UnsafetyViolationKind,
1786 }
1787
1788 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1789 pub struct UnsafetyCheckResult {
1790     /// Violations that are propagated *upwards* from this function
1791     pub violations: Rc<[UnsafetyViolation]>,
1792     /// unsafe blocks in this function, along with whether they are used. This is
1793     /// used for the "unused_unsafe" lint.
1794     pub unsafe_blocks: Rc<[(ast::NodeId, bool)]>,
1795 }
1796
1797 /// The layout of generator state
1798 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1799 pub struct GeneratorLayout<'tcx> {
1800     pub fields: Vec<LocalDecl<'tcx>>,
1801 }
1802
1803 /// After we borrow check a closure, we are left with various
1804 /// requirements that we have inferred between the free regions that
1805 /// appear in the closure's signature or on its field types.  These
1806 /// requirements are then verified and proved by the closure's
1807 /// creating function. This struct encodes those requirements.
1808 ///
1809 /// The requirements are listed as being between various
1810 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
1811 /// vids refer to the free regions that appear in the closure (or
1812 /// generator's) type, in order of appearance. (This numbering is
1813 /// actually defined by the `UniversalRegions` struct in the NLL
1814 /// region checker. See for example
1815 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
1816 /// regions in the closure's type "as if" they were erased, so their
1817 /// precise identity is not important, only their position.
1818 ///
1819 /// Example: If type check produces a closure with the closure substs:
1820 ///
1821 /// ```
1822 /// ClosureSubsts = [
1823 ///     i8,                                  // the "closure kind"
1824 ///     for<'x> fn(&'a &'x u32) -> &'x u32,  // the "closure signature"
1825 ///     &'a String,                          // some upvar
1826 /// ]
1827 /// ```
1828 ///
1829 /// here, there is one unique free region (`'a`) but it appears
1830 /// twice. We would "renumber" each occurence to a unique vid, as follows:
1831 ///
1832 /// ```
1833 /// ClosureSubsts = [
1834 ///     i8,                                  // the "closure kind"
1835 ///     for<'x> fn(&'1 &'x u32) -> &'x u32,  // the "closure signature"
1836 ///     &'2 String,                          // some upvar
1837 /// ]
1838 /// ```
1839 ///
1840 /// Now the code might impose a requirement like `'1: '2`. When an
1841 /// instance of the closure is created, the corresponding free regions
1842 /// can be extracted from its type and constrained to have the given
1843 /// outlives relationship.
1844 ///
1845 /// In some cases, we have to record outlives requirements between
1846 /// types and regions as well. In that case, if those types include
1847 /// any regions, those regions are recorded as `ReClosureBound`
1848 /// instances assigned one of these same indices. Those regions will
1849 /// be substituted away by the creator. We use `ReClosureBound` in
1850 /// that case because the regions must be allocated in the global
1851 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
1852 /// internally within the rest of the NLL code).
1853 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1854 pub struct ClosureRegionRequirements<'gcx> {
1855     /// The number of external regions defined on the closure.  In our
1856     /// example above, it would be 3 -- one for `'static`, then `'1`
1857     /// and `'2`. This is just used for a sanity check later on, to
1858     /// make sure that the number of regions we see at the callsite
1859     /// matches.
1860     pub num_external_vids: usize,
1861
1862     /// Requirements between the various free regions defined in
1863     /// indices.
1864     pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
1865 }
1866
1867 /// Indicates an outlives constraint between a type or between two
1868 /// free-regions declared on the closure.
1869 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
1870 pub struct ClosureOutlivesRequirement<'tcx> {
1871     // This region or type ...
1872     pub subject: ClosureOutlivesSubject<'tcx>,
1873
1874     // .. must outlive this one.
1875     pub outlived_free_region: ty::RegionVid,
1876
1877     // If not, report an error here.
1878     pub blame_span: Span,
1879 }
1880
1881 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
1882 /// that must outlive some region.
1883 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
1884 pub enum ClosureOutlivesSubject<'tcx> {
1885     /// Subject is a type, typically a type parameter, but could also
1886     /// be a projection. Indicates a requirement like `T: 'a` being
1887     /// passed to the caller, where the type here is `T`.
1888     ///
1889     /// The type here is guaranteed not to contain any free regions at
1890     /// present.
1891     Ty(Ty<'tcx>),
1892
1893     /// Subject is a free region from the closure. Indicates a requirement
1894     /// like `'a: 'b` being passed to the caller; the region here is `'a`.
1895     Region(ty::RegionVid),
1896 }
1897
1898 /*
1899  * TypeFoldable implementations for MIR types
1900  */
1901
1902 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1903     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1904         Mir {
1905             basic_blocks: self.basic_blocks.fold_with(folder),
1906             visibility_scopes: self.visibility_scopes.clone(),
1907             visibility_scope_info: self.visibility_scope_info.clone(),
1908             promoted: self.promoted.fold_with(folder),
1909             yield_ty: self.yield_ty.fold_with(folder),
1910             generator_drop: self.generator_drop.fold_with(folder),
1911             generator_layout: self.generator_layout.fold_with(folder),
1912             local_decls: self.local_decls.fold_with(folder),
1913             arg_count: self.arg_count,
1914             upvar_decls: self.upvar_decls.clone(),
1915             spread_arg: self.spread_arg,
1916             span: self.span,
1917             cache: cache::Cache::new()
1918         }
1919     }
1920
1921     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1922         self.basic_blocks.visit_with(visitor) ||
1923         self.generator_drop.visit_with(visitor) ||
1924         self.generator_layout.visit_with(visitor) ||
1925         self.yield_ty.visit_with(visitor) ||
1926         self.promoted.visit_with(visitor)     ||
1927         self.local_decls.visit_with(visitor)
1928     }
1929 }
1930
1931 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
1932     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1933         GeneratorLayout {
1934             fields: self.fields.fold_with(folder),
1935         }
1936     }
1937
1938     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1939         self.fields.visit_with(visitor)
1940     }
1941 }
1942
1943 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1944     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1945         LocalDecl {
1946             ty: self.ty.fold_with(folder),
1947             ..self.clone()
1948         }
1949     }
1950
1951     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1952         self.ty.visit_with(visitor)
1953     }
1954 }
1955
1956 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1957     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1958         BasicBlockData {
1959             statements: self.statements.fold_with(folder),
1960             terminator: self.terminator.fold_with(folder),
1961             is_cleanup: self.is_cleanup
1962         }
1963     }
1964
1965     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1966         self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1967     }
1968 }
1969
1970 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
1971     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1972         ValidationOperand {
1973             place: self.place.fold_with(folder),
1974             ty: self.ty.fold_with(folder),
1975             re: self.re,
1976             mutbl: self.mutbl,
1977         }
1978     }
1979
1980     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1981         self.place.visit_with(visitor) || self.ty.visit_with(visitor)
1982     }
1983 }
1984
1985 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1986     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1987         use mir::StatementKind::*;
1988
1989         let kind = match self.kind {
1990             Assign(ref place, ref rval) => Assign(place.fold_with(folder), rval.fold_with(folder)),
1991             SetDiscriminant { ref place, variant_index } => SetDiscriminant {
1992                 place: place.fold_with(folder),
1993                 variant_index,
1994             },
1995             StorageLive(ref local) => StorageLive(local.fold_with(folder)),
1996             StorageDead(ref local) => StorageDead(local.fold_with(folder)),
1997             InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1998                 asm: asm.clone(),
1999                 outputs: outputs.fold_with(folder),
2000                 inputs: inputs.fold_with(folder)
2001             },
2002
2003             // Note for future: If we want to expose the region scopes
2004             // during the fold, we need to either generalize EndRegion
2005             // to carry `[ty::Region]`, or extend the `TypeFolder`
2006             // trait with a `fn fold_scope`.
2007             EndRegion(ref region_scope) => EndRegion(region_scope.clone()),
2008
2009             Validate(ref op, ref places) =>
2010                 Validate(op.clone(),
2011                          places.iter().map(|operand| operand.fold_with(folder)).collect()),
2012
2013             Nop => Nop,
2014         };
2015         Statement {
2016             source_info: self.source_info,
2017             kind,
2018         }
2019     }
2020
2021     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2022         use mir::StatementKind::*;
2023
2024         match self.kind {
2025             Assign(ref place, ref rval) => { place.visit_with(visitor) || rval.visit_with(visitor) }
2026             SetDiscriminant { ref place, .. } => place.visit_with(visitor),
2027             StorageLive(ref local) |
2028             StorageDead(ref local) => local.visit_with(visitor),
2029             InlineAsm { ref outputs, ref inputs, .. } =>
2030                 outputs.visit_with(visitor) || inputs.visit_with(visitor),
2031
2032             // Note for future: If we want to expose the region scopes
2033             // during the visit, we need to either generalize EndRegion
2034             // to carry `[ty::Region]`, or extend the `TypeVisitor`
2035             // trait with a `fn visit_scope`.
2036             EndRegion(ref _scope) => false,
2037
2038             Validate(ref _op, ref places) =>
2039                 places.iter().any(|ty_and_place| ty_and_place.visit_with(visitor)),
2040
2041             Nop => false,
2042         }
2043     }
2044 }
2045
2046 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2047     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2048         use mir::TerminatorKind::*;
2049
2050         let kind = match self.kind {
2051             Goto { target } => Goto { target: target },
2052             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2053                 discr: discr.fold_with(folder),
2054                 switch_ty: switch_ty.fold_with(folder),
2055                 values: values.clone(),
2056                 targets: targets.clone()
2057             },
2058             Drop { ref location, target, unwind } => Drop {
2059                 location: location.fold_with(folder),
2060                 target,
2061                 unwind,
2062             },
2063             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2064                 location: location.fold_with(folder),
2065                 value: value.fold_with(folder),
2066                 target,
2067                 unwind,
2068             },
2069             Yield { ref value, resume, drop } => Yield {
2070                 value: value.fold_with(folder),
2071                 resume: resume,
2072                 drop: drop,
2073             },
2074             Call { ref func, ref args, ref destination, cleanup } => {
2075                 let dest = destination.as_ref().map(|&(ref loc, dest)| {
2076                     (loc.fold_with(folder), dest)
2077                 });
2078
2079                 Call {
2080                     func: func.fold_with(folder),
2081                     args: args.fold_with(folder),
2082                     destination: dest,
2083                     cleanup,
2084                 }
2085             },
2086             Assert { ref cond, expected, ref msg, target, cleanup } => {
2087                 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2088                     AssertMessage::BoundsCheck {
2089                         len: len.fold_with(folder),
2090                         index: index.fold_with(folder),
2091                     }
2092                 } else {
2093                     msg.clone()
2094                 };
2095                 Assert {
2096                     cond: cond.fold_with(folder),
2097                     expected,
2098                     msg,
2099                     target,
2100                     cleanup,
2101                 }
2102             },
2103             GeneratorDrop => GeneratorDrop,
2104             Resume => Resume,
2105             Return => Return,
2106             Unreachable => Unreachable,
2107             FalseEdges { real_target, ref imaginary_targets } =>
2108                 FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() }
2109         };
2110         Terminator {
2111             source_info: self.source_info,
2112             kind,
2113         }
2114     }
2115
2116     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2117         use mir::TerminatorKind::*;
2118
2119         match self.kind {
2120             SwitchInt { ref discr, switch_ty, .. } =>
2121                 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
2122             Drop { ref location, ..} => location.visit_with(visitor),
2123             DropAndReplace { ref location, ref value, ..} =>
2124                 location.visit_with(visitor) || value.visit_with(visitor),
2125             Yield { ref value, ..} =>
2126                 value.visit_with(visitor),
2127             Call { ref func, ref args, ref destination, .. } => {
2128                 let dest = if let Some((ref loc, _)) = *destination {
2129                     loc.visit_with(visitor)
2130                 } else { false };
2131                 dest || func.visit_with(visitor) || args.visit_with(visitor)
2132             },
2133             Assert { ref cond, ref msg, .. } => {
2134                 if cond.visit_with(visitor) {
2135                     if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2136                         len.visit_with(visitor) || index.visit_with(visitor)
2137                     } else {
2138                         false
2139                     }
2140                 } else {
2141                     false
2142                 }
2143             },
2144             Goto { .. } |
2145             Resume |
2146             Return |
2147             GeneratorDrop |
2148             Unreachable |
2149             FalseEdges { .. } => false
2150         }
2151     }
2152 }
2153
2154 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2155     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2156         match self {
2157             &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
2158             _ => self.clone()
2159         }
2160     }
2161
2162     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2163         if let &Place::Projection(ref p) = self {
2164             p.visit_with(visitor)
2165         } else {
2166             false
2167         }
2168     }
2169 }
2170
2171 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2172     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2173         use mir::Rvalue::*;
2174         match *self {
2175             Use(ref op) => Use(op.fold_with(folder)),
2176             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2177             Ref(region, bk, ref place) =>
2178                 Ref(region.fold_with(folder), bk, place.fold_with(folder)),
2179             Len(ref place) => Len(place.fold_with(folder)),
2180             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2181             BinaryOp(op, ref rhs, ref lhs) =>
2182                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2183             CheckedBinaryOp(op, ref rhs, ref lhs) =>
2184                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2185             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2186             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
2187             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2188             Aggregate(ref kind, ref fields) => {
2189                 let kind = box match **kind {
2190                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2191                     AggregateKind::Tuple => AggregateKind::Tuple,
2192                     AggregateKind::Adt(def, v, substs, n) =>
2193                         AggregateKind::Adt(def, v, substs.fold_with(folder), n),
2194                     AggregateKind::Closure(id, substs) =>
2195                         AggregateKind::Closure(id, substs.fold_with(folder)),
2196                     AggregateKind::Generator(id, substs, interior) =>
2197                         AggregateKind::Generator(id,
2198                                                  substs.fold_with(folder),
2199                                                  interior.fold_with(folder)),
2200                 };
2201                 Aggregate(kind, fields.fold_with(folder))
2202             }
2203         }
2204     }
2205
2206     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2207         use mir::Rvalue::*;
2208         match *self {
2209             Use(ref op) => op.visit_with(visitor),
2210             Repeat(ref op, _) => op.visit_with(visitor),
2211             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
2212             Len(ref place) => place.visit_with(visitor),
2213             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2214             BinaryOp(_, ref rhs, ref lhs) |
2215             CheckedBinaryOp(_, ref rhs, ref lhs) =>
2216                 rhs.visit_with(visitor) || lhs.visit_with(visitor),
2217             UnaryOp(_, ref val) => val.visit_with(visitor),
2218             Discriminant(ref place) => place.visit_with(visitor),
2219             NullaryOp(_, ty) => ty.visit_with(visitor),
2220             Aggregate(ref kind, ref fields) => {
2221                 (match **kind {
2222                     AggregateKind::Array(ty) => ty.visit_with(visitor),
2223                     AggregateKind::Tuple => false,
2224                     AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
2225                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2226                     AggregateKind::Generator(_, substs, interior) => substs.visit_with(visitor) ||
2227                         interior.visit_with(visitor),
2228                 }) || fields.visit_with(visitor)
2229             }
2230         }
2231     }
2232 }
2233
2234 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2235     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2236         match *self {
2237             Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
2238             Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
2239             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2240         }
2241     }
2242
2243     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2244         match *self {
2245             Operand::Copy(ref place) |
2246             Operand::Move(ref place) => place.visit_with(visitor),
2247             Operand::Constant(ref c) => c.visit_with(visitor)
2248         }
2249     }
2250 }
2251
2252 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
2253     where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
2254 {
2255     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2256         use mir::ProjectionElem::*;
2257
2258         let base = self.base.fold_with(folder);
2259         let elem = match self.elem {
2260             Deref => Deref,
2261             Field(f, ref ty) => Field(f, ty.fold_with(folder)),
2262             Index(ref v) => Index(v.fold_with(folder)),
2263             ref elem => elem.clone()
2264         };
2265
2266         Projection {
2267             base,
2268             elem,
2269         }
2270     }
2271
2272     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2273         use mir::ProjectionElem::*;
2274
2275         self.base.visit_with(visitor) ||
2276             match self.elem {
2277                 Field(_, ref ty) => ty.visit_with(visitor),
2278                 Index(ref v) => v.visit_with(visitor),
2279                 _ => false
2280             }
2281     }
2282 }
2283
2284 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2285     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2286         Constant {
2287             span: self.span.clone(),
2288             ty: self.ty.fold_with(folder),
2289             literal: self.literal.fold_with(folder)
2290         }
2291     }
2292     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2293         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
2294     }
2295 }
2296
2297 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
2298     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2299         match *self {
2300             Literal::Value { value } => Literal::Value {
2301                 value: value.fold_with(folder)
2302             },
2303             Literal::Promoted { index } => Literal::Promoted { index }
2304         }
2305     }
2306     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2307         match *self {
2308             Literal::Value { value } => value.visit_with(visitor),
2309             Literal::Promoted { .. } => false
2310         }
2311     }
2312 }