]> git.proxmox.com Git - rustc.git/blob - src/librustc/mir/repr.rs
Imported Upstream version 1.11.0+dfsg1
[rustc.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, FnOutput, 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: FnOutput<'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: FnOutput<'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 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
692 }
693
694 impl<'tcx> Debug for Statement<'tcx> {
695 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
696 use self::StatementKind::*;
697 match self.kind {
698 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv)
699 }
700 }
701 }
702
703 ///////////////////////////////////////////////////////////////////////////
704 // Lvalues
705
706 newtype_index!(Var, "var");
707 newtype_index!(Temp, "tmp");
708 newtype_index!(Arg, "arg");
709 newtype_index!(Local, "local");
710
711 /// A path to a value; something that can be evaluated without
712 /// changing or disturbing program state.
713 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
714 pub enum Lvalue<'tcx> {
715 /// local variable declared by the user
716 Var(Var),
717
718 /// temporary introduced during lowering into MIR
719 Temp(Temp),
720
721 /// formal parameter of the function; note that these are NOT the
722 /// bindings that the user declares, which are vars
723 Arg(Arg),
724
725 /// static or static mut variable
726 Static(DefId),
727
728 /// the return pointer of the fn
729 ReturnPointer,
730
731 /// projection out of an lvalue (access a field, deref a pointer, etc)
732 Projection(Box<LvalueProjection<'tcx>>),
733 }
734
735 /// The `Projection` data structure defines things of the form `B.x`
736 /// or `*B` or `B[index]`. Note that it is parameterized because it is
737 /// shared between `Constant` and `Lvalue`. See the aliases
738 /// `LvalueProjection` etc below.
739 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
740 pub struct Projection<'tcx, B, V> {
741 pub base: B,
742 pub elem: ProjectionElem<'tcx, V>,
743 }
744
745 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
746 pub enum ProjectionElem<'tcx, V> {
747 Deref,
748 Field(Field, Ty<'tcx>),
749 Index(V),
750
751 /// These indices are generated by slice patterns. Easiest to explain
752 /// by example:
753 ///
754 /// ```
755 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
756 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
757 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
758 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
759 /// ```
760 ConstantIndex {
761 /// index or -index (in Python terms), depending on from_end
762 offset: u32,
763 /// thing being indexed must be at least this long
764 min_length: u32,
765 /// counting backwards from end?
766 from_end: bool,
767 },
768
769 /// These indices are generated by slice patterns.
770 ///
771 /// slice[from:-to] in Python terms.
772 Subslice {
773 from: u32,
774 to: u32,
775 },
776
777 /// "Downcast" to a variant of an ADT. Currently, we only introduce
778 /// this for ADTs with more than one variant. It may be better to
779 /// just introduce it always, or always for enums.
780 Downcast(AdtDef<'tcx>, usize),
781 }
782
783 /// Alias for projections as they appear in lvalues, where the base is an lvalue
784 /// and the index is an operand.
785 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
786
787 /// Alias for projections as they appear in lvalues, where the base is an lvalue
788 /// and the index is an operand.
789 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
790
791 newtype_index!(Field, "field");
792
793 impl<'tcx> Lvalue<'tcx> {
794 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
795 self.elem(ProjectionElem::Field(f, ty))
796 }
797
798 pub fn deref(self) -> Lvalue<'tcx> {
799 self.elem(ProjectionElem::Deref)
800 }
801
802 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
803 self.elem(ProjectionElem::Index(index))
804 }
805
806 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
807 Lvalue::Projection(Box::new(LvalueProjection {
808 base: self,
809 elem: elem,
810 }))
811 }
812 }
813
814 impl<'tcx> Debug for Lvalue<'tcx> {
815 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
816 use self::Lvalue::*;
817
818 match *self {
819 Var(id) => write!(fmt, "{:?}", id),
820 Arg(id) => write!(fmt, "{:?}", id),
821 Temp(id) => write!(fmt, "{:?}", id),
822 Static(def_id) =>
823 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
824 ReturnPointer =>
825 write!(fmt, "return"),
826 Projection(ref data) =>
827 match data.elem {
828 ProjectionElem::Downcast(ref adt_def, index) =>
829 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
830 ProjectionElem::Deref =>
831 write!(fmt, "(*{:?})", data.base),
832 ProjectionElem::Field(field, ty) =>
833 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
834 ProjectionElem::Index(ref index) =>
835 write!(fmt, "{:?}[{:?}]", data.base, index),
836 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
837 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
838 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
839 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
840 ProjectionElem::Subslice { from, to } if to == 0 =>
841 write!(fmt, "{:?}[{:?}:", data.base, from),
842 ProjectionElem::Subslice { from, to } if from == 0 =>
843 write!(fmt, "{:?}[:-{:?}]", data.base, to),
844 ProjectionElem::Subslice { from, to } =>
845 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
846 from, to),
847
848 },
849 }
850 }
851 }
852
853 ///////////////////////////////////////////////////////////////////////////
854 // Scopes
855
856 newtype_index!(VisibilityScope, "scope");
857 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
858
859 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
860 pub struct VisibilityScopeData {
861 pub span: Span,
862 pub parent_scope: Option<VisibilityScope>,
863 }
864
865 ///////////////////////////////////////////////////////////////////////////
866 // Operands
867
868 /// These are values that can appear inside an rvalue (or an index
869 /// lvalue). They are intentionally limited to prevent rvalues from
870 /// being nested in one another.
871 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
872 pub enum Operand<'tcx> {
873 Consume(Lvalue<'tcx>),
874 Constant(Constant<'tcx>),
875 }
876
877 impl<'tcx> Debug for Operand<'tcx> {
878 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
879 use self::Operand::*;
880 match *self {
881 Constant(ref a) => write!(fmt, "{:?}", a),
882 Consume(ref lv) => write!(fmt, "{:?}", lv),
883 }
884 }
885 }
886
887 ///////////////////////////////////////////////////////////////////////////
888 /// Rvalues
889
890 #[derive(Clone, RustcEncodable, RustcDecodable)]
891 pub enum Rvalue<'tcx> {
892 /// x (either a move or copy, depending on type of x)
893 Use(Operand<'tcx>),
894
895 /// [x; 32]
896 Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
897
898 /// &x or &mut x
899 Ref(Region, BorrowKind, Lvalue<'tcx>),
900
901 /// length of a [X] or [X;n] value
902 Len(Lvalue<'tcx>),
903
904 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
905
906 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
907 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
908
909 UnaryOp(UnOp, Operand<'tcx>),
910
911 /// Creates an *uninitialized* Box
912 Box(Ty<'tcx>),
913
914 /// Create an aggregate value, like a tuple or struct. This is
915 /// only needed because we want to distinguish `dest = Foo { x:
916 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
917 /// that `Foo` has a destructor. These rvalues can be optimized
918 /// away after type-checking and before lowering.
919 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
920
921 InlineAsm {
922 asm: InlineAsm,
923 outputs: Vec<Lvalue<'tcx>>,
924 inputs: Vec<Operand<'tcx>>
925 }
926 }
927
928 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
929 pub enum CastKind {
930 Misc,
931
932 /// Convert unique, zero-sized type for a fn to fn()
933 ReifyFnPointer,
934
935 /// Convert safe fn() to unsafe fn()
936 UnsafeFnPointer,
937
938 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
939 /// trans must figure out the details once full monomorphization
940 /// is known. For example, this could be used to cast from a
941 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
942 /// (presuming `T: Trait`).
943 Unsize,
944 }
945
946 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
947 pub enum AggregateKind<'tcx> {
948 Vec,
949 Tuple,
950 Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
951 Closure(DefId, ClosureSubsts<'tcx>),
952 }
953
954 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
955 pub enum BinOp {
956 /// The `+` operator (addition)
957 Add,
958 /// The `-` operator (subtraction)
959 Sub,
960 /// The `*` operator (multiplication)
961 Mul,
962 /// The `/` operator (division)
963 Div,
964 /// The `%` operator (modulus)
965 Rem,
966 /// The `^` operator (bitwise xor)
967 BitXor,
968 /// The `&` operator (bitwise and)
969 BitAnd,
970 /// The `|` operator (bitwise or)
971 BitOr,
972 /// The `<<` operator (shift left)
973 Shl,
974 /// The `>>` operator (shift right)
975 Shr,
976 /// The `==` operator (equality)
977 Eq,
978 /// The `<` operator (less than)
979 Lt,
980 /// The `<=` operator (less than or equal to)
981 Le,
982 /// The `!=` operator (not equal to)
983 Ne,
984 /// The `>=` operator (greater than or equal to)
985 Ge,
986 /// The `>` operator (greater than)
987 Gt,
988 }
989
990 impl BinOp {
991 pub fn is_checkable(self) -> bool {
992 use self::BinOp::*;
993 match self {
994 Add | Sub | Mul | Shl | Shr => true,
995 _ => false
996 }
997 }
998 }
999
1000 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1001 pub enum UnOp {
1002 /// The `!` operator for logical inversion
1003 Not,
1004 /// The `-` operator for negation
1005 Neg,
1006 }
1007
1008 impl<'tcx> Debug for Rvalue<'tcx> {
1009 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1010 use self::Rvalue::*;
1011
1012 match *self {
1013 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1014 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1015 Len(ref a) => write!(fmt, "Len({:?})", a),
1016 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1017 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1018 CheckedBinaryOp(ref op, ref a, ref b) => {
1019 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1020 }
1021 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1022 Box(ref t) => write!(fmt, "Box({:?})", t),
1023 InlineAsm { ref asm, ref outputs, ref inputs } => {
1024 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1025 }
1026
1027 Ref(_, borrow_kind, ref lv) => {
1028 let kind_str = match borrow_kind {
1029 BorrowKind::Shared => "",
1030 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1031 };
1032 write!(fmt, "&{}{:?}", kind_str, lv)
1033 }
1034
1035 Aggregate(ref kind, ref lvs) => {
1036 use self::AggregateKind::*;
1037
1038 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1039 let mut tuple_fmt = fmt.debug_tuple("");
1040 for lv in lvs {
1041 tuple_fmt.field(lv);
1042 }
1043 tuple_fmt.finish()
1044 }
1045
1046 match *kind {
1047 Vec => write!(fmt, "{:?}", lvs),
1048
1049 Tuple => {
1050 match lvs.len() {
1051 0 => write!(fmt, "()"),
1052 1 => write!(fmt, "({:?},)", lvs[0]),
1053 _ => fmt_tuple(fmt, lvs),
1054 }
1055 }
1056
1057 Adt(adt_def, variant, substs) => {
1058 let variant_def = &adt_def.variants[variant];
1059
1060 ppaux::parameterized(fmt, substs, variant_def.did,
1061 ppaux::Ns::Value, &[],
1062 |tcx| {
1063 Some(tcx.lookup_item_type(variant_def.did).generics)
1064 })?;
1065
1066 match variant_def.kind() {
1067 ty::VariantKind::Unit => Ok(()),
1068 ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
1069 ty::VariantKind::Struct => {
1070 let mut struct_fmt = fmt.debug_struct("");
1071 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1072 struct_fmt.field(&field.name.as_str(), lv);
1073 }
1074 struct_fmt.finish()
1075 }
1076 }
1077 }
1078
1079 Closure(def_id, _) => ty::tls::with(|tcx| {
1080 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1081 let name = format!("[closure@{:?}]", tcx.map.span(node_id));
1082 let mut struct_fmt = fmt.debug_struct(&name);
1083
1084 tcx.with_freevars(node_id, |freevars| {
1085 for (freevar, lv) in freevars.iter().zip(lvs) {
1086 let var_name = tcx.local_var_name_str(freevar.def.var_id());
1087 struct_fmt.field(&var_name, lv);
1088 }
1089 });
1090
1091 struct_fmt.finish()
1092 } else {
1093 write!(fmt, "[closure]")
1094 }
1095 }),
1096 }
1097 }
1098 }
1099 }
1100 }
1101
1102 ///////////////////////////////////////////////////////////////////////////
1103 /// Constants
1104 ///
1105 /// Two constants are equal if they are the same constant. Note that
1106 /// this does not necessarily mean that they are "==" in Rust -- in
1107 /// particular one must be wary of `NaN`!
1108
1109 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1110 pub struct Constant<'tcx> {
1111 pub span: Span,
1112 pub ty: Ty<'tcx>,
1113 pub literal: Literal<'tcx>,
1114 }
1115
1116 #[derive(Clone, RustcEncodable, RustcDecodable)]
1117 pub struct TypedConstVal<'tcx> {
1118 pub ty: Ty<'tcx>,
1119 pub span: Span,
1120 pub value: ConstUsize,
1121 }
1122
1123 impl<'tcx> Debug for TypedConstVal<'tcx> {
1124 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1125 write!(fmt, "const {}", ConstInt::Usize(self.value))
1126 }
1127 }
1128
1129 newtype_index!(Promoted, "promoted");
1130
1131 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1132 pub enum Literal<'tcx> {
1133 Item {
1134 def_id: DefId,
1135 substs: &'tcx Substs<'tcx>,
1136 },
1137 Value {
1138 value: ConstVal,
1139 },
1140 Promoted {
1141 // Index into the `promoted` vector of `Mir`.
1142 index: Promoted
1143 },
1144 }
1145
1146 impl<'tcx> Debug for Constant<'tcx> {
1147 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1148 write!(fmt, "{:?}", self.literal)
1149 }
1150 }
1151
1152 impl<'tcx> Debug for Literal<'tcx> {
1153 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1154 use self::Literal::*;
1155 match *self {
1156 Item { def_id, substs } => {
1157 ppaux::parameterized(
1158 fmt, substs, def_id, ppaux::Ns::Value, &[],
1159 |tcx| Some(tcx.lookup_item_type(def_id).generics))
1160 }
1161 Value { ref value } => {
1162 write!(fmt, "const ")?;
1163 fmt_const_val(fmt, value)
1164 }
1165 Promoted { index } => {
1166 write!(fmt, "{:?}", index)
1167 }
1168 }
1169 }
1170 }
1171
1172 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1173 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1174 use middle::const_val::ConstVal::*;
1175 match *const_val {
1176 Float(f) => write!(fmt, "{:?}", f),
1177 Integral(n) => write!(fmt, "{}", n),
1178 Str(ref s) => write!(fmt, "{:?}", s),
1179 ByteStr(ref bytes) => {
1180 let escaped: String = bytes
1181 .iter()
1182 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1183 .collect();
1184 write!(fmt, "b\"{}\"", escaped)
1185 }
1186 Bool(b) => write!(fmt, "{:?}", b),
1187 Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1188 Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1189 write!(fmt, "{}", node_to_string(node_id)),
1190 Char(c) => write!(fmt, "{:?}", c),
1191 Dummy => bug!(),
1192 }
1193 }
1194
1195 fn node_to_string(node_id: ast::NodeId) -> String {
1196 ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1197 }
1198
1199 fn item_path_str(def_id: DefId) -> String {
1200 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1201 }
1202
1203 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1204
1205 type Node = BasicBlock;
1206
1207 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1208
1209 fn start_node(&self) -> Self::Node { START_BLOCK }
1210
1211 fn predecessors<'graph>(&'graph self, node: Self::Node)
1212 -> <Self as GraphPredecessors<'graph>>::Iter
1213 {
1214 self.predecessors_for(node).clone().into_iter()
1215 }
1216 fn successors<'graph>(&'graph self, node: Self::Node)
1217 -> <Self as GraphSuccessors<'graph>>::Iter
1218 {
1219 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1220 }
1221 }
1222
1223 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1224 type Item = BasicBlock;
1225 type Iter = IntoIter<BasicBlock>;
1226 }
1227
1228 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1229 type Item = BasicBlock;
1230 type Iter = IntoIter<BasicBlock>;
1231 }