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