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 //! MIR datatypes and passes. See [the README](README.md) for details.
13 use graphviz::IntoCow;
14 use middle::const_val::ConstVal;
15 use middle::region::CodeExtent;
16 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
17 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
18 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
19 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
20 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
21 use hir::def::CtorKind;
22 use hir::def_id::DefId;
23 use ty::subst::{Subst, Substs};
24 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
25 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
27 use rustc_back::slice;
30 use std::borrow::{Cow};
32 use std::fmt::{self, Debug, Formatter, Write};
34 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use syntax::ast::Name;
45 macro_rules! newtype_index {
46 ($name:ident, $debug_name:expr) => (
47 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
48 RustcEncodable, RustcDecodable)]
49 pub struct $name(u32);
52 fn new(value: usize) -> Self {
53 assert!(value < (u32::MAX) as usize);
56 fn index(self) -> usize {
61 impl Debug for $name {
62 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
63 write!(fmt, "{}{}", $debug_name, self.0)
69 /// Lowered representation of a single function.
70 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
71 pub struct Mir<'tcx> {
72 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
73 /// that indexes into this vector.
74 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
76 /// List of visibility (lexical) scopes; these are referenced by statements
77 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
78 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
80 /// Rvalues promoted from this function, such as borrows of constants.
81 /// Each of them is the Mir of a constant with the fn's type parameters
82 /// in scope, but a separate set of locals.
83 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
85 /// Return type of the function.
86 pub return_ty: Ty<'tcx>,
88 /// Declarations of locals.
90 /// The first local is the return value pointer, followed by `arg_count`
91 /// locals for the function arguments, followed by any user-declared
92 /// variables and temporaries.
93 pub local_decls: IndexVec<Local, LocalDecl<'tcx>>,
95 /// Number of arguments this function takes.
97 /// Starting at local 1, `arg_count` locals will be provided by the caller
98 /// and can be assumed to be initialized.
100 /// If this MIR was built for a constant, this will be 0.
101 pub arg_count: usize,
103 /// Names and capture modes of all the closure upvars, assuming
104 /// the first argument is either the closure or a reference to it.
105 pub upvar_decls: Vec<UpvarDecl>,
107 /// Mark an argument local (which must be a tuple) as getting passed as
108 /// its individual components at the LLVM level.
110 /// This is used for the "rust-call" ABI.
111 pub spread_arg: Option<Local>,
113 /// A span representing this MIR, for error reporting
116 /// A cache for various calculations
120 /// where execution begins
121 pub const START_BLOCK: BasicBlock = BasicBlock(0);
123 impl<'tcx> Mir<'tcx> {
124 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
125 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
126 promoted: IndexVec<Promoted, Mir<'tcx>>,
128 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
130 upvar_decls: Vec<UpvarDecl>,
133 // We need `arg_count` locals, and one for the return pointer
134 assert!(local_decls.len() >= arg_count + 1,
135 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
136 assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
148 cache: cache::Cache::new()
153 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
158 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
159 self.cache.invalidate();
160 &mut self.basic_blocks
164 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
165 self.cache.predecessors(self)
169 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
170 Ref::map(self.predecessors(), |p| &p[bb])
174 pub fn dominators(&self) -> Dominators<BasicBlock> {
179 pub fn local_kind(&self, local: Local) -> LocalKind {
180 let index = local.0 as usize;
182 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
183 "return pointer should be mutable");
185 LocalKind::ReturnPointer
186 } else if index < self.arg_count + 1 {
188 } else if self.local_decls[local].name.is_some() {
191 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
192 "temp should be mutable");
198 /// Returns an iterator over all temporaries.
200 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
201 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
202 let local = Local::new(index);
203 if self.local_decls[local].is_user_variable {
211 /// Returns an iterator over all user-declared locals.
213 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
214 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
215 let local = Local::new(index);
216 if self.local_decls[local].is_user_variable {
224 /// Returns an iterator over all function arguments.
226 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
227 let arg_count = self.arg_count;
228 (1..arg_count+1).map(Local::new)
231 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
232 /// locals that are neither arguments nor the return pointer).
234 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
235 let arg_count = self.arg_count;
236 let local_count = self.local_decls.len();
237 (arg_count+1..local_count).map(Local::new)
240 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
241 /// invalidating statement indices in `Location`s.
242 pub fn make_statement_nop(&mut self, location: Location) {
243 let block = &mut self[location.block];
244 debug_assert!(location.statement_index < block.statements.len());
245 block.statements[location.statement_index].make_nop()
249 impl_stable_hash_for!(struct Mir<'tcx> {
262 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
263 type Output = BasicBlockData<'tcx>;
266 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
267 &self.basic_blocks()[index]
271 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
273 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
274 &mut self.basic_blocks_mut()[index]
278 /// Grouped information about the source code origin of a MIR entity.
279 /// Intended to be inspected by diagnostics and debuginfo.
280 /// Most passes can work with it as a whole, within a single function.
281 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
282 pub struct SourceInfo {
283 /// Source span for the AST pertaining to this MIR entity.
286 /// The lexical visibility scope, i.e. which bindings can be seen.
287 pub scope: VisibilityScope
290 ///////////////////////////////////////////////////////////////////////////
291 // Mutability and borrow kinds
293 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
294 pub enum Mutability {
299 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
300 pub enum BorrowKind {
301 /// Data must be immutable and is aliasable.
304 /// Data must be immutable but not aliasable. This kind of borrow
305 /// cannot currently be expressed by the user and is used only in
306 /// implicit closure bindings. It is needed when you the closure
307 /// is borrowing or mutating a mutable referent, e.g.:
309 /// let x: &mut isize = ...;
310 /// let y = || *x += 5;
312 /// If we were to try to translate this closure into a more explicit
313 /// form, we'd encounter an error with the code as written:
315 /// struct Env { x: & &mut isize }
316 /// let x: &mut isize = ...;
317 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
318 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
320 /// This is then illegal because you cannot mutate a `&mut` found
321 /// in an aliasable location. To solve, you'd have to translate with
322 /// an `&mut` borrow:
324 /// struct Env { x: & &mut isize }
325 /// let x: &mut isize = ...;
326 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
327 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
329 /// Now the assignment to `**env.x` is legal, but creating a
330 /// mutable pointer to `x` is not because `x` is not mutable. We
331 /// could fix this by declaring `x` as `let mut x`. This is ok in
332 /// user code, if awkward, but extra weird for closures, since the
333 /// borrow is hidden.
335 /// So we introduce a "unique imm" borrow -- the referent is
336 /// immutable, but not aliasable. This solves the problem. For
337 /// simplicity, we don't give users the way to express this
338 /// borrow, it's just used when translating closures.
341 /// Data is mutable and not aliasable.
345 ///////////////////////////////////////////////////////////////////////////
346 // Variables and temps
348 newtype_index!(Local, "_");
350 pub const RETURN_POINTER: Local = Local(0);
352 /// Classifies locals into categories. See `Mir::local_kind`.
353 #[derive(PartialEq, Eq, Debug)]
355 /// User-declared variable binding
357 /// Compiler-introduced temporary
359 /// Function argument
361 /// Location of function's return value
367 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
368 /// argument, or the return pointer.
369 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
370 pub struct LocalDecl<'tcx> {
371 /// `let mut x` vs `let x`.
373 /// Temporaries and the return pointer are always mutable.
374 pub mutability: Mutability,
376 /// True if this corresponds to a user-declared local variable.
377 pub is_user_variable: bool,
379 /// Type of this local.
382 /// Name of the local, used in debuginfo and pretty-printing.
384 /// Note that function arguments can also have this set to `Some(_)`
385 /// to generate better debuginfo.
386 pub name: Option<Name>,
388 /// Source info of the local.
389 pub source_info: SourceInfo,
392 impl<'tcx> LocalDecl<'tcx> {
393 /// Create a new `LocalDecl` for a temporary.
395 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
397 mutability: Mutability::Mut,
400 source_info: SourceInfo {
402 scope: ARGUMENT_VISIBILITY_SCOPE
404 is_user_variable: false
408 /// Builds a `LocalDecl` for the return pointer.
410 /// This must be inserted into the `local_decls` list as the first local.
412 pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
414 mutability: Mutability::Mut,
416 source_info: SourceInfo {
418 scope: ARGUMENT_VISIBILITY_SCOPE
420 name: None, // FIXME maybe we do want some name here?
421 is_user_variable: false
426 /// A closure capture, with its name and mode.
427 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
428 pub struct UpvarDecl {
429 pub debug_name: Name,
431 /// If true, the capture is behind a reference.
435 ///////////////////////////////////////////////////////////////////////////
438 newtype_index!(BasicBlock, "bb");
440 ///////////////////////////////////////////////////////////////////////////
441 // BasicBlockData and Terminator
443 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
444 pub struct BasicBlockData<'tcx> {
445 /// List of statements in this block.
446 pub statements: Vec<Statement<'tcx>>,
448 /// Terminator for this block.
450 /// NB. This should generally ONLY be `None` during construction.
451 /// Therefore, you should generally access it via the
452 /// `terminator()` or `terminator_mut()` methods. The only
453 /// exception is that certain passes, such as `simplify_cfg`, swap
454 /// out the terminator temporarily with `None` while they continue
455 /// to recurse over the set of basic blocks.
456 pub terminator: Option<Terminator<'tcx>>,
458 /// If true, this block lies on an unwind path. This is used
459 /// during trans where distinct kinds of basic blocks may be
460 /// generated (particularly for MSVC cleanup). Unwind blocks must
461 /// only branch to other unwind blocks.
462 pub is_cleanup: bool,
465 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
466 pub struct Terminator<'tcx> {
467 pub source_info: SourceInfo,
468 pub kind: TerminatorKind<'tcx>
471 #[derive(Clone, RustcEncodable, RustcDecodable)]
472 pub enum TerminatorKind<'tcx> {
473 /// block should have one successor in the graph; we jump there
478 /// operand evaluates to an integer; jump depending on its value
479 /// to one of the targets, and otherwise fallback to `otherwise`
481 /// discriminant value being tested
482 discr: Operand<'tcx>,
484 /// type of value being tested
487 /// Possible values. The locations to branch to in each case
488 /// are found in the corresponding indices from the `targets` vector.
489 values: Cow<'tcx, [ConstInt]>,
491 /// Possible branch sites. The last element of this vector is used
492 /// for the otherwise branch, so targets.len() == values.len() + 1
494 // This invariant is quite non-obvious and also could be improved.
495 // One way to make this invariant is to have something like this instead:
497 // branches: Vec<(ConstInt, BasicBlock)>,
498 // otherwise: Option<BasicBlock> // exhaustive if None
500 // However we’ve decided to keep this as-is until we figure a case
501 // where some other approach seems to be strictly better than other.
502 targets: Vec<BasicBlock>,
505 /// Indicates that the landing pad is finished and unwinding should
506 /// continue. Emitted by build::scope::diverge_cleanup.
509 /// Indicates a normal return. The return pointer lvalue should
510 /// have been filled in by now. This should occur at most once.
513 /// Indicates a terminator that can never be reached.
518 location: Lvalue<'tcx>,
520 unwind: Option<BasicBlock>
523 /// Drop the Lvalue and assign the new value over it
525 location: Lvalue<'tcx>,
526 value: Operand<'tcx>,
528 unwind: Option<BasicBlock>,
531 /// Block ends with a call of a converging function
533 /// The function that’s being called
535 /// Arguments the function is called with
536 args: Vec<Operand<'tcx>>,
537 /// Destination for the return value. If some, the call is converging.
538 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
539 /// Cleanups to be done if the call unwinds.
540 cleanup: Option<BasicBlock>
543 /// Jump to the target if the condition has the expected value,
544 /// otherwise panic with a message and a cleanup target.
548 msg: AssertMessage<'tcx>,
550 cleanup: Option<BasicBlock>
554 impl<'tcx> Terminator<'tcx> {
555 pub fn successors(&self) -> Cow<[BasicBlock]> {
556 self.kind.successors()
559 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
560 self.kind.successors_mut()
564 impl<'tcx> TerminatorKind<'tcx> {
565 pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
566 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
567 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
568 TerminatorKind::SwitchInt {
570 switch_ty: tcx.types.bool,
571 values: From::from(BOOL_SWITCH_FALSE),
576 pub fn successors(&self) -> Cow<[BasicBlock]> {
577 use self::TerminatorKind::*;
579 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
580 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
581 Resume => (&[]).into_cow(),
582 Return => (&[]).into_cow(),
583 Unreachable => (&[]).into_cow(),
584 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
585 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
586 slice::ref_slice(t).into_cow(),
587 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
588 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
589 DropAndReplace { target, unwind: Some(unwind), .. } |
590 Drop { target, unwind: Some(unwind), .. } => {
591 vec![target, unwind].into_cow()
593 DropAndReplace { ref target, unwind: None, .. } |
594 Drop { ref target, unwind: None, .. } => {
595 slice::ref_slice(target).into_cow()
597 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
598 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
602 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
603 // `Vec<&mut BasicBlock>` would look like in the first place.
604 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
605 use self::TerminatorKind::*;
607 Goto { target: ref mut b } => vec![b],
608 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
609 Resume => Vec::new(),
610 Return => Vec::new(),
611 Unreachable => Vec::new(),
612 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
613 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
614 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
615 Call { destination: None, cleanup: None, .. } => vec![],
616 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
617 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
618 DropAndReplace { ref mut target, unwind: None, .. } |
619 Drop { ref mut target, unwind: None, .. } => {
622 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
623 Assert { ref mut target, .. } => vec![target]
628 impl<'tcx> BasicBlockData<'tcx> {
629 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
637 /// Accessor for terminator.
639 /// Terminator may not be None after construction of the basic block is complete. This accessor
640 /// provides a convenience way to reach the terminator.
641 pub fn terminator(&self) -> &Terminator<'tcx> {
642 self.terminator.as_ref().expect("invalid terminator state")
645 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
646 self.terminator.as_mut().expect("invalid terminator state")
650 impl<'tcx> Debug for TerminatorKind<'tcx> {
651 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
653 let successors = self.successors();
654 let labels = self.fmt_successor_labels();
655 assert_eq!(successors.len(), labels.len());
657 match successors.len() {
660 1 => write!(fmt, " -> {:?}", successors[0]),
663 write!(fmt, " -> [")?;
664 for (i, target) in successors.iter().enumerate() {
668 write!(fmt, "{}: {:?}", labels[i], target)?;
677 impl<'tcx> TerminatorKind<'tcx> {
678 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
679 /// successor basic block, if any. The only information not inlcuded is the list of possible
680 /// successors, which may be rendered differently between the text and the graphviz format.
681 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
682 use self::TerminatorKind::*;
684 Goto { .. } => write!(fmt, "goto"),
685 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
686 Return => write!(fmt, "return"),
687 Resume => write!(fmt, "resume"),
688 Unreachable => write!(fmt, "unreachable"),
689 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
690 DropAndReplace { ref location, ref value, .. } =>
691 write!(fmt, "replace({:?} <- {:?})", location, value),
692 Call { ref func, ref args, ref destination, .. } => {
693 if let Some((ref destination, _)) = *destination {
694 write!(fmt, "{:?} = ", destination)?;
696 write!(fmt, "{:?}(", func)?;
697 for (index, arg) in args.iter().enumerate() {
701 write!(fmt, "{:?}", arg)?;
705 Assert { ref cond, expected, ref msg, .. } => {
706 write!(fmt, "assert(")?;
710 write!(fmt, "{:?}, ", cond)?;
713 AssertMessage::BoundsCheck { ref len, ref index } => {
714 write!(fmt, "{:?}, {:?}, {:?}",
715 "index out of bounds: the len is {} but the index is {}",
718 AssertMessage::Math(ref err) => {
719 write!(fmt, "{:?}", err.description())?;
728 /// Return the list of labels for the edges to the successor basic blocks.
729 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
730 use self::TerminatorKind::*;
732 Return | Resume | Unreachable => vec![],
733 Goto { .. } => vec!["".into()],
734 SwitchInt { ref values, .. } => {
737 let mut buf = String::new();
738 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
741 .chain(iter::once(String::from("otherwise").into()))
744 Call { destination: Some(_), cleanup: Some(_), .. } =>
745 vec!["return".into_cow(), "unwind".into_cow()],
746 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
747 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
748 Call { destination: None, cleanup: None, .. } => vec![],
749 DropAndReplace { unwind: None, .. } |
750 Drop { unwind: None, .. } => vec!["return".into_cow()],
751 DropAndReplace { unwind: Some(_), .. } |
752 Drop { unwind: Some(_), .. } => {
753 vec!["return".into_cow(), "unwind".into_cow()]
755 Assert { cleanup: None, .. } => vec!["".into()],
757 vec!["success".into_cow(), "unwind".into_cow()]
762 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
763 pub enum AssertMessage<'tcx> {
771 ///////////////////////////////////////////////////////////////////////////
774 #[derive(Clone, RustcEncodable, RustcDecodable)]
775 pub struct Statement<'tcx> {
776 pub source_info: SourceInfo,
777 pub kind: StatementKind<'tcx>,
780 impl<'tcx> Statement<'tcx> {
781 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
782 /// invalidating statement indices in `Location`s.
783 pub fn make_nop(&mut self) {
784 self.kind = StatementKind::Nop
788 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
789 pub enum StatementKind<'tcx> {
790 /// Write the RHS Rvalue to the LHS Lvalue.
791 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
793 /// Write the discriminant for a variant to the enum Lvalue.
794 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
796 /// Start a live range for the storage of the local.
797 StorageLive(Lvalue<'tcx>),
799 /// End the current live range for the storage of the local.
800 StorageDead(Lvalue<'tcx>),
804 outputs: Vec<Lvalue<'tcx>>,
805 inputs: Vec<Operand<'tcx>>
808 /// Mark one terminating point of an extent (i.e. static region).
809 /// (The starting point(s) arise implicitly from borrows.)
810 EndRegion(CodeExtent),
812 /// No-op. Useful for deleting instructions without affecting statement indices.
816 impl<'tcx> Debug for Statement<'tcx> {
817 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
818 use self::StatementKind::*;
820 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
821 // (reuse lifetime rendering policy from ppaux.)
822 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
823 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
824 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
825 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
826 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
828 InlineAsm { ref asm, ref outputs, ref inputs } => {
829 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
831 Nop => write!(fmt, "nop"),
836 ///////////////////////////////////////////////////////////////////////////
839 /// A path to a value; something that can be evaluated without
840 /// changing or disturbing program state.
841 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
842 pub enum Lvalue<'tcx> {
846 /// static or static mut variable
847 Static(Box<Static<'tcx>>),
849 /// projection out of an lvalue (access a field, deref a pointer, etc)
850 Projection(Box<LvalueProjection<'tcx>>),
853 /// The def-id of a static, along with its normalized type (which is
854 /// stored to avoid requiring normalization when reading MIR).
855 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
856 pub struct Static<'tcx> {
861 impl_stable_hash_for!(struct Static<'tcx> {
866 /// The `Projection` data structure defines things of the form `B.x`
867 /// or `*B` or `B[index]`. Note that it is parameterized because it is
868 /// shared between `Constant` and `Lvalue`. See the aliases
869 /// `LvalueProjection` etc below.
870 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
871 pub struct Projection<'tcx, B, V> {
873 pub elem: ProjectionElem<'tcx, V>,
876 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
877 pub enum ProjectionElem<'tcx, V> {
879 Field(Field, Ty<'tcx>),
882 /// These indices are generated by slice patterns. Easiest to explain
886 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
887 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
888 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
889 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
892 /// index or -index (in Python terms), depending on from_end
894 /// thing being indexed must be at least this long
896 /// counting backwards from end?
900 /// These indices are generated by slice patterns.
902 /// slice[from:-to] in Python terms.
908 /// "Downcast" to a variant of an ADT. Currently, we only introduce
909 /// this for ADTs with more than one variant. It may be better to
910 /// just introduce it always, or always for enums.
911 Downcast(&'tcx AdtDef, usize),
914 /// Alias for projections as they appear in lvalues, where the base is an lvalue
915 /// and the index is an operand.
916 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
918 /// Alias for projections as they appear in lvalues, where the base is an lvalue
919 /// and the index is an operand.
920 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
922 newtype_index!(Field, "field");
924 impl<'tcx> Lvalue<'tcx> {
925 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
926 self.elem(ProjectionElem::Field(f, ty))
929 pub fn deref(self) -> Lvalue<'tcx> {
930 self.elem(ProjectionElem::Deref)
933 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
934 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
937 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
938 self.elem(ProjectionElem::Index(index))
941 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
942 Lvalue::Projection(Box::new(LvalueProjection {
949 impl<'tcx> Debug for Lvalue<'tcx> {
950 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
954 Local(id) => write!(fmt, "{:?}", id),
955 Static(box self::Static { def_id, ty }) =>
956 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
957 Projection(ref data) =>
959 ProjectionElem::Downcast(ref adt_def, index) =>
960 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
961 ProjectionElem::Deref =>
962 write!(fmt, "(*{:?})", data.base),
963 ProjectionElem::Field(field, ty) =>
964 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
965 ProjectionElem::Index(ref index) =>
966 write!(fmt, "{:?}[{:?}]", data.base, index),
967 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
968 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
969 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
970 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
971 ProjectionElem::Subslice { from, to } if to == 0 =>
972 write!(fmt, "{:?}[{:?}:]", data.base, from),
973 ProjectionElem::Subslice { from, to } if from == 0 =>
974 write!(fmt, "{:?}[:-{:?}]", data.base, to),
975 ProjectionElem::Subslice { from, to } =>
976 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
984 ///////////////////////////////////////////////////////////////////////////
987 newtype_index!(VisibilityScope, "scope");
988 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
990 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
991 pub struct VisibilityScopeData {
993 pub parent_scope: Option<VisibilityScope>,
996 ///////////////////////////////////////////////////////////////////////////
999 /// These are values that can appear inside an rvalue (or an index
1000 /// lvalue). They are intentionally limited to prevent rvalues from
1001 /// being nested in one another.
1002 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1003 pub enum Operand<'tcx> {
1004 Consume(Lvalue<'tcx>),
1005 Constant(Box<Constant<'tcx>>),
1008 impl<'tcx> Debug for Operand<'tcx> {
1009 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1010 use self::Operand::*;
1012 Constant(ref a) => write!(fmt, "{:?}", a),
1013 Consume(ref lv) => write!(fmt, "{:?}", lv),
1018 impl<'tcx> Operand<'tcx> {
1019 pub fn function_handle<'a>(
1020 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1022 substs: &'tcx Substs<'tcx>,
1025 Operand::Constant(box Constant {
1027 ty: tcx.type_of(def_id).subst(tcx, substs),
1028 literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1034 ///////////////////////////////////////////////////////////////////////////
1037 #[derive(Clone, RustcEncodable, RustcDecodable)]
1038 pub enum Rvalue<'tcx> {
1039 /// x (either a move or copy, depending on type of x)
1043 Repeat(Operand<'tcx>, ConstUsize),
1046 Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1048 /// length of a [X] or [X;n] value
1051 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1053 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1054 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1056 NullaryOp(NullOp, Ty<'tcx>),
1057 UnaryOp(UnOp, Operand<'tcx>),
1059 /// Read the discriminant of an ADT.
1061 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1062 /// be defined to return, say, a 0) if ADT is not an enum.
1063 Discriminant(Lvalue<'tcx>),
1065 /// Create an aggregate value, like a tuple or struct. This is
1066 /// only needed because we want to distinguish `dest = Foo { x:
1067 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1068 /// that `Foo` has a destructor. These rvalues can be optimized
1069 /// away after type-checking and before lowering.
1070 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1073 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1077 /// Convert unique, zero-sized type for a fn to fn()
1080 /// Convert non capturing closure to fn()
1083 /// Convert safe fn() to unsafe fn()
1086 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1087 /// trans must figure out the details once full monomorphization
1088 /// is known. For example, this could be used to cast from a
1089 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1090 /// (presuming `T: Trait`).
1094 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1095 pub enum AggregateKind<'tcx> {
1096 /// The type is of the element
1099 /// The second field is variant number (discriminant), it's equal to 0
1100 /// for struct and union expressions. The fourth field is active field
1101 /// number and is present only for union expressions.
1102 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1103 Closure(DefId, ClosureSubsts<'tcx>),
1106 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1108 /// The `+` operator (addition)
1110 /// The `-` operator (subtraction)
1112 /// The `*` operator (multiplication)
1114 /// The `/` operator (division)
1116 /// The `%` operator (modulus)
1118 /// The `^` operator (bitwise xor)
1120 /// The `&` operator (bitwise and)
1122 /// The `|` operator (bitwise or)
1124 /// The `<<` operator (shift left)
1126 /// The `>>` operator (shift right)
1128 /// The `==` operator (equality)
1130 /// The `<` operator (less than)
1132 /// The `<=` operator (less than or equal to)
1134 /// The `!=` operator (not equal to)
1136 /// The `>=` operator (greater than or equal to)
1138 /// The `>` operator (greater than)
1140 /// The `ptr.offset` operator
1145 pub fn is_checkable(self) -> bool {
1148 Add | Sub | Mul | Shl | Shr => true,
1154 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1156 /// Return the size of a value of that type
1158 /// Create a new uninitialized box for a value of that type
1162 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1164 /// The `!` operator for logical inversion
1166 /// The `-` operator for negation
1170 impl<'tcx> Debug for Rvalue<'tcx> {
1171 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1172 use self::Rvalue::*;
1175 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1176 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1177 Len(ref a) => write!(fmt, "Len({:?})", a),
1178 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1179 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1180 CheckedBinaryOp(ref op, ref a, ref b) => {
1181 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1183 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1184 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1185 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1186 Ref(region, borrow_kind, ref lv) => {
1187 let kind_str = match borrow_kind {
1188 BorrowKind::Shared => "",
1189 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1192 // When identifying regions, add trailing space if
1194 let region = if ppaux::identify_regions() {
1195 let mut region = format!("{}", region);
1196 if region.len() > 0 { region.push(' '); }
1201 write!(fmt, "&{}{}{:?}", region, kind_str, lv)
1204 Aggregate(ref kind, ref lvs) => {
1205 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1206 let mut tuple_fmt = fmt.debug_tuple("");
1208 tuple_fmt.field(lv);
1214 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1216 AggregateKind::Tuple => {
1218 0 => write!(fmt, "()"),
1219 1 => write!(fmt, "({:?},)", lvs[0]),
1220 _ => fmt_tuple(fmt, lvs),
1224 AggregateKind::Adt(adt_def, variant, substs, _) => {
1225 let variant_def = &adt_def.variants[variant];
1227 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1229 match variant_def.ctor_kind {
1230 CtorKind::Const => Ok(()),
1231 CtorKind::Fn => fmt_tuple(fmt, lvs),
1232 CtorKind::Fictive => {
1233 let mut struct_fmt = fmt.debug_struct("");
1234 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1235 struct_fmt.field(&field.name.as_str(), lv);
1242 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1243 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1244 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1245 format!("[closure@{:?}]", node_id)
1247 format!("[closure@{:?}]", tcx.hir.span(node_id))
1249 let mut struct_fmt = fmt.debug_struct(&name);
1251 tcx.with_freevars(node_id, |freevars| {
1252 for (freevar, lv) in freevars.iter().zip(lvs) {
1253 let def_id = freevar.def.def_id();
1254 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1255 let var_name = tcx.local_var_name_str(var_id);
1256 struct_fmt.field(&var_name, lv);
1262 write!(fmt, "[closure]")
1271 ///////////////////////////////////////////////////////////////////////////
1274 /// Two constants are equal if they are the same constant. Note that
1275 /// this does not necessarily mean that they are "==" in Rust -- in
1276 /// particular one must be wary of `NaN`!
1278 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1279 pub struct Constant<'tcx> {
1282 pub literal: Literal<'tcx>,
1285 newtype_index!(Promoted, "promoted");
1287 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1288 pub enum Literal<'tcx> {
1291 substs: &'tcx Substs<'tcx>,
1294 value: ConstVal<'tcx>,
1297 // Index into the `promoted` vector of `Mir`.
1302 impl<'tcx> Debug for Constant<'tcx> {
1303 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1304 write!(fmt, "{:?}", self.literal)
1308 impl<'tcx> Debug for Literal<'tcx> {
1309 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1310 use self::Literal::*;
1312 Item { def_id, substs } => {
1313 ppaux::parameterized(fmt, substs, def_id, &[])
1315 Value { ref value } => {
1316 write!(fmt, "const ")?;
1317 fmt_const_val(fmt, value)
1319 Promoted { index } => {
1320 write!(fmt, "{:?}", index)
1326 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1327 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1328 use middle::const_val::ConstVal::*;
1330 Float(f) => write!(fmt, "{:?}", f),
1331 Integral(n) => write!(fmt, "{}", n),
1332 Str(ref s) => write!(fmt, "{:?}", s),
1333 ByteStr(ref bytes) => {
1334 let escaped: String = bytes
1336 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1338 write!(fmt, "b\"{}\"", escaped)
1340 Bool(b) => write!(fmt, "{:?}", b),
1341 Char(c) => write!(fmt, "{:?}", c),
1343 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1344 Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1345 bug!("ConstVal `{:?}` should not be in MIR", const_val),
1349 fn item_path_str(def_id: DefId) -> String {
1350 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1353 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1355 type Node = BasicBlock;
1357 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1359 fn start_node(&self) -> Self::Node { START_BLOCK }
1361 fn predecessors<'graph>(&'graph self, node: Self::Node)
1362 -> <Self as GraphPredecessors<'graph>>::Iter
1364 self.predecessors_for(node).clone().into_iter()
1366 fn successors<'graph>(&'graph self, node: Self::Node)
1367 -> <Self as GraphSuccessors<'graph>>::Iter
1369 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1373 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1374 type Item = BasicBlock;
1375 type Iter = IntoIter<BasicBlock>;
1378 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1379 type Item = BasicBlock;
1380 type Iter = IntoIter<BasicBlock>;
1383 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1384 pub struct Location {
1385 /// the location is within this block
1386 pub block: BasicBlock,
1388 /// the location is the start of the this statement; or, if `statement_index`
1389 /// == num-statements, then the start of the terminator.
1390 pub statement_index: usize,
1393 impl fmt::Debug for Location {
1394 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1395 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1400 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1401 if self.block == other.block {
1402 self.statement_index <= other.statement_index
1404 dominators.is_dominated_by(other.block, self.block)
1411 * TypeFoldable implementations for MIR types
1414 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1415 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1417 basic_blocks: self.basic_blocks.fold_with(folder),
1418 visibility_scopes: self.visibility_scopes.clone(),
1419 promoted: self.promoted.fold_with(folder),
1420 return_ty: self.return_ty.fold_with(folder),
1421 local_decls: self.local_decls.fold_with(folder),
1422 arg_count: self.arg_count,
1423 upvar_decls: self.upvar_decls.clone(),
1424 spread_arg: self.spread_arg,
1426 cache: cache::Cache::new()
1430 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1431 self.basic_blocks.visit_with(visitor) ||
1432 self.promoted.visit_with(visitor) ||
1433 self.return_ty.visit_with(visitor) ||
1434 self.local_decls.visit_with(visitor)
1438 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1439 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1441 ty: self.ty.fold_with(folder),
1446 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1447 self.ty.visit_with(visitor)
1451 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1452 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1454 statements: self.statements.fold_with(folder),
1455 terminator: self.terminator.fold_with(folder),
1456 is_cleanup: self.is_cleanup
1460 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1461 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1465 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1466 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1467 use mir::StatementKind::*;
1469 let kind = match self.kind {
1470 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1471 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1472 lvalue: lvalue.fold_with(folder),
1475 StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1476 StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1477 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1479 outputs: outputs.fold_with(folder),
1480 inputs: inputs.fold_with(folder)
1483 // Note for future: If we want to expose the extents
1484 // during the fold, we need to either generalize EndRegion
1485 // to carry `[ty::Region]`, or extend the `TypeFolder`
1486 // trait with a `fn fold_extent`.
1487 EndRegion(ref extent) => EndRegion(extent.clone()),
1492 source_info: self.source_info,
1497 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1498 use mir::StatementKind::*;
1501 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1502 SetDiscriminant { ref lvalue, .. } |
1503 StorageLive(ref lvalue) |
1504 StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1505 InlineAsm { ref outputs, ref inputs, .. } =>
1506 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1508 // Note for future: If we want to expose the extents
1509 // during the visit, we need to either generalize EndRegion
1510 // to carry `[ty::Region]`, or extend the `TypeVisitor`
1511 // trait with a `fn visit_extent`.
1512 EndRegion(ref _extent) => false,
1519 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1520 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1521 use mir::TerminatorKind::*;
1523 let kind = match self.kind {
1524 Goto { target } => Goto { target: target },
1525 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1526 discr: discr.fold_with(folder),
1527 switch_ty: switch_ty.fold_with(folder),
1528 values: values.clone(),
1529 targets: targets.clone()
1531 Drop { ref location, target, unwind } => Drop {
1532 location: location.fold_with(folder),
1536 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1537 location: location.fold_with(folder),
1538 value: value.fold_with(folder),
1542 Call { ref func, ref args, ref destination, cleanup } => {
1543 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1544 (loc.fold_with(folder), dest)
1548 func: func.fold_with(folder),
1549 args: args.fold_with(folder),
1554 Assert { ref cond, expected, ref msg, target, cleanup } => {
1555 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1556 AssertMessage::BoundsCheck {
1557 len: len.fold_with(folder),
1558 index: index.fold_with(folder),
1564 cond: cond.fold_with(folder),
1573 Unreachable => Unreachable,
1576 source_info: self.source_info,
1581 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1582 use mir::TerminatorKind::*;
1585 SwitchInt { ref discr, switch_ty, .. } =>
1586 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1587 Drop { ref location, ..} => location.visit_with(visitor),
1588 DropAndReplace { ref location, ref value, ..} =>
1589 location.visit_with(visitor) || value.visit_with(visitor),
1590 Call { ref func, ref args, ref destination, .. } => {
1591 let dest = if let Some((ref loc, _)) = *destination {
1592 loc.visit_with(visitor)
1594 dest || func.visit_with(visitor) || args.visit_with(visitor)
1596 Assert { ref cond, ref msg, .. } => {
1597 if cond.visit_with(visitor) {
1598 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1599 len.visit_with(visitor) || index.visit_with(visitor)
1610 Unreachable => false
1615 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1616 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1618 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1623 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1624 if let &Lvalue::Projection(ref p) = self {
1625 p.visit_with(visitor)
1632 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1633 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1636 Use(ref op) => Use(op.fold_with(folder)),
1637 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1638 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1639 Len(ref lval) => Len(lval.fold_with(folder)),
1640 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1641 BinaryOp(op, ref rhs, ref lhs) =>
1642 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1643 CheckedBinaryOp(op, ref rhs, ref lhs) =>
1644 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1645 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1646 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1647 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
1648 Aggregate(ref kind, ref fields) => {
1649 let kind = box match **kind {
1650 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1651 AggregateKind::Tuple => AggregateKind::Tuple,
1652 AggregateKind::Adt(def, v, substs, n) =>
1653 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1654 AggregateKind::Closure(id, substs) =>
1655 AggregateKind::Closure(id, substs.fold_with(folder))
1657 Aggregate(kind, fields.fold_with(folder))
1662 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1665 Use(ref op) => op.visit_with(visitor),
1666 Repeat(ref op, _) => op.visit_with(visitor),
1667 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1668 Len(ref lval) => lval.visit_with(visitor),
1669 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1670 BinaryOp(_, ref rhs, ref lhs) |
1671 CheckedBinaryOp(_, ref rhs, ref lhs) =>
1672 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1673 UnaryOp(_, ref val) => val.visit_with(visitor),
1674 Discriminant(ref lval) => lval.visit_with(visitor),
1675 NullaryOp(_, ty) => ty.visit_with(visitor),
1676 Aggregate(ref kind, ref fields) => {
1678 AggregateKind::Array(ty) => ty.visit_with(visitor),
1679 AggregateKind::Tuple => false,
1680 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1681 AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1682 }) || fields.visit_with(visitor)
1688 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1689 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1691 Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1692 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1696 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1698 Operand::Consume(ref lval) => lval.visit_with(visitor),
1699 Operand::Constant(ref c) => c.visit_with(visitor)
1704 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1705 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1707 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1708 use mir::ProjectionElem::*;
1710 let base = self.base.fold_with(folder);
1711 let elem = match self.elem {
1713 Field(f, ty) => Field(f, ty.fold_with(folder)),
1714 Index(ref v) => Index(v.fold_with(folder)),
1715 ref elem => elem.clone()
1724 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1725 use mir::ProjectionElem::*;
1727 self.base.visit_with(visitor) ||
1729 Field(_, ty) => ty.visit_with(visitor),
1730 Index(ref v) => v.visit_with(visitor),
1736 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1737 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1739 span: self.span.clone(),
1740 ty: self.ty.fold_with(folder),
1741 literal: self.literal.fold_with(folder)
1744 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1745 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1749 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1750 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1752 Literal::Item { def_id, substs } => Literal::Item {
1754 substs: substs.fold_with(folder)
1759 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1761 Literal::Item { substs, .. } => substs.visit_with(visitor),