1 // ignore-tidy-filelength
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, InlineAsm as HirInlineAsm};
10 use crate::mir::interpret::{ConstValue, InterpError, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use polonius_engine::Atom;
13 use rustc_data_structures::bit_set::BitMatrix;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_data_structures::graph::dominators::{dominators, Dominators};
16 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
17 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
18 use rustc_data_structures::sync::Lrc;
19 use rustc_data_structures::sync::MappedReadGuard;
20 use rustc_macros::HashStable;
21 use crate::rustc_serialize::{self as serialize};
22 use smallvec::SmallVec;
24 use std::fmt::{self, Debug, Formatter, Write, Display};
25 use std::iter::FusedIterator;
26 use std::ops::{Index, IndexMut};
28 use std::vec::IntoIter;
29 use std::{iter, mem, option, u32};
30 use syntax::ast::Name;
31 use syntax::symbol::{InternedString, Symbol};
32 use syntax_pos::{Span, DUMMY_SP};
33 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
34 use crate::ty::subst::{Subst, SubstsRef};
35 use crate::ty::layout::VariantIdx;
37 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
38 UserTypeAnnotationIndex,
40 use crate::ty::print::{FmtPrinter, Printer};
41 use crate::ty::adjustment::{PointerCast};
43 pub use crate::mir::interpret::AssertMessage;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// The various "big phases" that MIR goes through.
73 /// Warning: ordering of variants is significant
74 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
83 /// Gets the index of the current MirPhase within the set of all MirPhases.
84 pub fn phase_index(&self) -> usize {
89 /// Lowered representation of a single function.
90 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
91 pub struct Body<'tcx> {
92 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
93 /// that indexes into this vector.
94 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
96 /// Records how far through the "desugaring and optimization" process this particular
97 /// MIR has traversed. This is particularly useful when inlining, since in that context
98 /// we instantiate the promoted constants and add them to our promoted vector -- but those
99 /// promoted items have already been optimized, whereas ours have not. This field allows
100 /// us to see the difference and forego optimization on the inlined promoted items.
103 /// List of source scopes; these are referenced by statements
104 /// and used for debuginfo. Indexed by a `SourceScope`.
105 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
107 /// Crate-local information for each source scope, that can't (and
108 /// needn't) be tracked across crates.
109 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
111 /// Rvalues promoted from this function, such as borrows of constants.
112 /// Each of them is the Body of a constant with the fn's type parameters
113 /// in scope, but a separate set of locals.
114 pub promoted: IndexVec<Promoted, Body<'tcx>>,
116 /// Yields type of the function, if it is a generator.
117 pub yield_ty: Option<Ty<'tcx>>,
119 /// Generator drop glue
120 pub generator_drop: Option<Box<Body<'tcx>>>,
122 /// The layout of a generator. Produced by the state transformation.
123 pub generator_layout: Option<GeneratorLayout<'tcx>>,
125 /// Declarations of locals.
127 /// The first local is the return value pointer, followed by `arg_count`
128 /// locals for the function arguments, followed by any user-declared
129 /// variables and temporaries.
130 pub local_decls: LocalDecls<'tcx>,
132 /// User type annotations
133 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
135 /// Number of arguments this function takes.
137 /// Starting at local 1, `arg_count` locals will be provided by the caller
138 /// and can be assumed to be initialized.
140 /// If this MIR was built for a constant, this will be 0.
141 pub arg_count: usize,
143 /// Mark an argument local (which must be a tuple) as getting passed as
144 /// its individual components at the LLVM level.
146 /// This is used for the "rust-call" ABI.
147 pub spread_arg: Option<Local>,
149 /// Names and capture modes of all the closure upvars, assuming
150 /// the first argument is either the closure or a reference to it.
151 // NOTE(eddyb) This is *strictly* a temporary hack for codegen
152 // debuginfo generation, and will be removed at some point.
153 // Do **NOT** use it for anything else, upvar information should not be
154 // in the MIR, please rely on local crate HIR or other side-channels.
155 pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
157 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
158 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
159 /// this conversion from happening and use short circuiting, we will cause the following code
160 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
162 /// List of places where control flow was destroyed. Used for error reporting.
163 pub control_flow_destroyed: Vec<(Span, String)>,
165 /// A span representing this MIR, for error reporting
168 /// A cache for various calculations
172 impl<'tcx> Body<'tcx> {
174 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
175 source_scopes: IndexVec<SourceScope, SourceScopeData>,
176 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
177 promoted: IndexVec<Promoted, Body<'tcx>>,
178 yield_ty: Option<Ty<'tcx>>,
179 local_decls: LocalDecls<'tcx>,
180 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
182 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
184 control_flow_destroyed: Vec<(Span, String)>,
186 // We need `arg_count` locals, and one for the return place
188 local_decls.len() >= arg_count + 1,
189 "expected at least {} locals, got {}",
195 phase: MirPhase::Build,
198 source_scope_local_data,
201 generator_drop: None,
202 generator_layout: None,
204 user_type_annotations,
206 __upvar_debuginfo_codegen_only_do_not_use,
209 cache: cache::Cache::new(),
210 control_flow_destroyed,
215 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
220 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
221 self.cache.invalidate();
222 &mut self.basic_blocks
226 pub fn basic_blocks_and_local_decls_mut(
229 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
230 &mut LocalDecls<'tcx>,
232 self.cache.invalidate();
233 (&mut self.basic_blocks, &mut self.local_decls)
237 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
238 self.cache.predecessors(self)
242 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
243 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
247 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
248 let if_zero_locations = if loc.statement_index == 0 {
249 let predecessor_blocks = self.predecessors_for(loc.block);
250 let num_predecessor_blocks = predecessor_blocks.len();
252 (0..num_predecessor_blocks)
253 .map(move |i| predecessor_blocks[i])
254 .map(move |bb| self.terminator_loc(bb)),
260 let if_not_zero_locations = if loc.statement_index == 0 {
265 statement_index: loc.statement_index - 1,
272 .chain(if_not_zero_locations)
276 pub fn dominators(&self) -> Dominators<BasicBlock> {
281 pub fn local_kind(&self, local: Local) -> LocalKind {
282 let index = local.as_usize();
285 self.local_decls[local].mutability == Mutability::Mut,
286 "return place should be mutable"
289 LocalKind::ReturnPointer
290 } else if index < self.arg_count + 1 {
292 } else if self.local_decls[local].name.is_some() {
299 /// Returns an iterator over all temporaries.
301 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
302 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
303 let local = Local::new(index);
304 if self.local_decls[local].is_user_variable.is_some() {
312 /// Returns an iterator over all user-declared locals.
314 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
315 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
316 let local = Local::new(index);
317 if self.local_decls[local].is_user_variable.is_some() {
325 /// Returns an iterator over all user-declared mutable locals.
327 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
328 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
329 let local = Local::new(index);
330 let decl = &self.local_decls[local];
331 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
339 /// Returns an iterator over all user-declared mutable arguments and locals.
341 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
342 (1..self.local_decls.len()).filter_map(move |index| {
343 let local = Local::new(index);
344 let decl = &self.local_decls[local];
345 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
346 && decl.mutability == Mutability::Mut
355 /// Returns an iterator over all function arguments.
357 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
358 let arg_count = self.arg_count;
359 (1..=arg_count).map(Local::new)
362 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
363 /// locals that are neither arguments nor the return place).
365 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
366 let arg_count = self.arg_count;
367 let local_count = self.local_decls.len();
368 (arg_count + 1..local_count).map(Local::new)
371 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
372 /// invalidating statement indices in `Location`s.
373 pub fn make_statement_nop(&mut self, location: Location) {
374 let block = &mut self[location.block];
375 debug_assert!(location.statement_index < block.statements.len());
376 block.statements[location.statement_index].make_nop()
379 /// Returns the source info associated with `location`.
380 pub fn source_info(&self, location: Location) -> &SourceInfo {
381 let block = &self[location.block];
382 let stmts = &block.statements;
383 let idx = location.statement_index;
384 if idx < stmts.len() {
385 &stmts[idx].source_info
387 assert_eq!(idx, stmts.len());
388 &block.terminator().source_info
392 /// Checks if `sub` is a sub scope of `sup`
393 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
395 match self.source_scopes[sub].parent_scope {
396 None => return false,
403 /// Returns the return type, it always return first element from `local_decls` array
404 pub fn return_ty(&self) -> Ty<'tcx> {
405 self.local_decls[RETURN_PLACE].ty
408 /// Gets the location of the terminator for the given block
409 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
412 statement_index: self[bb].statements.len(),
417 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
420 /// Unsafe because of a PushUnsafeBlock
422 /// Unsafe because of an unsafe fn
424 /// Unsafe because of an `unsafe` block
425 ExplicitUnsafe(hir::HirId),
428 impl_stable_hash_for!(struct Body<'tcx> {
432 source_scope_local_data,
438 user_type_annotations,
440 __upvar_debuginfo_codegen_only_do_not_use,
442 control_flow_destroyed,
447 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
448 type Output = BasicBlockData<'tcx>;
451 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
452 &self.basic_blocks()[index]
456 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
458 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
459 &mut self.basic_blocks_mut()[index]
463 #[derive(Copy, Clone, Debug, HashStable)]
464 pub enum ClearCrossCrate<T> {
469 impl<T> ClearCrossCrate<T> {
470 pub fn assert_crate_local(self) -> T {
472 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
473 ClearCrossCrate::Set(v) => v,
478 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
479 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
481 /// Grouped information about the source code origin of a MIR entity.
482 /// Intended to be inspected by diagnostics and debuginfo.
483 /// Most passes can work with it as a whole, within a single function.
484 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
485 pub struct SourceInfo {
486 /// Source span for the AST pertaining to this MIR entity.
489 /// The source scope, keeping track of which bindings can be
490 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
491 pub scope: SourceScope,
494 ///////////////////////////////////////////////////////////////////////////
495 // Mutability and borrow kinds
497 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
498 pub enum Mutability {
503 impl From<Mutability> for hir::Mutability {
504 fn from(m: Mutability) -> Self {
506 Mutability::Mut => hir::MutMutable,
507 Mutability::Not => hir::MutImmutable,
512 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd,
513 Ord, RustcEncodable, RustcDecodable, HashStable)]
514 pub enum BorrowKind {
515 /// Data must be immutable and is aliasable.
518 /// The immediately borrowed place must be immutable, but projections from
519 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
520 /// conflict with a mutable borrow of `a.b.c`.
522 /// This is used when lowering matches: when matching on a place we want to
523 /// ensure that place have the same value from the start of the match until
524 /// an arm is selected. This prevents this code from compiling:
526 /// let mut x = &Some(0);
529 /// Some(_) if { x = &None; false } => (),
533 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
534 /// should not prevent `if let None = x { ... }`, for example, because the
535 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
536 /// We can also report errors with this kind of borrow differently.
539 /// Data must be immutable but not aliasable. This kind of borrow
540 /// cannot currently be expressed by the user and is used only in
541 /// implicit closure bindings. It is needed when the closure is
542 /// borrowing or mutating a mutable referent, e.g.:
544 /// let x: &mut isize = ...;
545 /// let y = || *x += 5;
547 /// If we were to try to translate this closure into a more explicit
548 /// form, we'd encounter an error with the code as written:
550 /// struct Env { x: & &mut isize }
551 /// let x: &mut isize = ...;
552 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
553 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
555 /// This is then illegal because you cannot mutate an `&mut` found
556 /// in an aliasable location. To solve, you'd have to translate with
557 /// an `&mut` borrow:
559 /// struct Env { x: & &mut isize }
560 /// let x: &mut isize = ...;
561 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
562 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
564 /// Now the assignment to `**env.x` is legal, but creating a
565 /// mutable pointer to `x` is not because `x` is not mutable. We
566 /// could fix this by declaring `x` as `let mut x`. This is ok in
567 /// user code, if awkward, but extra weird for closures, since the
568 /// borrow is hidden.
570 /// So we introduce a "unique imm" borrow -- the referent is
571 /// immutable, but not aliasable. This solves the problem. For
572 /// simplicity, we don't give users the way to express this
573 /// borrow, it's just used when translating closures.
576 /// Data is mutable and not aliasable.
578 /// `true` if this borrow arose from method-call auto-ref
579 /// (i.e., `adjustment::Adjust::Borrow`).
580 allow_two_phase_borrow: bool,
585 pub fn allows_two_phase_borrow(&self) -> bool {
587 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
588 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
593 ///////////////////////////////////////////////////////////////////////////
594 // Variables and temps
599 DEBUG_FORMAT = "_{}",
600 const RETURN_PLACE = 0,
604 impl Atom for Local {
605 fn index(self) -> usize {
610 /// Classifies locals into categories. See `Body::local_kind`.
611 #[derive(PartialEq, Eq, Debug, HashStable)]
613 /// User-declared variable binding
615 /// Compiler-introduced temporary
617 /// Function argument
619 /// Location of function's return value
623 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
624 pub struct VarBindingForm<'tcx> {
625 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
626 pub binding_mode: ty::BindingMode,
627 /// If an explicit type was provided for this variable binding,
628 /// this holds the source Span of that type.
630 /// NOTE: if you want to change this to a `HirId`, be wary that
631 /// doing so breaks incremental compilation (as of this writing),
632 /// while a `Span` does not cause our tests to fail.
633 pub opt_ty_info: Option<Span>,
634 /// Place of the RHS of the =, or the subject of the `match` where this
635 /// variable is initialized. None in the case of `let PATTERN;`.
636 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
637 /// (a) the right-hand side isn't evaluated as a place expression.
638 /// (b) it gives a way to separate this case from the remaining cases
640 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
641 /// Span of the pattern in which this variable was bound.
645 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
646 pub enum BindingForm<'tcx> {
647 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
648 Var(VarBindingForm<'tcx>),
649 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
650 ImplicitSelf(ImplicitSelfKind),
651 /// Reference used in a guard expression to ensure immutability.
655 /// Represents what type of implicit self a function has, if any.
656 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
657 pub enum ImplicitSelfKind {
658 /// Represents a `fn x(self);`.
660 /// Represents a `fn x(mut self);`.
662 /// Represents a `fn x(&self);`.
664 /// Represents a `fn x(&mut self);`.
666 /// Represents when a function does not have a self argument or
667 /// when a function has a `self: X` argument.
671 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
673 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
680 impl_stable_hash_for!(enum self::ImplicitSelfKind {
688 impl_stable_hash_for!(enum self::MirPhase {
695 mod binding_form_impl {
696 use crate::ich::StableHashingContext;
697 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
699 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
700 fn hash_stable<W: StableHasherResult>(
702 hcx: &mut StableHashingContext<'a>,
703 hasher: &mut StableHasher<W>,
705 use super::BindingForm::*;
706 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
709 Var(binding) => binding.hash_stable(hcx, hasher),
710 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
717 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
718 /// created during evaluation of expressions in a block tail
719 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
721 /// It is used to improve diagnostics when such temporaries are
722 /// involved in borrow_check errors, e.g., explanations of where the
723 /// temporaries come from, when their destructors are run, and/or how
724 /// one might revise the code to satisfy the borrow checker's rules.
725 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
726 pub struct BlockTailInfo {
727 /// If `true`, then the value resulting from evaluating this tail
728 /// expression is ignored by the block's expression context.
730 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
731 /// but not e.g., `let _x = { ...; tail };`
732 pub tail_result_is_ignored: bool,
735 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
739 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
740 /// argument, or the return place.
741 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
742 pub struct LocalDecl<'tcx> {
743 /// `let mut x` vs `let x`.
745 /// Temporaries and the return place are always mutable.
746 pub mutability: Mutability,
748 /// Some(binding_mode) if this corresponds to a user-declared local variable.
750 /// This is solely used for local diagnostics when generating
751 /// warnings/errors when compiling the current crate, and
752 /// therefore it need not be visible across crates. pnkfelix
753 /// currently hypothesized we *need* to wrap this in a
754 /// `ClearCrossCrate` as long as it carries as `HirId`.
755 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
757 /// `true` if this is an internal local.
759 /// These locals are not based on types in the source code and are only used
760 /// for a few desugarings at the moment.
762 /// The generator transformation will sanity check the locals which are live
763 /// across a suspension point against the type components of the generator
764 /// which type checking knows are live across a suspension point. We need to
765 /// flag drop flags to avoid triggering this check as they are introduced
768 /// Unsafety checking will also ignore dereferences of these locals,
769 /// so they can be used for raw pointers only used in a desugaring.
771 /// This should be sound because the drop flags are fully algebraic, and
772 /// therefore don't affect the OIBIT or outlives properties of the
776 /// If this local is a temporary and `is_block_tail` is `Some`,
777 /// then it is a temporary created for evaluation of some
778 /// subexpression of some block's tail expression (with no
779 /// intervening statement context).
780 pub is_block_tail: Option<BlockTailInfo>,
782 /// Type of this local.
785 /// If the user manually ascribed a type to this variable,
786 /// e.g., via `let x: T`, then we carry that type here. The MIR
787 /// borrow checker needs this information since it can affect
788 /// region inference.
789 pub user_ty: UserTypeProjections,
791 /// Name of the local, used in debuginfo and pretty-printing.
793 /// Note that function arguments can also have this set to `Some(_)`
794 /// to generate better debuginfo.
795 pub name: Option<Name>,
797 /// The *syntactic* (i.e., not visibility) source scope the local is defined
798 /// in. If the local was defined in a let-statement, this
799 /// is *within* the let-statement, rather than outside
802 /// This is needed because the visibility source scope of locals within
803 /// a let-statement is weird.
805 /// The reason is that we want the local to be *within* the let-statement
806 /// for lint purposes, but we want the local to be *after* the let-statement
807 /// for names-in-scope purposes.
809 /// That's it, if we have a let-statement like the one in this
813 /// fn foo(x: &str) {
814 /// #[allow(unused_mut)]
815 /// let mut x: u32 = { // <- one unused mut
816 /// let mut y: u32 = x.parse().unwrap();
823 /// Then, from a lint point of view, the declaration of `x: u32`
824 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
825 /// lint scopes are the same as the AST/HIR nesting.
827 /// However, from a name lookup point of view, the scopes look more like
828 /// as if the let-statements were `match` expressions:
831 /// fn foo(x: &str) {
833 /// match x.parse().unwrap() {
842 /// We care about the name-lookup scopes for debuginfo - if the
843 /// debuginfo instruction pointer is at the call to `x.parse()`, we
844 /// want `x` to refer to `x: &str`, but if it is at the call to
845 /// `drop(x)`, we want it to refer to `x: u32`.
847 /// To allow both uses to work, we need to have more than a single scope
848 /// for a local. We have the `source_info.scope` represent the
849 /// "syntactic" lint scope (with a variable being under its let
850 /// block) while the `visibility_scope` represents the "local variable"
851 /// scope (where the "rest" of a block is under all prior let-statements).
853 /// The end result looks like this:
857 /// │{ argument x: &str }
859 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
860 /// │ │ // in practice because I'm lazy.
862 /// │ │← x.source_info.scope
863 /// │ │← `x.parse().unwrap()`
865 /// │ │ │← y.source_info.scope
867 /// │ │ │{ let y: u32 }
869 /// │ │ │← y.visibility_scope
872 /// │ │{ let x: u32 }
873 /// │ │← x.visibility_scope
874 /// │ │← `drop(x)` // this accesses `x: u32`
876 pub source_info: SourceInfo,
878 /// Source scope within which the local is visible (for debuginfo)
879 /// (see `source_info` for more details).
880 pub visibility_scope: SourceScope,
883 impl<'tcx> LocalDecl<'tcx> {
884 /// Returns `true` only if local is a binding that can itself be
885 /// made mutable via the addition of the `mut` keyword, namely
886 /// something like the occurrences of `x` in:
887 /// - `fn foo(x: Type) { ... }`,
889 /// - or `match ... { C(x) => ... }`
890 pub fn can_be_made_mutable(&self) -> bool {
891 match self.is_user_variable {
892 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
893 binding_mode: ty::BindingMode::BindByValue(_),
899 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
906 /// Returns `true` if local is definitely not a `ref ident` or
907 /// `ref mut ident` binding. (Such bindings cannot be made into
908 /// mutable bindings, but the inverse does not necessarily hold).
909 pub fn is_nonref_binding(&self) -> bool {
910 match self.is_user_variable {
911 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
912 binding_mode: ty::BindingMode::BindByValue(_),
918 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
924 /// Returns `true` if this is a reference to a variable bound in a `match`
925 /// expression that is used to access said variable for the guard of the
927 pub fn is_ref_for_guard(&self) -> bool {
928 match self.is_user_variable {
929 Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
934 /// Returns `true` is the local is from a compiler desugaring, e.g.,
935 /// `__next` from a `for` loop.
937 pub fn from_compiler_desugaring(&self) -> bool {
938 self.source_info.span.desugaring_kind().is_some()
941 /// Creates a new `LocalDecl` for a temporary.
943 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
944 Self::new_local(ty, Mutability::Mut, false, span)
947 /// Converts `self` into same `LocalDecl` except tagged as immutable.
949 pub fn immutable(mut self) -> Self {
950 self.mutability = Mutability::Not;
954 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
956 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
957 assert!(self.is_block_tail.is_none());
958 self.is_block_tail = Some(info);
962 /// Creates a new `LocalDecl` for a internal temporary.
964 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
965 Self::new_local(ty, Mutability::Mut, true, span)
971 mutability: Mutability,
978 user_ty: UserTypeProjections::none(),
980 source_info: SourceInfo {
982 scope: OUTERMOST_SOURCE_SCOPE,
984 visibility_scope: OUTERMOST_SOURCE_SCOPE,
986 is_user_variable: None,
991 /// Builds a `LocalDecl` for the return place.
993 /// This must be inserted into the `local_decls` list as the first local.
995 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
997 mutability: Mutability::Mut,
999 user_ty: UserTypeProjections::none(),
1000 source_info: SourceInfo {
1002 scope: OUTERMOST_SOURCE_SCOPE,
1004 visibility_scope: OUTERMOST_SOURCE_SCOPE,
1006 is_block_tail: None,
1007 name: None, // FIXME maybe we do want some name here?
1008 is_user_variable: None,
1013 /// A closure capture, with its name and mode.
1014 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1015 pub struct UpvarDebuginfo {
1016 pub debug_name: Name,
1018 /// If true, the capture is behind a reference.
1022 ///////////////////////////////////////////////////////////////////////////
1026 pub struct BasicBlock {
1028 DEBUG_FORMAT = "bb{}",
1029 const START_BLOCK = 0,
1034 pub fn start_location(self) -> Location {
1042 ///////////////////////////////////////////////////////////////////////////
1043 // BasicBlockData and Terminator
1045 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1046 pub struct BasicBlockData<'tcx> {
1047 /// List of statements in this block.
1048 pub statements: Vec<Statement<'tcx>>,
1050 /// Terminator for this block.
1052 /// N.B., this should generally ONLY be `None` during construction.
1053 /// Therefore, you should generally access it via the
1054 /// `terminator()` or `terminator_mut()` methods. The only
1055 /// exception is that certain passes, such as `simplify_cfg`, swap
1056 /// out the terminator temporarily with `None` while they continue
1057 /// to recurse over the set of basic blocks.
1058 pub terminator: Option<Terminator<'tcx>>,
1060 /// If true, this block lies on an unwind path. This is used
1061 /// during codegen where distinct kinds of basic blocks may be
1062 /// generated (particularly for MSVC cleanup). Unwind blocks must
1063 /// only branch to other unwind blocks.
1064 pub is_cleanup: bool,
1067 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1068 pub struct Terminator<'tcx> {
1069 pub source_info: SourceInfo,
1070 pub kind: TerminatorKind<'tcx>,
1073 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1074 pub enum TerminatorKind<'tcx> {
1075 /// block should have one successor in the graph; we jump there
1076 Goto { target: BasicBlock },
1078 /// operand evaluates to an integer; jump depending on its value
1079 /// to one of the targets, and otherwise fallback to `otherwise`
1081 /// discriminant value being tested
1082 discr: Operand<'tcx>,
1084 /// type of value being tested
1085 switch_ty: Ty<'tcx>,
1087 /// Possible values. The locations to branch to in each case
1088 /// are found in the corresponding indices from the `targets` vector.
1089 values: Cow<'tcx, [u128]>,
1091 /// Possible branch sites. The last element of this vector is used
1092 /// for the otherwise branch, so targets.len() == values.len() + 1
1094 // This invariant is quite non-obvious and also could be improved.
1095 // One way to make this invariant is to have something like this instead:
1097 // branches: Vec<(ConstInt, BasicBlock)>,
1098 // otherwise: Option<BasicBlock> // exhaustive if None
1100 // However we’ve decided to keep this as-is until we figure a case
1101 // where some other approach seems to be strictly better than other.
1102 targets: Vec<BasicBlock>,
1105 /// Indicates that the landing pad is finished and unwinding should
1106 /// continue. Emitted by build::scope::diverge_cleanup.
1109 /// Indicates that the landing pad is finished and that the process
1110 /// should abort. Used to prevent unwinding for foreign items.
1113 /// Indicates a normal return. The return place should have
1114 /// been filled in by now. This should occur at most once.
1117 /// Indicates a terminator that can never be reached.
1122 location: Place<'tcx>,
1124 unwind: Option<BasicBlock>,
1127 /// Drop the Place and assign the new value over it. This ensures
1128 /// that the assignment to `P` occurs *even if* the destructor for
1129 /// place unwinds. Its semantics are best explained by the
1134 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1142 /// Drop(P, goto BB1, unwind BB2)
1145 /// // P is now uninitialized
1149 /// // P is now uninitialized -- its dtor panicked
1154 location: Place<'tcx>,
1155 value: Operand<'tcx>,
1157 unwind: Option<BasicBlock>,
1160 /// Block ends with a call of a converging function
1162 /// The function that’s being called
1163 func: Operand<'tcx>,
1164 /// Arguments the function is called with.
1165 /// These are owned by the callee, which is free to modify them.
1166 /// This allows the memory occupied by "by-value" arguments to be
1167 /// reused across function calls without duplicating the contents.
1168 args: Vec<Operand<'tcx>>,
1169 /// Destination for the return value. If some, the call is converging.
1170 destination: Option<(Place<'tcx>, BasicBlock)>,
1171 /// Cleanups to be done if the call unwinds.
1172 cleanup: Option<BasicBlock>,
1173 /// Whether this is from a call in HIR, rather than from an overloaded
1174 /// operator. True for overloaded function call.
1175 from_hir_call: bool,
1178 /// Jump to the target if the condition has the expected value,
1179 /// otherwise panic with a message and a cleanup target.
1181 cond: Operand<'tcx>,
1183 msg: AssertMessage<'tcx>,
1185 cleanup: Option<BasicBlock>,
1190 /// The value to return
1191 value: Operand<'tcx>,
1192 /// Where to resume to
1194 /// Cleanup to be done if the generator is dropped at this suspend point
1195 drop: Option<BasicBlock>,
1198 /// Indicates the end of the dropping of a generator
1201 /// A block where control flow only ever takes one real path, but borrowck
1202 /// needs to be more conservative.
1204 /// The target normal control flow will take
1205 real_target: BasicBlock,
1206 /// A block control flow could conceptually jump to, but won't in
1208 imaginary_target: BasicBlock,
1210 /// A terminator for blocks that only take one path in reality, but where we
1211 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1212 /// This can arise in infinite loops with no function calls for example.
1214 /// The target normal control flow will take
1215 real_target: BasicBlock,
1216 /// The imaginary cleanup block link. This particular path will never be taken
1217 /// in practice, but in order to avoid fragility we want to always
1218 /// consider it in borrowck. We don't want to accept programs which
1219 /// pass borrowck only when panic=abort or some assertions are disabled
1220 /// due to release vs. debug mode builds. This needs to be an Option because
1221 /// of the remove_noop_landing_pads and no_landing_pads passes
1222 unwind: Option<BasicBlock>,
1226 pub type Successors<'a> =
1227 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1228 pub type SuccessorsMut<'a> =
1229 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1231 impl<'tcx> Terminator<'tcx> {
1232 pub fn successors(&self) -> Successors<'_> {
1233 self.kind.successors()
1236 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1237 self.kind.successors_mut()
1240 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1244 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1245 self.kind.unwind_mut()
1249 impl<'tcx> TerminatorKind<'tcx> {
1252 cond: Operand<'tcx>,
1255 ) -> TerminatorKind<'tcx> {
1256 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1257 TerminatorKind::SwitchInt {
1259 switch_ty: tcx.types.bool,
1260 values: From::from(BOOL_SWITCH_FALSE),
1261 targets: vec![f, t],
1265 pub fn successors(&self) -> Successors<'_> {
1266 use self::TerminatorKind::*;
1277 } => None.into_iter().chain(&[]),
1278 Goto { target: ref t }
1281 cleanup: Some(ref t),
1285 destination: Some((_, ref t)),
1312 } => Some(t).into_iter().chain(&[]),
1314 destination: Some((_, ref t)),
1315 cleanup: Some(ref u),
1325 unwind: Some(ref u),
1330 unwind: Some(ref u),
1335 cleanup: Some(ref u),
1340 unwind: Some(ref u),
1341 } => Some(t).into_iter().chain(slice::from_ref(u)),
1342 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1345 ref imaginary_target,
1346 } => Some(real_target).into_iter().chain(slice::from_ref(imaginary_target)),
1350 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1351 use self::TerminatorKind::*;
1362 } => None.into_iter().chain(&mut []),
1363 Goto { target: ref mut t }
1366 cleanup: Some(ref mut t),
1370 destination: Some((_, ref mut t)),
1395 real_target: ref mut t,
1397 } => Some(t).into_iter().chain(&mut []),
1399 destination: Some((_, ref mut t)),
1400 cleanup: Some(ref mut u),
1405 drop: Some(ref mut u),
1410 unwind: Some(ref mut u),
1415 unwind: Some(ref mut u),
1420 cleanup: Some(ref mut u),
1424 real_target: ref mut t,
1425 unwind: Some(ref mut u),
1426 } => Some(t).into_iter().chain(slice::from_mut(u)),
1429 } => None.into_iter().chain(&mut targets[..]),
1431 ref mut real_target,
1432 ref mut imaginary_target,
1433 } => Some(real_target)
1435 .chain(slice::from_mut(imaginary_target)),
1439 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1441 TerminatorKind::Goto { .. }
1442 | TerminatorKind::Resume
1443 | TerminatorKind::Abort
1444 | TerminatorKind::Return
1445 | TerminatorKind::Unreachable
1446 | TerminatorKind::GeneratorDrop
1447 | TerminatorKind::Yield { .. }
1448 | TerminatorKind::SwitchInt { .. }
1449 | TerminatorKind::FalseEdges { .. } => None,
1450 TerminatorKind::Call {
1451 cleanup: ref unwind,
1454 | TerminatorKind::Assert {
1455 cleanup: ref unwind,
1458 | TerminatorKind::DropAndReplace { ref unwind, .. }
1459 | TerminatorKind::Drop { ref unwind, .. }
1460 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1464 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1466 TerminatorKind::Goto { .. }
1467 | TerminatorKind::Resume
1468 | TerminatorKind::Abort
1469 | TerminatorKind::Return
1470 | TerminatorKind::Unreachable
1471 | TerminatorKind::GeneratorDrop
1472 | TerminatorKind::Yield { .. }
1473 | TerminatorKind::SwitchInt { .. }
1474 | TerminatorKind::FalseEdges { .. } => None,
1475 TerminatorKind::Call {
1476 cleanup: ref mut unwind,
1479 | TerminatorKind::Assert {
1480 cleanup: ref mut unwind,
1483 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1484 | TerminatorKind::Drop { ref mut unwind, .. }
1485 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1490 impl<'tcx> BasicBlockData<'tcx> {
1491 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1499 /// Accessor for terminator.
1501 /// Terminator may not be None after construction of the basic block is complete. This accessor
1502 /// provides a convenience way to reach the terminator.
1503 pub fn terminator(&self) -> &Terminator<'tcx> {
1504 self.terminator.as_ref().expect("invalid terminator state")
1507 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1508 self.terminator.as_mut().expect("invalid terminator state")
1511 pub fn retain_statements<F>(&mut self, mut f: F)
1513 F: FnMut(&mut Statement<'_>) -> bool,
1515 for s in &mut self.statements {
1522 pub fn expand_statements<F, I>(&mut self, mut f: F)
1524 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1525 I: iter::TrustedLen<Item = Statement<'tcx>>,
1527 // Gather all the iterators we'll need to splice in, and their positions.
1528 let mut splices: Vec<(usize, I)> = vec![];
1529 let mut extra_stmts = 0;
1530 for (i, s) in self.statements.iter_mut().enumerate() {
1531 if let Some(mut new_stmts) = f(s) {
1532 if let Some(first) = new_stmts.next() {
1533 // We can already store the first new statement.
1536 // Save the other statements for optimized splicing.
1537 let remaining = new_stmts.size_hint().0;
1539 splices.push((i + 1 + extra_stmts, new_stmts));
1540 extra_stmts += remaining;
1548 // Splice in the new statements, from the end of the block.
1549 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1550 // where a range of elements ("gap") is left uninitialized, with
1551 // splicing adding new elements to the end of that gap and moving
1552 // existing elements from before the gap to the end of the gap.
1553 // For now, this is safe code, emulating a gap but initializing it.
1554 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1555 self.statements.resize(
1558 source_info: SourceInfo {
1560 scope: OUTERMOST_SOURCE_SCOPE,
1562 kind: StatementKind::Nop,
1565 for (splice_start, new_stmts) in splices.into_iter().rev() {
1566 let splice_end = splice_start + new_stmts.size_hint().0;
1567 while gap.end > splice_end {
1570 self.statements.swap(gap.start, gap.end);
1572 self.statements.splice(splice_start..splice_end, new_stmts);
1573 gap.end = splice_start;
1577 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1578 if index < self.statements.len() {
1579 &self.statements[index]
1586 impl<'tcx> Debug for TerminatorKind<'tcx> {
1587 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1588 self.fmt_head(fmt)?;
1589 let successor_count = self.successors().count();
1590 let labels = self.fmt_successor_labels();
1591 assert_eq!(successor_count, labels.len());
1593 match successor_count {
1596 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1599 write!(fmt, " -> [")?;
1600 for (i, target) in self.successors().enumerate() {
1604 write!(fmt, "{}: {:?}", labels[i], target)?;
1612 impl<'tcx> TerminatorKind<'tcx> {
1613 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1614 /// successor basic block, if any. The only information not included is the list of possible
1615 /// successors, which may be rendered differently between the text and the graphviz format.
1616 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1617 use self::TerminatorKind::*;
1619 Goto { .. } => write!(fmt, "goto"),
1621 discr: ref place, ..
1622 } => write!(fmt, "switchInt({:?})", place),
1623 Return => write!(fmt, "return"),
1624 GeneratorDrop => write!(fmt, "generator_drop"),
1625 Resume => write!(fmt, "resume"),
1626 Abort => write!(fmt, "abort"),
1627 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1628 Unreachable => write!(fmt, "unreachable"),
1629 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1634 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1641 if let Some((ref destination, _)) = *destination {
1642 write!(fmt, "{:?} = ", destination)?;
1644 write!(fmt, "{:?}(", func)?;
1645 for (index, arg) in args.iter().enumerate() {
1649 write!(fmt, "{:?}", arg)?;
1659 write!(fmt, "assert(")?;
1663 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1665 FalseEdges { .. } => write!(fmt, "falseEdges"),
1666 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1670 /// Returns the list of labels for the edges to the successor basic blocks.
1671 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1672 use self::TerminatorKind::*;
1674 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1675 Goto { .. } => vec!["".into()],
1681 ty::tls::with(|tcx| {
1682 let param_env = ty::ParamEnv::empty();
1683 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1684 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1688 tcx.mk_const(ty::Const {
1689 val: ConstValue::Scalar(
1690 Scalar::from_uint(u, size).into(),
1693 }).to_string().into()
1694 }).chain(iter::once("otherwise".into()))
1699 destination: Some(_),
1702 } => vec!["return".into(), "unwind".into()],
1704 destination: Some(_),
1707 } => vec!["return".into()],
1712 } => vec!["unwind".into()],
1718 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1719 Yield { drop: None, .. } => vec!["resume".into()],
1720 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1721 vec!["return".into()]
1728 } => vec!["return".into(), "unwind".into()],
1729 Assert { cleanup: None, .. } => vec!["".into()],
1730 Assert { .. } => vec!["success".into(), "unwind".into()],
1734 vec!["real".into(), "imaginary".into()]
1738 } => vec!["real".into(), "cleanup".into()],
1739 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1744 ///////////////////////////////////////////////////////////////////////////
1747 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1748 pub struct Statement<'tcx> {
1749 pub source_info: SourceInfo,
1750 pub kind: StatementKind<'tcx>,
1753 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1754 #[cfg(target_arch = "x86_64")]
1755 static_assert_size!(Statement<'_>, 56);
1757 impl<'tcx> Statement<'tcx> {
1758 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1759 /// invalidating statement indices in `Location`s.
1760 pub fn make_nop(&mut self) {
1761 self.kind = StatementKind::Nop
1764 /// Changes a statement to a nop and returns the original statement.
1765 pub fn replace_nop(&mut self) -> Self {
1767 source_info: self.source_info,
1768 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1773 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1774 pub enum StatementKind<'tcx> {
1775 /// Write the RHS Rvalue to the LHS Place.
1776 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1778 /// This represents all the reading that a pattern match may do
1779 /// (e.g., inspecting constants and discriminant values), and the
1780 /// kind of pattern it comes from. This is in order to adapt potential
1781 /// error messages to these specific patterns.
1783 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1784 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1785 FakeRead(FakeReadCause, Place<'tcx>),
1787 /// Write the discriminant for a variant to the enum Place.
1790 variant_index: VariantIdx,
1793 /// Start a live range for the storage of the local.
1796 /// End the current live range for the storage of the local.
1799 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1800 /// of `StatementKind` low.
1801 InlineAsm(Box<InlineAsm<'tcx>>),
1803 /// Retag references in the given place, ensuring they got fresh tags. This is
1804 /// part of the Stacked Borrows model. These statements are currently only interpreted
1805 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1806 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1807 /// for more details.
1808 Retag(RetagKind, Place<'tcx>),
1810 /// Encodes a user's type ascription. These need to be preserved
1811 /// intact so that NLL can respect them. For example:
1815 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1816 /// to the user-given type `T`. The effect depends on the specified variance:
1818 /// - `Covariant` -- requires that `T_y <: T`
1819 /// - `Contravariant` -- requires that `T_y :> T`
1820 /// - `Invariant` -- requires that `T_y == T`
1821 /// - `Bivariant` -- no effect
1822 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1824 /// No-op. Useful for deleting instructions without affecting statement indices.
1828 /// `RetagKind` describes what kind of retag is to be performed.
1829 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1830 pub enum RetagKind {
1831 /// The initial retag when entering a function
1833 /// Retag preparing for a two-phase borrow
1835 /// Retagging raw pointers
1837 /// A "normal" retag
1841 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1842 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1843 pub enum FakeReadCause {
1844 /// Inject a fake read of the borrowed input at the end of each guards
1847 /// This should ensure that you cannot change the variant for an enum while
1848 /// you are in the midst of matching on it.
1851 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1852 /// generate a read of x to check that it is initialized and safe.
1855 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1856 /// in a match guard to ensure that it's value hasn't change by the time
1857 /// we create the OutsideGuard version.
1860 /// Officially, the semantics of
1862 /// `let pattern = <expr>;`
1864 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1865 /// into the pattern.
1867 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1868 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1869 /// but in some cases it can affect the borrow checker, as in #53695.
1870 /// Therefore, we insert a "fake read" here to ensure that we get
1871 /// appropriate errors.
1875 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1876 pub struct InlineAsm<'tcx> {
1877 pub asm: HirInlineAsm,
1878 pub outputs: Box<[Place<'tcx>]>,
1879 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1882 impl<'tcx> Debug for Statement<'tcx> {
1883 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1884 use self::StatementKind::*;
1886 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1887 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1888 Retag(ref kind, ref place) =>
1889 write!(fmt, "Retag({}{:?})",
1891 RetagKind::FnEntry => "[fn entry] ",
1892 RetagKind::TwoPhase => "[2phase] ",
1893 RetagKind::Raw => "[raw] ",
1894 RetagKind::Default => "",
1898 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1899 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1903 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1904 InlineAsm(ref asm) =>
1905 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs),
1906 AscribeUserType(ref place, ref variance, ref c_ty) => {
1907 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1909 Nop => write!(fmt, "nop"),
1914 ///////////////////////////////////////////////////////////////////////////
1917 /// A path to a value; something that can be evaluated without
1918 /// changing or disturbing program state.
1919 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1920 pub enum Place<'tcx> {
1921 Base(PlaceBase<'tcx>),
1923 /// projection out of a place (access a field, deref a pointer, etc)
1924 Projection(Box<Projection<'tcx>>),
1927 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1928 pub enum PlaceBase<'tcx> {
1932 /// static or static mut variable
1933 Static(Box<Static<'tcx>>),
1936 /// We store the normalized type to avoid requiring normalization when reading MIR
1937 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1938 pub struct Static<'tcx> {
1940 pub kind: StaticKind,
1943 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable)]
1944 pub enum StaticKind {
1949 impl_stable_hash_for!(struct Static<'tcx> {
1954 /// The `Projection` data structure defines things of the form `base.x`, `*b` or `b[index]`.
1955 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1956 Hash, RustcEncodable, RustcDecodable, HashStable)]
1957 pub struct Projection<'tcx> {
1958 pub base: Place<'tcx>,
1959 pub elem: PlaceElem<'tcx>,
1962 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1963 Hash, RustcEncodable, RustcDecodable, HashStable)]
1964 pub enum ProjectionElem<V, T> {
1969 /// These indices are generated by slice patterns. Easiest to explain
1973 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1974 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1975 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1976 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1979 /// index or -index (in Python terms), depending on from_end
1981 /// thing being indexed must be at least this long
1983 /// counting backwards from end?
1987 /// These indices are generated by slice patterns.
1989 /// slice[from:-to] in Python terms.
1995 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1996 /// this for ADTs with more than one variant. It may be better to
1997 /// just introduce it always, or always for enums.
1999 /// The included Symbol is the name of the variant, used for printing MIR.
2000 Downcast(Option<Symbol>, VariantIdx),
2003 /// Alias for projections as they appear in places, where the base is a place
2004 /// and the index is a local.
2005 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
2007 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
2008 #[cfg(target_arch = "x86_64")]
2009 static_assert_size!(PlaceElem<'_>, 16);
2011 /// Alias for projections as they appear in `UserTypeProjection`, where we
2012 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
2013 pub type ProjectionKind = ProjectionElem<(), ()>;
2018 DEBUG_FORMAT = "field[{}]"
2022 impl<'tcx> Place<'tcx> {
2023 pub const RETURN_PLACE: Place<'tcx> = Place::Base(PlaceBase::Local(RETURN_PLACE));
2025 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2026 self.elem(ProjectionElem::Field(f, ty))
2029 pub fn deref(self) -> Place<'tcx> {
2030 self.elem(ProjectionElem::Deref)
2033 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2034 self.elem(ProjectionElem::Downcast(
2035 Some(adt_def.variants[variant_index].ident.name),
2039 pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
2040 self.elem(ProjectionElem::Downcast(None, variant_index))
2043 pub fn index(self, index: Local) -> Place<'tcx> {
2044 self.elem(ProjectionElem::Index(index))
2047 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2048 Place::Projection(Box::new(Projection { base: self, elem }))
2051 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2052 /// a single deref of a local.
2054 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2055 pub fn local_or_deref_local(&self) -> Option<Local> {
2057 Place::Base(PlaceBase::Local(local)) |
2058 Place::Projection(box Projection {
2059 base: Place::Base(PlaceBase::Local(local)),
2060 elem: ProjectionElem::Deref,
2066 /// Finds the innermost `Local` from this `Place`.
2067 pub fn base_local(&self) -> Option<Local> {
2068 let mut place = self;
2071 Place::Projection(proj) => place = &proj.base,
2072 Place::Base(PlaceBase::Static(_)) => return None,
2073 Place::Base(PlaceBase::Local(local)) => return Some(*local),
2078 /// Recursively "iterates" over place components, generating a `PlaceBase` and
2079 /// `Projections` list and invoking `op` with a `ProjectionsIter`.
2082 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2084 self.iterate2(&Projections::Empty, op)
2089 next: &Projections<'_, 'tcx>,
2090 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2093 Place::Projection(interior) => interior.base.iterate2(
2094 &Projections::List {
2095 projection: interior,
2101 Place::Base(base) => op(base, next.iter()),
2106 impl From<Local> for Place<'_> {
2107 fn from(local: Local) -> Self {
2108 Place::Base(local.into())
2112 impl From<Local> for PlaceBase<'_> {
2113 fn from(local: Local) -> Self {
2114 PlaceBase::Local(local)
2118 /// A linked list of projections running up the stack; begins with the
2119 /// innermost projection and extends to the outermost (e.g., `a.b.c`
2120 /// would have the place `b` with a "next" pointer to `b.c`).
2121 /// Created by `Place::iterate`.
2123 /// N.B., this particular impl strategy is not the most obvious. It was
2124 /// chosen because it makes a measurable difference to NLL
2125 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
2126 pub enum Projections<'p, 'tcx> {
2130 projection: &'p Projection<'tcx>,
2131 next: &'p Projections<'p, 'tcx>,
2135 impl<'p, 'tcx> Projections<'p, 'tcx> {
2136 fn iter(&self) -> ProjectionsIter<'_, 'tcx> {
2137 ProjectionsIter { value: self }
2141 impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
2142 type Item = &'p Projection<'tcx>;
2143 type IntoIter = ProjectionsIter<'p, 'tcx>;
2145 /// Converts a list of `Projection` components into an iterator;
2146 /// this iterator yields up a never-ending stream of `Option<&Place>`.
2147 /// These begin with the "innermost" projection and then with each
2148 /// projection therefrom. So given a place like `a.b.c` it would
2152 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2154 fn into_iter(self) -> Self::IntoIter {
2159 /// Iterator over components; see `Projections::iter` for more
2162 /// N.B., this is not a *true* Rust iterator -- the code above just
2163 /// manually invokes `next`. This is because we (sometimes) want to
2164 /// keep executing even after `None` has been returned.
2165 pub struct ProjectionsIter<'p, 'tcx> {
2166 pub value: &'p Projections<'p, 'tcx>,
2169 impl<'p, 'tcx> Iterator for ProjectionsIter<'p, 'tcx> {
2170 type Item = &'p Projection<'tcx>;
2172 fn next(&mut self) -> Option<Self::Item> {
2173 if let &Projections::List { projection, next } = self.value {
2182 impl<'p, 'tcx> FusedIterator for ProjectionsIter<'p, 'tcx> {}
2184 impl<'tcx> Debug for Place<'tcx> {
2185 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2186 self.iterate(|_place_base, place_projections| {
2187 // FIXME: remove this collect once we have migrated to slices
2188 let projs_vec: Vec<_> = place_projections.collect();
2189 for projection in projs_vec.iter().rev() {
2190 match projection.elem {
2191 ProjectionElem::Downcast(_, _) |
2192 ProjectionElem::Field(_, _) => {
2193 write!(fmt, "(").unwrap();
2195 ProjectionElem::Deref => {
2196 write!(fmt, "(*").unwrap();
2198 ProjectionElem::Index(_) |
2199 ProjectionElem::ConstantIndex { .. } |
2200 ProjectionElem::Subslice { .. } => {}
2205 self.iterate(|place_base, place_projections| {
2206 write!(fmt, "{:?}", place_base)?;
2208 for projection in place_projections {
2209 match projection.elem {
2210 ProjectionElem::Downcast(Some(name), _index) => {
2211 write!(fmt, " as {})", name)?;
2213 ProjectionElem::Downcast(None, index) => {
2214 write!(fmt, " as variant#{:?})", index)?;
2216 ProjectionElem::Deref => {
2219 ProjectionElem::Field(field, ty) => {
2220 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2222 ProjectionElem::Index(ref index) => {
2223 write!(fmt, "[{:?}]", index)?;
2225 ProjectionElem::ConstantIndex {
2230 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2232 ProjectionElem::ConstantIndex {
2237 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2239 ProjectionElem::Subslice { from, to } if to == 0 => {
2240 write!(fmt, "[{:?}:]", from)?;
2242 ProjectionElem::Subslice { from, to } if from == 0 => {
2243 write!(fmt, "[:-{:?}]", to)?;
2245 ProjectionElem::Subslice { from, to } => {
2246 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2256 impl Debug for PlaceBase<'_> {
2257 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2259 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2260 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2264 ty::tls::with(|tcx| tcx.def_path_str(def_id)),
2268 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Promoted(promoted) }) => {
2280 ///////////////////////////////////////////////////////////////////////////
2284 pub struct SourceScope {
2286 DEBUG_FORMAT = "scope[{}]",
2287 const OUTERMOST_SOURCE_SCOPE = 0,
2291 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2292 pub struct SourceScopeData {
2294 pub parent_scope: Option<SourceScope>,
2297 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2298 pub struct SourceScopeLocalData {
2299 /// A HirId with lint levels equivalent to this scope's lint levels.
2300 pub lint_root: hir::HirId,
2301 /// The unsafe block that contains this node.
2305 ///////////////////////////////////////////////////////////////////////////
2308 /// These are values that can appear inside an rvalue. They are intentionally
2309 /// limited to prevent rvalues from being nested in one another.
2310 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2311 pub enum Operand<'tcx> {
2312 /// Copy: The value must be available for use afterwards.
2314 /// This implies that the type of the place must be `Copy`; this is true
2315 /// by construction during build, but also checked by the MIR type checker.
2318 /// Move: The value (including old borrows of it) will not be used again.
2320 /// Safe for values of all types (modulo future developments towards `?Move`).
2321 /// Correct usage patterns are enforced by the borrow checker for safe code.
2322 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2325 /// Synthesizes a constant value.
2326 Constant(Box<Constant<'tcx>>),
2329 impl<'tcx> Debug for Operand<'tcx> {
2330 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2331 use self::Operand::*;
2333 Constant(ref a) => write!(fmt, "{:?}", a),
2334 Copy(ref place) => write!(fmt, "{:?}", place),
2335 Move(ref place) => write!(fmt, "move {:?}", place),
2340 impl<'tcx> Operand<'tcx> {
2341 /// Convenience helper to make a constant that refers to the fn
2342 /// with given `DefId` and substs. Since this is used to synthesize
2343 /// MIR, assumes `user_ty` is None.
2344 pub fn function_handle(
2347 substs: SubstsRef<'tcx>,
2350 let ty = tcx.type_of(def_id).subst(tcx, substs);
2351 Operand::Constant(box Constant {
2355 literal: ty::Const::zero_sized(tcx, ty),
2359 pub fn to_copy(&self) -> Self {
2361 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2362 Operand::Move(ref place) => Operand::Copy(place.clone()),
2367 ///////////////////////////////////////////////////////////////////////////
2370 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2371 pub enum Rvalue<'tcx> {
2372 /// x (either a move or copy, depending on type of x)
2376 Repeat(Operand<'tcx>, u64),
2379 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2381 /// length of a [X] or [X;n] value
2384 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2386 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2387 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2389 NullaryOp(NullOp, Ty<'tcx>),
2390 UnaryOp(UnOp, Operand<'tcx>),
2392 /// Read the discriminant of an ADT.
2394 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2395 /// be defined to return, say, a 0) if ADT is not an enum.
2396 Discriminant(Place<'tcx>),
2398 /// Creates an aggregate value, like a tuple or struct. This is
2399 /// only needed because we want to distinguish `dest = Foo { x:
2400 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2401 /// that `Foo` has a destructor. These rvalues can be optimized
2402 /// away after type-checking and before lowering.
2403 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2407 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2410 Pointer(PointerCast),
2413 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2414 pub enum AggregateKind<'tcx> {
2415 /// The type is of the element
2419 /// The second field is the variant index. It's equal to 0 for struct
2420 /// and union expressions. The fourth field is
2421 /// active field number and is present only for union expressions
2422 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2423 /// active field index would identity the field `c`
2428 Option<UserTypeAnnotationIndex>,
2432 Closure(DefId, ClosureSubsts<'tcx>),
2433 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2436 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2438 /// The `+` operator (addition)
2440 /// The `-` operator (subtraction)
2442 /// The `*` operator (multiplication)
2444 /// The `/` operator (division)
2446 /// The `%` operator (modulus)
2448 /// The `^` operator (bitwise xor)
2450 /// The `&` operator (bitwise and)
2452 /// The `|` operator (bitwise or)
2454 /// The `<<` operator (shift left)
2456 /// The `>>` operator (shift right)
2458 /// The `==` operator (equality)
2460 /// The `<` operator (less than)
2462 /// The `<=` operator (less than or equal to)
2464 /// The `!=` operator (not equal to)
2466 /// The `>=` operator (greater than or equal to)
2468 /// The `>` operator (greater than)
2470 /// The `ptr.offset` operator
2475 pub fn is_checkable(self) -> bool {
2478 Add | Sub | Mul | Shl | Shr => true,
2484 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2486 /// Returns the size of a value of that type
2488 /// Creates a new uninitialized box for a value of that type
2492 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2494 /// The `!` operator for logical inversion
2496 /// The `-` operator for negation
2500 impl<'tcx> Debug for Rvalue<'tcx> {
2501 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2502 use self::Rvalue::*;
2505 Use(ref place) => write!(fmt, "{:?}", place),
2506 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2507 Len(ref a) => write!(fmt, "Len({:?})", a),
2508 Cast(ref kind, ref place, ref ty) => {
2509 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2511 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2512 CheckedBinaryOp(ref op, ref a, ref b) => {
2513 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2515 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2516 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2517 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2518 Ref(region, borrow_kind, ref place) => {
2519 let kind_str = match borrow_kind {
2520 BorrowKind::Shared => "",
2521 BorrowKind::Shallow => "shallow ",
2522 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2525 // When printing regions, add trailing space if necessary.
2526 let print_region = ty::tls::with(|tcx| {
2527 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2529 let region = if print_region {
2530 let mut region = region.to_string();
2531 if region.len() > 0 {
2536 // Do not even print 'static
2539 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2542 Aggregate(ref kind, ref places) => {
2543 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2544 let mut tuple_fmt = fmt.debug_tuple("");
2545 for place in places {
2546 tuple_fmt.field(place);
2552 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2554 AggregateKind::Tuple => match places.len() {
2555 0 => write!(fmt, "()"),
2556 1 => write!(fmt, "({:?},)", places[0]),
2557 _ => fmt_tuple(fmt, places),
2560 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2561 let variant_def = &adt_def.variants[variant];
2564 ty::tls::with(|tcx| {
2565 let substs = tcx.lift(&substs).expect("could not lift for printing");
2566 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2567 .print_def_path(variant_def.def_id, substs)?;
2571 match variant_def.ctor_kind {
2572 CtorKind::Const => Ok(()),
2573 CtorKind::Fn => fmt_tuple(fmt, places),
2574 CtorKind::Fictive => {
2575 let mut struct_fmt = fmt.debug_struct("");
2576 for (field, place) in variant_def.fields.iter().zip(places) {
2577 struct_fmt.field(&field.ident.as_str(), place);
2584 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2585 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2586 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2587 format!("[closure@{:?}]", hir_id)
2589 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2591 let mut struct_fmt = fmt.debug_struct(&name);
2593 if let Some(upvars) = tcx.upvars(def_id) {
2594 for (&var_id, place) in upvars.keys().zip(places) {
2595 let var_name = tcx.hir().name(var_id);
2596 struct_fmt.field(&var_name.as_str(), place);
2602 write!(fmt, "[closure]")
2606 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2607 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2608 let name = format!("[generator@{:?}]",
2609 tcx.hir().span(hir_id));
2610 let mut struct_fmt = fmt.debug_struct(&name);
2612 if let Some(upvars) = tcx.upvars(def_id) {
2613 for (&var_id, place) in upvars.keys().zip(places) {
2614 let var_name = tcx.hir().name(var_id);
2615 struct_fmt.field(&var_name.as_str(), place);
2621 write!(fmt, "[generator]")
2630 ///////////////////////////////////////////////////////////////////////////
2633 /// Two constants are equal if they are the same constant. Note that
2634 /// this does not necessarily mean that they are "==" in Rust -- in
2635 /// particular one must be wary of `NaN`!
2637 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2638 pub struct Constant<'tcx> {
2642 /// Optional user-given type: for something like
2643 /// `collect::<Vec<_>>`, this would be present and would
2644 /// indicate that `Vec<_>` was explicitly specified.
2646 /// Needed for NLL to impose user-given type constraints.
2647 pub user_ty: Option<UserTypeAnnotationIndex>,
2649 pub literal: &'tcx ty::Const<'tcx>,
2652 /// A collection of projections into user types.
2654 /// They are projections because a binding can occur a part of a
2655 /// parent pattern that has been ascribed a type.
2657 /// Its a collection because there can be multiple type ascriptions on
2658 /// the path from the root of the pattern down to the binding itself.
2663 /// struct S<'a>((i32, &'a str), String);
2664 /// let S((_, w): (i32, &'static str), _): S = ...;
2665 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2666 /// // --------------------------------- ^ (2)
2669 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2670 /// ascribed the type `(i32, &'static str)`.
2672 /// The highlights labelled `(2)` show the whole pattern being
2673 /// ascribed the type `S`.
2675 /// In this example, when we descend to `w`, we will have built up the
2676 /// following two projected types:
2678 /// * base: `S`, projection: `(base.0).1`
2679 /// * base: `(i32, &'static str)`, projection: `base.1`
2681 /// The first will lead to the constraint `w: &'1 str` (for some
2682 /// inferred region `'1`). The second will lead to the constraint `w:
2684 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2685 pub struct UserTypeProjections {
2686 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2689 BraceStructTypeFoldableImpl! {
2690 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2695 impl<'tcx> UserTypeProjections {
2696 pub fn none() -> Self {
2697 UserTypeProjections { contents: vec![] }
2700 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection, Span)>) -> Self {
2701 UserTypeProjections { contents: projs.collect() }
2704 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection, Span)> {
2705 self.contents.iter()
2708 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection> {
2709 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2712 pub fn push_projection(
2714 user_ty: &UserTypeProjection,
2717 self.contents.push((user_ty.clone(), span));
2723 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection
2725 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2729 pub fn index(self) -> Self {
2730 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2733 pub fn subslice(self, from: u32, to: u32) -> Self {
2734 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2737 pub fn deref(self) -> Self {
2738 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2741 pub fn leaf(self, field: Field) -> Self {
2742 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2747 adt_def: &'tcx AdtDef,
2748 variant_index: VariantIdx,
2751 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2755 /// Encodes the effect of a user-supplied type annotation on the
2756 /// subcomponents of a pattern. The effect is determined by applying the
2757 /// given list of proejctions to some underlying base type. Often,
2758 /// the projection element list `projs` is empty, in which case this
2759 /// directly encodes a type in `base`. But in the case of complex patterns with
2760 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2761 /// in which case the `projs` vector is used.
2765 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2767 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2768 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2769 /// determined by finding the type of the `.0` field from `T`.
2770 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2771 pub struct UserTypeProjection {
2772 pub base: UserTypeAnnotationIndex,
2773 pub projs: Vec<ProjectionKind>,
2776 impl Copy for ProjectionKind { }
2778 impl UserTypeProjection {
2779 pub(crate) fn index(mut self) -> Self {
2780 self.projs.push(ProjectionElem::Index(()));
2784 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2785 self.projs.push(ProjectionElem::Subslice { from, to });
2789 pub(crate) fn deref(mut self) -> Self {
2790 self.projs.push(ProjectionElem::Deref);
2794 pub(crate) fn leaf(mut self, field: Field) -> Self {
2795 self.projs.push(ProjectionElem::Field(field, ()));
2799 pub(crate) fn variant(
2801 adt_def: &'tcx AdtDef,
2802 variant_index: VariantIdx,
2805 self.projs.push(ProjectionElem::Downcast(
2806 Some(adt_def.variants[variant_index].ident.name),
2808 self.projs.push(ProjectionElem::Field(field, ()));
2813 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2815 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2816 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2817 use crate::mir::ProjectionElem::*;
2819 let base = self.base.fold_with(folder);
2820 let projs: Vec<_> = self.projs
2825 Field(f, ()) => Field(f.clone(), ()),
2826 Index(()) => Index(()),
2827 elem => elem.clone(),
2831 UserTypeProjection { base, projs }
2834 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2835 self.base.visit_with(visitor)
2836 // Note: there's nothing in `self.proj` to visit.
2841 pub struct Promoted {
2843 DEBUG_FORMAT = "promoted[{}]"
2847 impl<'tcx> Debug for Constant<'tcx> {
2848 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2849 write!(fmt, "{}", self)
2853 impl<'tcx> Display for Constant<'tcx> {
2854 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2855 write!(fmt, "const ")?;
2856 write!(fmt, "{}", self.literal)
2860 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2861 type Node = BasicBlock;
2864 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2865 fn num_nodes(&self) -> usize {
2866 self.basic_blocks.len()
2870 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2871 fn start_node(&self) -> Self::Node {
2876 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2880 ) -> <Self as GraphPredecessors<'_>>::Iter {
2881 self.predecessors_for(node).clone().into_iter()
2885 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2889 ) -> <Self as GraphSuccessors<'_>>::Iter {
2890 self.basic_blocks[node].terminator().successors().cloned()
2894 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2895 type Item = BasicBlock;
2896 type Iter = IntoIter<BasicBlock>;
2899 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2900 type Item = BasicBlock;
2901 type Iter = iter::Cloned<Successors<'b>>;
2904 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2905 pub struct Location {
2906 /// the location is within this block
2907 pub block: BasicBlock,
2909 /// the location is the start of the statement; or, if `statement_index`
2910 /// == num-statements, then the start of the terminator.
2911 pub statement_index: usize,
2914 impl fmt::Debug for Location {
2915 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2916 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2921 pub const START: Location = Location {
2926 /// Returns the location immediately after this one within the enclosing block.
2928 /// Note that if this location represents a terminator, then the
2929 /// resulting location would be out of bounds and invalid.
2930 pub fn successor_within_block(&self) -> Location {
2933 statement_index: self.statement_index + 1,
2937 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2938 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2939 // If we are in the same block as the other location and are an earlier statement
2940 // then we are a predecessor of `other`.
2941 if self.block == other.block && self.statement_index < other.statement_index {
2945 // If we're in another block, then we want to check that block is a predecessor of `other`.
2946 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2947 let mut visited = FxHashSet::default();
2949 while let Some(block) = queue.pop() {
2950 // If we haven't visited this block before, then make sure we visit it's predecessors.
2951 if visited.insert(block) {
2952 queue.append(&mut body.predecessors_for(block).clone());
2957 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2958 // we found that block by looking at the predecessors of `other`).
2959 if self.block == block {
2967 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2968 if self.block == other.block {
2969 self.statement_index <= other.statement_index
2971 dominators.is_dominated_by(other.block, self.block)
2976 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2977 pub enum UnsafetyViolationKind {
2979 /// Permitted in const fn and regular fns.
2981 ExternStatic(hir::HirId),
2982 BorrowPacked(hir::HirId),
2985 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2986 pub struct UnsafetyViolation {
2987 pub source_info: SourceInfo,
2988 pub description: InternedString,
2989 pub details: InternedString,
2990 pub kind: UnsafetyViolationKind,
2993 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2994 pub struct UnsafetyCheckResult {
2995 /// Violations that are propagated *upwards* from this function
2996 pub violations: Lrc<[UnsafetyViolation]>,
2997 /// unsafe blocks in this function, along with whether they are used. This is
2998 /// used for the "unused_unsafe" lint.
2999 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
3003 pub struct GeneratorSavedLocal {
3005 DEBUG_FORMAT = "_{}",
3009 /// The layout of generator state
3010 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3011 pub struct GeneratorLayout<'tcx> {
3012 /// The type of every local stored inside the generator.
3013 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
3015 /// Which of the above fields are in each variant. Note that one field may
3016 /// be stored in multiple variants.
3017 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
3019 /// Which saved locals are storage-live at the same time. Locals that do not
3020 /// have conflicts with each other are allowed to overlap in the computed
3022 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
3024 /// Names and scopes of all the stored generator locals.
3025 /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
3026 /// debuginfo generation, and will be removed at some point.
3027 /// Do **NOT** use it for anything else, local information should not be
3028 /// in the MIR, please rely on local crate HIR or other side-channels.
3029 pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
3032 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3033 pub struct BorrowCheckResult<'tcx> {
3034 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
3035 pub used_mut_upvars: SmallVec<[Field; 8]>,
3038 /// After we borrow check a closure, we are left with various
3039 /// requirements that we have inferred between the free regions that
3040 /// appear in the closure's signature or on its field types. These
3041 /// requirements are then verified and proved by the closure's
3042 /// creating function. This struct encodes those requirements.
3044 /// The requirements are listed as being between various
3045 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
3046 /// vids refer to the free regions that appear in the closure (or
3047 /// generator's) type, in order of appearance. (This numbering is
3048 /// actually defined by the `UniversalRegions` struct in the NLL
3049 /// region checker. See for example
3050 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
3051 /// regions in the closure's type "as if" they were erased, so their
3052 /// precise identity is not important, only their position.
3054 /// Example: If type check produces a closure with the closure substs:
3057 /// ClosureSubsts = [
3058 /// i8, // the "closure kind"
3059 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
3060 /// &'a String, // some upvar
3064 /// here, there is one unique free region (`'a`) but it appears
3065 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
3068 /// ClosureSubsts = [
3069 /// i8, // the "closure kind"
3070 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
3071 /// &'2 String, // some upvar
3075 /// Now the code might impose a requirement like `'1: '2`. When an
3076 /// instance of the closure is created, the corresponding free regions
3077 /// can be extracted from its type and constrained to have the given
3078 /// outlives relationship.
3080 /// In some cases, we have to record outlives requirements between
3081 /// types and regions as well. In that case, if those types include
3082 /// any regions, those regions are recorded as `ReClosureBound`
3083 /// instances assigned one of these same indices. Those regions will
3084 /// be substituted away by the creator. We use `ReClosureBound` in
3085 /// that case because the regions must be allocated in the global
3086 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
3087 /// internally within the rest of the NLL code).
3088 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3089 pub struct ClosureRegionRequirements<'tcx> {
3090 /// The number of external regions defined on the closure. In our
3091 /// example above, it would be 3 -- one for `'static`, then `'1`
3092 /// and `'2`. This is just used for a sanity check later on, to
3093 /// make sure that the number of regions we see at the callsite
3095 pub num_external_vids: usize,
3097 /// Requirements between the various free regions defined in
3099 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
3102 /// Indicates an outlives constraint between a type or between two
3103 /// free-regions declared on the closure.
3104 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3105 pub struct ClosureOutlivesRequirement<'tcx> {
3106 // This region or type ...
3107 pub subject: ClosureOutlivesSubject<'tcx>,
3109 // ... must outlive this one.
3110 pub outlived_free_region: ty::RegionVid,
3112 // If not, report an error here ...
3113 pub blame_span: Span,
3115 // ... due to this reason.
3116 pub category: ConstraintCategory,
3119 /// Outlives constraints can be categorized to determine whether and why they
3120 /// are interesting (for error reporting). Order of variants indicates sort
3121 /// order of the category, thereby influencing diagnostic output.
3123 /// See also [rustc_mir::borrow_check::nll::constraints]
3124 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
3125 Hash, RustcEncodable, RustcDecodable, HashStable)]
3126 pub enum ConstraintCategory {
3134 /// A constraint that came from checking the body of a closure.
3136 /// We try to get the category that the closure used when reporting this.
3144 /// A "boring" constraint (caused by the given location) is one that
3145 /// the user probably doesn't want to see described in diagnostics,
3146 /// because it is kind of an artifact of the type system setup.
3147 /// Example: `x = Foo { field: y }` technically creates
3148 /// intermediate regions representing the "type of `Foo { field: y
3149 /// }`", and data flows from `y` into those variables, but they
3150 /// are not very interesting. The assignment into `x` on the other
3153 // Boring and applicable everywhere.
3156 /// A constraint that doesn't correspond to anything the user sees.
3160 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
3161 /// that must outlive some region.
3162 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3163 pub enum ClosureOutlivesSubject<'tcx> {
3164 /// Subject is a type, typically a type parameter, but could also
3165 /// be a projection. Indicates a requirement like `T: 'a` being
3166 /// passed to the caller, where the type here is `T`.
3168 /// The type here is guaranteed not to contain any free regions at
3172 /// Subject is a free region from the closure. Indicates a requirement
3173 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3174 Region(ty::RegionVid),
3178 * TypeFoldable implementations for MIR types
3181 CloneTypeFoldableAndLiftImpls! {
3191 SourceScopeLocalData,
3192 UserTypeAnnotationIndex,
3195 BraceStructTypeFoldableImpl! {
3196 impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
3200 source_scope_local_data,
3206 user_type_annotations,
3208 __upvar_debuginfo_codegen_only_do_not_use,
3210 control_flow_destroyed,
3216 BraceStructTypeFoldableImpl! {
3217 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3221 __local_debuginfo_codegen_only_do_not_use,
3225 BraceStructTypeFoldableImpl! {
3226 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3239 BraceStructTypeFoldableImpl! {
3240 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3247 BraceStructTypeFoldableImpl! {
3248 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3253 EnumTypeFoldableImpl! {
3254 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3255 (StatementKind::Assign)(a, b),
3256 (StatementKind::FakeRead)(cause, place),
3257 (StatementKind::SetDiscriminant) { place, variant_index },
3258 (StatementKind::StorageLive)(a),
3259 (StatementKind::StorageDead)(a),
3260 (StatementKind::InlineAsm)(a),
3261 (StatementKind::Retag)(kind, place),
3262 (StatementKind::AscribeUserType)(a, v, b),
3263 (StatementKind::Nop),
3267 BraceStructTypeFoldableImpl! {
3268 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3275 EnumTypeFoldableImpl! {
3276 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3277 (ClearCrossCrate::Clear),
3278 (ClearCrossCrate::Set)(a),
3279 } where T: TypeFoldable<'tcx>
3282 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3283 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3284 use crate::mir::TerminatorKind::*;
3286 let kind = match self.kind {
3287 Goto { target } => Goto { target },
3294 discr: discr.fold_with(folder),
3295 switch_ty: switch_ty.fold_with(folder),
3296 values: values.clone(),
3297 targets: targets.clone(),
3304 location: location.fold_with(folder),
3313 } => DropAndReplace {
3314 location: location.fold_with(folder),
3315 value: value.fold_with(folder),
3324 value: value.fold_with(folder),
3335 let dest = destination
3337 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3340 func: func.fold_with(folder),
3341 args: args.fold_with(folder),
3354 let msg = if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3355 InterpError::BoundsCheck {
3356 len: len.fold_with(folder),
3357 index: index.fold_with(folder),
3363 cond: cond.fold_with(folder),
3370 GeneratorDrop => GeneratorDrop,
3374 Unreachable => Unreachable,
3391 source_info: self.source_info,
3396 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3397 use crate::mir::TerminatorKind::*;
3404 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3405 Drop { ref location, .. } => location.visit_with(visitor),
3410 } => location.visit_with(visitor) || value.visit_with(visitor),
3411 Yield { ref value, .. } => value.visit_with(visitor),
3418 let dest = if let Some((ref loc, _)) = *destination {
3419 loc.visit_with(visitor)
3423 dest || func.visit_with(visitor) || args.visit_with(visitor)
3426 ref cond, ref msg, ..
3428 if cond.visit_with(visitor) {
3429 if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3430 len.visit_with(visitor) || index.visit_with(visitor)
3445 | FalseUnwind { .. } => false,
3450 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3451 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3453 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3458 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3459 if let &Place::Projection(ref p) = self {
3460 p.visit_with(visitor)
3467 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3468 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3469 use crate::mir::Rvalue::*;
3471 Use(ref op) => Use(op.fold_with(folder)),
3472 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3473 Ref(region, bk, ref place) => {
3474 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3476 Len(ref place) => Len(place.fold_with(folder)),
3477 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3478 BinaryOp(op, ref rhs, ref lhs) => {
3479 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3481 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3482 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3484 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3485 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3486 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3487 Aggregate(ref kind, ref fields) => {
3488 let kind = box match **kind {
3489 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3490 AggregateKind::Tuple => AggregateKind::Tuple,
3491 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3494 substs.fold_with(folder),
3495 user_ty.fold_with(folder),
3498 AggregateKind::Closure(id, substs) => {
3499 AggregateKind::Closure(id, substs.fold_with(folder))
3501 AggregateKind::Generator(id, substs, movablity) => {
3502 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3505 Aggregate(kind, fields.fold_with(folder))
3510 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3511 use crate::mir::Rvalue::*;
3513 Use(ref op) => op.visit_with(visitor),
3514 Repeat(ref op, _) => op.visit_with(visitor),
3515 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3516 Len(ref place) => place.visit_with(visitor),
3517 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3518 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3519 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3521 UnaryOp(_, ref val) => val.visit_with(visitor),
3522 Discriminant(ref place) => place.visit_with(visitor),
3523 NullaryOp(_, ty) => ty.visit_with(visitor),
3524 Aggregate(ref kind, ref fields) => {
3526 AggregateKind::Array(ty) => ty.visit_with(visitor),
3527 AggregateKind::Tuple => false,
3528 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3529 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3531 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3532 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3533 }) || fields.visit_with(visitor)
3539 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3540 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3542 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3543 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3544 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3548 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3550 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3551 Operand::Constant(ref c) => c.visit_with(visitor),
3556 impl<'tcx> TypeFoldable<'tcx> for Projection<'tcx> {
3557 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3558 use crate::mir::ProjectionElem::*;
3560 let base = self.base.fold_with(folder);
3561 let elem = match self.elem {
3563 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3564 Index(ref v) => Index(v.fold_with(folder)),
3565 ref elem => elem.clone(),
3568 Projection { base, elem }
3571 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3572 use crate::mir::ProjectionElem::*;
3574 self.base.visit_with(visitor) || match self.elem {
3575 Field(_, ref ty) => ty.visit_with(visitor),
3576 Index(ref v) => v.visit_with(visitor),
3582 impl<'tcx> TypeFoldable<'tcx> for Field {
3583 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3586 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3591 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3592 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3595 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3600 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3601 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3604 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3609 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3610 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3612 span: self.span.clone(),
3613 ty: self.ty.fold_with(folder),
3614 user_ty: self.user_ty.fold_with(folder),
3615 literal: self.literal.fold_with(folder),
3618 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3619 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)