]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/repr.rs
Changed issue number to 36105
[rust.git] / src / librustc / mir / repr.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_id::DefId;
19 use ty::subst::Substs;
20 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
21 use util::ppaux;
22 use rustc_back::slice;
23 use hir::InlineAsm;
24 use std::ascii;
25 use std::borrow::{Cow};
26 use std::cell::Ref;
27 use std::fmt::{self, Debug, Formatter, Write};
28 use std::{iter, u32};
29 use std::ops::{Index, IndexMut};
30 use std::vec::IntoIter;
31 use syntax::ast::{self, Name};
32 use syntax_pos::Span;
33
34 use super::cache::Cache;
35
36 macro_rules! newtype_index {
37     ($name:ident, $debug_name:expr) => (
38         #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
39          RustcEncodable, RustcDecodable)]
40         pub struct $name(u32);
41
42         impl Idx for $name {
43             fn new(value: usize) -> Self {
44                 assert!(value < (u32::MAX) as usize);
45                 $name(value as u32)
46             }
47             fn index(self) -> usize {
48                 self.0 as usize
49             }
50         }
51
52         impl Debug for $name {
53             fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
54                 write!(fmt, "{}{}", $debug_name, self.0)
55             }
56         }
57     )
58 }
59
60 /// Lowered representation of a single function.
61 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
62 pub struct Mir<'tcx> {
63     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
64     /// that indexes into this vector.
65     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
66
67     /// List of visibility (lexical) scopes; these are referenced by statements
68     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
69     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
70
71     /// Rvalues promoted from this function, such as borrows of constants.
72     /// Each of them is the Mir of a constant with the fn's type parameters
73     /// in scope, but no vars or args and a separate set of temps.
74     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
75
76     /// Return type of the function.
77     pub return_ty: Ty<'tcx>,
78
79     /// Variables: these are stack slots corresponding to user variables. They may be
80     /// assigned many times.
81     pub var_decls: IndexVec<Var, VarDecl<'tcx>>,
82
83     /// Args: these are stack slots corresponding to the input arguments.
84     pub arg_decls: IndexVec<Arg, ArgDecl<'tcx>>,
85
86     /// Temp declarations: stack slots that for temporaries created by
87     /// the compiler. These are assigned once, but they are not SSA
88     /// values in that it is possible to borrow them and mutate them
89     /// through the resulting reference.
90     pub temp_decls: IndexVec<Temp, TempDecl<'tcx>>,
91
92     /// Names and capture modes of all the closure upvars, assuming
93     /// the first argument is either the closure or a reference to it.
94     pub upvar_decls: Vec<UpvarDecl>,
95
96     /// A span representing this MIR, for error reporting
97     pub span: Span,
98
99     /// A cache for various calculations
100     cache: Cache
101 }
102
103 /// where execution begins
104 pub const START_BLOCK: BasicBlock = BasicBlock(0);
105
106 impl<'tcx> Mir<'tcx> {
107     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
108                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
109                promoted: IndexVec<Promoted, Mir<'tcx>>,
110                return_ty: Ty<'tcx>,
111                var_decls: IndexVec<Var, VarDecl<'tcx>>,
112                arg_decls: IndexVec<Arg, ArgDecl<'tcx>>,
113                temp_decls: IndexVec<Temp, TempDecl<'tcx>>,
114                upvar_decls: Vec<UpvarDecl>,
115                span: Span) -> Self
116     {
117         Mir {
118             basic_blocks: basic_blocks,
119             visibility_scopes: visibility_scopes,
120             promoted: promoted,
121             return_ty: return_ty,
122             var_decls: var_decls,
123             arg_decls: arg_decls,
124             temp_decls: temp_decls,
125             upvar_decls: upvar_decls,
126             span: span,
127             cache: Cache::new()
128         }
129     }
130
131     #[inline]
132     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
133         &self.basic_blocks
134     }
135
136     #[inline]
137     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
138         self.cache.invalidate();
139         &mut self.basic_blocks
140     }
141
142     #[inline]
143     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
144         self.cache.predecessors(self)
145     }
146
147     #[inline]
148     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
149         Ref::map(self.predecessors(), |p| &p[bb])
150     }
151
152     #[inline]
153     pub fn dominators(&self) -> Dominators<BasicBlock> {
154         dominators(self)
155     }
156
157     /// Maps locals (Arg's, Var's, Temp's and ReturnPointer, in that order)
158     /// to their index in the whole list of locals. This is useful if you
159     /// want to treat all locals the same instead of repeating yourself.
160     pub fn local_index(&self, lvalue: &Lvalue<'tcx>) -> Option<Local> {
161         let idx = match *lvalue {
162             Lvalue::Arg(arg) => arg.index(),
163             Lvalue::Var(var) => {
164                 self.arg_decls.len() +
165                 var.index()
166             }
167             Lvalue::Temp(temp) => {
168                 self.arg_decls.len() +
169                 self.var_decls.len() +
170                 temp.index()
171             }
172             Lvalue::ReturnPointer => {
173                 self.arg_decls.len() +
174                 self.var_decls.len() +
175                 self.temp_decls.len()
176             }
177             Lvalue::Static(_) |
178             Lvalue::Projection(_) => return None
179         };
180         Some(Local::new(idx))
181     }
182
183     /// Counts the number of locals, such that that local_index
184     /// will always return an index smaller than this count.
185     pub fn count_locals(&self) -> usize {
186         self.arg_decls.len() +
187         self.var_decls.len() +
188         self.temp_decls.len() + 1
189     }
190 }
191
192 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
193     type Output = BasicBlockData<'tcx>;
194
195     #[inline]
196     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
197         &self.basic_blocks()[index]
198     }
199 }
200
201 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
202     #[inline]
203     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
204         &mut self.basic_blocks_mut()[index]
205     }
206 }
207
208 /// Grouped information about the source code origin of a MIR entity.
209 /// Intended to be inspected by diagnostics and debuginfo.
210 /// Most passes can work with it as a whole, within a single function.
211 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
212 pub struct SourceInfo {
213     /// Source span for the AST pertaining to this MIR entity.
214     pub span: Span,
215
216     /// The lexical visibility scope, i.e. which bindings can be seen.
217     pub scope: VisibilityScope
218 }
219
220 ///////////////////////////////////////////////////////////////////////////
221 // Mutability and borrow kinds
222
223 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
224 pub enum Mutability {
225     Mut,
226     Not,
227 }
228
229 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
230 pub enum BorrowKind {
231     /// Data must be immutable and is aliasable.
232     Shared,
233
234     /// Data must be immutable but not aliasable.  This kind of borrow
235     /// cannot currently be expressed by the user and is used only in
236     /// implicit closure bindings. It is needed when you the closure
237     /// is borrowing or mutating a mutable referent, e.g.:
238     ///
239     ///    let x: &mut isize = ...;
240     ///    let y = || *x += 5;
241     ///
242     /// If we were to try to translate this closure into a more explicit
243     /// form, we'd encounter an error with the code as written:
244     ///
245     ///    struct Env { x: & &mut isize }
246     ///    let x: &mut isize = ...;
247     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
248     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
249     ///
250     /// This is then illegal because you cannot mutate a `&mut` found
251     /// in an aliasable location. To solve, you'd have to translate with
252     /// an `&mut` borrow:
253     ///
254     ///    struct Env { x: & &mut isize }
255     ///    let x: &mut isize = ...;
256     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
257     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
258     ///
259     /// Now the assignment to `**env.x` is legal, but creating a
260     /// mutable pointer to `x` is not because `x` is not mutable. We
261     /// could fix this by declaring `x` as `let mut x`. This is ok in
262     /// user code, if awkward, but extra weird for closures, since the
263     /// borrow is hidden.
264     ///
265     /// So we introduce a "unique imm" borrow -- the referent is
266     /// immutable, but not aliasable. This solves the problem. For
267     /// simplicity, we don't give users the way to express this
268     /// borrow, it's just used when translating closures.
269     Unique,
270
271     /// Data is mutable and not aliasable.
272     Mut,
273 }
274
275 ///////////////////////////////////////////////////////////////////////////
276 // Variables and temps
277
278 /// A "variable" is a binding declared by the user as part of the fn
279 /// decl, a let, etc.
280 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
281 pub struct VarDecl<'tcx> {
282     /// `let mut x` vs `let x`
283     pub mutability: Mutability,
284
285     /// name that user gave the variable; not that, internally,
286     /// mir references variables by index
287     pub name: Name,
288
289     /// type inferred for this variable (`let x: ty = ...`)
290     pub ty: Ty<'tcx>,
291
292     /// source information (span, scope, etc.) for the declaration
293     pub source_info: SourceInfo,
294 }
295
296 /// A "temp" is a temporary that we place on the stack. They are
297 /// anonymous, always mutable, and have only a type.
298 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
299 pub struct TempDecl<'tcx> {
300     pub ty: Ty<'tcx>,
301 }
302
303 /// A "arg" is one of the function's formal arguments. These are
304 /// anonymous and distinct from the bindings that the user declares.
305 ///
306 /// For example, in this function:
307 ///
308 /// ```
309 /// fn foo((x, y): (i32, u32)) { ... }
310 /// ```
311 ///
312 /// there is only one argument, of type `(i32, u32)`, but two bindings
313 /// (`x` and `y`).
314 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
315 pub struct ArgDecl<'tcx> {
316     pub ty: Ty<'tcx>,
317
318     /// If true, this argument is a tuple after monomorphization,
319     /// and has to be collected from multiple actual arguments.
320     pub spread: bool,
321
322     /// Either keywords::Invalid or the name of a single-binding
323     /// pattern associated with this argument. Useful for debuginfo.
324     pub debug_name: Name
325 }
326
327 /// A closure capture, with its name and mode.
328 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
329 pub struct UpvarDecl {
330     pub debug_name: Name,
331
332     /// If true, the capture is behind a reference.
333     pub by_ref: bool
334 }
335
336 ///////////////////////////////////////////////////////////////////////////
337 // BasicBlock
338
339 newtype_index!(BasicBlock, "bb");
340
341 ///////////////////////////////////////////////////////////////////////////
342 // BasicBlockData and Terminator
343
344 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
345 pub struct BasicBlockData<'tcx> {
346     /// List of statements in this block.
347     pub statements: Vec<Statement<'tcx>>,
348
349     /// Terminator for this block.
350     ///
351     /// NB. This should generally ONLY be `None` during construction.
352     /// Therefore, you should generally access it via the
353     /// `terminator()` or `terminator_mut()` methods. The only
354     /// exception is that certain passes, such as `simplify_cfg`, swap
355     /// out the terminator temporarily with `None` while they continue
356     /// to recurse over the set of basic blocks.
357     pub terminator: Option<Terminator<'tcx>>,
358
359     /// If true, this block lies on an unwind path. This is used
360     /// during trans where distinct kinds of basic blocks may be
361     /// generated (particularly for MSVC cleanup). Unwind blocks must
362     /// only branch to other unwind blocks.
363     pub is_cleanup: bool,
364 }
365
366 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
367 pub struct Terminator<'tcx> {
368     pub source_info: SourceInfo,
369     pub kind: TerminatorKind<'tcx>
370 }
371
372 #[derive(Clone, RustcEncodable, RustcDecodable)]
373 pub enum TerminatorKind<'tcx> {
374     /// block should have one successor in the graph; we jump there
375     Goto {
376         target: BasicBlock,
377     },
378
379     /// jump to branch 0 if this lvalue evaluates to true
380     If {
381         cond: Operand<'tcx>,
382         targets: (BasicBlock, BasicBlock),
383     },
384
385     /// lvalue evaluates to some enum; jump depending on the branch
386     Switch {
387         discr: Lvalue<'tcx>,
388         adt_def: AdtDef<'tcx>,
389         targets: Vec<BasicBlock>,
390     },
391
392     /// operand evaluates to an integer; jump depending on its value
393     /// to one of the targets, and otherwise fallback to `otherwise`
394     SwitchInt {
395         /// discriminant value being tested
396         discr: Lvalue<'tcx>,
397
398         /// type of value being tested
399         switch_ty: Ty<'tcx>,
400
401         /// Possible values. The locations to branch to in each case
402         /// are found in the corresponding indices from the `targets` vector.
403         values: Vec<ConstVal>,
404
405         /// Possible branch sites. The length of this vector should be
406         /// equal to the length of the `values` vector plus 1 -- the
407         /// extra item is the block to branch to if none of the values
408         /// fit.
409         targets: Vec<BasicBlock>,
410     },
411
412     /// Indicates that the landing pad is finished and unwinding should
413     /// continue. Emitted by build::scope::diverge_cleanup.
414     Resume,
415
416     /// Indicates a normal return. The ReturnPointer lvalue should
417     /// have been filled in by now. This should occur at most once.
418     Return,
419
420     /// Indicates a terminator that can never be reached.
421     Unreachable,
422
423     /// Drop the Lvalue
424     Drop {
425         location: Lvalue<'tcx>,
426         target: BasicBlock,
427         unwind: Option<BasicBlock>
428     },
429
430     /// Drop the Lvalue and assign the new value over it
431     DropAndReplace {
432         location: Lvalue<'tcx>,
433         value: Operand<'tcx>,
434         target: BasicBlock,
435         unwind: Option<BasicBlock>,
436     },
437
438     /// Block ends with a call of a converging function
439     Call {
440         /// The function that’s being called
441         func: Operand<'tcx>,
442         /// Arguments the function is called with
443         args: Vec<Operand<'tcx>>,
444         /// Destination for the return value. If some, the call is converging.
445         destination: Option<(Lvalue<'tcx>, BasicBlock)>,
446         /// Cleanups to be done if the call unwinds.
447         cleanup: Option<BasicBlock>
448     },
449
450     /// Jump to the target if the condition has the expected value,
451     /// otherwise panic with a message and a cleanup target.
452     Assert {
453         cond: Operand<'tcx>,
454         expected: bool,
455         msg: AssertMessage<'tcx>,
456         target: BasicBlock,
457         cleanup: Option<BasicBlock>
458     }
459 }
460
461 impl<'tcx> Terminator<'tcx> {
462     pub fn successors(&self) -> Cow<[BasicBlock]> {
463         self.kind.successors()
464     }
465
466     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
467         self.kind.successors_mut()
468     }
469 }
470
471 impl<'tcx> TerminatorKind<'tcx> {
472     pub fn successors(&self) -> Cow<[BasicBlock]> {
473         use self::TerminatorKind::*;
474         match *self {
475             Goto { target: ref b } => slice::ref_slice(b).into_cow(),
476             If { targets: (b1, b2), .. } => vec![b1, b2].into_cow(),
477             Switch { targets: ref b, .. } => b[..].into_cow(),
478             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
479             Resume => (&[]).into_cow(),
480             Return => (&[]).into_cow(),
481             Unreachable => (&[]).into_cow(),
482             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
483             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
484                 slice::ref_slice(t).into_cow(),
485             Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
486             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
487             DropAndReplace { target, unwind: Some(unwind), .. } |
488             Drop { target, unwind: Some(unwind), .. } => {
489                 vec![target, unwind].into_cow()
490             }
491             DropAndReplace { ref target, unwind: None, .. } |
492             Drop { ref target, unwind: None, .. } => {
493                 slice::ref_slice(target).into_cow()
494             }
495             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
496             Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
497         }
498     }
499
500     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
501     // `Vec<&mut BasicBlock>` would look like in the first place.
502     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
503         use self::TerminatorKind::*;
504         match *self {
505             Goto { target: ref mut b } => vec![b],
506             If { targets: (ref mut b1, ref mut b2), .. } => vec![b1, b2],
507             Switch { targets: ref mut b, .. } => b.iter_mut().collect(),
508             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
509             Resume => Vec::new(),
510             Return => Vec::new(),
511             Unreachable => Vec::new(),
512             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
513             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
514             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
515             Call { destination: None, cleanup: None, .. } => vec![],
516             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
517             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
518             DropAndReplace { ref mut target, unwind: None, .. } |
519             Drop { ref mut target, unwind: None, .. } => {
520                 vec![target]
521             }
522             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
523             Assert { ref mut target, .. } => vec![target]
524         }
525     }
526 }
527
528 impl<'tcx> BasicBlockData<'tcx> {
529     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
530         BasicBlockData {
531             statements: vec![],
532             terminator: terminator,
533             is_cleanup: false,
534         }
535     }
536
537     /// Accessor for terminator.
538     ///
539     /// Terminator may not be None after construction of the basic block is complete. This accessor
540     /// provides a convenience way to reach the terminator.
541     pub fn terminator(&self) -> &Terminator<'tcx> {
542         self.terminator.as_ref().expect("invalid terminator state")
543     }
544
545     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
546         self.terminator.as_mut().expect("invalid terminator state")
547     }
548 }
549
550 impl<'tcx> Debug for TerminatorKind<'tcx> {
551     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
552         self.fmt_head(fmt)?;
553         let successors = self.successors();
554         let labels = self.fmt_successor_labels();
555         assert_eq!(successors.len(), labels.len());
556
557         match successors.len() {
558             0 => Ok(()),
559
560             1 => write!(fmt, " -> {:?}", successors[0]),
561
562             _ => {
563                 write!(fmt, " -> [")?;
564                 for (i, target) in successors.iter().enumerate() {
565                     if i > 0 {
566                         write!(fmt, ", ")?;
567                     }
568                     write!(fmt, "{}: {:?}", labels[i], target)?;
569                 }
570                 write!(fmt, "]")
571             }
572
573         }
574     }
575 }
576
577 impl<'tcx> TerminatorKind<'tcx> {
578     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
579     /// successor basic block, if any. The only information not inlcuded is the list of possible
580     /// successors, which may be rendered differently between the text and the graphviz format.
581     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
582         use self::TerminatorKind::*;
583         match *self {
584             Goto { .. } => write!(fmt, "goto"),
585             If { cond: ref lv, .. } => write!(fmt, "if({:?})", lv),
586             Switch { discr: ref lv, .. } => write!(fmt, "switch({:?})", lv),
587             SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
588             Return => write!(fmt, "return"),
589             Resume => write!(fmt, "resume"),
590             Unreachable => write!(fmt, "unreachable"),
591             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
592             DropAndReplace { ref location, ref value, .. } =>
593                 write!(fmt, "replace({:?} <- {:?})", location, value),
594             Call { ref func, ref args, ref destination, .. } => {
595                 if let Some((ref destination, _)) = *destination {
596                     write!(fmt, "{:?} = ", destination)?;
597                 }
598                 write!(fmt, "{:?}(", func)?;
599                 for (index, arg) in args.iter().enumerate() {
600                     if index > 0 {
601                         write!(fmt, ", ")?;
602                     }
603                     write!(fmt, "{:?}", arg)?;
604                 }
605                 write!(fmt, ")")
606             }
607             Assert { ref cond, expected, ref msg, .. } => {
608                 write!(fmt, "assert(")?;
609                 if !expected {
610                     write!(fmt, "!")?;
611                 }
612                 write!(fmt, "{:?}, ", cond)?;
613
614                 match *msg {
615                     AssertMessage::BoundsCheck { ref len, ref index } => {
616                         write!(fmt, "{:?}, {:?}, {:?}",
617                                "index out of bounds: the len is {} but the index is {}",
618                                len, index)?;
619                     }
620                     AssertMessage::Math(ref err) => {
621                         write!(fmt, "{:?}", err.description())?;
622                     }
623                 }
624
625                 write!(fmt, ")")
626             }
627         }
628     }
629
630     /// Return the list of labels for the edges to the successor basic blocks.
631     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
632         use self::TerminatorKind::*;
633         match *self {
634             Return | Resume | Unreachable => vec![],
635             Goto { .. } => vec!["".into()],
636             If { .. } => vec!["true".into(), "false".into()],
637             Switch { ref adt_def, .. } => {
638                 adt_def.variants
639                        .iter()
640                        .map(|variant| variant.name.to_string().into())
641                        .collect()
642             }
643             SwitchInt { ref values, .. } => {
644                 values.iter()
645                       .map(|const_val| {
646                           let mut buf = String::new();
647                           fmt_const_val(&mut buf, const_val).unwrap();
648                           buf.into()
649                       })
650                       .chain(iter::once(String::from("otherwise").into()))
651                       .collect()
652             }
653             Call { destination: Some(_), cleanup: Some(_), .. } =>
654                 vec!["return".into_cow(), "unwind".into_cow()],
655             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
656             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
657             Call { destination: None, cleanup: None, .. } => vec![],
658             DropAndReplace { unwind: None, .. } |
659             Drop { unwind: None, .. } => vec!["return".into_cow()],
660             DropAndReplace { unwind: Some(_), .. } |
661             Drop { unwind: Some(_), .. } => {
662                 vec!["return".into_cow(), "unwind".into_cow()]
663             }
664             Assert { cleanup: None, .. } => vec!["".into()],
665             Assert { .. } =>
666                 vec!["success".into_cow(), "unwind".into_cow()]
667         }
668     }
669 }
670
671 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
672 pub enum AssertMessage<'tcx> {
673     BoundsCheck {
674         len: Operand<'tcx>,
675         index: Operand<'tcx>
676     },
677     Math(ConstMathErr)
678 }
679
680 ///////////////////////////////////////////////////////////////////////////
681 // Statements
682
683 #[derive(Clone, RustcEncodable, RustcDecodable)]
684 pub struct Statement<'tcx> {
685     pub source_info: SourceInfo,
686     pub kind: StatementKind<'tcx>,
687 }
688
689 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
690 pub enum StatementKind<'tcx> {
691     /// Write the RHS Rvalue to the LHS Lvalue.
692     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
693
694     /// Write the discriminant for a variant to the enum Lvalue.
695     SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
696
697     /// Start a live range for the storage of the local.
698     StorageLive(Lvalue<'tcx>),
699
700     /// End the current live range for the storage of the local.
701     StorageDead(Lvalue<'tcx>),
702 }
703
704 impl<'tcx> Debug for Statement<'tcx> {
705     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
706         use self::StatementKind::*;
707         match self.kind {
708             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
709             StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
710             StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
711             SetDiscriminant{lvalue: ref lv, variant_index: index} => {
712                 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
713             }
714         }
715     }
716 }
717
718 ///////////////////////////////////////////////////////////////////////////
719 // Lvalues
720
721 newtype_index!(Var, "var");
722 newtype_index!(Temp, "tmp");
723 newtype_index!(Arg, "arg");
724 newtype_index!(Local, "local");
725
726 /// A path to a value; something that can be evaluated without
727 /// changing or disturbing program state.
728 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
729 pub enum Lvalue<'tcx> {
730     /// local variable declared by the user
731     Var(Var),
732
733     /// temporary introduced during lowering into MIR
734     Temp(Temp),
735
736     /// formal parameter of the function; note that these are NOT the
737     /// bindings that the user declares, which are vars
738     Arg(Arg),
739
740     /// static or static mut variable
741     Static(DefId),
742
743     /// the return pointer of the fn
744     ReturnPointer,
745
746     /// projection out of an lvalue (access a field, deref a pointer, etc)
747     Projection(Box<LvalueProjection<'tcx>>),
748 }
749
750 /// The `Projection` data structure defines things of the form `B.x`
751 /// or `*B` or `B[index]`. Note that it is parameterized because it is
752 /// shared between `Constant` and `Lvalue`. See the aliases
753 /// `LvalueProjection` etc below.
754 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
755 pub struct Projection<'tcx, B, V> {
756     pub base: B,
757     pub elem: ProjectionElem<'tcx, V>,
758 }
759
760 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
761 pub enum ProjectionElem<'tcx, V> {
762     Deref,
763     Field(Field, Ty<'tcx>),
764     Index(V),
765
766     /// These indices are generated by slice patterns. Easiest to explain
767     /// by example:
768     ///
769     /// ```
770     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
771     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
772     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
773     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
774     /// ```
775     ConstantIndex {
776         /// index or -index (in Python terms), depending on from_end
777         offset: u32,
778         /// thing being indexed must be at least this long
779         min_length: u32,
780         /// counting backwards from end?
781         from_end: bool,
782     },
783
784     /// These indices are generated by slice patterns.
785     ///
786     /// slice[from:-to] in Python terms.
787     Subslice {
788         from: u32,
789         to: u32,
790     },
791
792     /// "Downcast" to a variant of an ADT. Currently, we only introduce
793     /// this for ADTs with more than one variant. It may be better to
794     /// just introduce it always, or always for enums.
795     Downcast(AdtDef<'tcx>, usize),
796 }
797
798 /// Alias for projections as they appear in lvalues, where the base is an lvalue
799 /// and the index is an operand.
800 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
801
802 /// Alias for projections as they appear in lvalues, where the base is an lvalue
803 /// and the index is an operand.
804 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
805
806 newtype_index!(Field, "field");
807
808 impl<'tcx> Lvalue<'tcx> {
809     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
810         self.elem(ProjectionElem::Field(f, ty))
811     }
812
813     pub fn deref(self) -> Lvalue<'tcx> {
814         self.elem(ProjectionElem::Deref)
815     }
816
817     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
818         self.elem(ProjectionElem::Index(index))
819     }
820
821     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
822         Lvalue::Projection(Box::new(LvalueProjection {
823             base: self,
824             elem: elem,
825         }))
826     }
827 }
828
829 impl<'tcx> Debug for Lvalue<'tcx> {
830     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
831         use self::Lvalue::*;
832
833         match *self {
834             Var(id) => write!(fmt, "{:?}", id),
835             Arg(id) => write!(fmt, "{:?}", id),
836             Temp(id) => write!(fmt, "{:?}", id),
837             Static(def_id) =>
838                 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
839             ReturnPointer =>
840                 write!(fmt, "return"),
841             Projection(ref data) =>
842                 match data.elem {
843                     ProjectionElem::Downcast(ref adt_def, index) =>
844                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
845                     ProjectionElem::Deref =>
846                         write!(fmt, "(*{:?})", data.base),
847                     ProjectionElem::Field(field, ty) =>
848                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
849                     ProjectionElem::Index(ref index) =>
850                         write!(fmt, "{:?}[{:?}]", data.base, index),
851                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
852                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
853                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
854                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
855                     ProjectionElem::Subslice { from, to } if to == 0 =>
856                         write!(fmt, "{:?}[{:?}:", data.base, from),
857                     ProjectionElem::Subslice { from, to } if from == 0 =>
858                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
859                     ProjectionElem::Subslice { from, to } =>
860                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
861                                from, to),
862
863                 },
864         }
865     }
866 }
867
868 ///////////////////////////////////////////////////////////////////////////
869 // Scopes
870
871 newtype_index!(VisibilityScope, "scope");
872 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
873
874 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
875 pub struct VisibilityScopeData {
876     pub span: Span,
877     pub parent_scope: Option<VisibilityScope>,
878 }
879
880 ///////////////////////////////////////////////////////////////////////////
881 // Operands
882
883 /// These are values that can appear inside an rvalue (or an index
884 /// lvalue). They are intentionally limited to prevent rvalues from
885 /// being nested in one another.
886 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
887 pub enum Operand<'tcx> {
888     Consume(Lvalue<'tcx>),
889     Constant(Constant<'tcx>),
890 }
891
892 impl<'tcx> Debug for Operand<'tcx> {
893     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
894         use self::Operand::*;
895         match *self {
896             Constant(ref a) => write!(fmt, "{:?}", a),
897             Consume(ref lv) => write!(fmt, "{:?}", lv),
898         }
899     }
900 }
901
902 ///////////////////////////////////////////////////////////////////////////
903 /// Rvalues
904
905 #[derive(Clone, RustcEncodable, RustcDecodable)]
906 pub enum Rvalue<'tcx> {
907     /// x (either a move or copy, depending on type of x)
908     Use(Operand<'tcx>),
909
910     /// [x; 32]
911     Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
912
913     /// &x or &mut x
914     Ref(Region, BorrowKind, Lvalue<'tcx>),
915
916     /// length of a [X] or [X;n] value
917     Len(Lvalue<'tcx>),
918
919     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
920
921     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
922     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
923
924     UnaryOp(UnOp, Operand<'tcx>),
925
926     /// Creates an *uninitialized* Box
927     Box(Ty<'tcx>),
928
929     /// Create an aggregate value, like a tuple or struct.  This is
930     /// only needed because we want to distinguish `dest = Foo { x:
931     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
932     /// that `Foo` has a destructor. These rvalues can be optimized
933     /// away after type-checking and before lowering.
934     Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
935
936     InlineAsm {
937         asm: InlineAsm,
938         outputs: Vec<Lvalue<'tcx>>,
939         inputs: Vec<Operand<'tcx>>
940     }
941 }
942
943 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
944 pub enum CastKind {
945     Misc,
946
947     /// Convert unique, zero-sized type for a fn to fn()
948     ReifyFnPointer,
949
950     /// Convert safe fn() to unsafe fn()
951     UnsafeFnPointer,
952
953     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
954     /// trans must figure out the details once full monomorphization
955     /// is known. For example, this could be used to cast from a
956     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
957     /// (presuming `T: Trait`).
958     Unsize,
959 }
960
961 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
962 pub enum AggregateKind<'tcx> {
963     Vec,
964     Tuple,
965     Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
966     Closure(DefId, ClosureSubsts<'tcx>),
967 }
968
969 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
970 pub enum BinOp {
971     /// The `+` operator (addition)
972     Add,
973     /// The `-` operator (subtraction)
974     Sub,
975     /// The `*` operator (multiplication)
976     Mul,
977     /// The `/` operator (division)
978     Div,
979     /// The `%` operator (modulus)
980     Rem,
981     /// The `^` operator (bitwise xor)
982     BitXor,
983     /// The `&` operator (bitwise and)
984     BitAnd,
985     /// The `|` operator (bitwise or)
986     BitOr,
987     /// The `<<` operator (shift left)
988     Shl,
989     /// The `>>` operator (shift right)
990     Shr,
991     /// The `==` operator (equality)
992     Eq,
993     /// The `<` operator (less than)
994     Lt,
995     /// The `<=` operator (less than or equal to)
996     Le,
997     /// The `!=` operator (not equal to)
998     Ne,
999     /// The `>=` operator (greater than or equal to)
1000     Ge,
1001     /// The `>` operator (greater than)
1002     Gt,
1003 }
1004
1005 impl BinOp {
1006     pub fn is_checkable(self) -> bool {
1007         use self::BinOp::*;
1008         match self {
1009             Add | Sub | Mul | Shl | Shr => true,
1010             _ => false
1011         }
1012     }
1013 }
1014
1015 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1016 pub enum UnOp {
1017     /// The `!` operator for logical inversion
1018     Not,
1019     /// The `-` operator for negation
1020     Neg,
1021 }
1022
1023 impl<'tcx> Debug for Rvalue<'tcx> {
1024     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1025         use self::Rvalue::*;
1026
1027         match *self {
1028             Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1029             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1030             Len(ref a) => write!(fmt, "Len({:?})", a),
1031             Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1032             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1033             CheckedBinaryOp(ref op, ref a, ref b) => {
1034                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1035             }
1036             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1037             Box(ref t) => write!(fmt, "Box({:?})", t),
1038             InlineAsm { ref asm, ref outputs, ref inputs } => {
1039                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1040             }
1041
1042             Ref(_, borrow_kind, ref lv) => {
1043                 let kind_str = match borrow_kind {
1044                     BorrowKind::Shared => "",
1045                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1046                 };
1047                 write!(fmt, "&{}{:?}", kind_str, lv)
1048             }
1049
1050             Aggregate(ref kind, ref lvs) => {
1051                 use self::AggregateKind::*;
1052
1053                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1054                     let mut tuple_fmt = fmt.debug_tuple("");
1055                     for lv in lvs {
1056                         tuple_fmt.field(lv);
1057                     }
1058                     tuple_fmt.finish()
1059                 }
1060
1061                 match *kind {
1062                     Vec => write!(fmt, "{:?}", lvs),
1063
1064                     Tuple => {
1065                         match lvs.len() {
1066                             0 => write!(fmt, "()"),
1067                             1 => write!(fmt, "({:?},)", lvs[0]),
1068                             _ => fmt_tuple(fmt, lvs),
1069                         }
1070                     }
1071
1072                     Adt(adt_def, variant, substs) => {
1073                         let variant_def = &adt_def.variants[variant];
1074
1075                         ppaux::parameterized(fmt, substs, variant_def.did,
1076                                              ppaux::Ns::Value, &[])?;
1077
1078                         match variant_def.kind {
1079                             ty::VariantKind::Unit => Ok(()),
1080                             ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
1081                             ty::VariantKind::Struct => {
1082                                 let mut struct_fmt = fmt.debug_struct("");
1083                                 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1084                                     struct_fmt.field(&field.name.as_str(), lv);
1085                                 }
1086                                 struct_fmt.finish()
1087                             }
1088                         }
1089                     }
1090
1091                     Closure(def_id, _) => ty::tls::with(|tcx| {
1092                         if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1093                             let name = format!("[closure@{:?}]", tcx.map.span(node_id));
1094                             let mut struct_fmt = fmt.debug_struct(&name);
1095
1096                             tcx.with_freevars(node_id, |freevars| {
1097                                 for (freevar, lv) in freevars.iter().zip(lvs) {
1098                                     let var_name = tcx.local_var_name_str(freevar.def.var_id());
1099                                     struct_fmt.field(&var_name, lv);
1100                                 }
1101                             });
1102
1103                             struct_fmt.finish()
1104                         } else {
1105                             write!(fmt, "[closure]")
1106                         }
1107                     }),
1108                 }
1109             }
1110         }
1111     }
1112 }
1113
1114 ///////////////////////////////////////////////////////////////////////////
1115 /// Constants
1116 ///
1117 /// Two constants are equal if they are the same constant. Note that
1118 /// this does not necessarily mean that they are "==" in Rust -- in
1119 /// particular one must be wary of `NaN`!
1120
1121 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1122 pub struct Constant<'tcx> {
1123     pub span: Span,
1124     pub ty: Ty<'tcx>,
1125     pub literal: Literal<'tcx>,
1126 }
1127
1128 #[derive(Clone, RustcEncodable, RustcDecodable)]
1129 pub struct TypedConstVal<'tcx> {
1130     pub ty: Ty<'tcx>,
1131     pub span: Span,
1132     pub value: ConstUsize,
1133 }
1134
1135 impl<'tcx> Debug for TypedConstVal<'tcx> {
1136     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1137         write!(fmt, "const {}", ConstInt::Usize(self.value))
1138     }
1139 }
1140
1141 newtype_index!(Promoted, "promoted");
1142
1143 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1144 pub enum Literal<'tcx> {
1145     Item {
1146         def_id: DefId,
1147         substs: &'tcx Substs<'tcx>,
1148     },
1149     Value {
1150         value: ConstVal,
1151     },
1152     Promoted {
1153         // Index into the `promoted` vector of `Mir`.
1154         index: Promoted
1155     },
1156 }
1157
1158 impl<'tcx> Debug for Constant<'tcx> {
1159     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1160         write!(fmt, "{:?}", self.literal)
1161     }
1162 }
1163
1164 impl<'tcx> Debug for Literal<'tcx> {
1165     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1166         use self::Literal::*;
1167         match *self {
1168             Item { def_id, substs } => {
1169                 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[])
1170             }
1171             Value { ref value } => {
1172                 write!(fmt, "const ")?;
1173                 fmt_const_val(fmt, value)
1174             }
1175             Promoted { index } => {
1176                 write!(fmt, "{:?}", index)
1177             }
1178         }
1179     }
1180 }
1181
1182 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1183 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1184     use middle::const_val::ConstVal::*;
1185     match *const_val {
1186         Float(f) => write!(fmt, "{:?}", f),
1187         Integral(n) => write!(fmt, "{}", n),
1188         Str(ref s) => write!(fmt, "{:?}", s),
1189         ByteStr(ref bytes) => {
1190             let escaped: String = bytes
1191                 .iter()
1192                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1193                 .collect();
1194             write!(fmt, "b\"{}\"", escaped)
1195         }
1196         Bool(b) => write!(fmt, "{:?}", b),
1197         Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1198         Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1199             write!(fmt, "{}", node_to_string(node_id)),
1200         Char(c) => write!(fmt, "{:?}", c),
1201         Dummy => bug!(),
1202     }
1203 }
1204
1205 fn node_to_string(node_id: ast::NodeId) -> String {
1206     ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1207 }
1208
1209 fn item_path_str(def_id: DefId) -> String {
1210     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1211 }
1212
1213 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1214
1215     type Node = BasicBlock;
1216
1217     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1218
1219     fn start_node(&self) -> Self::Node { START_BLOCK }
1220
1221     fn predecessors<'graph>(&'graph self, node: Self::Node)
1222                             -> <Self as GraphPredecessors<'graph>>::Iter
1223     {
1224         self.predecessors_for(node).clone().into_iter()
1225     }
1226     fn successors<'graph>(&'graph self, node: Self::Node)
1227                           -> <Self as GraphSuccessors<'graph>>::Iter
1228     {
1229         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1230     }
1231 }
1232
1233 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1234     type Item = BasicBlock;
1235     type Iter = IntoIter<BasicBlock>;
1236 }
1237
1238 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1239     type Item = BasicBlock;
1240     type Iter = IntoIter<BasicBlock>;
1241 }