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;
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 rustc_serialize as serialize;
22 use hir::def::CtorKind;
23 use hir::def_id::DefId;
24 use ty::subst::{Subst, Substs};
25 use ty::{self, AdtDef, ClosureSubsts, Region, Ty, TyCtxt, GeneratorInterior};
26 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
28 use rustc_back::slice;
29 use hir::{self, InlineAsm};
31 use std::borrow::{Cow};
33 use std::fmt::{self, Debug, Formatter, Write};
35 use std::ops::{Index, IndexMut};
37 use std::vec::IntoIter;
38 use syntax::ast::{self, Name};
47 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
49 pub trait HasLocalDecls<'tcx> {
50 fn local_decls(&self) -> &LocalDecls<'tcx>;
53 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
54 fn local_decls(&self) -> &LocalDecls<'tcx> {
59 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 /// Lowered representation of a single function.
66 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
67 pub struct Mir<'tcx> {
68 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
69 /// that indexes into this vector.
70 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
72 /// List of visibility (lexical) scopes; these are referenced by statements
73 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
74 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
76 /// Crate-local information for each visibility scope, that can't (and
77 /// needn't) be tracked across crates.
78 pub visibility_scope_info: ClearOnDecode<IndexVec<VisibilityScope, VisibilityScopeInfo>>,
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 /// Yield type of the function, if it is a generator.
86 pub yield_ty: Option<Ty<'tcx>>,
88 /// Generator drop glue
89 pub generator_drop: Option<Box<Mir<'tcx>>>,
91 /// The layout of a generator. Produced by the state transformation.
92 pub generator_layout: Option<GeneratorLayout<'tcx>>,
94 /// Declarations of locals.
96 /// The first local is the return value pointer, followed by `arg_count`
97 /// locals for the function arguments, followed by any user-declared
98 /// variables and temporaries.
99 pub local_decls: LocalDecls<'tcx>,
101 /// Number of arguments this function takes.
103 /// Starting at local 1, `arg_count` locals will be provided by the caller
104 /// and can be assumed to be initialized.
106 /// If this MIR was built for a constant, this will be 0.
107 pub arg_count: usize,
109 /// Names and capture modes of all the closure upvars, assuming
110 /// the first argument is either the closure or a reference to it.
111 pub upvar_decls: Vec<UpvarDecl>,
113 /// Mark an argument local (which must be a tuple) as getting passed as
114 /// its individual components at the LLVM level.
116 /// This is used for the "rust-call" ABI.
117 pub spread_arg: Option<Local>,
119 /// A span representing this MIR, for error reporting
122 /// A cache for various calculations
126 /// where execution begins
127 pub const START_BLOCK: BasicBlock = BasicBlock(0);
129 impl<'tcx> Mir<'tcx> {
130 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
131 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
132 visibility_scope_info: ClearOnDecode<IndexVec<VisibilityScope,
133 VisibilityScopeInfo>>,
134 promoted: IndexVec<Promoted, Mir<'tcx>>,
135 yield_ty: Option<Ty<'tcx>>,
136 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
138 upvar_decls: Vec<UpvarDecl>,
141 // We need `arg_count` locals, and one for the return pointer
142 assert!(local_decls.len() >= arg_count + 1,
143 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
148 visibility_scope_info,
151 generator_drop: None,
152 generator_layout: None,
158 cache: cache::Cache::new()
163 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
168 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
169 self.cache.invalidate();
170 &mut self.basic_blocks
174 pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
175 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
176 &mut LocalDecls<'tcx>,
178 self.cache.invalidate();
179 (&mut self.basic_blocks, &mut self.local_decls)
183 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
184 self.cache.predecessors(self)
188 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
189 Ref::map(self.predecessors(), |p| &p[bb])
193 pub fn dominators(&self) -> Dominators<BasicBlock> {
198 pub fn local_kind(&self, local: Local) -> LocalKind {
199 let index = local.0 as usize;
201 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
202 "return pointer should be mutable");
204 LocalKind::ReturnPointer
205 } else if index < self.arg_count + 1 {
207 } else if self.local_decls[local].name.is_some() {
210 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
211 "temp should be mutable");
217 /// Returns an iterator over all temporaries.
219 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
220 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
221 let local = Local::new(index);
222 if self.local_decls[local].is_user_variable {
230 /// Returns an iterator over all user-declared locals.
232 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
233 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
234 let local = Local::new(index);
235 if self.local_decls[local].is_user_variable {
243 /// Returns an iterator over all function arguments.
245 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
246 let arg_count = self.arg_count;
247 (1..arg_count+1).map(Local::new)
250 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
251 /// locals that are neither arguments nor the return pointer).
253 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
254 let arg_count = self.arg_count;
255 let local_count = self.local_decls.len();
256 (arg_count+1..local_count).map(Local::new)
259 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
260 /// invalidating statement indices in `Location`s.
261 pub fn make_statement_nop(&mut self, location: Location) {
262 let block = &mut self[location.block];
263 debug_assert!(location.statement_index < block.statements.len());
264 block.statements[location.statement_index].make_nop()
267 /// Returns the source info associated with `location`.
268 pub fn source_info(&self, location: Location) -> &SourceInfo {
269 let block = &self[location.block];
270 let stmts = &block.statements;
271 let idx = location.statement_index;
272 if idx < stmts.len() {
273 &stmts[idx].source_info
275 assert!(idx == stmts.len());
276 &block.terminator().source_info
280 /// Return the return type, it always return first element from `local_decls` array
281 pub fn return_ty(&self) -> Ty<'tcx> {
282 self.local_decls[RETURN_POINTER].ty
286 #[derive(Clone, Debug)]
287 pub struct VisibilityScopeInfo {
288 /// A NodeId with lint levels equivalent to this scope's lint levels.
289 pub lint_root: ast::NodeId,
290 /// The unsafe block that contains this node.
294 #[derive(Copy, Clone, Debug)]
297 /// Unsafe because of a PushUnsafeBlock
299 /// Unsafe because of an unsafe fn
301 /// Unsafe because of an `unsafe` block
302 ExplicitUnsafe(ast::NodeId)
305 impl_stable_hash_for!(struct Mir<'tcx> {
308 visibility_scope_info,
321 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
322 type Output = BasicBlockData<'tcx>;
325 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
326 &self.basic_blocks()[index]
330 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
332 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
333 &mut self.basic_blocks_mut()[index]
337 #[derive(Clone, Debug)]
338 pub enum ClearOnDecode<T> {
343 impl<T> serialize::Encodable for ClearOnDecode<T> {
344 fn encode<S: serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
345 serialize::Encodable::encode(&(), s)
349 impl<T> serialize::Decodable for ClearOnDecode<T> {
350 fn decode<D: serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
351 serialize::Decodable::decode(d).map(|()| ClearOnDecode::Clear)
355 /// Grouped information about the source code origin of a MIR entity.
356 /// Intended to be inspected by diagnostics and debuginfo.
357 /// Most passes can work with it as a whole, within a single function.
358 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
359 pub struct SourceInfo {
360 /// Source span for the AST pertaining to this MIR entity.
363 /// The lexical visibility scope, i.e. which bindings can be seen.
364 pub scope: VisibilityScope
367 ///////////////////////////////////////////////////////////////////////////
368 // Mutability and borrow kinds
370 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
371 pub enum Mutability {
376 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
377 pub enum BorrowKind {
378 /// Data must be immutable and is aliasable.
381 /// Data must be immutable but not aliasable. This kind of borrow
382 /// cannot currently be expressed by the user and is used only in
383 /// implicit closure bindings. It is needed when you the closure
384 /// is borrowing or mutating a mutable referent, e.g.:
386 /// let x: &mut isize = ...;
387 /// let y = || *x += 5;
389 /// If we were to try to translate this closure into a more explicit
390 /// form, we'd encounter an error with the code as written:
392 /// struct Env { x: & &mut isize }
393 /// let x: &mut isize = ...;
394 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
395 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
397 /// This is then illegal because you cannot mutate a `&mut` found
398 /// in an aliasable location. To solve, you'd have to translate with
399 /// an `&mut` borrow:
401 /// struct Env { x: & &mut isize }
402 /// let x: &mut isize = ...;
403 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
404 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
406 /// Now the assignment to `**env.x` is legal, but creating a
407 /// mutable pointer to `x` is not because `x` is not mutable. We
408 /// could fix this by declaring `x` as `let mut x`. This is ok in
409 /// user code, if awkward, but extra weird for closures, since the
410 /// borrow is hidden.
412 /// So we introduce a "unique imm" borrow -- the referent is
413 /// immutable, but not aliasable. This solves the problem. For
414 /// simplicity, we don't give users the way to express this
415 /// borrow, it's just used when translating closures.
418 /// Data is mutable and not aliasable.
422 ///////////////////////////////////////////////////////////////////////////
423 // Variables and temps
427 DEBUG_FORMAT = "_{}",
428 const RETURN_POINTER = 0,
431 /// Classifies locals into categories. See `Mir::local_kind`.
432 #[derive(PartialEq, Eq, Debug)]
434 /// User-declared variable binding
436 /// Compiler-introduced temporary
438 /// Function argument
440 /// Location of function's return value
446 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
447 /// argument, or the return pointer.
448 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
449 pub struct LocalDecl<'tcx> {
450 /// `let mut x` vs `let x`.
452 /// Temporaries and the return pointer are always mutable.
453 pub mutability: Mutability,
455 /// True if this corresponds to a user-declared local variable.
456 pub is_user_variable: bool,
458 /// True if this is an internal local
460 /// These locals are not based on types in the source code and are only used
461 /// for a few desugarings at the moment.
463 /// The generator transformation will sanity check the locals which are live
464 /// across a suspension point against the type components of the generator
465 /// which type checking knows are live across a suspension point. We need to
466 /// flag drop flags to avoid triggering this check as they are introduced
469 /// Unsafety checking will also ignore dereferences of these locals,
470 /// so they can be used for raw pointers only used in a desugaring.
472 /// This should be sound because the drop flags are fully algebraic, and
473 /// therefore don't affect the OIBIT or outlives properties of the
477 /// Type of this local.
480 /// Name of the local, used in debuginfo and pretty-printing.
482 /// Note that function arguments can also have this set to `Some(_)`
483 /// to generate better debuginfo.
484 pub name: Option<Name>,
486 /// Source info of the local.
487 pub source_info: SourceInfo,
489 /// The *lexical* visibility scope the local is defined
490 /// in. If the local was defined in a let-statement, this
491 /// is *within* the let-statement, rather than outside
493 pub lexical_scope: VisibilityScope,
496 impl<'tcx> LocalDecl<'tcx> {
497 /// Create a new `LocalDecl` for a temporary.
499 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
501 mutability: Mutability::Mut,
504 source_info: SourceInfo {
506 scope: ARGUMENT_VISIBILITY_SCOPE
508 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
510 is_user_variable: false
514 /// Create a new `LocalDecl` for a internal temporary.
516 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
518 mutability: Mutability::Mut,
521 source_info: SourceInfo {
523 scope: ARGUMENT_VISIBILITY_SCOPE
525 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
527 is_user_variable: false
531 /// Builds a `LocalDecl` for the return pointer.
533 /// This must be inserted into the `local_decls` list as the first local.
535 pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
537 mutability: Mutability::Mut,
539 source_info: SourceInfo {
541 scope: ARGUMENT_VISIBILITY_SCOPE
543 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
545 name: None, // FIXME maybe we do want some name here?
546 is_user_variable: false
551 /// A closure capture, with its name and mode.
552 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
553 pub struct UpvarDecl {
554 pub debug_name: Name,
556 /// If true, the capture is behind a reference.
560 ///////////////////////////////////////////////////////////////////////////
563 newtype_index!(BasicBlock { DEBUG_FORMAT = "bb{}" });
566 pub fn start_location(self) -> Location {
574 ///////////////////////////////////////////////////////////////////////////
575 // BasicBlockData and Terminator
577 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
578 pub struct BasicBlockData<'tcx> {
579 /// List of statements in this block.
580 pub statements: Vec<Statement<'tcx>>,
582 /// Terminator for this block.
584 /// NB. This should generally ONLY be `None` during construction.
585 /// Therefore, you should generally access it via the
586 /// `terminator()` or `terminator_mut()` methods. The only
587 /// exception is that certain passes, such as `simplify_cfg`, swap
588 /// out the terminator temporarily with `None` while they continue
589 /// to recurse over the set of basic blocks.
590 pub terminator: Option<Terminator<'tcx>>,
592 /// If true, this block lies on an unwind path. This is used
593 /// during trans where distinct kinds of basic blocks may be
594 /// generated (particularly for MSVC cleanup). Unwind blocks must
595 /// only branch to other unwind blocks.
596 pub is_cleanup: bool,
599 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
600 pub struct Terminator<'tcx> {
601 pub source_info: SourceInfo,
602 pub kind: TerminatorKind<'tcx>
605 #[derive(Clone, RustcEncodable, RustcDecodable)]
606 pub enum TerminatorKind<'tcx> {
607 /// block should have one successor in the graph; we jump there
612 /// operand evaluates to an integer; jump depending on its value
613 /// to one of the targets, and otherwise fallback to `otherwise`
615 /// discriminant value being tested
616 discr: Operand<'tcx>,
618 /// type of value being tested
621 /// Possible values. The locations to branch to in each case
622 /// are found in the corresponding indices from the `targets` vector.
623 values: Cow<'tcx, [ConstInt]>,
625 /// Possible branch sites. The last element of this vector is used
626 /// for the otherwise branch, so targets.len() == values.len() + 1
628 // This invariant is quite non-obvious and also could be improved.
629 // One way to make this invariant is to have something like this instead:
631 // branches: Vec<(ConstInt, BasicBlock)>,
632 // otherwise: Option<BasicBlock> // exhaustive if None
634 // However we’ve decided to keep this as-is until we figure a case
635 // where some other approach seems to be strictly better than other.
636 targets: Vec<BasicBlock>,
639 /// Indicates that the landing pad is finished and unwinding should
640 /// continue. Emitted by build::scope::diverge_cleanup.
643 /// Indicates a normal return. The return pointer lvalue should
644 /// have been filled in by now. This should occur at most once.
647 /// Indicates a terminator that can never be reached.
652 location: Lvalue<'tcx>,
654 unwind: Option<BasicBlock>
657 /// Drop the Lvalue and assign the new value over it. This ensures
658 /// that the assignment to LV occurs *even if* the destructor for
659 /// lvalue unwinds. Its semantics are best explained by by the
664 /// DropAndReplace(LV <- RV, goto BB1, unwind BB2)
672 /// Drop(LV, goto BB1, unwind BB2)
675 /// // LV is now unitialized
679 /// // LV is now unitialized -- its dtor panicked
684 location: Lvalue<'tcx>,
685 value: Operand<'tcx>,
687 unwind: Option<BasicBlock>,
690 /// Block ends with a call of a converging function
692 /// The function that’s being called
694 /// Arguments the function is called with.
695 /// These are owned by the callee, which is free to modify them.
696 /// This allows the memory occupied by "by-value" arguments to be
697 /// reused across function calls without duplicating the contents.
698 args: Vec<Operand<'tcx>>,
699 /// Destination for the return value. If some, the call is converging.
700 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
701 /// Cleanups to be done if the call unwinds.
702 cleanup: Option<BasicBlock>
705 /// Jump to the target if the condition has the expected value,
706 /// otherwise panic with a message and a cleanup target.
710 msg: AssertMessage<'tcx>,
712 cleanup: Option<BasicBlock>
717 /// The value to return
718 value: Operand<'tcx>,
719 /// Where to resume to
721 /// Cleanup to be done if the generator is dropped at this suspend point
722 drop: Option<BasicBlock>,
725 /// Indicates the end of the dropping of a generator
729 real_target: BasicBlock,
730 imaginary_targets: Vec<BasicBlock>
734 impl<'tcx> Terminator<'tcx> {
735 pub fn successors(&self) -> Cow<[BasicBlock]> {
736 self.kind.successors()
739 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
740 self.kind.successors_mut()
744 impl<'tcx> TerminatorKind<'tcx> {
745 pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
746 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
747 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
748 TerminatorKind::SwitchInt {
750 switch_ty: tcx.types.bool,
751 values: From::from(BOOL_SWITCH_FALSE),
756 pub fn successors(&self) -> Cow<[BasicBlock]> {
757 use self::TerminatorKind::*;
759 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
760 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
761 Resume | GeneratorDrop => (&[]).into_cow(),
762 Return => (&[]).into_cow(),
763 Unreachable => (&[]).into_cow(),
764 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
765 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
766 slice::ref_slice(t).into_cow(),
767 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
768 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
769 Yield { resume: t, drop: Some(c), .. } => vec![t, c].into_cow(),
770 Yield { resume: ref t, drop: None, .. } => slice::ref_slice(t).into_cow(),
771 DropAndReplace { target, unwind: Some(unwind), .. } |
772 Drop { target, unwind: Some(unwind), .. } => {
773 vec![target, unwind].into_cow()
775 DropAndReplace { ref target, unwind: None, .. } |
776 Drop { ref target, unwind: None, .. } => {
777 slice::ref_slice(target).into_cow()
779 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
780 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
781 FalseEdges { ref real_target, ref imaginary_targets } => {
782 let mut s = vec![*real_target];
783 s.extend_from_slice(imaginary_targets);
789 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
790 // `Vec<&mut BasicBlock>` would look like in the first place.
791 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
792 use self::TerminatorKind::*;
794 Goto { target: ref mut b } => vec![b],
795 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
796 Resume | GeneratorDrop => Vec::new(),
797 Return => Vec::new(),
798 Unreachable => Vec::new(),
799 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
800 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
801 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
802 Call { destination: None, cleanup: None, .. } => vec![],
803 Yield { resume: ref mut t, drop: Some(ref mut c), .. } => vec![t, c],
804 Yield { resume: ref mut t, drop: None, .. } => vec![t],
805 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
806 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
807 DropAndReplace { ref mut target, unwind: None, .. } |
808 Drop { ref mut target, unwind: None, .. } => {
811 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
812 Assert { ref mut target, .. } => vec![target],
813 FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
814 let mut s = vec![real_target];
815 s.extend(imaginary_targets.iter_mut());
822 impl<'tcx> BasicBlockData<'tcx> {
823 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
831 /// Accessor for terminator.
833 /// Terminator may not be None after construction of the basic block is complete. This accessor
834 /// provides a convenience way to reach the terminator.
835 pub fn terminator(&self) -> &Terminator<'tcx> {
836 self.terminator.as_ref().expect("invalid terminator state")
839 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
840 self.terminator.as_mut().expect("invalid terminator state")
843 pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
844 for s in &mut self.statements {
846 s.kind = StatementKind::Nop;
852 impl<'tcx> Debug for TerminatorKind<'tcx> {
853 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
855 let successors = self.successors();
856 let labels = self.fmt_successor_labels();
857 assert_eq!(successors.len(), labels.len());
859 match successors.len() {
862 1 => write!(fmt, " -> {:?}", successors[0]),
865 write!(fmt, " -> [")?;
866 for (i, target) in successors.iter().enumerate() {
870 write!(fmt, "{}: {:?}", labels[i], target)?;
879 impl<'tcx> TerminatorKind<'tcx> {
880 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
881 /// successor basic block, if any. The only information not included is the list of possible
882 /// successors, which may be rendered differently between the text and the graphviz format.
883 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
884 use self::TerminatorKind::*;
886 Goto { .. } => write!(fmt, "goto"),
887 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
888 Return => write!(fmt, "return"),
889 GeneratorDrop => write!(fmt, "generator_drop"),
890 Resume => write!(fmt, "resume"),
891 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
892 Unreachable => write!(fmt, "unreachable"),
893 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
894 DropAndReplace { ref location, ref value, .. } =>
895 write!(fmt, "replace({:?} <- {:?})", location, value),
896 Call { ref func, ref args, ref destination, .. } => {
897 if let Some((ref destination, _)) = *destination {
898 write!(fmt, "{:?} = ", destination)?;
900 write!(fmt, "{:?}(", func)?;
901 for (index, arg) in args.iter().enumerate() {
905 write!(fmt, "{:?}", arg)?;
909 Assert { ref cond, expected, ref msg, .. } => {
910 write!(fmt, "assert(")?;
914 write!(fmt, "{:?}, ", cond)?;
917 AssertMessage::BoundsCheck { ref len, ref index } => {
918 write!(fmt, "{:?}, {:?}, {:?}",
919 "index out of bounds: the len is {} but the index is {}",
922 AssertMessage::Math(ref err) => {
923 write!(fmt, "{:?}", err.description())?;
925 AssertMessage::GeneratorResumedAfterReturn => {
926 write!(fmt, "{:?}", "generator resumed after completion")?;
928 AssertMessage::GeneratorResumedAfterPanic => {
929 write!(fmt, "{:?}", "generator resumed after panicking")?;
935 FalseEdges { .. } => write!(fmt, "falseEdges")
939 /// Return the list of labels for the edges to the successor basic blocks.
940 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
941 use self::TerminatorKind::*;
943 Return | Resume | Unreachable | GeneratorDrop => vec![],
944 Goto { .. } => vec!["".into()],
945 SwitchInt { ref values, .. } => {
948 let mut buf = String::new();
949 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
952 .chain(iter::once(String::from("otherwise").into()))
955 Call { destination: Some(_), cleanup: Some(_), .. } =>
956 vec!["return".into_cow(), "unwind".into_cow()],
957 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
958 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
959 Call { destination: None, cleanup: None, .. } => vec![],
960 Yield { drop: Some(_), .. } =>
961 vec!["resume".into_cow(), "drop".into_cow()],
962 Yield { drop: None, .. } => vec!["resume".into_cow()],
963 DropAndReplace { unwind: None, .. } |
964 Drop { unwind: None, .. } => vec!["return".into_cow()],
965 DropAndReplace { unwind: Some(_), .. } |
966 Drop { unwind: Some(_), .. } => {
967 vec!["return".into_cow(), "unwind".into_cow()]
969 Assert { cleanup: None, .. } => vec!["".into()],
971 vec!["success".into_cow(), "unwind".into_cow()],
972 FalseEdges { ref imaginary_targets, .. } => {
973 let mut l = vec!["real".into()];
974 l.resize(imaginary_targets.len() + 1, "imaginary".into());
981 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
982 pub enum AssertMessage<'tcx> {
988 GeneratorResumedAfterReturn,
989 GeneratorResumedAfterPanic,
992 ///////////////////////////////////////////////////////////////////////////
995 #[derive(Clone, RustcEncodable, RustcDecodable)]
996 pub struct Statement<'tcx> {
997 pub source_info: SourceInfo,
998 pub kind: StatementKind<'tcx>,
1001 impl<'tcx> Statement<'tcx> {
1002 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1003 /// invalidating statement indices in `Location`s.
1004 pub fn make_nop(&mut self) {
1005 self.kind = StatementKind::Nop
1009 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1010 pub enum StatementKind<'tcx> {
1011 /// Write the RHS Rvalue to the LHS Lvalue.
1012 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
1014 /// Write the discriminant for a variant to the enum Lvalue.
1015 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
1017 /// Start a live range for the storage of the local.
1020 /// End the current live range for the storage of the local.
1023 /// Execute a piece of inline Assembly.
1025 asm: Box<InlineAsm>,
1026 outputs: Vec<Lvalue<'tcx>>,
1027 inputs: Vec<Operand<'tcx>>
1030 /// Assert the given lvalues to be valid inhabitants of their type. These statements are
1031 /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1032 /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1033 Validate(ValidationOp, Vec<ValidationOperand<'tcx, Lvalue<'tcx>>>),
1035 /// Mark one terminating point of a region scope (i.e. static region).
1036 /// (The starting point(s) arise implicitly from borrows.)
1037 EndRegion(region::Scope),
1039 /// No-op. Useful for deleting instructions without affecting statement indices.
1043 /// The `ValidationOp` describes what happens with each of the operands of a
1044 /// `Validate` statement.
1045 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1046 pub enum ValidationOp {
1047 /// Recursively traverse the lvalue following the type and validate that all type
1048 /// invariants are maintained. Furthermore, acquire exclusive/read-only access to the
1049 /// memory reachable from the lvalue.
1051 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1054 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1055 /// access *until* the given region ends. Then, access will be recovered.
1056 Suspend(region::Scope),
1059 impl Debug for ValidationOp {
1060 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1061 use self::ValidationOp::*;
1063 Acquire => write!(fmt, "Acquire"),
1064 Release => write!(fmt, "Release"),
1065 // (reuse lifetime rendering policy from ppaux.)
1066 Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1071 // This is generic so that it can be reused by miri
1072 #[derive(Clone, RustcEncodable, RustcDecodable)]
1073 pub struct ValidationOperand<'tcx, T> {
1076 pub re: Option<region::Scope>,
1077 pub mutbl: hir::Mutability,
1080 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1081 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1082 write!(fmt, "{:?}: {:?}", self.lval, self.ty)?;
1083 if let Some(ce) = self.re {
1084 // (reuse lifetime rendering policy from ppaux.)
1085 write!(fmt, "/{}", ty::ReScope(ce))?;
1087 if let hir::MutImmutable = self.mutbl {
1088 write!(fmt, " (imm)")?;
1094 impl<'tcx> Debug for Statement<'tcx> {
1095 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1096 use self::StatementKind::*;
1098 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
1099 // (reuse lifetime rendering policy from ppaux.)
1100 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1101 Validate(ref op, ref lvalues) => write!(fmt, "Validate({:?}, {:?})", op, lvalues),
1102 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
1103 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
1104 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
1105 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
1107 InlineAsm { ref asm, ref outputs, ref inputs } => {
1108 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1110 Nop => write!(fmt, "nop"),
1115 ///////////////////////////////////////////////////////////////////////////
1118 /// A path to a value; something that can be evaluated without
1119 /// changing or disturbing program state.
1120 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1121 pub enum Lvalue<'tcx> {
1125 /// static or static mut variable
1126 Static(Box<Static<'tcx>>),
1128 /// projection out of an lvalue (access a field, deref a pointer, etc)
1129 Projection(Box<LvalueProjection<'tcx>>),
1132 /// The def-id of a static, along with its normalized type (which is
1133 /// stored to avoid requiring normalization when reading MIR).
1134 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1135 pub struct Static<'tcx> {
1140 impl_stable_hash_for!(struct Static<'tcx> {
1145 /// The `Projection` data structure defines things of the form `B.x`
1146 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1147 /// shared between `Constant` and `Lvalue`. See the aliases
1148 /// `LvalueProjection` etc below.
1149 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1150 pub struct Projection<'tcx, B, V, T> {
1152 pub elem: ProjectionElem<'tcx, V, T>,
1155 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1156 pub enum ProjectionElem<'tcx, V, T> {
1161 /// These indices are generated by slice patterns. Easiest to explain
1165 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1166 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1167 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1168 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1171 /// index or -index (in Python terms), depending on from_end
1173 /// thing being indexed must be at least this long
1175 /// counting backwards from end?
1179 /// These indices are generated by slice patterns.
1181 /// slice[from:-to] in Python terms.
1187 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1188 /// this for ADTs with more than one variant. It may be better to
1189 /// just introduce it always, or always for enums.
1190 Downcast(&'tcx AdtDef, usize),
1193 /// Alias for projections as they appear in lvalues, where the base is an lvalue
1194 /// and the index is a local.
1195 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Local, Ty<'tcx>>;
1197 /// Alias for projections as they appear in lvalues, where the base is an lvalue
1198 /// and the index is a local.
1199 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1201 newtype_index!(Field { DEBUG_FORMAT = "field[{}]" });
1203 impl<'tcx> Lvalue<'tcx> {
1204 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
1205 self.elem(ProjectionElem::Field(f, ty))
1208 pub fn deref(self) -> Lvalue<'tcx> {
1209 self.elem(ProjectionElem::Deref)
1212 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
1213 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1216 pub fn index(self, index: Local) -> Lvalue<'tcx> {
1217 self.elem(ProjectionElem::Index(index))
1220 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
1221 Lvalue::Projection(Box::new(LvalueProjection {
1228 impl<'tcx> Debug for Lvalue<'tcx> {
1229 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1230 use self::Lvalue::*;
1233 Local(id) => write!(fmt, "{:?}", id),
1234 Static(box self::Static { def_id, ty }) =>
1235 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
1236 Projection(ref data) =>
1238 ProjectionElem::Downcast(ref adt_def, index) =>
1239 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
1240 ProjectionElem::Deref =>
1241 write!(fmt, "(*{:?})", data.base),
1242 ProjectionElem::Field(field, ty) =>
1243 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
1244 ProjectionElem::Index(ref index) =>
1245 write!(fmt, "{:?}[{:?}]", data.base, index),
1246 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
1247 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
1248 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
1249 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
1250 ProjectionElem::Subslice { from, to } if to == 0 =>
1251 write!(fmt, "{:?}[{:?}:]", data.base, from),
1252 ProjectionElem::Subslice { from, to } if from == 0 =>
1253 write!(fmt, "{:?}[:-{:?}]", data.base, to),
1254 ProjectionElem::Subslice { from, to } =>
1255 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
1263 ///////////////////////////////////////////////////////////////////////////
1266 newtype_index!(VisibilityScope
1268 DEBUG_FORMAT = "scope[{}]",
1269 const ARGUMENT_VISIBILITY_SCOPE = 0,
1272 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1273 pub struct VisibilityScopeData {
1275 pub parent_scope: Option<VisibilityScope>,
1278 ///////////////////////////////////////////////////////////////////////////
1281 /// These are values that can appear inside an rvalue (or an index
1282 /// lvalue). They are intentionally limited to prevent rvalues from
1283 /// being nested in one another.
1284 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1285 pub enum Operand<'tcx> {
1286 /// Copy: The value must be available for use afterwards.
1288 /// This implies that the type of the lvalue must be `Copy`; this is true
1289 /// by construction during build, but also checked by the MIR type checker.
1291 /// Move: The value (including old borrows of it) will not be used again.
1293 /// Safe for values of all types (modulo future developments towards `?Move`).
1294 /// Correct usage patterns are enforced by the borrow checker for safe code.
1295 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1297 Constant(Box<Constant<'tcx>>),
1300 impl<'tcx> Debug for Operand<'tcx> {
1301 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1302 use self::Operand::*;
1304 Constant(ref a) => write!(fmt, "{:?}", a),
1305 Copy(ref lv) => write!(fmt, "{:?}", lv),
1306 Move(ref lv) => write!(fmt, "move {:?}", lv),
1311 impl<'tcx> Operand<'tcx> {
1312 pub fn function_handle<'a>(
1313 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1315 substs: &'tcx Substs<'tcx>,
1318 let ty = tcx.type_of(def_id).subst(tcx, substs);
1319 Operand::Constant(box Constant {
1322 literal: Literal::Value {
1323 value: tcx.mk_const(ty::Const {
1324 val: ConstVal::Function(def_id, substs),
1333 ///////////////////////////////////////////////////////////////////////////
1336 #[derive(Clone, RustcEncodable, RustcDecodable)]
1337 pub enum Rvalue<'tcx> {
1338 /// x (either a move or copy, depending on type of x)
1342 Repeat(Operand<'tcx>, ConstUsize),
1345 Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1347 /// length of a [X] or [X;n] value
1350 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1352 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1353 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1355 NullaryOp(NullOp, Ty<'tcx>),
1356 UnaryOp(UnOp, Operand<'tcx>),
1358 /// Read the discriminant of an ADT.
1360 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1361 /// be defined to return, say, a 0) if ADT is not an enum.
1362 Discriminant(Lvalue<'tcx>),
1364 /// Create an aggregate value, like a tuple or struct. This is
1365 /// only needed because we want to distinguish `dest = Foo { x:
1366 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1367 /// that `Foo` has a destructor. These rvalues can be optimized
1368 /// away after type-checking and before lowering.
1369 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1372 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1376 /// Convert unique, zero-sized type for a fn to fn()
1379 /// Convert non capturing closure to fn()
1382 /// Convert safe fn() to unsafe fn()
1385 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1386 /// trans must figure out the details once full monomorphization
1387 /// is known. For example, this could be used to cast from a
1388 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1389 /// (presuming `T: Trait`).
1393 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1394 pub enum AggregateKind<'tcx> {
1395 /// The type is of the element
1399 /// The second field is variant number (discriminant), it's equal
1400 /// to 0 for struct and union expressions. The fourth field is
1401 /// active field number and is present only for union expressions
1402 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
1403 /// active field index would identity the field `c`
1404 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1406 Closure(DefId, ClosureSubsts<'tcx>),
1407 Generator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
1410 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1412 /// The `+` operator (addition)
1414 /// The `-` operator (subtraction)
1416 /// The `*` operator (multiplication)
1418 /// The `/` operator (division)
1420 /// The `%` operator (modulus)
1422 /// The `^` operator (bitwise xor)
1424 /// The `&` operator (bitwise and)
1426 /// The `|` operator (bitwise or)
1428 /// The `<<` operator (shift left)
1430 /// The `>>` operator (shift right)
1432 /// The `==` operator (equality)
1434 /// The `<` operator (less than)
1436 /// The `<=` operator (less than or equal to)
1438 /// The `!=` operator (not equal to)
1440 /// The `>=` operator (greater than or equal to)
1442 /// The `>` operator (greater than)
1444 /// The `ptr.offset` operator
1449 pub fn is_checkable(self) -> bool {
1452 Add | Sub | Mul | Shl | Shr => true,
1458 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1460 /// Return the size of a value of that type
1462 /// Create a new uninitialized box for a value of that type
1466 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1468 /// The `!` operator for logical inversion
1470 /// The `-` operator for negation
1474 impl<'tcx> Debug for Rvalue<'tcx> {
1475 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1476 use self::Rvalue::*;
1479 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1480 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1481 Len(ref a) => write!(fmt, "Len({:?})", a),
1482 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1483 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1484 CheckedBinaryOp(ref op, ref a, ref b) => {
1485 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1487 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1488 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1489 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1490 Ref(region, borrow_kind, ref lv) => {
1491 let kind_str = match borrow_kind {
1492 BorrowKind::Shared => "",
1493 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1496 // When printing regions, add trailing space if necessary.
1497 let region = if ppaux::verbose() || ppaux::identify_regions() {
1498 let mut region = format!("{}", region);
1499 if region.len() > 0 { region.push(' '); }
1502 // Do not even print 'static
1505 write!(fmt, "&{}{}{:?}", region, kind_str, lv)
1508 Aggregate(ref kind, ref lvs) => {
1509 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1510 let mut tuple_fmt = fmt.debug_tuple("");
1512 tuple_fmt.field(lv);
1518 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1520 AggregateKind::Tuple => {
1522 0 => write!(fmt, "()"),
1523 1 => write!(fmt, "({:?},)", lvs[0]),
1524 _ => fmt_tuple(fmt, lvs),
1528 AggregateKind::Adt(adt_def, variant, substs, _) => {
1529 let variant_def = &adt_def.variants[variant];
1531 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1533 match variant_def.ctor_kind {
1534 CtorKind::Const => Ok(()),
1535 CtorKind::Fn => fmt_tuple(fmt, lvs),
1536 CtorKind::Fictive => {
1537 let mut struct_fmt = fmt.debug_struct("");
1538 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1539 struct_fmt.field(&field.name.as_str(), lv);
1546 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1547 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1548 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1549 format!("[closure@{:?}]", node_id)
1551 format!("[closure@{:?}]", tcx.hir.span(node_id))
1553 let mut struct_fmt = fmt.debug_struct(&name);
1555 tcx.with_freevars(node_id, |freevars| {
1556 for (freevar, lv) in freevars.iter().zip(lvs) {
1557 let var_name = tcx.hir.name(freevar.var_id());
1558 struct_fmt.field(&var_name.as_str(), lv);
1564 write!(fmt, "[closure]")
1568 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
1569 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1570 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
1571 let mut struct_fmt = fmt.debug_struct(&name);
1573 tcx.with_freevars(node_id, |freevars| {
1574 for (freevar, lv) in freevars.iter().zip(lvs) {
1575 let var_name = tcx.hir.name(freevar.var_id());
1576 struct_fmt.field(&var_name.as_str(), lv);
1578 struct_fmt.field("$state", &lvs[freevars.len()]);
1579 for i in (freevars.len() + 1)..lvs.len() {
1580 struct_fmt.field(&format!("${}", i - freevars.len() - 1),
1587 write!(fmt, "[generator]")
1596 ///////////////////////////////////////////////////////////////////////////
1599 /// Two constants are equal if they are the same constant. Note that
1600 /// this does not necessarily mean that they are "==" in Rust -- in
1601 /// particular one must be wary of `NaN`!
1603 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1604 pub struct Constant<'tcx> {
1607 pub literal: Literal<'tcx>,
1610 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
1613 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1614 pub enum Literal<'tcx> {
1616 value: &'tcx ty::Const<'tcx>,
1619 // Index into the `promoted` vector of `Mir`.
1624 impl<'tcx> Debug for Constant<'tcx> {
1625 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1626 write!(fmt, "{:?}", self.literal)
1630 impl<'tcx> Debug for Literal<'tcx> {
1631 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1632 use self::Literal::*;
1634 Value { value } => {
1635 write!(fmt, "const ")?;
1636 fmt_const_val(fmt, &value.val)
1638 Promoted { index } => {
1639 write!(fmt, "{:?}", index)
1645 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1646 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1647 use middle::const_val::ConstVal::*;
1649 Float(f) => write!(fmt, "{:?}", f),
1650 Integral(n) => write!(fmt, "{}", n),
1651 Str(s) => write!(fmt, "{:?}", s),
1653 let escaped: String = bytes.data
1655 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1657 write!(fmt, "b\"{}\"", escaped)
1659 Bool(b) => write!(fmt, "{:?}", b),
1660 Char(c) => write!(fmt, "{:?}", c),
1662 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1663 Aggregate(_) => bug!("`ConstVal::{:?}` should not be in MIR", const_val),
1664 Unevaluated(..) => write!(fmt, "{:?}", const_val)
1668 fn item_path_str(def_id: DefId) -> String {
1669 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1672 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1674 type Node = BasicBlock;
1676 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1678 fn start_node(&self) -> Self::Node { START_BLOCK }
1680 fn predecessors<'graph>(&'graph self, node: Self::Node)
1681 -> <Self as GraphPredecessors<'graph>>::Iter
1683 self.predecessors_for(node).clone().into_iter()
1685 fn successors<'graph>(&'graph self, node: Self::Node)
1686 -> <Self as GraphSuccessors<'graph>>::Iter
1688 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1692 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1693 type Item = BasicBlock;
1694 type Iter = IntoIter<BasicBlock>;
1697 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1698 type Item = BasicBlock;
1699 type Iter = IntoIter<BasicBlock>;
1702 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1703 pub struct Location {
1704 /// the location is within this block
1705 pub block: BasicBlock,
1707 /// the location is the start of the this statement; or, if `statement_index`
1708 /// == num-statements, then the start of the terminator.
1709 pub statement_index: usize,
1712 impl fmt::Debug for Location {
1713 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1714 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1719 /// Returns the location immediately after this one within the enclosing block.
1721 /// Note that if this location represents a terminator, then the
1722 /// resulting location would be out of bounds and invalid.
1723 pub fn successor_within_block(&self) -> Location {
1724 Location { block: self.block, statement_index: self.statement_index + 1 }
1727 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1728 if self.block == other.block {
1729 self.statement_index <= other.statement_index
1731 dominators.is_dominated_by(other.block, self.block)
1736 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1737 pub enum UnsafetyViolationKind {
1739 ExternStatic(ast::NodeId),
1740 BorrowPacked(ast::NodeId),
1743 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1744 pub struct UnsafetyViolation {
1745 pub source_info: SourceInfo,
1746 pub description: &'static str,
1747 pub kind: UnsafetyViolationKind,
1750 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
1751 pub struct UnsafetyCheckResult {
1752 /// Violations that are propagated *upwards* from this function
1753 pub violations: Rc<[UnsafetyViolation]>,
1754 /// unsafe blocks in this function, along with whether they are used. This is
1755 /// used for the "unused_unsafe" lint.
1756 pub unsafe_blocks: Rc<[(ast::NodeId, bool)]>,
1759 /// The layout of generator state
1760 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1761 pub struct GeneratorLayout<'tcx> {
1762 pub fields: Vec<LocalDecl<'tcx>>,
1766 * TypeFoldable implementations for MIR types
1769 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1770 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1772 basic_blocks: self.basic_blocks.fold_with(folder),
1773 visibility_scopes: self.visibility_scopes.clone(),
1774 visibility_scope_info: self.visibility_scope_info.clone(),
1775 promoted: self.promoted.fold_with(folder),
1776 yield_ty: self.yield_ty.fold_with(folder),
1777 generator_drop: self.generator_drop.fold_with(folder),
1778 generator_layout: self.generator_layout.fold_with(folder),
1779 local_decls: self.local_decls.fold_with(folder),
1780 arg_count: self.arg_count,
1781 upvar_decls: self.upvar_decls.clone(),
1782 spread_arg: self.spread_arg,
1784 cache: cache::Cache::new()
1788 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1789 self.basic_blocks.visit_with(visitor) ||
1790 self.generator_drop.visit_with(visitor) ||
1791 self.generator_layout.visit_with(visitor) ||
1792 self.yield_ty.visit_with(visitor) ||
1793 self.promoted.visit_with(visitor) ||
1794 self.local_decls.visit_with(visitor)
1798 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
1799 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1801 fields: self.fields.fold_with(folder),
1805 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1806 self.fields.visit_with(visitor)
1810 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1811 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1813 ty: self.ty.fold_with(folder),
1818 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1819 self.ty.visit_with(visitor)
1823 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1824 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1826 statements: self.statements.fold_with(folder),
1827 terminator: self.terminator.fold_with(folder),
1828 is_cleanup: self.is_cleanup
1832 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1833 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1837 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Lvalue<'tcx>> {
1838 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1840 lval: self.lval.fold_with(folder),
1841 ty: self.ty.fold_with(folder),
1847 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1848 self.lval.visit_with(visitor) || self.ty.visit_with(visitor)
1852 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1853 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1854 use mir::StatementKind::*;
1856 let kind = match self.kind {
1857 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1858 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1859 lvalue: lvalue.fold_with(folder),
1862 StorageLive(ref local) => StorageLive(local.fold_with(folder)),
1863 StorageDead(ref local) => StorageDead(local.fold_with(folder)),
1864 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1866 outputs: outputs.fold_with(folder),
1867 inputs: inputs.fold_with(folder)
1870 // Note for future: If we want to expose the region scopes
1871 // during the fold, we need to either generalize EndRegion
1872 // to carry `[ty::Region]`, or extend the `TypeFolder`
1873 // trait with a `fn fold_scope`.
1874 EndRegion(ref region_scope) => EndRegion(region_scope.clone()),
1876 Validate(ref op, ref lvals) =>
1877 Validate(op.clone(),
1878 lvals.iter().map(|operand| operand.fold_with(folder)).collect()),
1883 source_info: self.source_info,
1888 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1889 use mir::StatementKind::*;
1892 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1893 SetDiscriminant { ref lvalue, .. } => lvalue.visit_with(visitor),
1894 StorageLive(ref local) |
1895 StorageDead(ref local) => local.visit_with(visitor),
1896 InlineAsm { ref outputs, ref inputs, .. } =>
1897 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1899 // Note for future: If we want to expose the region scopes
1900 // during the visit, we need to either generalize EndRegion
1901 // to carry `[ty::Region]`, or extend the `TypeVisitor`
1902 // trait with a `fn visit_scope`.
1903 EndRegion(ref _scope) => false,
1905 Validate(ref _op, ref lvalues) =>
1906 lvalues.iter().any(|ty_and_lvalue| ty_and_lvalue.visit_with(visitor)),
1913 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1914 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1915 use mir::TerminatorKind::*;
1917 let kind = match self.kind {
1918 Goto { target } => Goto { target: target },
1919 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1920 discr: discr.fold_with(folder),
1921 switch_ty: switch_ty.fold_with(folder),
1922 values: values.clone(),
1923 targets: targets.clone()
1925 Drop { ref location, target, unwind } => Drop {
1926 location: location.fold_with(folder),
1930 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1931 location: location.fold_with(folder),
1932 value: value.fold_with(folder),
1936 Yield { ref value, resume, drop } => Yield {
1937 value: value.fold_with(folder),
1941 Call { ref func, ref args, ref destination, cleanup } => {
1942 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1943 (loc.fold_with(folder), dest)
1947 func: func.fold_with(folder),
1948 args: args.fold_with(folder),
1953 Assert { ref cond, expected, ref msg, target, cleanup } => {
1954 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1955 AssertMessage::BoundsCheck {
1956 len: len.fold_with(folder),
1957 index: index.fold_with(folder),
1963 cond: cond.fold_with(folder),
1970 GeneratorDrop => GeneratorDrop,
1973 Unreachable => Unreachable,
1974 FalseEdges { real_target, ref imaginary_targets } =>
1975 FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() }
1978 source_info: self.source_info,
1983 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1984 use mir::TerminatorKind::*;
1987 SwitchInt { ref discr, switch_ty, .. } =>
1988 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1989 Drop { ref location, ..} => location.visit_with(visitor),
1990 DropAndReplace { ref location, ref value, ..} =>
1991 location.visit_with(visitor) || value.visit_with(visitor),
1992 Yield { ref value, ..} =>
1993 value.visit_with(visitor),
1994 Call { ref func, ref args, ref destination, .. } => {
1995 let dest = if let Some((ref loc, _)) = *destination {
1996 loc.visit_with(visitor)
1998 dest || func.visit_with(visitor) || args.visit_with(visitor)
2000 Assert { ref cond, ref msg, .. } => {
2001 if cond.visit_with(visitor) {
2002 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2003 len.visit_with(visitor) || index.visit_with(visitor)
2016 FalseEdges { .. } => false
2021 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
2022 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2024 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
2029 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2030 if let &Lvalue::Projection(ref p) = self {
2031 p.visit_with(visitor)
2038 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2039 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2042 Use(ref op) => Use(op.fold_with(folder)),
2043 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2044 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
2045 Len(ref lval) => Len(lval.fold_with(folder)),
2046 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2047 BinaryOp(op, ref rhs, ref lhs) =>
2048 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2049 CheckedBinaryOp(op, ref rhs, ref lhs) =>
2050 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2051 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2052 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
2053 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2054 Aggregate(ref kind, ref fields) => {
2055 let kind = box match **kind {
2056 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2057 AggregateKind::Tuple => AggregateKind::Tuple,
2058 AggregateKind::Adt(def, v, substs, n) =>
2059 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
2060 AggregateKind::Closure(id, substs) =>
2061 AggregateKind::Closure(id, substs.fold_with(folder)),
2062 AggregateKind::Generator(id, substs, interior) =>
2063 AggregateKind::Generator(id,
2064 substs.fold_with(folder),
2065 interior.fold_with(folder)),
2067 Aggregate(kind, fields.fold_with(folder))
2072 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2075 Use(ref op) => op.visit_with(visitor),
2076 Repeat(ref op, _) => op.visit_with(visitor),
2077 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
2078 Len(ref lval) => lval.visit_with(visitor),
2079 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2080 BinaryOp(_, ref rhs, ref lhs) |
2081 CheckedBinaryOp(_, ref rhs, ref lhs) =>
2082 rhs.visit_with(visitor) || lhs.visit_with(visitor),
2083 UnaryOp(_, ref val) => val.visit_with(visitor),
2084 Discriminant(ref lval) => lval.visit_with(visitor),
2085 NullaryOp(_, ty) => ty.visit_with(visitor),
2086 Aggregate(ref kind, ref fields) => {
2088 AggregateKind::Array(ty) => ty.visit_with(visitor),
2089 AggregateKind::Tuple => false,
2090 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
2091 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2092 AggregateKind::Generator(_, substs, interior) => substs.visit_with(visitor) ||
2093 interior.visit_with(visitor),
2094 }) || fields.visit_with(visitor)
2100 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2101 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2103 Operand::Copy(ref lval) => Operand::Copy(lval.fold_with(folder)),
2104 Operand::Move(ref lval) => Operand::Move(lval.fold_with(folder)),
2105 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2109 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2111 Operand::Copy(ref lval) |
2112 Operand::Move(ref lval) => lval.visit_with(visitor),
2113 Operand::Constant(ref c) => c.visit_with(visitor)
2118 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
2119 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
2121 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2122 use mir::ProjectionElem::*;
2124 let base = self.base.fold_with(folder);
2125 let elem = match self.elem {
2127 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
2128 Index(ref v) => Index(v.fold_with(folder)),
2129 ref elem => elem.clone()
2138 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2139 use mir::ProjectionElem::*;
2141 self.base.visit_with(visitor) ||
2143 Field(_, ref ty) => ty.visit_with(visitor),
2144 Index(ref v) => v.visit_with(visitor),
2150 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2151 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2153 span: self.span.clone(),
2154 ty: self.ty.fold_with(folder),
2155 literal: self.literal.fold_with(folder)
2158 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2159 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
2163 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
2164 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2166 Literal::Value { value } => Literal::Value {
2167 value: value.fold_with(folder)
2169 Literal::Promoted { index } => Literal::Promoted { index }
2172 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2174 Literal::Value { value } => value.visit_with(visitor),
2175 Literal::Promoted { .. } => false