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.
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.
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};
24 use rustc_back::slice;
27 use std::borrow::{Cow};
29 use std::fmt::{self, Debug, Formatter, Write};
31 use std::ops::{Index, IndexMut};
32 use std::vec::IntoIter;
33 use syntax::ast::Name;
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);
49 fn new(value: usize) -> Self {
50 assert!(value < (u32::MAX) as usize);
53 fn index(self) -> usize {
58 impl Debug for $name {
59 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
60 write!(fmt, "{}{}", $debug_name, self.0)
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>>,
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>,
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>>,
82 /// Return type of the function.
83 pub return_ty: Ty<'tcx>,
85 /// Declarations of locals.
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>>,
92 /// Number of arguments this function takes.
94 /// Starting at local 1, `arg_count` locals will be provided by the caller
95 /// and can be assumed to be initialized.
97 /// If this MIR was built for a constant, this will be 0.
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>,
104 /// Mark an argument local (which must be a tuple) as getting passed as
105 /// its individual components at the LLVM level.
107 /// This is used for the "rust-call" ABI.
108 pub spread_arg: Option<Local>,
110 /// A span representing this MIR, for error reporting
113 /// A cache for various calculations
117 /// where execution begins
118 pub const START_BLOCK: BasicBlock = BasicBlock(0);
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>>,
125 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
127 upvar_decls: Vec<UpvarDecl>,
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);
136 basic_blocks: basic_blocks,
137 visibility_scopes: visibility_scopes,
139 return_ty: return_ty,
140 local_decls: local_decls,
141 arg_count: arg_count,
142 upvar_decls: upvar_decls,
145 cache: cache::Cache::new()
150 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
155 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
156 self.cache.invalidate();
157 &mut self.basic_blocks
161 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
162 self.cache.predecessors(self)
166 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
167 Ref::map(self.predecessors(), |p| &p[bb])
171 pub fn dominators(&self) -> Dominators<BasicBlock> {
176 pub fn local_kind(&self, local: Local) -> LocalKind {
177 let index = local.0 as usize;
179 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
180 "return pointer should be mutable");
182 LocalKind::ReturnPointer
183 } else if index < self.arg_count + 1 {
185 } else if self.local_decls[local].name.is_some() {
188 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
189 "temp should be mutable");
195 /// Returns an iterator over all temporaries.
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].is_user_variable {
208 /// Returns an iterator over all user-declared locals.
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].is_user_variable {
221 /// Returns an iterator over all function arguments.
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)
228 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
229 /// locals that are neither arguments nor the return pointer).
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)
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()
246 impl_stable_hash_for!(struct Mir<'tcx> {
259 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
260 type Output = BasicBlockData<'tcx>;
263 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
264 &self.basic_blocks()[index]
268 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
270 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
271 &mut self.basic_blocks_mut()[index]
275 /// Grouped information about the source code origin of a MIR entity.
276 /// Intended to be inspected by diagnostics and debuginfo.
277 /// Most passes can work with it as a whole, within a single function.
278 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
279 pub struct SourceInfo {
280 /// Source span for the AST pertaining to this MIR entity.
283 /// The lexical visibility scope, i.e. which bindings can be seen.
284 pub scope: VisibilityScope
287 ///////////////////////////////////////////////////////////////////////////
288 // Mutability and borrow kinds
290 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
291 pub enum Mutability {
296 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
297 pub enum BorrowKind {
298 /// Data must be immutable and is aliasable.
301 /// Data must be immutable but not aliasable. This kind of borrow
302 /// cannot currently be expressed by the user and is used only in
303 /// implicit closure bindings. It is needed when you the closure
304 /// is borrowing or mutating a mutable referent, e.g.:
306 /// let x: &mut isize = ...;
307 /// let y = || *x += 5;
309 /// If we were to try to translate this closure into a more explicit
310 /// form, we'd encounter an error with the code as written:
312 /// struct Env { x: & &mut isize }
313 /// let x: &mut isize = ...;
314 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
315 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
317 /// This is then illegal because you cannot mutate a `&mut` found
318 /// in an aliasable location. To solve, you'd have to translate with
319 /// an `&mut` borrow:
321 /// struct Env { x: & &mut isize }
322 /// let x: &mut isize = ...;
323 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
324 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
326 /// Now the assignment to `**env.x` is legal, but creating a
327 /// mutable pointer to `x` is not because `x` is not mutable. We
328 /// could fix this by declaring `x` as `let mut x`. This is ok in
329 /// user code, if awkward, but extra weird for closures, since the
330 /// borrow is hidden.
332 /// So we introduce a "unique imm" borrow -- the referent is
333 /// immutable, but not aliasable. This solves the problem. For
334 /// simplicity, we don't give users the way to express this
335 /// borrow, it's just used when translating closures.
338 /// Data is mutable and not aliasable.
342 ///////////////////////////////////////////////////////////////////////////
343 // Variables and temps
345 newtype_index!(Local, "_");
347 pub const RETURN_POINTER: Local = Local(0);
349 /// Classifies locals into categories. See `Mir::local_kind`.
350 #[derive(PartialEq, Eq, Debug)]
352 /// User-declared variable binding
354 /// Compiler-introduced temporary
356 /// Function argument
358 /// Location of function's return value
364 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
365 /// argument, or the return pointer.
366 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
367 pub struct LocalDecl<'tcx> {
368 /// `let mut x` vs `let x`.
370 /// Temporaries and the return pointer are always mutable.
371 pub mutability: Mutability,
373 /// True if this corresponds to a user-declared local variable.
374 pub is_user_variable: bool,
376 /// Type of this local.
379 /// Name of the local, used in debuginfo and pretty-printing.
381 /// Note that function arguments can also have this set to `Some(_)`
382 /// to generate better debuginfo.
383 pub name: Option<Name>,
385 /// Source info of the local.
386 pub source_info: SourceInfo,
389 impl<'tcx> LocalDecl<'tcx> {
390 /// Create a new `LocalDecl` for a temporary.
392 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
394 mutability: Mutability::Mut,
397 source_info: SourceInfo {
399 scope: ARGUMENT_VISIBILITY_SCOPE
401 is_user_variable: false
405 /// Builds a `LocalDecl` for the return pointer.
407 /// This must be inserted into the `local_decls` list as the first local.
409 pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
411 mutability: Mutability::Mut,
413 source_info: SourceInfo {
415 scope: ARGUMENT_VISIBILITY_SCOPE
417 name: None, // FIXME maybe we do want some name here?
418 is_user_variable: false
423 /// A closure capture, with its name and mode.
424 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
425 pub struct UpvarDecl {
426 pub debug_name: Name,
428 /// If true, the capture is behind a reference.
432 ///////////////////////////////////////////////////////////////////////////
435 newtype_index!(BasicBlock, "bb");
437 ///////////////////////////////////////////////////////////////////////////
438 // BasicBlockData and Terminator
440 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
441 pub struct BasicBlockData<'tcx> {
442 /// List of statements in this block.
443 pub statements: Vec<Statement<'tcx>>,
445 /// Terminator for this block.
447 /// NB. This should generally ONLY be `None` during construction.
448 /// Therefore, you should generally access it via the
449 /// `terminator()` or `terminator_mut()` methods. The only
450 /// exception is that certain passes, such as `simplify_cfg`, swap
451 /// out the terminator temporarily with `None` while they continue
452 /// to recurse over the set of basic blocks.
453 pub terminator: Option<Terminator<'tcx>>,
455 /// If true, this block lies on an unwind path. This is used
456 /// during trans where distinct kinds of basic blocks may be
457 /// generated (particularly for MSVC cleanup). Unwind blocks must
458 /// only branch to other unwind blocks.
459 pub is_cleanup: bool,
462 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
463 pub struct Terminator<'tcx> {
464 pub source_info: SourceInfo,
465 pub kind: TerminatorKind<'tcx>
468 #[derive(Clone, RustcEncodable, RustcDecodable)]
469 pub enum TerminatorKind<'tcx> {
470 /// block should have one successor in the graph; we jump there
475 /// operand evaluates to an integer; jump depending on its value
476 /// to one of the targets, and otherwise fallback to `otherwise`
478 /// discriminant value being tested
479 discr: Operand<'tcx>,
481 /// type of value being tested
484 /// Possible values. The locations to branch to in each case
485 /// are found in the corresponding indices from the `targets` vector.
486 values: Cow<'tcx, [ConstInt]>,
488 /// Possible branch sites. The last element of this vector is used
489 /// for the otherwise branch, so targets.len() == values.len() + 1
491 // This invariant is quite non-obvious and also could be improved.
492 // One way to make this invariant is to have something like this instead:
494 // branches: Vec<(ConstInt, BasicBlock)>,
495 // otherwise: Option<BasicBlock> // exhaustive if None
497 // However we’ve decided to keep this as-is until we figure a case
498 // where some other approach seems to be strictly better than other.
499 targets: Vec<BasicBlock>,
502 /// Indicates that the landing pad is finished and unwinding should
503 /// continue. Emitted by build::scope::diverge_cleanup.
506 /// Indicates a normal return. The return pointer lvalue should
507 /// have been filled in by now. This should occur at most once.
510 /// Indicates a terminator that can never be reached.
515 location: Lvalue<'tcx>,
517 unwind: Option<BasicBlock>
520 /// Drop the Lvalue and assign the new value over it
522 location: Lvalue<'tcx>,
523 value: Operand<'tcx>,
525 unwind: Option<BasicBlock>,
528 /// Block ends with a call of a converging function
530 /// The function that’s being called
532 /// Arguments the function is called with
533 args: Vec<Operand<'tcx>>,
534 /// Destination for the return value. If some, the call is converging.
535 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
536 /// Cleanups to be done if the call unwinds.
537 cleanup: Option<BasicBlock>
540 /// Jump to the target if the condition has the expected value,
541 /// otherwise panic with a message and a cleanup target.
545 msg: AssertMessage<'tcx>,
547 cleanup: Option<BasicBlock>
551 impl<'tcx> Terminator<'tcx> {
552 pub fn successors(&self) -> Cow<[BasicBlock]> {
553 self.kind.successors()
556 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
557 self.kind.successors_mut()
561 impl<'tcx> TerminatorKind<'tcx> {
562 pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
563 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
564 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
565 TerminatorKind::SwitchInt {
567 switch_ty: tcx.types.bool,
568 values: From::from(BOOL_SWITCH_FALSE),
573 pub fn successors(&self) -> Cow<[BasicBlock]> {
574 use self::TerminatorKind::*;
576 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
577 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
578 Resume => (&[]).into_cow(),
579 Return => (&[]).into_cow(),
580 Unreachable => (&[]).into_cow(),
581 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
582 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
583 slice::ref_slice(t).into_cow(),
584 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
585 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
586 DropAndReplace { target, unwind: Some(unwind), .. } |
587 Drop { target, unwind: Some(unwind), .. } => {
588 vec![target, unwind].into_cow()
590 DropAndReplace { ref target, unwind: None, .. } |
591 Drop { ref target, unwind: None, .. } => {
592 slice::ref_slice(target).into_cow()
594 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
595 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
599 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
600 // `Vec<&mut BasicBlock>` would look like in the first place.
601 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
602 use self::TerminatorKind::*;
604 Goto { target: ref mut b } => vec![b],
605 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
606 Resume => Vec::new(),
607 Return => Vec::new(),
608 Unreachable => Vec::new(),
609 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
610 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
611 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
612 Call { destination: None, cleanup: None, .. } => vec![],
613 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
614 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
615 DropAndReplace { ref mut target, unwind: None, .. } |
616 Drop { ref mut target, unwind: None, .. } => {
619 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
620 Assert { ref mut target, .. } => vec![target]
625 impl<'tcx> BasicBlockData<'tcx> {
626 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
629 terminator: terminator,
634 /// Accessor for terminator.
636 /// Terminator may not be None after construction of the basic block is complete. This accessor
637 /// provides a convenience way to reach the terminator.
638 pub fn terminator(&self) -> &Terminator<'tcx> {
639 self.terminator.as_ref().expect("invalid terminator state")
642 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
643 self.terminator.as_mut().expect("invalid terminator state")
647 impl<'tcx> Debug for TerminatorKind<'tcx> {
648 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
650 let successors = self.successors();
651 let labels = self.fmt_successor_labels();
652 assert_eq!(successors.len(), labels.len());
654 match successors.len() {
657 1 => write!(fmt, " -> {:?}", successors[0]),
660 write!(fmt, " -> [")?;
661 for (i, target) in successors.iter().enumerate() {
665 write!(fmt, "{}: {:?}", labels[i], target)?;
674 impl<'tcx> TerminatorKind<'tcx> {
675 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
676 /// successor basic block, if any. The only information not inlcuded is the list of possible
677 /// successors, which may be rendered differently between the text and the graphviz format.
678 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
679 use self::TerminatorKind::*;
681 Goto { .. } => write!(fmt, "goto"),
682 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
683 Return => write!(fmt, "return"),
684 Resume => write!(fmt, "resume"),
685 Unreachable => write!(fmt, "unreachable"),
686 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
687 DropAndReplace { ref location, ref value, .. } =>
688 write!(fmt, "replace({:?} <- {:?})", location, value),
689 Call { ref func, ref args, ref destination, .. } => {
690 if let Some((ref destination, _)) = *destination {
691 write!(fmt, "{:?} = ", destination)?;
693 write!(fmt, "{:?}(", func)?;
694 for (index, arg) in args.iter().enumerate() {
698 write!(fmt, "{:?}", arg)?;
702 Assert { ref cond, expected, ref msg, .. } => {
703 write!(fmt, "assert(")?;
707 write!(fmt, "{:?}, ", cond)?;
710 AssertMessage::BoundsCheck { ref len, ref index } => {
711 write!(fmt, "{:?}, {:?}, {:?}",
712 "index out of bounds: the len is {} but the index is {}",
715 AssertMessage::Math(ref err) => {
716 write!(fmt, "{:?}", err.description())?;
725 /// Return the list of labels for the edges to the successor basic blocks.
726 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
727 use self::TerminatorKind::*;
729 Return | Resume | Unreachable => vec![],
730 Goto { .. } => vec!["".into()],
731 SwitchInt { ref values, .. } => {
734 let mut buf = String::new();
735 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
738 .chain(iter::once(String::from("otherwise").into()))
741 Call { destination: Some(_), cleanup: Some(_), .. } =>
742 vec!["return".into_cow(), "unwind".into_cow()],
743 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
744 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
745 Call { destination: None, cleanup: None, .. } => vec![],
746 DropAndReplace { unwind: None, .. } |
747 Drop { unwind: None, .. } => vec!["return".into_cow()],
748 DropAndReplace { unwind: Some(_), .. } |
749 Drop { unwind: Some(_), .. } => {
750 vec!["return".into_cow(), "unwind".into_cow()]
752 Assert { cleanup: None, .. } => vec!["".into()],
754 vec!["success".into_cow(), "unwind".into_cow()]
759 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
760 pub enum AssertMessage<'tcx> {
768 ///////////////////////////////////////////////////////////////////////////
771 #[derive(Clone, RustcEncodable, RustcDecodable)]
772 pub struct Statement<'tcx> {
773 pub source_info: SourceInfo,
774 pub kind: StatementKind<'tcx>,
777 impl<'tcx> Statement<'tcx> {
778 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
779 /// invalidating statement indices in `Location`s.
780 pub fn make_nop(&mut self) {
781 self.kind = StatementKind::Nop
785 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
786 pub enum StatementKind<'tcx> {
787 /// Write the RHS Rvalue to the LHS Lvalue.
788 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
790 /// Write the discriminant for a variant to the enum Lvalue.
791 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
793 /// Start a live range for the storage of the local.
794 StorageLive(Lvalue<'tcx>),
796 /// End the current live range for the storage of the local.
797 StorageDead(Lvalue<'tcx>),
801 outputs: Vec<Lvalue<'tcx>>,
802 inputs: Vec<Operand<'tcx>>
805 /// No-op. Useful for deleting instructions without affecting statement indices.
809 impl<'tcx> Debug for Statement<'tcx> {
810 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
811 use self::StatementKind::*;
813 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
814 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
815 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
816 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
817 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
819 InlineAsm { ref asm, ref outputs, ref inputs } => {
820 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
822 Nop => write!(fmt, "nop"),
827 ///////////////////////////////////////////////////////////////////////////
830 /// A path to a value; something that can be evaluated without
831 /// changing or disturbing program state.
832 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
833 pub enum Lvalue<'tcx> {
837 /// static or static mut variable
838 Static(Box<Static<'tcx>>),
840 /// projection out of an lvalue (access a field, deref a pointer, etc)
841 Projection(Box<LvalueProjection<'tcx>>),
844 /// The def-id of a static, along with its normalized type (which is
845 /// stored to avoid requiring normalization when reading MIR).
846 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
847 pub struct Static<'tcx> {
852 impl_stable_hash_for!(struct Static<'tcx> {
857 /// The `Projection` data structure defines things of the form `B.x`
858 /// or `*B` or `B[index]`. Note that it is parameterized because it is
859 /// shared between `Constant` and `Lvalue`. See the aliases
860 /// `LvalueProjection` etc below.
861 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
862 pub struct Projection<'tcx, B, V> {
864 pub elem: ProjectionElem<'tcx, V>,
867 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
868 pub enum ProjectionElem<'tcx, V> {
870 Field(Field, Ty<'tcx>),
873 /// These indices are generated by slice patterns. Easiest to explain
877 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
878 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
879 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
880 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
883 /// index or -index (in Python terms), depending on from_end
885 /// thing being indexed must be at least this long
887 /// counting backwards from end?
891 /// These indices are generated by slice patterns.
893 /// slice[from:-to] in Python terms.
899 /// "Downcast" to a variant of an ADT. Currently, we only introduce
900 /// this for ADTs with more than one variant. It may be better to
901 /// just introduce it always, or always for enums.
902 Downcast(&'tcx AdtDef, usize),
905 /// Alias for projections as they appear in lvalues, where the base is an lvalue
906 /// and the index is an operand.
907 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
909 /// Alias for projections as they appear in lvalues, where the base is an lvalue
910 /// and the index is an operand.
911 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
913 newtype_index!(Field, "field");
915 impl<'tcx> Lvalue<'tcx> {
916 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
917 self.elem(ProjectionElem::Field(f, ty))
920 pub fn deref(self) -> Lvalue<'tcx> {
921 self.elem(ProjectionElem::Deref)
924 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
925 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
928 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
929 self.elem(ProjectionElem::Index(index))
932 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
933 Lvalue::Projection(Box::new(LvalueProjection {
940 impl<'tcx> Debug for Lvalue<'tcx> {
941 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
945 Local(id) => write!(fmt, "{:?}", id),
946 Static(box self::Static { def_id, ty }) =>
947 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
948 Projection(ref data) =>
950 ProjectionElem::Downcast(ref adt_def, index) =>
951 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
952 ProjectionElem::Deref =>
953 write!(fmt, "(*{:?})", data.base),
954 ProjectionElem::Field(field, ty) =>
955 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
956 ProjectionElem::Index(ref index) =>
957 write!(fmt, "{:?}[{:?}]", data.base, index),
958 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
959 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
960 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
961 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
962 ProjectionElem::Subslice { from, to } if to == 0 =>
963 write!(fmt, "{:?}[{:?}:]", data.base, from),
964 ProjectionElem::Subslice { from, to } if from == 0 =>
965 write!(fmt, "{:?}[:-{:?}]", data.base, to),
966 ProjectionElem::Subslice { from, to } =>
967 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
975 ///////////////////////////////////////////////////////////////////////////
978 newtype_index!(VisibilityScope, "scope");
979 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
981 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
982 pub struct VisibilityScopeData {
984 pub parent_scope: Option<VisibilityScope>,
987 ///////////////////////////////////////////////////////////////////////////
990 /// These are values that can appear inside an rvalue (or an index
991 /// lvalue). They are intentionally limited to prevent rvalues from
992 /// being nested in one another.
993 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
994 pub enum Operand<'tcx> {
995 Consume(Lvalue<'tcx>),
996 Constant(Constant<'tcx>),
999 impl<'tcx> Debug for Operand<'tcx> {
1000 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1001 use self::Operand::*;
1003 Constant(ref a) => write!(fmt, "{:?}", a),
1004 Consume(ref lv) => write!(fmt, "{:?}", lv),
1009 impl<'tcx> Operand<'tcx> {
1010 pub fn function_handle<'a>(
1011 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1013 substs: &'tcx Substs<'tcx>,
1016 Operand::Constant(Constant {
1018 ty: tcx.type_of(def_id).subst(tcx, substs),
1019 literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1025 ///////////////////////////////////////////////////////////////////////////
1028 #[derive(Clone, RustcEncodable, RustcDecodable)]
1029 pub enum Rvalue<'tcx> {
1030 /// x (either a move or copy, depending on type of x)
1034 Repeat(Operand<'tcx>, ConstUsize),
1037 Ref(&'tcx Region, BorrowKind, Lvalue<'tcx>),
1039 /// length of a [X] or [X;n] value
1042 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1044 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1045 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1047 UnaryOp(UnOp, Operand<'tcx>),
1049 /// Read the discriminant of an ADT.
1051 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1052 /// be defined to return, say, a 0) if ADT is not an enum.
1053 Discriminant(Lvalue<'tcx>),
1055 /// Creates an *uninitialized* Box
1058 /// Create an aggregate value, like a tuple or struct. This is
1059 /// only needed because we want to distinguish `dest = Foo { x:
1060 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1061 /// that `Foo` has a destructor. These rvalues can be optimized
1062 /// away after type-checking and before lowering.
1063 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
1066 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1070 /// Convert unique, zero-sized type for a fn to fn()
1073 /// Convert non capturing closure to fn()
1076 /// Convert safe fn() to unsafe fn()
1079 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1080 /// trans must figure out the details once full monomorphization
1081 /// is known. For example, this could be used to cast from a
1082 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1083 /// (presuming `T: Trait`).
1087 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1088 pub enum AggregateKind<'tcx> {
1089 /// The type is of the element
1092 /// The second field is variant number (discriminant), it's equal to 0
1093 /// for struct and union expressions. The fourth field is active field
1094 /// number and is present only for union expressions.
1095 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1096 Closure(DefId, ClosureSubsts<'tcx>),
1099 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1101 /// The `+` operator (addition)
1103 /// The `-` operator (subtraction)
1105 /// The `*` operator (multiplication)
1107 /// The `/` operator (division)
1109 /// The `%` operator (modulus)
1111 /// The `^` operator (bitwise xor)
1113 /// The `&` operator (bitwise and)
1115 /// The `|` operator (bitwise or)
1117 /// The `<<` operator (shift left)
1119 /// The `>>` operator (shift right)
1121 /// The `==` operator (equality)
1123 /// The `<` operator (less than)
1125 /// The `<=` operator (less than or equal to)
1127 /// The `!=` operator (not equal to)
1129 /// The `>=` operator (greater than or equal to)
1131 /// The `>` operator (greater than)
1136 pub fn is_checkable(self) -> bool {
1139 Add | Sub | Mul | Shl | Shr => true,
1145 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1147 /// The `!` operator for logical inversion
1149 /// The `-` operator for negation
1153 impl<'tcx> Debug for Rvalue<'tcx> {
1154 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1155 use self::Rvalue::*;
1158 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1159 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1160 Len(ref a) => write!(fmt, "Len({:?})", a),
1161 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1162 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1163 CheckedBinaryOp(ref op, ref a, ref b) => {
1164 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1166 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1167 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1168 Box(ref t) => write!(fmt, "Box({:?})", t),
1169 Ref(_, borrow_kind, ref lv) => {
1170 let kind_str = match borrow_kind {
1171 BorrowKind::Shared => "",
1172 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1174 write!(fmt, "&{}{:?}", kind_str, lv)
1177 Aggregate(ref kind, ref lvs) => {
1178 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1179 let mut tuple_fmt = fmt.debug_tuple("");
1181 tuple_fmt.field(lv);
1187 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1189 AggregateKind::Tuple => {
1191 0 => write!(fmt, "()"),
1192 1 => write!(fmt, "({:?},)", lvs[0]),
1193 _ => fmt_tuple(fmt, lvs),
1197 AggregateKind::Adt(adt_def, variant, substs, _) => {
1198 let variant_def = &adt_def.variants[variant];
1200 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1202 match variant_def.ctor_kind {
1203 CtorKind::Const => Ok(()),
1204 CtorKind::Fn => fmt_tuple(fmt, lvs),
1205 CtorKind::Fictive => {
1206 let mut struct_fmt = fmt.debug_struct("");
1207 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1208 struct_fmt.field(&field.name.as_str(), lv);
1215 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1216 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1217 let name = format!("[closure@{:?}]", tcx.hir.span(node_id));
1218 let mut struct_fmt = fmt.debug_struct(&name);
1220 tcx.with_freevars(node_id, |freevars| {
1221 for (freevar, lv) in freevars.iter().zip(lvs) {
1222 let def_id = freevar.def.def_id();
1223 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1224 let var_name = tcx.local_var_name_str(var_id);
1225 struct_fmt.field(&var_name, lv);
1231 write!(fmt, "[closure]")
1240 ///////////////////////////////////////////////////////////////////////////
1243 /// Two constants are equal if they are the same constant. Note that
1244 /// this does not necessarily mean that they are "==" in Rust -- in
1245 /// particular one must be wary of `NaN`!
1247 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1248 pub struct Constant<'tcx> {
1251 pub literal: Literal<'tcx>,
1254 newtype_index!(Promoted, "promoted");
1256 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1257 pub enum Literal<'tcx> {
1260 substs: &'tcx Substs<'tcx>,
1263 value: ConstVal<'tcx>,
1266 // Index into the `promoted` vector of `Mir`.
1271 impl<'tcx> Debug for Constant<'tcx> {
1272 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1273 write!(fmt, "{:?}", self.literal)
1277 impl<'tcx> Debug for Literal<'tcx> {
1278 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1279 use self::Literal::*;
1281 Item { def_id, substs } => {
1282 ppaux::parameterized(fmt, substs, def_id, &[])
1284 Value { ref value } => {
1285 write!(fmt, "const ")?;
1286 fmt_const_val(fmt, value)
1288 Promoted { index } => {
1289 write!(fmt, "{:?}", index)
1295 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1296 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1297 use middle::const_val::ConstVal::*;
1299 Float(f) => write!(fmt, "{:?}", f),
1300 Integral(n) => write!(fmt, "{}", n),
1301 Str(ref s) => write!(fmt, "{:?}", s),
1302 ByteStr(ref bytes) => {
1303 let escaped: String = bytes
1305 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1307 write!(fmt, "b\"{}\"", escaped)
1309 Bool(b) => write!(fmt, "{:?}", b),
1310 Char(c) => write!(fmt, "{:?}", c),
1312 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1313 Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1314 bug!("ConstVal `{:?}` should not be in MIR", const_val),
1318 fn item_path_str(def_id: DefId) -> String {
1319 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1322 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1324 type Node = BasicBlock;
1326 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1328 fn start_node(&self) -> Self::Node { START_BLOCK }
1330 fn predecessors<'graph>(&'graph self, node: Self::Node)
1331 -> <Self as GraphPredecessors<'graph>>::Iter
1333 self.predecessors_for(node).clone().into_iter()
1335 fn successors<'graph>(&'graph self, node: Self::Node)
1336 -> <Self as GraphSuccessors<'graph>>::Iter
1338 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1342 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1343 type Item = BasicBlock;
1344 type Iter = IntoIter<BasicBlock>;
1347 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1348 type Item = BasicBlock;
1349 type Iter = IntoIter<BasicBlock>;
1352 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1353 pub struct Location {
1354 /// the location is within this block
1355 pub block: BasicBlock,
1357 /// the location is the start of the this statement; or, if `statement_index`
1358 /// == num-statements, then the start of the terminator.
1359 pub statement_index: usize,
1362 impl fmt::Debug for Location {
1363 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1364 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1369 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1370 if self.block == other.block {
1371 self.statement_index <= other.statement_index
1373 dominators.is_dominated_by(other.block, self.block)
1380 * TypeFoldable implementations for MIR types
1383 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1384 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1386 basic_blocks: self.basic_blocks.fold_with(folder),
1387 visibility_scopes: self.visibility_scopes.clone(),
1388 promoted: self.promoted.fold_with(folder),
1389 return_ty: self.return_ty.fold_with(folder),
1390 local_decls: self.local_decls.fold_with(folder),
1391 arg_count: self.arg_count,
1392 upvar_decls: self.upvar_decls.clone(),
1393 spread_arg: self.spread_arg,
1395 cache: cache::Cache::new()
1399 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1400 self.basic_blocks.visit_with(visitor) ||
1401 self.promoted.visit_with(visitor) ||
1402 self.return_ty.visit_with(visitor) ||
1403 self.local_decls.visit_with(visitor)
1407 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1408 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1410 ty: self.ty.fold_with(folder),
1415 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1416 self.ty.visit_with(visitor)
1420 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1421 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1423 statements: self.statements.fold_with(folder),
1424 terminator: self.terminator.fold_with(folder),
1425 is_cleanup: self.is_cleanup
1429 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1430 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1434 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1435 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1436 use mir::StatementKind::*;
1438 let kind = match self.kind {
1439 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1440 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1441 lvalue: lvalue.fold_with(folder),
1442 variant_index: variant_index
1444 StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1445 StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1446 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1448 outputs: outputs.fold_with(folder),
1449 inputs: inputs.fold_with(folder)
1454 source_info: self.source_info,
1459 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1460 use mir::StatementKind::*;
1463 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1464 SetDiscriminant { ref lvalue, .. } |
1465 StorageLive(ref lvalue) |
1466 StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1467 InlineAsm { ref outputs, ref inputs, .. } =>
1468 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1474 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1475 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1476 use mir::TerminatorKind::*;
1478 let kind = match self.kind {
1479 Goto { target } => Goto { target: target },
1480 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1481 discr: discr.fold_with(folder),
1482 switch_ty: switch_ty.fold_with(folder),
1483 values: values.clone(),
1484 targets: targets.clone()
1486 Drop { ref location, target, unwind } => Drop {
1487 location: location.fold_with(folder),
1491 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1492 location: location.fold_with(folder),
1493 value: value.fold_with(folder),
1497 Call { ref func, ref args, ref destination, cleanup } => {
1498 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1499 (loc.fold_with(folder), dest)
1503 func: func.fold_with(folder),
1504 args: args.fold_with(folder),
1509 Assert { ref cond, expected, ref msg, target, cleanup } => {
1510 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1511 AssertMessage::BoundsCheck {
1512 len: len.fold_with(folder),
1513 index: index.fold_with(folder),
1519 cond: cond.fold_with(folder),
1528 Unreachable => Unreachable,
1531 source_info: self.source_info,
1536 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1537 use mir::TerminatorKind::*;
1540 SwitchInt { ref discr, switch_ty, .. } =>
1541 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1542 Drop { ref location, ..} => location.visit_with(visitor),
1543 DropAndReplace { ref location, ref value, ..} =>
1544 location.visit_with(visitor) || value.visit_with(visitor),
1545 Call { ref func, ref args, ref destination, .. } => {
1546 let dest = if let Some((ref loc, _)) = *destination {
1547 loc.visit_with(visitor)
1549 dest || func.visit_with(visitor) || args.visit_with(visitor)
1551 Assert { ref cond, ref msg, .. } => {
1552 if cond.visit_with(visitor) {
1553 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1554 len.visit_with(visitor) || index.visit_with(visitor)
1565 Unreachable => false
1570 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1571 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1573 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1578 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1579 if let &Lvalue::Projection(ref p) = self {
1580 p.visit_with(visitor)
1587 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1588 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1591 Use(ref op) => Use(op.fold_with(folder)),
1592 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1593 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1594 Len(ref lval) => Len(lval.fold_with(folder)),
1595 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1596 BinaryOp(op, ref rhs, ref lhs) =>
1597 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1598 CheckedBinaryOp(op, ref rhs, ref lhs) =>
1599 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1600 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1601 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1602 Box(ty) => Box(ty.fold_with(folder)),
1603 Aggregate(ref kind, ref fields) => {
1604 let kind = match *kind {
1605 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1606 AggregateKind::Tuple => AggregateKind::Tuple,
1607 AggregateKind::Adt(def, v, substs, n) =>
1608 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1609 AggregateKind::Closure(id, substs) =>
1610 AggregateKind::Closure(id, substs.fold_with(folder))
1612 Aggregate(kind, fields.fold_with(folder))
1617 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1620 Use(ref op) => op.visit_with(visitor),
1621 Repeat(ref op, _) => op.visit_with(visitor),
1622 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1623 Len(ref lval) => lval.visit_with(visitor),
1624 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1625 BinaryOp(_, ref rhs, ref lhs) |
1626 CheckedBinaryOp(_, ref rhs, ref lhs) =>
1627 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1628 UnaryOp(_, ref val) => val.visit_with(visitor),
1629 Discriminant(ref lval) => lval.visit_with(visitor),
1630 Box(ty) => ty.visit_with(visitor),
1631 Aggregate(ref kind, ref fields) => {
1633 AggregateKind::Array(ty) => ty.visit_with(visitor),
1634 AggregateKind::Tuple => false,
1635 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1636 AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1637 }) || fields.visit_with(visitor)
1643 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1644 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1646 Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1647 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1651 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1653 Operand::Consume(ref lval) => lval.visit_with(visitor),
1654 Operand::Constant(ref c) => c.visit_with(visitor)
1659 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1660 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1662 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1663 use mir::ProjectionElem::*;
1665 let base = self.base.fold_with(folder);
1666 let elem = match self.elem {
1668 Field(f, ty) => Field(f, ty.fold_with(folder)),
1669 Index(ref v) => Index(v.fold_with(folder)),
1670 ref elem => elem.clone()
1679 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1680 use mir::ProjectionElem::*;
1682 self.base.visit_with(visitor) ||
1684 Field(_, ty) => ty.visit_with(visitor),
1685 Index(ref v) => v.visit_with(visitor),
1691 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1692 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1694 span: self.span.clone(),
1695 ty: self.ty.fold_with(folder),
1696 literal: self.literal.fold_with(folder)
1699 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1700 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1704 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1705 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1707 Literal::Item { def_id, substs } => Literal::Item {
1709 substs: substs.fold_with(folder)
1714 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1716 Literal::Item { substs, .. } => substs.visit_with(visitor),