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