1 //! MIR datatypes and passes. See the [rustc guide] for more info.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
5 use crate::hir::def::{CtorKind, Namespace};
6 use crate::hir::def_id::DefId;
7 use crate::hir::{self, HirId, InlineAsm as HirInlineAsm};
8 use crate::mir::interpret::{ConstValue, InterpError, Scalar};
9 use crate::mir::visit::MirVisitable;
10 use rustc_apfloat::ieee::{Double, Single};
11 use rustc_apfloat::Float;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::graph::dominators::{dominators, Dominators};
14 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
15 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
16 use rustc_data_structures::sync::Lrc;
17 use rustc_data_structures::sync::MappedReadGuard;
18 use rustc_macros::HashStable;
19 use crate::rustc_serialize::{self as serialize};
20 use smallvec::SmallVec;
22 use std::fmt::{self, Debug, Formatter, Write};
23 use std::ops::{Index, IndexMut};
25 use std::vec::IntoIter;
26 use std::{iter, mem, option, u32};
27 use syntax::ast::{self, Name};
28 use syntax::symbol::{InternedString, Symbol};
29 use syntax_pos::{Span, DUMMY_SP};
30 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
31 use crate::ty::subst::{Subst, SubstsRef};
32 use crate::ty::layout::VariantIdx;
34 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
35 UserTypeAnnotationIndex,
37 use crate::ty::print::{FmtPrinter, Printer};
39 pub use crate::mir::interpret::AssertMessage;
49 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
51 pub trait HasLocalDecls<'tcx> {
52 fn local_decls(&self) -> &LocalDecls<'tcx>;
55 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx> {
61 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
62 fn local_decls(&self) -> &LocalDecls<'tcx> {
67 /// The various "big phases" that MIR goes through.
69 /// Warning: ordering of variants is significant
70 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
79 /// Gets the index of the current MirPhase within the set of all MirPhases.
80 pub fn phase_index(&self) -> usize {
85 /// Lowered representation of a single function.
86 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
87 pub struct Mir<'tcx> {
88 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
89 /// that indexes into this vector.
90 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
92 /// Records how far through the "desugaring and optimization" process this particular
93 /// MIR has traversed. This is particularly useful when inlining, since in that context
94 /// we instantiate the promoted constants and add them to our promoted vector -- but those
95 /// promoted items have already been optimized, whereas ours have not. This field allows
96 /// us to see the difference and forego optimization on the inlined promoted items.
99 /// List of source scopes; these are referenced by statements
100 /// and used for debuginfo. Indexed by a `SourceScope`.
101 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
103 /// Crate-local information for each source scope, that can't (and
104 /// needn't) be tracked across crates.
105 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
107 /// Rvalues promoted from this function, such as borrows of constants.
108 /// Each of them is the Mir of a constant with the fn's type parameters
109 /// in scope, but a separate set of locals.
110 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
112 /// Yields type of the function, if it is a generator.
113 pub yield_ty: Option<Ty<'tcx>>,
115 /// Generator drop glue
116 pub generator_drop: Option<Box<Mir<'tcx>>>,
118 /// The layout of a generator. Produced by the state transformation.
119 pub generator_layout: Option<GeneratorLayout<'tcx>>,
121 /// Declarations of locals.
123 /// The first local is the return value pointer, followed by `arg_count`
124 /// locals for the function arguments, followed by any user-declared
125 /// variables and temporaries.
126 pub local_decls: LocalDecls<'tcx>,
128 /// User type annotations
129 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
131 /// Number of arguments this function takes.
133 /// Starting at local 1, `arg_count` locals will be provided by the caller
134 /// and can be assumed to be initialized.
136 /// If this MIR was built for a constant, this will be 0.
137 pub arg_count: usize,
139 /// Names and capture modes of all the closure upvars, assuming
140 /// the first argument is either the closure or a reference to it.
141 pub upvar_decls: Vec<UpvarDecl>,
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 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
150 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
151 /// this conversion from happening and use short circuiting, we will cause the following code
152 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
154 /// List of places where control flow was destroyed. Used for error reporting.
155 pub control_flow_destroyed: Vec<(Span, String)>,
157 /// A span representing this MIR, for error reporting
160 /// A cache for various calculations
164 impl<'tcx> Mir<'tcx> {
166 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
167 source_scopes: IndexVec<SourceScope, SourceScopeData>,
168 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
169 promoted: IndexVec<Promoted, Mir<'tcx>>,
170 yield_ty: Option<Ty<'tcx>>,
171 local_decls: LocalDecls<'tcx>,
172 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
174 upvar_decls: Vec<UpvarDecl>,
176 control_flow_destroyed: Vec<(Span, String)>,
178 // We need `arg_count` locals, and one for the return place
180 local_decls.len() >= arg_count + 1,
181 "expected at least {} locals, got {}",
187 phase: MirPhase::Build,
190 source_scope_local_data,
193 generator_drop: None,
194 generator_layout: None,
196 user_type_annotations,
201 cache: cache::Cache::new(),
202 control_flow_destroyed,
207 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
212 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
213 self.cache.invalidate();
214 &mut self.basic_blocks
218 pub fn basic_blocks_and_local_decls_mut(
221 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
222 &mut LocalDecls<'tcx>,
224 self.cache.invalidate();
225 (&mut self.basic_blocks, &mut self.local_decls)
229 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
230 self.cache.predecessors(self)
234 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
235 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
239 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
240 let if_zero_locations = if loc.statement_index == 0 {
241 let predecessor_blocks = self.predecessors_for(loc.block);
242 let num_predecessor_blocks = predecessor_blocks.len();
244 (0..num_predecessor_blocks)
245 .map(move |i| predecessor_blocks[i])
246 .map(move |bb| self.terminator_loc(bb)),
252 let if_not_zero_locations = if loc.statement_index == 0 {
257 statement_index: loc.statement_index - 1,
264 .chain(if_not_zero_locations)
268 pub fn dominators(&self) -> Dominators<BasicBlock> {
273 pub fn local_kind(&self, local: Local) -> LocalKind {
274 let index = local.as_usize();
277 self.local_decls[local].mutability == Mutability::Mut,
278 "return place should be mutable"
281 LocalKind::ReturnPointer
282 } else if index < self.arg_count + 1 {
284 } else if self.local_decls[local].name.is_some() {
291 /// Returns an iterator over all temporaries.
293 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
294 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
295 let local = Local::new(index);
296 if self.local_decls[local].is_user_variable.is_some() {
304 /// Returns an iterator over all user-declared locals.
306 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
307 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
308 let local = Local::new(index);
309 if self.local_decls[local].is_user_variable.is_some() {
317 /// Returns an iterator over all user-declared mutable locals.
319 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
320 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
321 let local = Local::new(index);
322 let decl = &self.local_decls[local];
323 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
331 /// Returns an iterator over all user-declared mutable arguments and locals.
333 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
334 (1..self.local_decls.len()).filter_map(move |index| {
335 let local = Local::new(index);
336 let decl = &self.local_decls[local];
337 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
338 && decl.mutability == Mutability::Mut
347 /// Returns an iterator over all function arguments.
349 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
350 let arg_count = self.arg_count;
351 (1..=arg_count).map(Local::new)
354 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
355 /// locals that are neither arguments nor the return place).
357 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
358 let arg_count = self.arg_count;
359 let local_count = self.local_decls.len();
360 (arg_count + 1..local_count).map(Local::new)
363 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
364 /// invalidating statement indices in `Location`s.
365 pub fn make_statement_nop(&mut self, location: Location) {
366 let block = &mut self[location.block];
367 debug_assert!(location.statement_index < block.statements.len());
368 block.statements[location.statement_index].make_nop()
371 /// Returns the source info associated with `location`.
372 pub fn source_info(&self, location: Location) -> &SourceInfo {
373 let block = &self[location.block];
374 let stmts = &block.statements;
375 let idx = location.statement_index;
376 if idx < stmts.len() {
377 &stmts[idx].source_info
379 assert_eq!(idx, stmts.len());
380 &block.terminator().source_info
384 /// Checks if `sub` is a sub scope of `sup`
385 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
387 match self.source_scopes[sub].parent_scope {
388 None => return false,
395 /// Returns the return type, it always return first element from `local_decls` array
396 pub fn return_ty(&self) -> Ty<'tcx> {
397 self.local_decls[RETURN_PLACE].ty
400 /// Gets the location of the terminator for the given block
401 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
404 statement_index: self[bb].statements.len(),
409 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
412 /// Unsafe because of a PushUnsafeBlock
414 /// Unsafe because of an unsafe fn
416 /// Unsafe because of an `unsafe` block
417 ExplicitUnsafe(hir::HirId),
420 impl_stable_hash_for!(struct Mir<'tcx> {
424 source_scope_local_data,
430 user_type_annotations,
434 control_flow_destroyed,
439 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
440 type Output = BasicBlockData<'tcx>;
443 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
444 &self.basic_blocks()[index]
448 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
450 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
451 &mut self.basic_blocks_mut()[index]
455 #[derive(Copy, Clone, Debug, HashStable)]
456 pub enum ClearCrossCrate<T> {
461 impl<T> ClearCrossCrate<T> {
462 pub fn assert_crate_local(self) -> T {
464 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
465 ClearCrossCrate::Set(v) => v,
470 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
471 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
473 /// Grouped information about the source code origin of a MIR entity.
474 /// Intended to be inspected by diagnostics and debuginfo.
475 /// Most passes can work with it as a whole, within a single function.
476 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
477 pub struct SourceInfo {
478 /// Source span for the AST pertaining to this MIR entity.
481 /// The source scope, keeping track of which bindings can be
482 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
483 pub scope: SourceScope,
486 ///////////////////////////////////////////////////////////////////////////
487 // Mutability and borrow kinds
489 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
490 pub enum Mutability {
495 impl From<Mutability> for hir::Mutability {
496 fn from(m: Mutability) -> Self {
498 Mutability::Mut => hir::MutMutable,
499 Mutability::Not => hir::MutImmutable,
504 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd,
505 Ord, RustcEncodable, RustcDecodable, HashStable)]
506 pub enum BorrowKind {
507 /// Data must be immutable and is aliasable.
510 /// The immediately borrowed place must be immutable, but projections from
511 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
512 /// conflict with a mutable borrow of `a.b.c`.
514 /// This is used when lowering matches: when matching on a place we want to
515 /// ensure that place have the same value from the start of the match until
516 /// an arm is selected. This prevents this code from compiling:
518 /// let mut x = &Some(0);
521 /// Some(_) if { x = &None; false } => (),
525 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
526 /// should not prevent `if let None = x { ... }`, for example, because the
527 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
528 /// We can also report errors with this kind of borrow differently.
531 /// Data must be immutable but not aliasable. This kind of borrow
532 /// cannot currently be expressed by the user and is used only in
533 /// implicit closure bindings. It is needed when the closure is
534 /// borrowing or mutating a mutable referent, e.g.:
536 /// let x: &mut isize = ...;
537 /// let y = || *x += 5;
539 /// If we were to try to translate this closure into a more explicit
540 /// form, we'd encounter an error with the code as written:
542 /// struct Env { x: & &mut isize }
543 /// let x: &mut isize = ...;
544 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
545 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
547 /// This is then illegal because you cannot mutate an `&mut` found
548 /// in an aliasable location. To solve, you'd have to translate with
549 /// an `&mut` borrow:
551 /// struct Env { x: & &mut isize }
552 /// let x: &mut isize = ...;
553 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
554 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
556 /// Now the assignment to `**env.x` is legal, but creating a
557 /// mutable pointer to `x` is not because `x` is not mutable. We
558 /// could fix this by declaring `x` as `let mut x`. This is ok in
559 /// user code, if awkward, but extra weird for closures, since the
560 /// borrow is hidden.
562 /// So we introduce a "unique imm" borrow -- the referent is
563 /// immutable, but not aliasable. This solves the problem. For
564 /// simplicity, we don't give users the way to express this
565 /// borrow, it's just used when translating closures.
568 /// Data is mutable and not aliasable.
570 /// `true` if this borrow arose from method-call auto-ref
571 /// (i.e., `adjustment::Adjust::Borrow`).
572 allow_two_phase_borrow: bool,
577 pub fn allows_two_phase_borrow(&self) -> bool {
579 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
580 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
585 ///////////////////////////////////////////////////////////////////////////
586 // Variables and temps
591 DEBUG_FORMAT = "_{}",
592 const RETURN_PLACE = 0,
596 /// Classifies locals into categories. See `Mir::local_kind`.
597 #[derive(PartialEq, Eq, Debug, HashStable)]
599 /// User-declared variable binding
601 /// Compiler-introduced temporary
603 /// Function argument
605 /// Location of function's return value
609 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
610 pub struct VarBindingForm<'tcx> {
611 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
612 pub binding_mode: ty::BindingMode,
613 /// If an explicit type was provided for this variable binding,
614 /// this holds the source Span of that type.
616 /// NOTE: if you want to change this to a `HirId`, be wary that
617 /// doing so breaks incremental compilation (as of this writing),
618 /// while a `Span` does not cause our tests to fail.
619 pub opt_ty_info: Option<Span>,
620 /// Place of the RHS of the =, or the subject of the `match` where this
621 /// variable is initialized. None in the case of `let PATTERN;`.
622 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
623 /// (a) the right-hand side isn't evaluated as a place expression.
624 /// (b) it gives a way to separate this case from the remaining cases
626 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
627 /// Span of the pattern in which this variable was bound.
631 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
632 pub enum BindingForm<'tcx> {
633 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
634 Var(VarBindingForm<'tcx>),
635 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
636 ImplicitSelf(ImplicitSelfKind),
637 /// Reference used in a guard expression to ensure immutability.
641 /// Represents what type of implicit self a function has, if any.
642 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
643 pub enum ImplicitSelfKind {
644 /// Represents a `fn x(self);`.
646 /// Represents a `fn x(mut self);`.
648 /// Represents a `fn x(&self);`.
650 /// Represents a `fn x(&mut self);`.
652 /// Represents when a function does not have a self argument or
653 /// when a function has a `self: X` argument.
657 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
659 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
666 impl_stable_hash_for!(enum self::ImplicitSelfKind {
674 impl_stable_hash_for!(enum self::MirPhase {
681 mod binding_form_impl {
682 use crate::ich::StableHashingContext;
683 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
685 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
686 fn hash_stable<W: StableHasherResult>(
688 hcx: &mut StableHashingContext<'a>,
689 hasher: &mut StableHasher<W>,
691 use super::BindingForm::*;
692 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
695 Var(binding) => binding.hash_stable(hcx, hasher),
696 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
703 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
704 /// created during evaluation of expressions in a block tail
705 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
707 /// It is used to improve diagnostics when such temporaries are
708 /// involved in borrow_check errors, e.g., explanations of where the
709 /// temporaries come from, when their destructors are run, and/or how
710 /// one might revise the code to satisfy the borrow checker's rules.
711 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
712 pub struct BlockTailInfo {
713 /// If `true`, then the value resulting from evaluating this tail
714 /// expression is ignored by the block's expression context.
716 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
717 /// but not e.g., `let _x = { ...; tail };`
718 pub tail_result_is_ignored: bool,
721 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
725 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
726 /// argument, or the return place.
727 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
728 pub struct LocalDecl<'tcx> {
729 /// `let mut x` vs `let x`.
731 /// Temporaries and the return place are always mutable.
732 pub mutability: Mutability,
734 /// Some(binding_mode) if this corresponds to a user-declared local variable.
736 /// This is solely used for local diagnostics when generating
737 /// warnings/errors when compiling the current crate, and
738 /// therefore it need not be visible across crates. pnkfelix
739 /// currently hypothesized we *need* to wrap this in a
740 /// `ClearCrossCrate` as long as it carries as `HirId`.
741 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
743 /// `true` if this is an internal local.
745 /// These locals are not based on types in the source code and are only used
746 /// for a few desugarings at the moment.
748 /// The generator transformation will sanity check the locals which are live
749 /// across a suspension point against the type components of the generator
750 /// which type checking knows are live across a suspension point. We need to
751 /// flag drop flags to avoid triggering this check as they are introduced
754 /// Unsafety checking will also ignore dereferences of these locals,
755 /// so they can be used for raw pointers only used in a desugaring.
757 /// This should be sound because the drop flags are fully algebraic, and
758 /// therefore don't affect the OIBIT or outlives properties of the
762 /// If this local is a temporary and `is_block_tail` is `Some`,
763 /// then it is a temporary created for evaluation of some
764 /// subexpression of some block's tail expression (with no
765 /// intervening statement context).
766 pub is_block_tail: Option<BlockTailInfo>,
768 /// Type of this local.
771 /// If the user manually ascribed a type to this variable,
772 /// e.g., via `let x: T`, then we carry that type here. The MIR
773 /// borrow checker needs this information since it can affect
774 /// region inference.
775 pub user_ty: UserTypeProjections,
777 /// Name of the local, used in debuginfo and pretty-printing.
779 /// Note that function arguments can also have this set to `Some(_)`
780 /// to generate better debuginfo.
781 pub name: Option<Name>,
783 /// The *syntactic* (i.e., not visibility) source scope the local is defined
784 /// in. If the local was defined in a let-statement, this
785 /// is *within* the let-statement, rather than outside
788 /// This is needed because the visibility source scope of locals within
789 /// a let-statement is weird.
791 /// The reason is that we want the local to be *within* the let-statement
792 /// for lint purposes, but we want the local to be *after* the let-statement
793 /// for names-in-scope purposes.
795 /// That's it, if we have a let-statement like the one in this
799 /// fn foo(x: &str) {
800 /// #[allow(unused_mut)]
801 /// let mut x: u32 = { // <- one unused mut
802 /// let mut y: u32 = x.parse().unwrap();
809 /// Then, from a lint point of view, the declaration of `x: u32`
810 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
811 /// lint scopes are the same as the AST/HIR nesting.
813 /// However, from a name lookup point of view, the scopes look more like
814 /// as if the let-statements were `match` expressions:
817 /// fn foo(x: &str) {
819 /// match x.parse().unwrap() {
828 /// We care about the name-lookup scopes for debuginfo - if the
829 /// debuginfo instruction pointer is at the call to `x.parse()`, we
830 /// want `x` to refer to `x: &str`, but if it is at the call to
831 /// `drop(x)`, we want it to refer to `x: u32`.
833 /// To allow both uses to work, we need to have more than a single scope
834 /// for a local. We have the `source_info.scope` represent the
835 /// "syntactic" lint scope (with a variable being under its let
836 /// block) while the `visibility_scope` represents the "local variable"
837 /// scope (where the "rest" of a block is under all prior let-statements).
839 /// The end result looks like this:
843 /// │{ argument x: &str }
845 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
846 /// │ │ // in practice because I'm lazy.
848 /// │ │← x.source_info.scope
849 /// │ │← `x.parse().unwrap()`
851 /// │ │ │← y.source_info.scope
853 /// │ │ │{ let y: u32 }
855 /// │ │ │← y.visibility_scope
858 /// │ │{ let x: u32 }
859 /// │ │← x.visibility_scope
860 /// │ │← `drop(x)` // this accesses `x: u32`
862 pub source_info: SourceInfo,
864 /// Source scope within which the local is visible (for debuginfo)
865 /// (see `source_info` for more details).
866 pub visibility_scope: SourceScope,
869 impl<'tcx> LocalDecl<'tcx> {
870 /// Returns `true` only if local is a binding that can itself be
871 /// made mutable via the addition of the `mut` keyword, namely
872 /// something like the occurrences of `x` in:
873 /// - `fn foo(x: Type) { ... }`,
875 /// - or `match ... { C(x) => ... }`
876 pub fn can_be_made_mutable(&self) -> bool {
877 match self.is_user_variable {
878 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
879 binding_mode: ty::BindingMode::BindByValue(_),
885 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
892 /// Returns `true` if local is definitely not a `ref ident` or
893 /// `ref mut ident` binding. (Such bindings cannot be made into
894 /// mutable bindings, but the inverse does not necessarily hold).
895 pub fn is_nonref_binding(&self) -> bool {
896 match self.is_user_variable {
897 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
898 binding_mode: ty::BindingMode::BindByValue(_),
904 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
910 /// Creates a new `LocalDecl` for a temporary.
912 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
913 Self::new_local(ty, Mutability::Mut, false, span)
916 /// Converts `self` into same `LocalDecl` except tagged as immutable.
918 pub fn immutable(mut self) -> Self {
919 self.mutability = Mutability::Not;
923 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
925 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
926 assert!(self.is_block_tail.is_none());
927 self.is_block_tail = Some(info);
931 /// Creates a new `LocalDecl` for a internal temporary.
933 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
934 Self::new_local(ty, Mutability::Mut, true, span)
940 mutability: Mutability,
947 user_ty: UserTypeProjections::none(),
949 source_info: SourceInfo {
951 scope: OUTERMOST_SOURCE_SCOPE,
953 visibility_scope: OUTERMOST_SOURCE_SCOPE,
955 is_user_variable: None,
960 /// Builds a `LocalDecl` for the return place.
962 /// This must be inserted into the `local_decls` list as the first local.
964 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
966 mutability: Mutability::Mut,
968 user_ty: UserTypeProjections::none(),
969 source_info: SourceInfo {
971 scope: OUTERMOST_SOURCE_SCOPE,
973 visibility_scope: OUTERMOST_SOURCE_SCOPE,
976 name: None, // FIXME maybe we do want some name here?
977 is_user_variable: None,
982 /// A closure capture, with its name and mode.
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
984 pub struct UpvarDecl {
985 pub debug_name: Name,
987 /// `HirId` of the captured variable
988 pub var_hir_id: ClearCrossCrate<HirId>,
990 /// If true, the capture is behind a reference.
993 pub mutability: Mutability,
996 ///////////////////////////////////////////////////////////////////////////
1000 pub struct BasicBlock {
1002 DEBUG_FORMAT = "bb{}",
1003 const START_BLOCK = 0,
1008 pub fn start_location(self) -> Location {
1016 ///////////////////////////////////////////////////////////////////////////
1017 // BasicBlockData and Terminator
1019 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1020 pub struct BasicBlockData<'tcx> {
1021 /// List of statements in this block.
1022 pub statements: Vec<Statement<'tcx>>,
1024 /// Terminator for this block.
1026 /// N.B., this should generally ONLY be `None` during construction.
1027 /// Therefore, you should generally access it via the
1028 /// `terminator()` or `terminator_mut()` methods. The only
1029 /// exception is that certain passes, such as `simplify_cfg`, swap
1030 /// out the terminator temporarily with `None` while they continue
1031 /// to recurse over the set of basic blocks.
1032 pub terminator: Option<Terminator<'tcx>>,
1034 /// If true, this block lies on an unwind path. This is used
1035 /// during codegen where distinct kinds of basic blocks may be
1036 /// generated (particularly for MSVC cleanup). Unwind blocks must
1037 /// only branch to other unwind blocks.
1038 pub is_cleanup: bool,
1041 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1042 pub struct Terminator<'tcx> {
1043 pub source_info: SourceInfo,
1044 pub kind: TerminatorKind<'tcx>,
1047 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1048 pub enum TerminatorKind<'tcx> {
1049 /// block should have one successor in the graph; we jump there
1050 Goto { target: BasicBlock },
1052 /// operand evaluates to an integer; jump depending on its value
1053 /// to one of the targets, and otherwise fallback to `otherwise`
1055 /// discriminant value being tested
1056 discr: Operand<'tcx>,
1058 /// type of value being tested
1059 switch_ty: Ty<'tcx>,
1061 /// Possible values. The locations to branch to in each case
1062 /// are found in the corresponding indices from the `targets` vector.
1063 values: Cow<'tcx, [u128]>,
1065 /// Possible branch sites. The last element of this vector is used
1066 /// for the otherwise branch, so targets.len() == values.len() + 1
1068 // This invariant is quite non-obvious and also could be improved.
1069 // One way to make this invariant is to have something like this instead:
1071 // branches: Vec<(ConstInt, BasicBlock)>,
1072 // otherwise: Option<BasicBlock> // exhaustive if None
1074 // However we’ve decided to keep this as-is until we figure a case
1075 // where some other approach seems to be strictly better than other.
1076 targets: Vec<BasicBlock>,
1079 /// Indicates that the landing pad is finished and unwinding should
1080 /// continue. Emitted by build::scope::diverge_cleanup.
1083 /// Indicates that the landing pad is finished and that the process
1084 /// should abort. Used to prevent unwinding for foreign items.
1087 /// Indicates a normal return. The return place should have
1088 /// been filled in by now. This should occur at most once.
1091 /// Indicates a terminator that can never be reached.
1096 location: Place<'tcx>,
1098 unwind: Option<BasicBlock>,
1101 /// Drop the Place and assign the new value over it. This ensures
1102 /// that the assignment to `P` occurs *even if* the destructor for
1103 /// place unwinds. Its semantics are best explained by the
1108 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1116 /// Drop(P, goto BB1, unwind BB2)
1119 /// // P is now uninitialized
1123 /// // P is now uninitialized -- its dtor panicked
1128 location: Place<'tcx>,
1129 value: Operand<'tcx>,
1131 unwind: Option<BasicBlock>,
1134 /// Block ends with a call of a converging function
1136 /// The function that’s being called
1137 func: Operand<'tcx>,
1138 /// Arguments the function is called with.
1139 /// These are owned by the callee, which is free to modify them.
1140 /// This allows the memory occupied by "by-value" arguments to be
1141 /// reused across function calls without duplicating the contents.
1142 args: Vec<Operand<'tcx>>,
1143 /// Destination for the return value. If some, the call is converging.
1144 destination: Option<(Place<'tcx>, BasicBlock)>,
1145 /// Cleanups to be done if the call unwinds.
1146 cleanup: Option<BasicBlock>,
1147 /// Whether this is from a call in HIR, rather than from an overloaded
1148 /// operator. True for overloaded function call.
1149 from_hir_call: bool,
1152 /// Jump to the target if the condition has the expected value,
1153 /// otherwise panic with a message and a cleanup target.
1155 cond: Operand<'tcx>,
1157 msg: AssertMessage<'tcx>,
1159 cleanup: Option<BasicBlock>,
1164 /// The value to return
1165 value: Operand<'tcx>,
1166 /// Where to resume to
1168 /// Cleanup to be done if the generator is dropped at this suspend point
1169 drop: Option<BasicBlock>,
1172 /// Indicates the end of the dropping of a generator
1175 /// A block where control flow only ever takes one real path, but borrowck
1176 /// needs to be more conservative.
1178 /// The target normal control flow will take
1179 real_target: BasicBlock,
1180 /// The list of blocks control flow could conceptually take, but won't
1182 imaginary_targets: Vec<BasicBlock>,
1184 /// A terminator for blocks that only take one path in reality, but where we
1185 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1186 /// This can arise in infinite loops with no function calls for example.
1188 /// The target normal control flow will take
1189 real_target: BasicBlock,
1190 /// The imaginary cleanup block link. This particular path will never be taken
1191 /// in practice, but in order to avoid fragility we want to always
1192 /// consider it in borrowck. We don't want to accept programs which
1193 /// pass borrowck only when panic=abort or some assertions are disabled
1194 /// due to release vs. debug mode builds. This needs to be an Option because
1195 /// of the remove_noop_landing_pads and no_landing_pads passes
1196 unwind: Option<BasicBlock>,
1200 pub type Successors<'a> =
1201 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1202 pub type SuccessorsMut<'a> =
1203 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1205 impl<'tcx> Terminator<'tcx> {
1206 pub fn successors(&self) -> Successors<'_> {
1207 self.kind.successors()
1210 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1211 self.kind.successors_mut()
1214 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1218 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1219 self.kind.unwind_mut()
1223 impl<'tcx> TerminatorKind<'tcx> {
1224 pub fn if_<'a, 'gcx>(
1225 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1226 cond: Operand<'tcx>,
1229 ) -> TerminatorKind<'tcx> {
1230 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1231 TerminatorKind::SwitchInt {
1233 switch_ty: tcx.types.bool,
1234 values: From::from(BOOL_SWITCH_FALSE),
1235 targets: vec![f, t],
1239 pub fn successors(&self) -> Successors<'_> {
1240 use self::TerminatorKind::*;
1251 } => None.into_iter().chain(&[]),
1252 Goto { target: ref t }
1255 cleanup: Some(ref t),
1259 destination: Some((_, ref t)),
1286 } => Some(t).into_iter().chain(&[]),
1288 destination: Some((_, ref t)),
1289 cleanup: Some(ref u),
1299 unwind: Some(ref u),
1304 unwind: Some(ref u),
1309 cleanup: Some(ref u),
1314 unwind: Some(ref u),
1315 } => Some(t).into_iter().chain(slice::from_ref(u)),
1316 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1319 ref imaginary_targets,
1320 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1324 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1325 use self::TerminatorKind::*;
1336 } => None.into_iter().chain(&mut []),
1337 Goto { target: ref mut t }
1340 cleanup: Some(ref mut t),
1344 destination: Some((_, ref mut t)),
1369 real_target: ref mut t,
1371 } => Some(t).into_iter().chain(&mut []),
1373 destination: Some((_, ref mut t)),
1374 cleanup: Some(ref mut u),
1379 drop: Some(ref mut u),
1384 unwind: Some(ref mut u),
1389 unwind: Some(ref mut u),
1394 cleanup: Some(ref mut u),
1398 real_target: ref mut t,
1399 unwind: Some(ref mut u),
1400 } => Some(t).into_iter().chain(slice::from_mut(u)),
1403 } => None.into_iter().chain(&mut targets[..]),
1405 ref mut real_target,
1406 ref mut imaginary_targets,
1407 } => Some(real_target)
1409 .chain(&mut imaginary_targets[..]),
1413 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1415 TerminatorKind::Goto { .. }
1416 | TerminatorKind::Resume
1417 | TerminatorKind::Abort
1418 | TerminatorKind::Return
1419 | TerminatorKind::Unreachable
1420 | TerminatorKind::GeneratorDrop
1421 | TerminatorKind::Yield { .. }
1422 | TerminatorKind::SwitchInt { .. }
1423 | TerminatorKind::FalseEdges { .. } => None,
1424 TerminatorKind::Call {
1425 cleanup: ref unwind,
1428 | TerminatorKind::Assert {
1429 cleanup: ref unwind,
1432 | TerminatorKind::DropAndReplace { ref unwind, .. }
1433 | TerminatorKind::Drop { ref unwind, .. }
1434 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1438 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1440 TerminatorKind::Goto { .. }
1441 | TerminatorKind::Resume
1442 | TerminatorKind::Abort
1443 | TerminatorKind::Return
1444 | TerminatorKind::Unreachable
1445 | TerminatorKind::GeneratorDrop
1446 | TerminatorKind::Yield { .. }
1447 | TerminatorKind::SwitchInt { .. }
1448 | TerminatorKind::FalseEdges { .. } => None,
1449 TerminatorKind::Call {
1450 cleanup: ref mut unwind,
1453 | TerminatorKind::Assert {
1454 cleanup: ref mut unwind,
1457 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1458 | TerminatorKind::Drop { ref mut unwind, .. }
1459 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1464 impl<'tcx> BasicBlockData<'tcx> {
1465 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1473 /// Accessor for terminator.
1475 /// Terminator may not be None after construction of the basic block is complete. This accessor
1476 /// provides a convenience way to reach the terminator.
1477 pub fn terminator(&self) -> &Terminator<'tcx> {
1478 self.terminator.as_ref().expect("invalid terminator state")
1481 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1482 self.terminator.as_mut().expect("invalid terminator state")
1485 pub fn retain_statements<F>(&mut self, mut f: F)
1487 F: FnMut(&mut Statement<'_>) -> bool,
1489 for s in &mut self.statements {
1496 pub fn expand_statements<F, I>(&mut self, mut f: F)
1498 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1499 I: iter::TrustedLen<Item = Statement<'tcx>>,
1501 // Gather all the iterators we'll need to splice in, and their positions.
1502 let mut splices: Vec<(usize, I)> = vec![];
1503 let mut extra_stmts = 0;
1504 for (i, s) in self.statements.iter_mut().enumerate() {
1505 if let Some(mut new_stmts) = f(s) {
1506 if let Some(first) = new_stmts.next() {
1507 // We can already store the first new statement.
1510 // Save the other statements for optimized splicing.
1511 let remaining = new_stmts.size_hint().0;
1513 splices.push((i + 1 + extra_stmts, new_stmts));
1514 extra_stmts += remaining;
1522 // Splice in the new statements, from the end of the block.
1523 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1524 // where a range of elements ("gap") is left uninitialized, with
1525 // splicing adding new elements to the end of that gap and moving
1526 // existing elements from before the gap to the end of the gap.
1527 // For now, this is safe code, emulating a gap but initializing it.
1528 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1529 self.statements.resize(
1532 source_info: SourceInfo {
1534 scope: OUTERMOST_SOURCE_SCOPE,
1536 kind: StatementKind::Nop,
1539 for (splice_start, new_stmts) in splices.into_iter().rev() {
1540 let splice_end = splice_start + new_stmts.size_hint().0;
1541 while gap.end > splice_end {
1544 self.statements.swap(gap.start, gap.end);
1546 self.statements.splice(splice_start..splice_end, new_stmts);
1547 gap.end = splice_start;
1551 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1552 if index < self.statements.len() {
1553 &self.statements[index]
1560 impl<'tcx> Debug for TerminatorKind<'tcx> {
1561 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1562 self.fmt_head(fmt)?;
1563 let successor_count = self.successors().count();
1564 let labels = self.fmt_successor_labels();
1565 assert_eq!(successor_count, labels.len());
1567 match successor_count {
1570 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1573 write!(fmt, " -> [")?;
1574 for (i, target) in self.successors().enumerate() {
1578 write!(fmt, "{}: {:?}", labels[i], target)?;
1586 impl<'tcx> TerminatorKind<'tcx> {
1587 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1588 /// successor basic block, if any. The only information not included is the list of possible
1589 /// successors, which may be rendered differently between the text and the graphviz format.
1590 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1591 use self::TerminatorKind::*;
1593 Goto { .. } => write!(fmt, "goto"),
1595 discr: ref place, ..
1596 } => write!(fmt, "switchInt({:?})", place),
1597 Return => write!(fmt, "return"),
1598 GeneratorDrop => write!(fmt, "generator_drop"),
1599 Resume => write!(fmt, "resume"),
1600 Abort => write!(fmt, "abort"),
1601 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1602 Unreachable => write!(fmt, "unreachable"),
1603 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1608 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1615 if let Some((ref destination, _)) = *destination {
1616 write!(fmt, "{:?} = ", destination)?;
1618 write!(fmt, "{:?}(", func)?;
1619 for (index, arg) in args.iter().enumerate() {
1623 write!(fmt, "{:?}", arg)?;
1633 write!(fmt, "assert(")?;
1637 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1639 FalseEdges { .. } => write!(fmt, "falseEdges"),
1640 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1644 /// Returns the list of labels for the edges to the successor basic blocks.
1645 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1646 use self::TerminatorKind::*;
1648 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1649 Goto { .. } => vec!["".into()],
1655 let size = ty::tls::with(|tcx| {
1656 let param_env = ty::ParamEnv::empty();
1657 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1658 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1663 let mut s = String::new();
1665 val: ConstValue::Scalar(
1668 size: size.bytes() as u8,
1673 fmt_const_val(&mut s, c).unwrap();
1675 }).chain(iter::once("otherwise".into()))
1679 destination: Some(_),
1682 } => vec!["return".into(), "unwind".into()],
1684 destination: Some(_),
1687 } => vec!["return".into()],
1692 } => vec!["unwind".into()],
1698 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1699 Yield { drop: None, .. } => vec!["resume".into()],
1700 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1701 vec!["return".into()]
1708 } => vec!["return".into(), "unwind".into()],
1709 Assert { cleanup: None, .. } => vec!["".into()],
1710 Assert { .. } => vec!["success".into(), "unwind".into()],
1712 ref imaginary_targets,
1715 let mut l = vec!["real".into()];
1716 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1721 } => vec!["real".into(), "cleanup".into()],
1722 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1727 ///////////////////////////////////////////////////////////////////////////
1730 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1731 pub struct Statement<'tcx> {
1732 pub source_info: SourceInfo,
1733 pub kind: StatementKind<'tcx>,
1736 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1737 #[cfg(target_arch = "x86_64")]
1738 static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Statement<'_>>() == 56);
1740 impl<'tcx> Statement<'tcx> {
1741 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1742 /// invalidating statement indices in `Location`s.
1743 pub fn make_nop(&mut self) {
1744 self.kind = StatementKind::Nop
1747 /// Changes a statement to a nop and returns the original statement.
1748 pub fn replace_nop(&mut self) -> Self {
1750 source_info: self.source_info,
1751 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1756 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1757 pub enum StatementKind<'tcx> {
1758 /// Write the RHS Rvalue to the LHS Place.
1759 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1761 /// This represents all the reading that a pattern match may do
1762 /// (e.g., inspecting constants and discriminant values), and the
1763 /// kind of pattern it comes from. This is in order to adapt potential
1764 /// error messages to these specific patterns.
1766 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1767 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1768 FakeRead(FakeReadCause, Place<'tcx>),
1770 /// Write the discriminant for a variant to the enum Place.
1773 variant_index: VariantIdx,
1776 /// Start a live range for the storage of the local.
1779 /// End the current live range for the storage of the local.
1782 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1783 /// of `StatementKind` low.
1784 InlineAsm(Box<InlineAsm<'tcx>>),
1786 /// Retag references in the given place, ensuring they got fresh tags. This is
1787 /// part of the Stacked Borrows model. These statements are currently only interpreted
1788 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1789 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1790 /// for more details.
1791 Retag(RetagKind, Place<'tcx>),
1793 /// Encodes a user's type ascription. These need to be preserved
1794 /// intact so that NLL can respect them. For example:
1798 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1799 /// to the user-given type `T`. The effect depends on the specified variance:
1801 /// - `Covariant` -- requires that `T_y <: T`
1802 /// - `Contravariant` -- requires that `T_y :> T`
1803 /// - `Invariant` -- requires that `T_y == T`
1804 /// - `Bivariant` -- no effect
1805 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1807 /// No-op. Useful for deleting instructions without affecting statement indices.
1811 /// `RetagKind` describes what kind of retag is to be performed.
1812 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1813 pub enum RetagKind {
1814 /// The initial retag when entering a function
1816 /// Retag preparing for a two-phase borrow
1818 /// Retagging raw pointers
1820 /// A "normal" retag
1824 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1825 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1826 pub enum FakeReadCause {
1827 /// Inject a fake read of the borrowed input at the end of each guards
1830 /// This should ensure that you cannot change the variant for an enum while
1831 /// you are in the midst of matching on it.
1834 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1835 /// generate a read of x to check that it is initialized and safe.
1838 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1839 /// in a match guard to ensure that it's value hasn't change by the time
1840 /// we create the OutsideGuard version.
1843 /// Officially, the semantics of
1845 /// `let pattern = <expr>;`
1847 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1848 /// into the pattern.
1850 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1851 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1852 /// but in some cases it can affect the borrow checker, as in #53695.
1853 /// Therefore, we insert a "fake read" here to ensure that we get
1854 /// appropriate errors.
1858 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1859 pub struct InlineAsm<'tcx> {
1860 pub asm: HirInlineAsm,
1861 pub outputs: Box<[Place<'tcx>]>,
1862 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1865 impl<'tcx> Debug for Statement<'tcx> {
1866 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1867 use self::StatementKind::*;
1869 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1870 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1871 Retag(ref kind, ref place) =>
1872 write!(fmt, "Retag({}{:?})",
1874 RetagKind::FnEntry => "[fn entry] ",
1875 RetagKind::TwoPhase => "[2phase] ",
1876 RetagKind::Raw => "[raw] ",
1877 RetagKind::Default => "",
1881 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1882 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1886 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1887 InlineAsm(ref asm) =>
1888 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs),
1889 AscribeUserType(ref place, ref variance, ref c_ty) => {
1890 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1892 Nop => write!(fmt, "nop"),
1897 ///////////////////////////////////////////////////////////////////////////
1900 /// A path to a value; something that can be evaluated without
1901 /// changing or disturbing program state.
1902 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1903 pub enum Place<'tcx> {
1904 Base(PlaceBase<'tcx>),
1906 /// projection out of a place (access a field, deref a pointer, etc)
1907 Projection(Box<PlaceProjection<'tcx>>),
1910 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1911 pub enum PlaceBase<'tcx> {
1915 /// static or static mut variable
1916 Static(Box<Static<'tcx>>),
1919 /// We store the normalized type to avoid requiring normalization when reading MIR
1920 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1921 pub struct Static<'tcx> {
1923 pub kind: StaticKind,
1926 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable)]
1927 pub enum StaticKind {
1932 impl_stable_hash_for!(struct Static<'tcx> {
1937 /// The `Projection` data structure defines things of the form `B.x`
1938 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1939 /// shared between `Constant` and `Place`. See the aliases
1940 /// `PlaceProjection` etc below.
1941 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1942 Hash, RustcEncodable, RustcDecodable, HashStable)]
1943 pub struct Projection<B, V, T> {
1945 pub elem: ProjectionElem<V, T>,
1948 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1949 Hash, RustcEncodable, RustcDecodable, HashStable)]
1950 pub enum ProjectionElem<V, T> {
1955 /// These indices are generated by slice patterns. Easiest to explain
1959 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1960 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1961 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1962 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1965 /// index or -index (in Python terms), depending on from_end
1967 /// thing being indexed must be at least this long
1969 /// counting backwards from end?
1973 /// These indices are generated by slice patterns.
1975 /// slice[from:-to] in Python terms.
1981 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1982 /// this for ADTs with more than one variant. It may be better to
1983 /// just introduce it always, or always for enums.
1985 /// The included Symbol is the name of the variant, used for printing MIR.
1986 Downcast(Option<Symbol>, VariantIdx),
1989 /// Alias for projections as they appear in places, where the base is a place
1990 /// and the index is a local.
1991 pub type PlaceProjection<'tcx> = Projection<Place<'tcx>, Local, Ty<'tcx>>;
1993 /// Alias for projections as they appear in places, where the base is a place
1994 /// and the index is a local.
1995 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1997 // at least on 64 bit systems, `PlaceElem` should not be larger than two pointers
1998 static_assert!(PROJECTION_ELEM_IS_2_PTRS_LARGE:
1999 mem::size_of::<PlaceElem<'_>>() <= 16
2002 /// Alias for projections as they appear in `UserTypeProjection`, where we
2003 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
2004 pub type ProjectionKind = ProjectionElem<(), ()>;
2009 DEBUG_FORMAT = "field[{}]"
2013 impl<'tcx> Place<'tcx> {
2014 pub const RETURN_PLACE: Place<'tcx> = Place::Base(PlaceBase::Local(RETURN_PLACE));
2016 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2017 self.elem(ProjectionElem::Field(f, ty))
2020 pub fn deref(self) -> Place<'tcx> {
2021 self.elem(ProjectionElem::Deref)
2024 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2025 self.elem(ProjectionElem::Downcast(
2026 Some(adt_def.variants[variant_index].ident.name),
2030 pub fn index(self, index: Local) -> Place<'tcx> {
2031 self.elem(ProjectionElem::Index(index))
2034 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2035 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
2038 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2039 /// a single deref of a local.
2041 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2042 pub fn local(&self) -> Option<Local> {
2044 Place::Base(PlaceBase::Local(local)) |
2045 Place::Projection(box Projection {
2046 base: Place::Base(PlaceBase::Local(local)),
2047 elem: ProjectionElem::Deref,
2053 /// Finds the innermost `Local` from this `Place`.
2054 pub fn base_local(&self) -> Option<Local> {
2056 Place::Base(PlaceBase::Local(local)) => Some(*local),
2057 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2058 Place::Base(PlaceBase::Static(..)) => None,
2062 /// Recursively "unroll" a place into a `PlaceComponents` list,
2063 /// invoking `op` with a `PlaceComponentsIter`.
2066 next: Option<&PlaceComponents<'_, 'tcx>>,
2067 op: impl FnOnce(PlaceComponentsIter<'_, 'tcx>) -> R,
2070 Place::Projection(interior) => interior.base.unroll(
2071 Some(&PlaceComponents {
2078 Place::Base(PlaceBase::Local(_)) | Place::Base(PlaceBase::Static(_)) => {
2079 let list = PlaceComponents {
2089 /// A linked list of places running up the stack; begins with the
2090 /// innermost place and extends to projections (e.g., `a.b` would have
2091 /// the place `a` with a "next" pointer to `a.b`). Created by
2092 /// `Place::unroll`.
2094 /// N.B., this particular impl strategy is not the most obvious. It was
2095 /// chosen because it makes a measurable difference to NLL
2096 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
2097 pub struct PlaceComponents<'p, 'tcx: 'p> {
2098 pub component: &'p Place<'tcx>,
2099 pub next: Option<&'p PlaceComponents<'p, 'tcx>>,
2102 impl<'p, 'tcx> PlaceComponents<'p, 'tcx> {
2103 /// Converts a list of `Place` components into an iterator; this
2104 /// iterator yields up a never-ending stream of `Option<&Place>`.
2105 /// These begin with the "innermost" place and then with each
2106 /// projection therefrom. So given a place like `a.b.c` it would
2110 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2112 fn iter(&self) -> PlaceComponentsIter<'_, 'tcx> {
2113 PlaceComponentsIter { value: Some(self) }
2117 /// Iterator over components; see `PlaceComponents::iter` for more
2120 /// N.B., this is not a *true* Rust iterator -- the code above just
2121 /// manually invokes `next`. This is because we (sometimes) want to
2122 /// keep executing even after `None` has been returned.
2123 pub struct PlaceComponentsIter<'p, 'tcx: 'p> {
2124 pub value: Option<&'p PlaceComponents<'p, 'tcx>>,
2127 impl<'p, 'tcx> PlaceComponentsIter<'p, 'tcx> {
2128 pub fn next(&mut self) -> Option<&'p Place<'tcx>> {
2129 if let Some(&PlaceComponents { component, next }) = self.value {
2138 impl<'tcx> Debug for Place<'tcx> {
2139 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2143 Base(PlaceBase::Local(id)) => write!(fmt, "{:?}", id),
2144 Base(PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) })) => {
2148 ty::tls::with(|tcx| tcx.def_path_str(def_id)),
2152 Base(PlaceBase::Static(
2153 box self::Static { ty, kind: StaticKind::Promoted(promoted) })
2162 Projection(ref data) => match data.elem {
2163 ProjectionElem::Downcast(Some(name), _index) => {
2164 write!(fmt, "({:?} as {})", data.base, name)
2166 ProjectionElem::Downcast(None, index) => {
2167 write!(fmt, "({:?} as variant#{:?})", data.base, index)
2169 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2170 ProjectionElem::Field(field, ty) => {
2171 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2173 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2174 ProjectionElem::ConstantIndex {
2178 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2179 ProjectionElem::ConstantIndex {
2183 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2184 ProjectionElem::Subslice { from, to } if to == 0 => {
2185 write!(fmt, "{:?}[{:?}:]", data.base, from)
2187 ProjectionElem::Subslice { from, to } if from == 0 => {
2188 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2190 ProjectionElem::Subslice { from, to } => {
2191 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2198 ///////////////////////////////////////////////////////////////////////////
2202 pub struct SourceScope {
2204 DEBUG_FORMAT = "scope[{}]",
2205 const OUTERMOST_SOURCE_SCOPE = 0,
2209 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2210 pub struct SourceScopeData {
2212 pub parent_scope: Option<SourceScope>,
2215 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2216 pub struct SourceScopeLocalData {
2217 /// A HirId with lint levels equivalent to this scope's lint levels.
2218 pub lint_root: hir::HirId,
2219 /// The unsafe block that contains this node.
2223 ///////////////////////////////////////////////////////////////////////////
2226 /// These are values that can appear inside an rvalue. They are intentionally
2227 /// limited to prevent rvalues from being nested in one another.
2228 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2229 pub enum Operand<'tcx> {
2230 /// Copy: The value must be available for use afterwards.
2232 /// This implies that the type of the place must be `Copy`; this is true
2233 /// by construction during build, but also checked by the MIR type checker.
2236 /// Move: The value (including old borrows of it) will not be used again.
2238 /// Safe for values of all types (modulo future developments towards `?Move`).
2239 /// Correct usage patterns are enforced by the borrow checker for safe code.
2240 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2243 /// Synthesizes a constant value.
2244 Constant(Box<Constant<'tcx>>),
2247 impl<'tcx> Debug for Operand<'tcx> {
2248 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2249 use self::Operand::*;
2251 Constant(ref a) => write!(fmt, "{:?}", a),
2252 Copy(ref place) => write!(fmt, "{:?}", place),
2253 Move(ref place) => write!(fmt, "move {:?}", place),
2258 impl<'tcx> Operand<'tcx> {
2259 /// Convenience helper to make a constant that refers to the fn
2260 /// with given `DefId` and substs. Since this is used to synthesize
2261 /// MIR, assumes `user_ty` is None.
2262 pub fn function_handle<'a>(
2263 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2265 substs: SubstsRef<'tcx>,
2268 let ty = tcx.type_of(def_id).subst(tcx, substs);
2269 Operand::Constant(box Constant {
2273 literal: tcx.mk_const(
2274 ty::Const::zero_sized(ty),
2279 pub fn to_copy(&self) -> Self {
2281 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2282 Operand::Move(ref place) => Operand::Copy(place.clone()),
2287 ///////////////////////////////////////////////////////////////////////////
2290 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2291 pub enum Rvalue<'tcx> {
2292 /// x (either a move or copy, depending on type of x)
2296 Repeat(Operand<'tcx>, u64),
2299 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2301 /// length of a [X] or [X;n] value
2304 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2306 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2307 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2309 NullaryOp(NullOp, Ty<'tcx>),
2310 UnaryOp(UnOp, Operand<'tcx>),
2312 /// Read the discriminant of an ADT.
2314 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2315 /// be defined to return, say, a 0) if ADT is not an enum.
2316 Discriminant(Place<'tcx>),
2318 /// Creates an aggregate value, like a tuple or struct. This is
2319 /// only needed because we want to distinguish `dest = Foo { x:
2320 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2321 /// that `Foo` has a destructor. These rvalues can be optimized
2322 /// away after type-checking and before lowering.
2323 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2326 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2330 /// Converts unique, zero-sized type for a fn to fn()
2333 /// Converts non capturing closure to fn() or unsafe fn().
2334 /// It cannot convert a closure that requires unsafe.
2335 ClosureFnPointer(hir::Unsafety),
2337 /// Converts safe fn() to unsafe fn()
2340 /// Coerces *mut T to *const T, preserving T.
2343 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2344 /// codegen must figure out the details once full monomorphization
2345 /// is known. For example, this could be used to cast from a
2346 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<dyn Trait>`
2347 /// (presuming `T: Trait`).
2351 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2352 pub enum AggregateKind<'tcx> {
2353 /// The type is of the element
2357 /// The second field is the variant index. It's equal to 0 for struct
2358 /// and union expressions. The fourth field is
2359 /// active field number and is present only for union expressions
2360 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2361 /// active field index would identity the field `c`
2366 Option<UserTypeAnnotationIndex>,
2370 Closure(DefId, ClosureSubsts<'tcx>),
2371 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2374 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2376 /// The `+` operator (addition)
2378 /// The `-` operator (subtraction)
2380 /// The `*` operator (multiplication)
2382 /// The `/` operator (division)
2384 /// The `%` operator (modulus)
2386 /// The `^` operator (bitwise xor)
2388 /// The `&` operator (bitwise and)
2390 /// The `|` operator (bitwise or)
2392 /// The `<<` operator (shift left)
2394 /// The `>>` operator (shift right)
2396 /// The `==` operator (equality)
2398 /// The `<` operator (less than)
2400 /// The `<=` operator (less than or equal to)
2402 /// The `!=` operator (not equal to)
2404 /// The `>=` operator (greater than or equal to)
2406 /// The `>` operator (greater than)
2408 /// The `ptr.offset` operator
2413 pub fn is_checkable(self) -> bool {
2416 Add | Sub | Mul | Shl | Shr => true,
2422 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2424 /// Returns the size of a value of that type
2426 /// Creates a new uninitialized box for a value of that type
2430 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2432 /// The `!` operator for logical inversion
2434 /// The `-` operator for negation
2438 impl<'tcx> Debug for Rvalue<'tcx> {
2439 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2440 use self::Rvalue::*;
2443 Use(ref place) => write!(fmt, "{:?}", place),
2444 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2445 Len(ref a) => write!(fmt, "Len({:?})", a),
2446 Cast(ref kind, ref place, ref ty) => {
2447 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2449 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2450 CheckedBinaryOp(ref op, ref a, ref b) => {
2451 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2453 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2454 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2455 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2456 Ref(region, borrow_kind, ref place) => {
2457 let kind_str = match borrow_kind {
2458 BorrowKind::Shared => "",
2459 BorrowKind::Shallow => "shallow ",
2460 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2463 // When printing regions, add trailing space if necessary.
2464 let print_region = ty::tls::with(|tcx| {
2465 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2467 let region = if print_region {
2468 let mut region = region.to_string();
2469 if region.len() > 0 {
2474 // Do not even print 'static
2477 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2480 Aggregate(ref kind, ref places) => {
2481 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2482 let mut tuple_fmt = fmt.debug_tuple("");
2483 for place in places {
2484 tuple_fmt.field(place);
2490 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2492 AggregateKind::Tuple => match places.len() {
2493 0 => write!(fmt, "()"),
2494 1 => write!(fmt, "({:?},)", places[0]),
2495 _ => fmt_tuple(fmt, places),
2498 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2499 let variant_def = &adt_def.variants[variant];
2502 ty::tls::with(|tcx| {
2503 let substs = tcx.lift(&substs).expect("could not lift for printing");
2504 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2505 .print_def_path(variant_def.def_id, substs)?;
2509 match variant_def.ctor_kind {
2510 CtorKind::Const => Ok(()),
2511 CtorKind::Fn => fmt_tuple(fmt, places),
2512 CtorKind::Fictive => {
2513 let mut struct_fmt = fmt.debug_struct("");
2514 for (field, place) in variant_def.fields.iter().zip(places) {
2515 struct_fmt.field(&field.ident.as_str(), place);
2522 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2523 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2524 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2525 format!("[closure@{:?}]", hir_id)
2527 format!("[closure@{:?}]", tcx.hir().span_by_hir_id(hir_id))
2529 let mut struct_fmt = fmt.debug_struct(&name);
2531 tcx.with_freevars(hir_id, |freevars| {
2532 for (freevar, place) in freevars.iter().zip(places) {
2533 let var_name = tcx.hir().name_by_hir_id(freevar.var_id());
2534 struct_fmt.field(&var_name.as_str(), place);
2540 write!(fmt, "[closure]")
2544 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2545 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2546 let name = format!("[generator@{:?}]",
2547 tcx.hir().span_by_hir_id(hir_id));
2548 let mut struct_fmt = fmt.debug_struct(&name);
2550 tcx.with_freevars(hir_id, |freevars| {
2551 for (freevar, place) in freevars.iter().zip(places) {
2552 let var_name = tcx.hir().name_by_hir_id(freevar.var_id());
2553 struct_fmt.field(&var_name.as_str(), place);
2555 struct_fmt.field("$state", &places[freevars.len()]);
2556 for i in (freevars.len() + 1)..places.len() {
2558 .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2564 write!(fmt, "[generator]")
2573 ///////////////////////////////////////////////////////////////////////////
2576 /// Two constants are equal if they are the same constant. Note that
2577 /// this does not necessarily mean that they are "==" in Rust -- in
2578 /// particular one must be wary of `NaN`!
2580 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2581 pub struct Constant<'tcx> {
2585 /// Optional user-given type: for something like
2586 /// `collect::<Vec<_>>`, this would be present and would
2587 /// indicate that `Vec<_>` was explicitly specified.
2589 /// Needed for NLL to impose user-given type constraints.
2590 pub user_ty: Option<UserTypeAnnotationIndex>,
2592 pub literal: &'tcx ty::Const<'tcx>,
2595 /// A collection of projections into user types.
2597 /// They are projections because a binding can occur a part of a
2598 /// parent pattern that has been ascribed a type.
2600 /// Its a collection because there can be multiple type ascriptions on
2601 /// the path from the root of the pattern down to the binding itself.
2606 /// struct S<'a>((i32, &'a str), String);
2607 /// let S((_, w): (i32, &'static str), _): S = ...;
2608 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2609 /// // --------------------------------- ^ (2)
2612 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2613 /// ascribed the type `(i32, &'static str)`.
2615 /// The highlights labelled `(2)` show the whole pattern being
2616 /// ascribed the type `S`.
2618 /// In this example, when we descend to `w`, we will have built up the
2619 /// following two projected types:
2621 /// * base: `S`, projection: `(base.0).1`
2622 /// * base: `(i32, &'static str)`, projection: `base.1`
2624 /// The first will lead to the constraint `w: &'1 str` (for some
2625 /// inferred region `'1`). The second will lead to the constraint `w:
2627 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2628 pub struct UserTypeProjections {
2629 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2632 BraceStructTypeFoldableImpl! {
2633 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2638 impl<'tcx> UserTypeProjections {
2639 pub fn none() -> Self {
2640 UserTypeProjections { contents: vec![] }
2643 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection, Span)>) -> Self {
2644 UserTypeProjections { contents: projs.collect() }
2647 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection, Span)> {
2648 self.contents.iter()
2651 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection> {
2652 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2655 pub fn push_projection(
2657 user_ty: &UserTypeProjection,
2660 self.contents.push((user_ty.clone(), span));
2666 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection
2668 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2672 pub fn index(self) -> Self {
2673 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2676 pub fn subslice(self, from: u32, to: u32) -> Self {
2677 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2680 pub fn deref(self) -> Self {
2681 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2684 pub fn leaf(self, field: Field) -> Self {
2685 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2690 adt_def: &'tcx AdtDef,
2691 variant_index: VariantIdx,
2694 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2698 /// Encodes the effect of a user-supplied type annotation on the
2699 /// subcomponents of a pattern. The effect is determined by applying the
2700 /// given list of proejctions to some underlying base type. Often,
2701 /// the projection element list `projs` is empty, in which case this
2702 /// directly encodes a type in `base`. But in the case of complex patterns with
2703 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2704 /// in which case the `projs` vector is used.
2708 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2710 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2711 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2712 /// determined by finding the type of the `.0` field from `T`.
2713 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2714 pub struct UserTypeProjection {
2715 pub base: UserTypeAnnotationIndex,
2716 pub projs: Vec<ProjectionElem<(), ()>>,
2719 impl Copy for ProjectionKind { }
2721 impl UserTypeProjection {
2722 pub(crate) fn index(mut self) -> Self {
2723 self.projs.push(ProjectionElem::Index(()));
2727 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2728 self.projs.push(ProjectionElem::Subslice { from, to });
2732 pub(crate) fn deref(mut self) -> Self {
2733 self.projs.push(ProjectionElem::Deref);
2737 pub(crate) fn leaf(mut self, field: Field) -> Self {
2738 self.projs.push(ProjectionElem::Field(field, ()));
2742 pub(crate) fn variant(
2744 adt_def: &'tcx AdtDef,
2745 variant_index: VariantIdx,
2748 self.projs.push(ProjectionElem::Downcast(
2749 Some(adt_def.variants[variant_index].ident.name),
2751 self.projs.push(ProjectionElem::Field(field, ()));
2756 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2758 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2759 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2760 use crate::mir::ProjectionElem::*;
2762 let base = self.base.fold_with(folder);
2763 let projs: Vec<_> = self.projs
2768 Field(f, ()) => Field(f.clone(), ()),
2769 Index(()) => Index(()),
2770 elem => elem.clone(),
2774 UserTypeProjection { base, projs }
2777 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2778 self.base.visit_with(visitor)
2779 // Note: there's nothing in `self.proj` to visit.
2784 pub struct Promoted {
2786 DEBUG_FORMAT = "promoted[{}]"
2790 impl<'tcx> Debug for Constant<'tcx> {
2791 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2792 write!(fmt, "const ")?;
2793 fmt_const_val(fmt, *self.literal)
2796 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2797 pub fn fmt_const_val(f: &mut impl Write, const_val: ty::Const<'_>) -> fmt::Result {
2798 use crate::ty::TyKind::*;
2799 let value = const_val.val;
2800 let ty = const_val.ty;
2801 // print some primitives
2802 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2804 Bool if bits == 0 => return write!(f, "false"),
2805 Bool if bits == 1 => return write!(f, "true"),
2806 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2807 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2808 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2810 let bit_width = ty::tls::with(|tcx| {
2811 let ty = tcx.lift_to_global(&ty).unwrap();
2812 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2817 let shift = 128 - bit_width;
2818 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2820 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2824 // print function definitions
2825 if let FnDef(did, _) = ty.sty {
2826 return write!(f, "{}", def_path_str(did));
2828 // print string literals
2829 if let ConstValue::Slice(ptr, len) = value {
2830 if let Scalar::Ptr(ptr) = ptr {
2831 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2832 return ty::tls::with(|tcx| {
2833 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2834 if let Some(interpret::AllocKind::Memory(alloc)) = alloc {
2835 assert_eq!(len as usize as u64, len);
2837 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2838 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2839 write!(f, "{:?}", s)
2841 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2847 // just raw dump everything else
2848 write!(f, "{:?} : {}", value, ty)
2851 fn def_path_str(def_id: DefId) -> String {
2852 ty::tls::with(|tcx| tcx.def_path_str(def_id))
2855 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2856 type Node = BasicBlock;
2859 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2860 fn num_nodes(&self) -> usize {
2861 self.basic_blocks.len()
2865 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2866 fn start_node(&self) -> Self::Node {
2871 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2872 fn predecessors<'graph>(
2875 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2876 self.predecessors_for(node).clone().into_iter()
2880 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2881 fn successors<'graph>(
2884 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2885 self.basic_blocks[node].terminator().successors().cloned()
2889 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2890 type Item = BasicBlock;
2891 type Iter = IntoIter<BasicBlock>;
2894 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2895 type Item = BasicBlock;
2896 type Iter = iter::Cloned<Successors<'b>>;
2899 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2900 pub struct Location {
2901 /// the location is within this block
2902 pub block: BasicBlock,
2904 /// the location is the start of the statement; or, if `statement_index`
2905 /// == num-statements, then the start of the terminator.
2906 pub statement_index: usize,
2909 impl fmt::Debug for Location {
2910 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2911 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2916 pub const START: Location = Location {
2921 /// Returns the location immediately after this one within the enclosing block.
2923 /// Note that if this location represents a terminator, then the
2924 /// resulting location would be out of bounds and invalid.
2925 pub fn successor_within_block(&self) -> Location {
2928 statement_index: self.statement_index + 1,
2932 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2933 pub fn is_predecessor_of<'tcx>(&self, other: Location, mir: &Mir<'tcx>) -> bool {
2934 // If we are in the same block as the other location and are an earlier statement
2935 // then we are a predecessor of `other`.
2936 if self.block == other.block && self.statement_index < other.statement_index {
2940 // If we're in another block, then we want to check that block is a predecessor of `other`.
2941 let mut queue: Vec<BasicBlock> = mir.predecessors_for(other.block).clone();
2942 let mut visited = FxHashSet::default();
2944 while let Some(block) = queue.pop() {
2945 // If we haven't visited this block before, then make sure we visit it's predecessors.
2946 if visited.insert(block) {
2947 queue.append(&mut mir.predecessors_for(block).clone());
2952 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2953 // we found that block by looking at the predecessors of `other`).
2954 if self.block == block {
2962 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2963 if self.block == other.block {
2964 self.statement_index <= other.statement_index
2966 dominators.is_dominated_by(other.block, self.block)
2971 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2972 pub enum UnsafetyViolationKind {
2974 /// Permitted in const fn and regular fns.
2976 ExternStatic(hir::HirId),
2977 BorrowPacked(hir::HirId),
2980 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2981 pub struct UnsafetyViolation {
2982 pub source_info: SourceInfo,
2983 pub description: InternedString,
2984 pub details: InternedString,
2985 pub kind: UnsafetyViolationKind,
2988 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2989 pub struct UnsafetyCheckResult {
2990 /// Violations that are propagated *upwards* from this function
2991 pub violations: Lrc<[UnsafetyViolation]>,
2992 /// unsafe blocks in this function, along with whether they are used. This is
2993 /// used for the "unused_unsafe" lint.
2994 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2997 /// The layout of generator state
2998 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2999 pub struct GeneratorLayout<'tcx> {
3000 pub fields: Vec<LocalDecl<'tcx>>,
3003 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3004 pub struct BorrowCheckResult<'gcx> {
3005 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
3006 pub used_mut_upvars: SmallVec<[Field; 8]>,
3009 /// After we borrow check a closure, we are left with various
3010 /// requirements that we have inferred between the free regions that
3011 /// appear in the closure's signature or on its field types. These
3012 /// requirements are then verified and proved by the closure's
3013 /// creating function. This struct encodes those requirements.
3015 /// The requirements are listed as being between various
3016 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
3017 /// vids refer to the free regions that appear in the closure (or
3018 /// generator's) type, in order of appearance. (This numbering is
3019 /// actually defined by the `UniversalRegions` struct in the NLL
3020 /// region checker. See for example
3021 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
3022 /// regions in the closure's type "as if" they were erased, so their
3023 /// precise identity is not important, only their position.
3025 /// Example: If type check produces a closure with the closure substs:
3028 /// ClosureSubsts = [
3029 /// i8, // the "closure kind"
3030 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
3031 /// &'a String, // some upvar
3035 /// here, there is one unique free region (`'a`) but it appears
3036 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
3039 /// ClosureSubsts = [
3040 /// i8, // the "closure kind"
3041 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
3042 /// &'2 String, // some upvar
3046 /// Now the code might impose a requirement like `'1: '2`. When an
3047 /// instance of the closure is created, the corresponding free regions
3048 /// can be extracted from its type and constrained to have the given
3049 /// outlives relationship.
3051 /// In some cases, we have to record outlives requirements between
3052 /// types and regions as well. In that case, if those types include
3053 /// any regions, those regions are recorded as `ReClosureBound`
3054 /// instances assigned one of these same indices. Those regions will
3055 /// be substituted away by the creator. We use `ReClosureBound` in
3056 /// that case because the regions must be allocated in the global
3057 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
3058 /// internally within the rest of the NLL code).
3059 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3060 pub struct ClosureRegionRequirements<'gcx> {
3061 /// The number of external regions defined on the closure. In our
3062 /// example above, it would be 3 -- one for `'static`, then `'1`
3063 /// and `'2`. This is just used for a sanity check later on, to
3064 /// make sure that the number of regions we see at the callsite
3066 pub num_external_vids: usize,
3068 /// Requirements between the various free regions defined in
3070 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
3073 /// Indicates an outlives constraint between a type or between two
3074 /// free-regions declared on the closure.
3075 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3076 pub struct ClosureOutlivesRequirement<'tcx> {
3077 // This region or type ...
3078 pub subject: ClosureOutlivesSubject<'tcx>,
3080 // ... must outlive this one.
3081 pub outlived_free_region: ty::RegionVid,
3083 // If not, report an error here ...
3084 pub blame_span: Span,
3086 // ... due to this reason.
3087 pub category: ConstraintCategory,
3090 /// Outlives constraints can be categorized to determine whether and why they
3091 /// are interesting (for error reporting). Order of variants indicates sort
3092 /// order of the category, thereby influencing diagnostic output.
3094 /// See also [rustc_mir::borrow_check::nll::constraints]
3095 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
3096 Hash, RustcEncodable, RustcDecodable, HashStable)]
3097 pub enum ConstraintCategory {
3105 /// A constraint that came from checking the body of a closure.
3107 /// We try to get the category that the closure used when reporting this.
3115 /// A "boring" constraint (caused by the given location) is one that
3116 /// the user probably doesn't want to see described in diagnostics,
3117 /// because it is kind of an artifact of the type system setup.
3118 /// Example: `x = Foo { field: y }` technically creates
3119 /// intermediate regions representing the "type of `Foo { field: y
3120 /// }`", and data flows from `y` into those variables, but they
3121 /// are not very interesting. The assignment into `x` on the other
3124 // Boring and applicable everywhere.
3127 /// A constraint that doesn't correspond to anything the user sees.
3131 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
3132 /// that must outlive some region.
3133 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3134 pub enum ClosureOutlivesSubject<'tcx> {
3135 /// Subject is a type, typically a type parameter, but could also
3136 /// be a projection. Indicates a requirement like `T: 'a` being
3137 /// passed to the caller, where the type here is `T`.
3139 /// The type here is guaranteed not to contain any free regions at
3143 /// Subject is a free region from the closure. Indicates a requirement
3144 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3145 Region(ty::RegionVid),
3149 * TypeFoldable implementations for MIR types
3152 CloneTypeFoldableAndLiftImpls! {
3162 SourceScopeLocalData,
3163 UserTypeAnnotationIndex,
3166 BraceStructTypeFoldableImpl! {
3167 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
3171 source_scope_local_data,
3177 user_type_annotations,
3181 control_flow_destroyed,
3187 BraceStructTypeFoldableImpl! {
3188 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3193 BraceStructTypeFoldableImpl! {
3194 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3207 BraceStructTypeFoldableImpl! {
3208 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3215 BraceStructTypeFoldableImpl! {
3216 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3221 EnumTypeFoldableImpl! {
3222 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3223 (StatementKind::Assign)(a, b),
3224 (StatementKind::FakeRead)(cause, place),
3225 (StatementKind::SetDiscriminant) { place, variant_index },
3226 (StatementKind::StorageLive)(a),
3227 (StatementKind::StorageDead)(a),
3228 (StatementKind::InlineAsm)(a),
3229 (StatementKind::Retag)(kind, place),
3230 (StatementKind::AscribeUserType)(a, v, b),
3231 (StatementKind::Nop),
3235 BraceStructTypeFoldableImpl! {
3236 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3243 EnumTypeFoldableImpl! {
3244 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3245 (ClearCrossCrate::Clear),
3246 (ClearCrossCrate::Set)(a),
3247 } where T: TypeFoldable<'tcx>
3250 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3251 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3252 use crate::mir::TerminatorKind::*;
3254 let kind = match self.kind {
3255 Goto { target } => Goto { target },
3262 discr: discr.fold_with(folder),
3263 switch_ty: switch_ty.fold_with(folder),
3264 values: values.clone(),
3265 targets: targets.clone(),
3272 location: location.fold_with(folder),
3281 } => DropAndReplace {
3282 location: location.fold_with(folder),
3283 value: value.fold_with(folder),
3292 value: value.fold_with(folder),
3303 let dest = destination
3305 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3308 func: func.fold_with(folder),
3309 args: args.fold_with(folder),
3322 let msg = if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3323 InterpError::BoundsCheck {
3324 len: len.fold_with(folder),
3325 index: index.fold_with(folder),
3331 cond: cond.fold_with(folder),
3338 GeneratorDrop => GeneratorDrop,
3342 Unreachable => Unreachable,
3345 ref imaginary_targets,
3348 imaginary_targets: imaginary_targets.clone(),
3359 source_info: self.source_info,
3364 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3365 use crate::mir::TerminatorKind::*;
3372 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3373 Drop { ref location, .. } => location.visit_with(visitor),
3378 } => location.visit_with(visitor) || value.visit_with(visitor),
3379 Yield { ref value, .. } => value.visit_with(visitor),
3386 let dest = if let Some((ref loc, _)) = *destination {
3387 loc.visit_with(visitor)
3391 dest || func.visit_with(visitor) || args.visit_with(visitor)
3394 ref cond, ref msg, ..
3396 if cond.visit_with(visitor) {
3397 if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3398 len.visit_with(visitor) || index.visit_with(visitor)
3413 | FalseUnwind { .. } => false,
3418 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3419 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3421 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3426 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3427 if let &Place::Projection(ref p) = self {
3428 p.visit_with(visitor)
3435 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3436 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3437 use crate::mir::Rvalue::*;
3439 Use(ref op) => Use(op.fold_with(folder)),
3440 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3441 Ref(region, bk, ref place) => {
3442 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3444 Len(ref place) => Len(place.fold_with(folder)),
3445 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3446 BinaryOp(op, ref rhs, ref lhs) => {
3447 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3449 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3450 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3452 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3453 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3454 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3455 Aggregate(ref kind, ref fields) => {
3456 let kind = box match **kind {
3457 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3458 AggregateKind::Tuple => AggregateKind::Tuple,
3459 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3462 substs.fold_with(folder),
3463 user_ty.fold_with(folder),
3466 AggregateKind::Closure(id, substs) => {
3467 AggregateKind::Closure(id, substs.fold_with(folder))
3469 AggregateKind::Generator(id, substs, movablity) => {
3470 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3473 Aggregate(kind, fields.fold_with(folder))
3478 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3479 use crate::mir::Rvalue::*;
3481 Use(ref op) => op.visit_with(visitor),
3482 Repeat(ref op, _) => op.visit_with(visitor),
3483 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3484 Len(ref place) => place.visit_with(visitor),
3485 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3486 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3487 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3489 UnaryOp(_, ref val) => val.visit_with(visitor),
3490 Discriminant(ref place) => place.visit_with(visitor),
3491 NullaryOp(_, ty) => ty.visit_with(visitor),
3492 Aggregate(ref kind, ref fields) => {
3494 AggregateKind::Array(ty) => ty.visit_with(visitor),
3495 AggregateKind::Tuple => false,
3496 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3497 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3499 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3500 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3501 }) || fields.visit_with(visitor)
3507 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3508 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3510 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3511 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3512 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3516 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3518 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3519 Operand::Constant(ref c) => c.visit_with(visitor),
3524 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<B, V, T>
3526 B: TypeFoldable<'tcx>,
3527 V: TypeFoldable<'tcx>,
3528 T: TypeFoldable<'tcx>,
3530 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3531 use crate::mir::ProjectionElem::*;
3533 let base = self.base.fold_with(folder);
3534 let elem = match self.elem {
3536 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3537 Index(ref v) => Index(v.fold_with(folder)),
3538 ref elem => elem.clone(),
3541 Projection { base, elem }
3544 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3545 use crate::mir::ProjectionElem::*;
3547 self.base.visit_with(visitor) || match self.elem {
3548 Field(_, ref ty) => ty.visit_with(visitor),
3549 Index(ref v) => v.visit_with(visitor),
3555 impl<'tcx> TypeFoldable<'tcx> for Field {
3556 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3559 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3564 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3565 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3567 span: self.span.clone(),
3568 ty: self.ty.fold_with(folder),
3569 user_ty: self.user_ty.fold_with(folder),
3570 literal: self.literal.fold_with(folder),
3573 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3574 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)