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