1 // ignore-tidy-filelength
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, InlineAsm as HirInlineAsm};
10 use crate::mir::interpret::{ConstValue, InterpError, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use 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, Display};
23 use std::iter::FusedIterator;
24 use std::ops::{Index, IndexMut};
26 use std::vec::IntoIter;
27 use std::{iter, mem, option, u32};
28 use syntax::ast::Name;
29 use syntax::symbol::{InternedString, Symbol};
30 use syntax_pos::{Span, DUMMY_SP};
31 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
32 use crate::ty::subst::{Subst, SubstsRef};
33 use crate::ty::layout::VariantIdx;
35 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
36 UserTypeAnnotationIndex,
38 use crate::ty::print::{FmtPrinter, Printer};
39 use crate::ty::adjustment::{PointerCast};
41 pub use crate::mir::interpret::AssertMessage;
51 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
53 pub trait HasLocalDecls<'tcx> {
54 fn local_decls(&self) -> &LocalDecls<'tcx>;
57 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx> {
63 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
64 fn local_decls(&self) -> &LocalDecls<'tcx> {
69 /// The various "big phases" that MIR goes through.
71 /// Warning: ordering of variants is significant
72 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
81 /// Gets the index of the current MirPhase within the set of all MirPhases.
82 pub fn phase_index(&self) -> usize {
87 /// Lowered representation of a single function.
88 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
89 pub struct Body<'tcx> {
90 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
91 /// that indexes into this vector.
92 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
94 /// Records how far through the "desugaring and optimization" process this particular
95 /// MIR has traversed. This is particularly useful when inlining, since in that context
96 /// we instantiate the promoted constants and add them to our promoted vector -- but those
97 /// promoted items have already been optimized, whereas ours have not. This field allows
98 /// us to see the difference and forego optimization on the inlined promoted items.
101 /// List of source scopes; these are referenced by statements
102 /// and used for debuginfo. Indexed by a `SourceScope`.
103 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
105 /// Crate-local information for each source scope, that can't (and
106 /// needn't) be tracked across crates.
107 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
109 /// Rvalues promoted from this function, such as borrows of constants.
110 /// Each of them is the Body of a constant with the fn's type parameters
111 /// in scope, but a separate set of locals.
112 pub promoted: IndexVec<Promoted, Body<'tcx>>,
114 /// Yields type of the function, if it is a generator.
115 pub yield_ty: Option<Ty<'tcx>>,
117 /// Generator drop glue
118 pub generator_drop: Option<Box<Body<'tcx>>>,
120 /// The layout of a generator. Produced by the state transformation.
121 pub generator_layout: Option<GeneratorLayout<'tcx>>,
123 /// Declarations of locals.
125 /// The first local is the return value pointer, followed by `arg_count`
126 /// locals for the function arguments, followed by any user-declared
127 /// variables and temporaries.
128 pub local_decls: LocalDecls<'tcx>,
130 /// User type annotations
131 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
133 /// Number of arguments this function takes.
135 /// Starting at local 1, `arg_count` locals will be provided by the caller
136 /// and can be assumed to be initialized.
138 /// If this MIR was built for a constant, this will be 0.
139 pub arg_count: usize,
141 /// Mark an argument local (which must be a tuple) as getting passed as
142 /// its individual components at the LLVM level.
144 /// This is used for the "rust-call" ABI.
145 pub spread_arg: Option<Local>,
147 /// Names and capture modes of all the closure upvars, assuming
148 /// the first argument is either the closure or a reference to it.
149 // NOTE(eddyb) This is *strictly* a temporary hack for codegen
150 // debuginfo generation, and will be removed at some point.
151 // Do **NOT** use it for anything else, upvar information should not be
152 // in the MIR, please rely on local crate HIR or other side-channels.
153 pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
155 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
156 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
157 /// this conversion from happening and use short circuiting, we will cause the following code
158 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
160 /// List of places where control flow was destroyed. Used for error reporting.
161 pub control_flow_destroyed: Vec<(Span, String)>,
163 /// A span representing this MIR, for error reporting
166 /// A cache for various calculations
170 impl<'tcx> Body<'tcx> {
172 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
173 source_scopes: IndexVec<SourceScope, SourceScopeData>,
174 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
175 promoted: IndexVec<Promoted, Body<'tcx>>,
176 yield_ty: Option<Ty<'tcx>>,
177 local_decls: LocalDecls<'tcx>,
178 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
180 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
182 control_flow_destroyed: Vec<(Span, String)>,
184 // We need `arg_count` locals, and one for the return place
186 local_decls.len() >= arg_count + 1,
187 "expected at least {} locals, got {}",
193 phase: MirPhase::Build,
196 source_scope_local_data,
199 generator_drop: None,
200 generator_layout: None,
202 user_type_annotations,
204 __upvar_debuginfo_codegen_only_do_not_use,
207 cache: cache::Cache::new(),
208 control_flow_destroyed,
213 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
218 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
219 self.cache.invalidate();
220 &mut self.basic_blocks
224 pub fn basic_blocks_and_local_decls_mut(
227 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
228 &mut LocalDecls<'tcx>,
230 self.cache.invalidate();
231 (&mut self.basic_blocks, &mut self.local_decls)
235 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
236 self.cache.predecessors(self)
240 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
241 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
245 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
246 let if_zero_locations = if loc.statement_index == 0 {
247 let predecessor_blocks = self.predecessors_for(loc.block);
248 let num_predecessor_blocks = predecessor_blocks.len();
250 (0..num_predecessor_blocks)
251 .map(move |i| predecessor_blocks[i])
252 .map(move |bb| self.terminator_loc(bb)),
258 let if_not_zero_locations = if loc.statement_index == 0 {
263 statement_index: loc.statement_index - 1,
270 .chain(if_not_zero_locations)
274 pub fn dominators(&self) -> Dominators<BasicBlock> {
279 pub fn local_kind(&self, local: Local) -> LocalKind {
280 let index = local.as_usize();
283 self.local_decls[local].mutability == Mutability::Mut,
284 "return place should be mutable"
287 LocalKind::ReturnPointer
288 } else if index < self.arg_count + 1 {
290 } else if self.local_decls[local].name.is_some() {
297 /// Returns an iterator over all temporaries.
299 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
300 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
301 let local = Local::new(index);
302 if self.local_decls[local].is_user_variable.is_some() {
310 /// Returns an iterator over all user-declared locals.
312 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
313 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
314 let local = Local::new(index);
315 if self.local_decls[local].is_user_variable.is_some() {
323 /// Returns an iterator over all user-declared mutable locals.
325 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
326 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
327 let local = Local::new(index);
328 let decl = &self.local_decls[local];
329 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
337 /// Returns an iterator over all user-declared mutable arguments and locals.
339 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
340 (1..self.local_decls.len()).filter_map(move |index| {
341 let local = Local::new(index);
342 let decl = &self.local_decls[local];
343 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
344 && decl.mutability == Mutability::Mut
353 /// Returns an iterator over all function arguments.
355 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
356 let arg_count = self.arg_count;
357 (1..=arg_count).map(Local::new)
360 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
361 /// locals that are neither arguments nor the return place).
363 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
364 let arg_count = self.arg_count;
365 let local_count = self.local_decls.len();
366 (arg_count + 1..local_count).map(Local::new)
369 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
370 /// invalidating statement indices in `Location`s.
371 pub fn make_statement_nop(&mut self, location: Location) {
372 let block = &mut self[location.block];
373 debug_assert!(location.statement_index < block.statements.len());
374 block.statements[location.statement_index].make_nop()
377 /// Returns the source info associated with `location`.
378 pub fn source_info(&self, location: Location) -> &SourceInfo {
379 let block = &self[location.block];
380 let stmts = &block.statements;
381 let idx = location.statement_index;
382 if idx < stmts.len() {
383 &stmts[idx].source_info
385 assert_eq!(idx, stmts.len());
386 &block.terminator().source_info
390 /// Checks if `sub` is a sub scope of `sup`
391 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
393 match self.source_scopes[sub].parent_scope {
394 None => return false,
401 /// Returns the return type, it always return first element from `local_decls` array
402 pub fn return_ty(&self) -> Ty<'tcx> {
403 self.local_decls[RETURN_PLACE].ty
406 /// Gets the location of the terminator for the given block
407 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
410 statement_index: self[bb].statements.len(),
415 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
418 /// Unsafe because of a PushUnsafeBlock
420 /// Unsafe because of an unsafe fn
422 /// Unsafe because of an `unsafe` block
423 ExplicitUnsafe(hir::HirId),
426 impl_stable_hash_for!(struct Body<'tcx> {
430 source_scope_local_data,
436 user_type_annotations,
438 __upvar_debuginfo_codegen_only_do_not_use,
440 control_flow_destroyed,
445 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
446 type Output = BasicBlockData<'tcx>;
449 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
450 &self.basic_blocks()[index]
454 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
456 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
457 &mut self.basic_blocks_mut()[index]
461 #[derive(Copy, Clone, Debug, HashStable)]
462 pub enum ClearCrossCrate<T> {
467 impl<T> ClearCrossCrate<T> {
468 pub fn assert_crate_local(self) -> T {
470 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
471 ClearCrossCrate::Set(v) => v,
476 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
477 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
479 /// Grouped information about the source code origin of a MIR entity.
480 /// Intended to be inspected by diagnostics and debuginfo.
481 /// Most passes can work with it as a whole, within a single function.
482 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
483 pub struct SourceInfo {
484 /// Source span for the AST pertaining to this MIR entity.
487 /// The source scope, keeping track of which bindings can be
488 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
489 pub scope: SourceScope,
492 ///////////////////////////////////////////////////////////////////////////
493 // Mutability and borrow kinds
495 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
496 pub enum Mutability {
501 impl From<Mutability> for hir::Mutability {
502 fn from(m: Mutability) -> Self {
504 Mutability::Mut => hir::MutMutable,
505 Mutability::Not => hir::MutImmutable,
510 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd,
511 Ord, RustcEncodable, RustcDecodable, HashStable)]
512 pub enum BorrowKind {
513 /// Data must be immutable and is aliasable.
516 /// The immediately borrowed place must be immutable, but projections from
517 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
518 /// conflict with a mutable borrow of `a.b.c`.
520 /// This is used when lowering matches: when matching on a place we want to
521 /// ensure that place have the same value from the start of the match until
522 /// an arm is selected. This prevents this code from compiling:
524 /// let mut x = &Some(0);
527 /// Some(_) if { x = &None; false } => (),
531 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
532 /// should not prevent `if let None = x { ... }`, for example, because the
533 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
534 /// We can also report errors with this kind of borrow differently.
537 /// Data must be immutable but not aliasable. This kind of borrow
538 /// cannot currently be expressed by the user and is used only in
539 /// implicit closure bindings. It is needed when the closure is
540 /// borrowing or mutating a mutable referent, e.g.:
542 /// let x: &mut isize = ...;
543 /// let y = || *x += 5;
545 /// If we were to try to translate this closure into a more explicit
546 /// form, we'd encounter an error with the code as written:
548 /// struct Env { x: & &mut isize }
549 /// let x: &mut isize = ...;
550 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
551 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
553 /// This is then illegal because you cannot mutate an `&mut` found
554 /// in an aliasable location. To solve, you'd have to translate with
555 /// an `&mut` borrow:
557 /// struct Env { x: & &mut isize }
558 /// let x: &mut isize = ...;
559 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
560 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
562 /// Now the assignment to `**env.x` is legal, but creating a
563 /// mutable pointer to `x` is not because `x` is not mutable. We
564 /// could fix this by declaring `x` as `let mut x`. This is ok in
565 /// user code, if awkward, but extra weird for closures, since the
566 /// borrow is hidden.
568 /// So we introduce a "unique imm" borrow -- the referent is
569 /// immutable, but not aliasable. This solves the problem. For
570 /// simplicity, we don't give users the way to express this
571 /// borrow, it's just used when translating closures.
574 /// Data is mutable and not aliasable.
576 /// `true` if this borrow arose from method-call auto-ref
577 /// (i.e., `adjustment::Adjust::Borrow`).
578 allow_two_phase_borrow: bool,
583 pub fn allows_two_phase_borrow(&self) -> bool {
585 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
586 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
591 ///////////////////////////////////////////////////////////////////////////
592 // Variables and temps
597 DEBUG_FORMAT = "_{}",
598 const RETURN_PLACE = 0,
602 /// Classifies locals into categories. See `Body::local_kind`.
603 #[derive(PartialEq, Eq, Debug, HashStable)]
605 /// User-declared variable binding
607 /// Compiler-introduced temporary
609 /// Function argument
611 /// Location of function's return value
615 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
616 pub struct VarBindingForm<'tcx> {
617 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
618 pub binding_mode: ty::BindingMode,
619 /// If an explicit type was provided for this variable binding,
620 /// this holds the source Span of that type.
622 /// NOTE: if you want to change this to a `HirId`, be wary that
623 /// doing so breaks incremental compilation (as of this writing),
624 /// while a `Span` does not cause our tests to fail.
625 pub opt_ty_info: Option<Span>,
626 /// Place of the RHS of the =, or the subject of the `match` where this
627 /// variable is initialized. None in the case of `let PATTERN;`.
628 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
629 /// (a) the right-hand side isn't evaluated as a place expression.
630 /// (b) it gives a way to separate this case from the remaining cases
632 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
633 /// Span of the pattern in which this variable was bound.
637 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
638 pub enum BindingForm<'tcx> {
639 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
640 Var(VarBindingForm<'tcx>),
641 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
642 ImplicitSelf(ImplicitSelfKind),
643 /// Reference used in a guard expression to ensure immutability.
647 /// Represents what type of implicit self a function has, if any.
648 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
649 pub enum ImplicitSelfKind {
650 /// Represents a `fn x(self);`.
652 /// Represents a `fn x(mut self);`.
654 /// Represents a `fn x(&self);`.
656 /// Represents a `fn x(&mut self);`.
658 /// Represents when a function does not have a self argument or
659 /// when a function has a `self: X` argument.
663 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
665 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
672 impl_stable_hash_for!(enum self::ImplicitSelfKind {
680 impl_stable_hash_for!(enum self::MirPhase {
687 mod binding_form_impl {
688 use crate::ich::StableHashingContext;
689 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
691 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
692 fn hash_stable<W: StableHasherResult>(
694 hcx: &mut StableHashingContext<'a>,
695 hasher: &mut StableHasher<W>,
697 use super::BindingForm::*;
698 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
701 Var(binding) => binding.hash_stable(hcx, hasher),
702 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
709 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
710 /// created during evaluation of expressions in a block tail
711 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
713 /// It is used to improve diagnostics when such temporaries are
714 /// involved in borrow_check errors, e.g., explanations of where the
715 /// temporaries come from, when their destructors are run, and/or how
716 /// one might revise the code to satisfy the borrow checker's rules.
717 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
718 pub struct BlockTailInfo {
719 /// If `true`, then the value resulting from evaluating this tail
720 /// expression is ignored by the block's expression context.
722 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
723 /// but not e.g., `let _x = { ...; tail };`
724 pub tail_result_is_ignored: bool,
727 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
731 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
732 /// argument, or the return place.
733 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
734 pub struct LocalDecl<'tcx> {
735 /// `let mut x` vs `let x`.
737 /// Temporaries and the return place are always mutable.
738 pub mutability: Mutability,
740 /// Some(binding_mode) if this corresponds to a user-declared local variable.
742 /// This is solely used for local diagnostics when generating
743 /// warnings/errors when compiling the current crate, and
744 /// therefore it need not be visible across crates. pnkfelix
745 /// currently hypothesized we *need* to wrap this in a
746 /// `ClearCrossCrate` as long as it carries as `HirId`.
747 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
749 /// `true` if this is an internal local.
751 /// These locals are not based on types in the source code and are only used
752 /// for a few desugarings at the moment.
754 /// The generator transformation will sanity check the locals which are live
755 /// across a suspension point against the type components of the generator
756 /// which type checking knows are live across a suspension point. We need to
757 /// flag drop flags to avoid triggering this check as they are introduced
760 /// Unsafety checking will also ignore dereferences of these locals,
761 /// so they can be used for raw pointers only used in a desugaring.
763 /// This should be sound because the drop flags are fully algebraic, and
764 /// therefore don't affect the OIBIT or outlives properties of the
768 /// If this local is a temporary and `is_block_tail` is `Some`,
769 /// then it is a temporary created for evaluation of some
770 /// subexpression of some block's tail expression (with no
771 /// intervening statement context).
772 pub is_block_tail: Option<BlockTailInfo>,
774 /// Type of this local.
777 /// If the user manually ascribed a type to this variable,
778 /// e.g., via `let x: T`, then we carry that type here. The MIR
779 /// borrow checker needs this information since it can affect
780 /// region inference.
781 pub user_ty: UserTypeProjections,
783 /// Name of the local, used in debuginfo and pretty-printing.
785 /// Note that function arguments can also have this set to `Some(_)`
786 /// to generate better debuginfo.
787 pub name: Option<Name>,
789 /// The *syntactic* (i.e., not visibility) source scope the local is defined
790 /// in. If the local was defined in a let-statement, this
791 /// is *within* the let-statement, rather than outside
794 /// This is needed because the visibility source scope of locals within
795 /// a let-statement is weird.
797 /// The reason is that we want the local to be *within* the let-statement
798 /// for lint purposes, but we want the local to be *after* the let-statement
799 /// for names-in-scope purposes.
801 /// That's it, if we have a let-statement like the one in this
805 /// fn foo(x: &str) {
806 /// #[allow(unused_mut)]
807 /// let mut x: u32 = { // <- one unused mut
808 /// let mut y: u32 = x.parse().unwrap();
815 /// Then, from a lint point of view, the declaration of `x: u32`
816 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
817 /// lint scopes are the same as the AST/HIR nesting.
819 /// However, from a name lookup point of view, the scopes look more like
820 /// as if the let-statements were `match` expressions:
823 /// fn foo(x: &str) {
825 /// match x.parse().unwrap() {
834 /// We care about the name-lookup scopes for debuginfo - if the
835 /// debuginfo instruction pointer is at the call to `x.parse()`, we
836 /// want `x` to refer to `x: &str`, but if it is at the call to
837 /// `drop(x)`, we want it to refer to `x: u32`.
839 /// To allow both uses to work, we need to have more than a single scope
840 /// for a local. We have the `source_info.scope` represent the
841 /// "syntactic" lint scope (with a variable being under its let
842 /// block) while the `visibility_scope` represents the "local variable"
843 /// scope (where the "rest" of a block is under all prior let-statements).
845 /// The end result looks like this:
849 /// │{ argument x: &str }
851 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
852 /// │ │ // in practice because I'm lazy.
854 /// │ │← x.source_info.scope
855 /// │ │← `x.parse().unwrap()`
857 /// │ │ │← y.source_info.scope
859 /// │ │ │{ let y: u32 }
861 /// │ │ │← y.visibility_scope
864 /// │ │{ let x: u32 }
865 /// │ │← x.visibility_scope
866 /// │ │← `drop(x)` // this accesses `x: u32`
868 pub source_info: SourceInfo,
870 /// Source scope within which the local is visible (for debuginfo)
871 /// (see `source_info` for more details).
872 pub visibility_scope: SourceScope,
875 impl<'tcx> LocalDecl<'tcx> {
876 /// Returns `true` only if local is a binding that can itself be
877 /// made mutable via the addition of the `mut` keyword, namely
878 /// something like the occurrences of `x` in:
879 /// - `fn foo(x: Type) { ... }`,
881 /// - or `match ... { C(x) => ... }`
882 pub fn can_be_made_mutable(&self) -> bool {
883 match self.is_user_variable {
884 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
885 binding_mode: ty::BindingMode::BindByValue(_),
891 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
898 /// Returns `true` if local is definitely not a `ref ident` or
899 /// `ref mut ident` binding. (Such bindings cannot be made into
900 /// mutable bindings, but the inverse does not necessarily hold).
901 pub fn is_nonref_binding(&self) -> bool {
902 match self.is_user_variable {
903 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
904 binding_mode: ty::BindingMode::BindByValue(_),
910 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
916 /// Returns `true` is the local is from a compiler desugaring, e.g.,
917 /// `__next` from a `for` loop.
919 pub fn from_compiler_desugaring(&self) -> bool {
920 self.source_info.span.compiler_desugaring_kind().is_some()
923 /// Creates a new `LocalDecl` for a temporary.
925 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
926 Self::new_local(ty, Mutability::Mut, false, span)
929 /// Converts `self` into same `LocalDecl` except tagged as immutable.
931 pub fn immutable(mut self) -> Self {
932 self.mutability = Mutability::Not;
936 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
938 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
939 assert!(self.is_block_tail.is_none());
940 self.is_block_tail = Some(info);
944 /// Creates a new `LocalDecl` for a internal temporary.
946 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
947 Self::new_local(ty, Mutability::Mut, true, span)
953 mutability: Mutability,
960 user_ty: UserTypeProjections::none(),
962 source_info: SourceInfo {
964 scope: OUTERMOST_SOURCE_SCOPE,
966 visibility_scope: OUTERMOST_SOURCE_SCOPE,
968 is_user_variable: None,
973 /// Builds a `LocalDecl` for the return place.
975 /// This must be inserted into the `local_decls` list as the first local.
977 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
979 mutability: Mutability::Mut,
981 user_ty: UserTypeProjections::none(),
982 source_info: SourceInfo {
984 scope: OUTERMOST_SOURCE_SCOPE,
986 visibility_scope: OUTERMOST_SOURCE_SCOPE,
989 name: None, // FIXME maybe we do want some name here?
990 is_user_variable: None,
995 /// A closure capture, with its name and mode.
996 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
997 pub struct UpvarDebuginfo {
998 pub debug_name: Name,
1000 /// If true, the capture is behind a reference.
1004 ///////////////////////////////////////////////////////////////////////////
1008 pub struct BasicBlock {
1010 DEBUG_FORMAT = "bb{}",
1011 const START_BLOCK = 0,
1016 pub fn start_location(self) -> Location {
1024 ///////////////////////////////////////////////////////////////////////////
1025 // BasicBlockData and Terminator
1027 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1028 pub struct BasicBlockData<'tcx> {
1029 /// List of statements in this block.
1030 pub statements: Vec<Statement<'tcx>>,
1032 /// Terminator for this block.
1034 /// N.B., this should generally ONLY be `None` during construction.
1035 /// Therefore, you should generally access it via the
1036 /// `terminator()` or `terminator_mut()` methods. The only
1037 /// exception is that certain passes, such as `simplify_cfg`, swap
1038 /// out the terminator temporarily with `None` while they continue
1039 /// to recurse over the set of basic blocks.
1040 pub terminator: Option<Terminator<'tcx>>,
1042 /// If true, this block lies on an unwind path. This is used
1043 /// during codegen where distinct kinds of basic blocks may be
1044 /// generated (particularly for MSVC cleanup). Unwind blocks must
1045 /// only branch to other unwind blocks.
1046 pub is_cleanup: bool,
1049 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1050 pub struct Terminator<'tcx> {
1051 pub source_info: SourceInfo,
1052 pub kind: TerminatorKind<'tcx>,
1055 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1056 pub enum TerminatorKind<'tcx> {
1057 /// block should have one successor in the graph; we jump there
1058 Goto { target: BasicBlock },
1060 /// operand evaluates to an integer; jump depending on its value
1061 /// to one of the targets, and otherwise fallback to `otherwise`
1063 /// discriminant value being tested
1064 discr: Operand<'tcx>,
1066 /// type of value being tested
1067 switch_ty: Ty<'tcx>,
1069 /// Possible values. The locations to branch to in each case
1070 /// are found in the corresponding indices from the `targets` vector.
1071 values: Cow<'tcx, [u128]>,
1073 /// Possible branch sites. The last element of this vector is used
1074 /// for the otherwise branch, so targets.len() == values.len() + 1
1076 // This invariant is quite non-obvious and also could be improved.
1077 // One way to make this invariant is to have something like this instead:
1079 // branches: Vec<(ConstInt, BasicBlock)>,
1080 // otherwise: Option<BasicBlock> // exhaustive if None
1082 // However we’ve decided to keep this as-is until we figure a case
1083 // where some other approach seems to be strictly better than other.
1084 targets: Vec<BasicBlock>,
1087 /// Indicates that the landing pad is finished and unwinding should
1088 /// continue. Emitted by build::scope::diverge_cleanup.
1091 /// Indicates that the landing pad is finished and that the process
1092 /// should abort. Used to prevent unwinding for foreign items.
1095 /// Indicates a normal return. The return place should have
1096 /// been filled in by now. This should occur at most once.
1099 /// Indicates a terminator that can never be reached.
1104 location: Place<'tcx>,
1106 unwind: Option<BasicBlock>,
1109 /// Drop the Place and assign the new value over it. This ensures
1110 /// that the assignment to `P` occurs *even if* the destructor for
1111 /// place unwinds. Its semantics are best explained by the
1116 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1124 /// Drop(P, goto BB1, unwind BB2)
1127 /// // P is now uninitialized
1131 /// // P is now uninitialized -- its dtor panicked
1136 location: Place<'tcx>,
1137 value: Operand<'tcx>,
1139 unwind: Option<BasicBlock>,
1142 /// Block ends with a call of a converging function
1144 /// The function that’s being called
1145 func: Operand<'tcx>,
1146 /// Arguments the function is called with.
1147 /// These are owned by the callee, which is free to modify them.
1148 /// This allows the memory occupied by "by-value" arguments to be
1149 /// reused across function calls without duplicating the contents.
1150 args: Vec<Operand<'tcx>>,
1151 /// Destination for the return value. If some, the call is converging.
1152 destination: Option<(Place<'tcx>, BasicBlock)>,
1153 /// Cleanups to be done if the call unwinds.
1154 cleanup: Option<BasicBlock>,
1155 /// Whether this is from a call in HIR, rather than from an overloaded
1156 /// operator. True for overloaded function call.
1157 from_hir_call: bool,
1160 /// Jump to the target if the condition has the expected value,
1161 /// otherwise panic with a message and a cleanup target.
1163 cond: Operand<'tcx>,
1165 msg: AssertMessage<'tcx>,
1167 cleanup: Option<BasicBlock>,
1172 /// The value to return
1173 value: Operand<'tcx>,
1174 /// Where to resume to
1176 /// Cleanup to be done if the generator is dropped at this suspend point
1177 drop: Option<BasicBlock>,
1180 /// Indicates the end of the dropping of a generator
1183 /// A block where control flow only ever takes one real path, but borrowck
1184 /// needs to be more conservative.
1186 /// The target normal control flow will take
1187 real_target: BasicBlock,
1188 /// The list of blocks control flow could conceptually take, but won't
1190 imaginary_targets: Vec<BasicBlock>,
1192 /// A terminator for blocks that only take one path in reality, but where we
1193 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1194 /// This can arise in infinite loops with no function calls for example.
1196 /// The target normal control flow will take
1197 real_target: BasicBlock,
1198 /// The imaginary cleanup block link. This particular path will never be taken
1199 /// in practice, but in order to avoid fragility we want to always
1200 /// consider it in borrowck. We don't want to accept programs which
1201 /// pass borrowck only when panic=abort or some assertions are disabled
1202 /// due to release vs. debug mode builds. This needs to be an Option because
1203 /// of the remove_noop_landing_pads and no_landing_pads passes
1204 unwind: Option<BasicBlock>,
1208 pub type Successors<'a> =
1209 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1210 pub type SuccessorsMut<'a> =
1211 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1213 impl<'tcx> Terminator<'tcx> {
1214 pub fn successors(&self) -> Successors<'_> {
1215 self.kind.successors()
1218 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1219 self.kind.successors_mut()
1222 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1226 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1227 self.kind.unwind_mut()
1231 impl<'tcx> TerminatorKind<'tcx> {
1232 pub fn if_<'a, 'gcx>(
1233 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1234 cond: Operand<'tcx>,
1237 ) -> TerminatorKind<'tcx> {
1238 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1239 TerminatorKind::SwitchInt {
1241 switch_ty: tcx.types.bool,
1242 values: From::from(BOOL_SWITCH_FALSE),
1243 targets: vec![f, t],
1247 pub fn successors(&self) -> Successors<'_> {
1248 use self::TerminatorKind::*;
1259 } => None.into_iter().chain(&[]),
1260 Goto { target: ref t }
1263 cleanup: Some(ref t),
1267 destination: Some((_, ref t)),
1294 } => Some(t).into_iter().chain(&[]),
1296 destination: Some((_, ref t)),
1297 cleanup: Some(ref u),
1307 unwind: Some(ref u),
1312 unwind: Some(ref u),
1317 cleanup: Some(ref u),
1322 unwind: Some(ref u),
1323 } => Some(t).into_iter().chain(slice::from_ref(u)),
1324 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1327 ref imaginary_targets,
1328 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1332 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1333 use self::TerminatorKind::*;
1344 } => None.into_iter().chain(&mut []),
1345 Goto { target: ref mut t }
1348 cleanup: Some(ref mut t),
1352 destination: Some((_, ref mut t)),
1377 real_target: ref mut t,
1379 } => Some(t).into_iter().chain(&mut []),
1381 destination: Some((_, ref mut t)),
1382 cleanup: Some(ref mut u),
1387 drop: Some(ref mut u),
1392 unwind: Some(ref mut u),
1397 unwind: Some(ref mut u),
1402 cleanup: Some(ref mut u),
1406 real_target: ref mut t,
1407 unwind: Some(ref mut u),
1408 } => Some(t).into_iter().chain(slice::from_mut(u)),
1411 } => None.into_iter().chain(&mut targets[..]),
1413 ref mut real_target,
1414 ref mut imaginary_targets,
1415 } => Some(real_target)
1417 .chain(&mut imaginary_targets[..]),
1421 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1423 TerminatorKind::Goto { .. }
1424 | TerminatorKind::Resume
1425 | TerminatorKind::Abort
1426 | TerminatorKind::Return
1427 | TerminatorKind::Unreachable
1428 | TerminatorKind::GeneratorDrop
1429 | TerminatorKind::Yield { .. }
1430 | TerminatorKind::SwitchInt { .. }
1431 | TerminatorKind::FalseEdges { .. } => None,
1432 TerminatorKind::Call {
1433 cleanup: ref unwind,
1436 | TerminatorKind::Assert {
1437 cleanup: ref unwind,
1440 | TerminatorKind::DropAndReplace { ref unwind, .. }
1441 | TerminatorKind::Drop { ref unwind, .. }
1442 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1446 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1448 TerminatorKind::Goto { .. }
1449 | TerminatorKind::Resume
1450 | TerminatorKind::Abort
1451 | TerminatorKind::Return
1452 | TerminatorKind::Unreachable
1453 | TerminatorKind::GeneratorDrop
1454 | TerminatorKind::Yield { .. }
1455 | TerminatorKind::SwitchInt { .. }
1456 | TerminatorKind::FalseEdges { .. } => None,
1457 TerminatorKind::Call {
1458 cleanup: ref mut unwind,
1461 | TerminatorKind::Assert {
1462 cleanup: ref mut unwind,
1465 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1466 | TerminatorKind::Drop { ref mut unwind, .. }
1467 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1472 impl<'tcx> BasicBlockData<'tcx> {
1473 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1481 /// Accessor for terminator.
1483 /// Terminator may not be None after construction of the basic block is complete. This accessor
1484 /// provides a convenience way to reach the terminator.
1485 pub fn terminator(&self) -> &Terminator<'tcx> {
1486 self.terminator.as_ref().expect("invalid terminator state")
1489 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1490 self.terminator.as_mut().expect("invalid terminator state")
1493 pub fn retain_statements<F>(&mut self, mut f: F)
1495 F: FnMut(&mut Statement<'_>) -> bool,
1497 for s in &mut self.statements {
1504 pub fn expand_statements<F, I>(&mut self, mut f: F)
1506 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1507 I: iter::TrustedLen<Item = Statement<'tcx>>,
1509 // Gather all the iterators we'll need to splice in, and their positions.
1510 let mut splices: Vec<(usize, I)> = vec![];
1511 let mut extra_stmts = 0;
1512 for (i, s) in self.statements.iter_mut().enumerate() {
1513 if let Some(mut new_stmts) = f(s) {
1514 if let Some(first) = new_stmts.next() {
1515 // We can already store the first new statement.
1518 // Save the other statements for optimized splicing.
1519 let remaining = new_stmts.size_hint().0;
1521 splices.push((i + 1 + extra_stmts, new_stmts));
1522 extra_stmts += remaining;
1530 // Splice in the new statements, from the end of the block.
1531 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1532 // where a range of elements ("gap") is left uninitialized, with
1533 // splicing adding new elements to the end of that gap and moving
1534 // existing elements from before the gap to the end of the gap.
1535 // For now, this is safe code, emulating a gap but initializing it.
1536 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1537 self.statements.resize(
1540 source_info: SourceInfo {
1542 scope: OUTERMOST_SOURCE_SCOPE,
1544 kind: StatementKind::Nop,
1547 for (splice_start, new_stmts) in splices.into_iter().rev() {
1548 let splice_end = splice_start + new_stmts.size_hint().0;
1549 while gap.end > splice_end {
1552 self.statements.swap(gap.start, gap.end);
1554 self.statements.splice(splice_start..splice_end, new_stmts);
1555 gap.end = splice_start;
1559 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1560 if index < self.statements.len() {
1561 &self.statements[index]
1568 impl<'tcx> Debug for TerminatorKind<'tcx> {
1569 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1570 self.fmt_head(fmt)?;
1571 let successor_count = self.successors().count();
1572 let labels = self.fmt_successor_labels();
1573 assert_eq!(successor_count, labels.len());
1575 match successor_count {
1578 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1581 write!(fmt, " -> [")?;
1582 for (i, target) in self.successors().enumerate() {
1586 write!(fmt, "{}: {:?}", labels[i], target)?;
1594 impl<'tcx> TerminatorKind<'tcx> {
1595 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1596 /// successor basic block, if any. The only information not included is the list of possible
1597 /// successors, which may be rendered differently between the text and the graphviz format.
1598 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1599 use self::TerminatorKind::*;
1601 Goto { .. } => write!(fmt, "goto"),
1603 discr: ref place, ..
1604 } => write!(fmt, "switchInt({:?})", place),
1605 Return => write!(fmt, "return"),
1606 GeneratorDrop => write!(fmt, "generator_drop"),
1607 Resume => write!(fmt, "resume"),
1608 Abort => write!(fmt, "abort"),
1609 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1610 Unreachable => write!(fmt, "unreachable"),
1611 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1616 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1623 if let Some((ref destination, _)) = *destination {
1624 write!(fmt, "{:?} = ", destination)?;
1626 write!(fmt, "{:?}(", func)?;
1627 for (index, arg) in args.iter().enumerate() {
1631 write!(fmt, "{:?}", arg)?;
1641 write!(fmt, "assert(")?;
1645 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1647 FalseEdges { .. } => write!(fmt, "falseEdges"),
1648 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1652 /// Returns the list of labels for the edges to the successor basic blocks.
1653 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1654 use self::TerminatorKind::*;
1656 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1657 Goto { .. } => vec!["".into()],
1663 ty::tls::with(|tcx| {
1664 let param_env = ty::ParamEnv::empty();
1665 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1666 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1670 tcx.mk_const(ty::Const {
1671 val: ConstValue::Scalar(
1672 Scalar::from_uint(u, size).into(),
1675 }).to_string().into()
1676 }).chain(iter::once("otherwise".into()))
1681 destination: Some(_),
1684 } => vec!["return".into(), "unwind".into()],
1686 destination: Some(_),
1689 } => vec!["return".into()],
1694 } => vec!["unwind".into()],
1700 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1701 Yield { drop: None, .. } => vec!["resume".into()],
1702 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1703 vec!["return".into()]
1710 } => vec!["return".into(), "unwind".into()],
1711 Assert { cleanup: None, .. } => vec!["".into()],
1712 Assert { .. } => vec!["success".into(), "unwind".into()],
1714 ref imaginary_targets,
1717 let mut l = vec!["real".into()];
1718 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1723 } => vec!["real".into(), "cleanup".into()],
1724 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1729 ///////////////////////////////////////////////////////////////////////////
1732 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1733 pub struct Statement<'tcx> {
1734 pub source_info: SourceInfo,
1735 pub kind: StatementKind<'tcx>,
1738 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1739 #[cfg(target_arch = "x86_64")]
1740 static_assert_size!(Statement<'_>, 56);
1742 impl<'tcx> Statement<'tcx> {
1743 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1744 /// invalidating statement indices in `Location`s.
1745 pub fn make_nop(&mut self) {
1746 self.kind = StatementKind::Nop
1749 /// Changes a statement to a nop and returns the original statement.
1750 pub fn replace_nop(&mut self) -> Self {
1752 source_info: self.source_info,
1753 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1758 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1759 pub enum StatementKind<'tcx> {
1760 /// Write the RHS Rvalue to the LHS Place.
1761 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1763 /// This represents all the reading that a pattern match may do
1764 /// (e.g., inspecting constants and discriminant values), and the
1765 /// kind of pattern it comes from. This is in order to adapt potential
1766 /// error messages to these specific patterns.
1768 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1769 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1770 FakeRead(FakeReadCause, Place<'tcx>),
1772 /// Write the discriminant for a variant to the enum Place.
1775 variant_index: VariantIdx,
1778 /// Start a live range for the storage of the local.
1781 /// End the current live range for the storage of the local.
1784 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1785 /// of `StatementKind` low.
1786 InlineAsm(Box<InlineAsm<'tcx>>),
1788 /// Retag references in the given place, ensuring they got fresh tags. This is
1789 /// part of the Stacked Borrows model. These statements are currently only interpreted
1790 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1791 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1792 /// for more details.
1793 Retag(RetagKind, Place<'tcx>),
1795 /// Encodes a user's type ascription. These need to be preserved
1796 /// intact so that NLL can respect them. For example:
1800 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1801 /// to the user-given type `T`. The effect depends on the specified variance:
1803 /// - `Covariant` -- requires that `T_y <: T`
1804 /// - `Contravariant` -- requires that `T_y :> T`
1805 /// - `Invariant` -- requires that `T_y == T`
1806 /// - `Bivariant` -- no effect
1807 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1809 /// No-op. Useful for deleting instructions without affecting statement indices.
1813 /// `RetagKind` describes what kind of retag is to be performed.
1814 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1815 pub enum RetagKind {
1816 /// The initial retag when entering a function
1818 /// Retag preparing for a two-phase borrow
1820 /// Retagging raw pointers
1822 /// A "normal" retag
1826 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1827 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1828 pub enum FakeReadCause {
1829 /// Inject a fake read of the borrowed input at the end of each guards
1832 /// This should ensure that you cannot change the variant for an enum while
1833 /// you are in the midst of matching on it.
1836 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1837 /// generate a read of x to check that it is initialized and safe.
1840 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1841 /// in a match guard to ensure that it's value hasn't change by the time
1842 /// we create the OutsideGuard version.
1845 /// Officially, the semantics of
1847 /// `let pattern = <expr>;`
1849 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1850 /// into the pattern.
1852 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1853 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1854 /// but in some cases it can affect the borrow checker, as in #53695.
1855 /// Therefore, we insert a "fake read" here to ensure that we get
1856 /// appropriate errors.
1860 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1861 pub struct InlineAsm<'tcx> {
1862 pub asm: HirInlineAsm,
1863 pub outputs: Box<[Place<'tcx>]>,
1864 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1867 impl<'tcx> Debug for Statement<'tcx> {
1868 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1869 use self::StatementKind::*;
1871 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1872 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1873 Retag(ref kind, ref place) =>
1874 write!(fmt, "Retag({}{:?})",
1876 RetagKind::FnEntry => "[fn entry] ",
1877 RetagKind::TwoPhase => "[2phase] ",
1878 RetagKind::Raw => "[raw] ",
1879 RetagKind::Default => "",
1883 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1884 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1888 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1889 InlineAsm(ref asm) =>
1890 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs),
1891 AscribeUserType(ref place, ref variance, ref c_ty) => {
1892 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1894 Nop => write!(fmt, "nop"),
1899 ///////////////////////////////////////////////////////////////////////////
1902 /// A path to a value; something that can be evaluated without
1903 /// changing or disturbing program state.
1904 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1905 pub enum Place<'tcx> {
1906 Base(PlaceBase<'tcx>),
1908 /// projection out of a place (access a field, deref a pointer, etc)
1909 Projection(Box<Projection<'tcx>>),
1912 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1913 pub enum PlaceBase<'tcx> {
1917 /// static or static mut variable
1918 Static(Box<Static<'tcx>>),
1921 /// We store the normalized type to avoid requiring normalization when reading MIR
1922 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1923 pub struct Static<'tcx> {
1925 pub kind: StaticKind,
1928 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable)]
1929 pub enum StaticKind {
1934 impl_stable_hash_for!(struct Static<'tcx> {
1939 /// The `Projection` data structure defines things of the form `base.x`, `*b` or `b[index]`.
1940 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1941 Hash, RustcEncodable, RustcDecodable, HashStable)]
1942 pub struct Projection<'tcx> {
1943 pub base: Place<'tcx>,
1944 pub elem: PlaceElem<'tcx>,
1947 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1948 Hash, RustcEncodable, RustcDecodable, HashStable)]
1949 pub enum ProjectionElem<V, T> {
1954 /// These indices are generated by slice patterns. Easiest to explain
1958 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1959 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1960 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1961 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1964 /// index or -index (in Python terms), depending on from_end
1966 /// thing being indexed must be at least this long
1968 /// counting backwards from end?
1972 /// These indices are generated by slice patterns.
1974 /// slice[from:-to] in Python terms.
1980 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1981 /// this for ADTs with more than one variant. It may be better to
1982 /// just introduce it always, or always for enums.
1984 /// The included Symbol is the name of the variant, used for printing MIR.
1985 Downcast(Option<Symbol>, VariantIdx),
1988 /// Alias for projections as they appear in places, where the base is a place
1989 /// and the index is a local.
1990 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1992 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1993 #[cfg(target_arch = "x86_64")]
1994 static_assert_size!(PlaceElem<'_>, 16);
1996 /// Alias for projections as they appear in `UserTypeProjection`, where we
1997 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1998 pub type ProjectionKind = ProjectionElem<(), ()>;
2003 DEBUG_FORMAT = "field[{}]"
2007 impl<'tcx> Place<'tcx> {
2008 pub const RETURN_PLACE: Place<'tcx> = Place::Base(PlaceBase::Local(RETURN_PLACE));
2010 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2011 self.elem(ProjectionElem::Field(f, ty))
2014 pub fn deref(self) -> Place<'tcx> {
2015 self.elem(ProjectionElem::Deref)
2018 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2019 self.elem(ProjectionElem::Downcast(
2020 Some(adt_def.variants[variant_index].ident.name),
2024 pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
2025 self.elem(ProjectionElem::Downcast(None, variant_index))
2028 pub fn index(self, index: Local) -> Place<'tcx> {
2029 self.elem(ProjectionElem::Index(index))
2032 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2033 Place::Projection(Box::new(Projection { base: self, elem }))
2036 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2037 /// a single deref of a local.
2039 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2040 pub fn local_or_deref_local(&self) -> Option<Local> {
2042 Place::Base(PlaceBase::Local(local)) |
2043 Place::Projection(box Projection {
2044 base: Place::Base(PlaceBase::Local(local)),
2045 elem: ProjectionElem::Deref,
2051 /// Finds the innermost `Local` from this `Place`.
2052 pub fn base_local(&self) -> Option<Local> {
2053 let mut place = self;
2056 Place::Projection(proj) => place = &proj.base,
2057 Place::Base(PlaceBase::Static(_)) => return None,
2058 Place::Base(PlaceBase::Local(local)) => return Some(*local),
2063 /// Recursively "iterates" over place components, generating a `PlaceBase` and
2064 /// `Projections` list and invoking `op` with a `ProjectionsIter`.
2067 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2069 self.iterate2(&Projections::Empty, op)
2074 next: &Projections<'_, 'tcx>,
2075 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2078 Place::Projection(interior) => interior.base.iterate2(
2079 &Projections::List {
2080 projection: interior,
2086 Place::Base(base) => op(base, next.iter()),
2091 /// A linked list of projections running up the stack; begins with the
2092 /// innermost projection and extends to the outermost (e.g., `a.b.c`
2093 /// would have the place `b` with a "next" pointer to `b.c`).
2094 /// Created by `Place::iterate`.
2096 /// N.B., this particular impl strategy is not the most obvious. It was
2097 /// chosen because it makes a measurable difference to NLL
2098 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
2099 pub enum Projections<'p, 'tcx: 'p> {
2103 projection: &'p Projection<'tcx>,
2104 next: &'p Projections<'p, 'tcx>,
2108 impl<'p, 'tcx> Projections<'p, 'tcx> {
2109 fn iter(&self) -> ProjectionsIter<'_, 'tcx> {
2110 ProjectionsIter { value: self }
2114 impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
2115 type Item = &'p Projection<'tcx>;
2116 type IntoIter = ProjectionsIter<'p, 'tcx>;
2118 /// Converts a list of `Projection` components into an iterator;
2119 /// this iterator yields up a never-ending stream of `Option<&Place>`.
2120 /// These begin with the "innermost" projection and then with each
2121 /// projection therefrom. So given a place like `a.b.c` it would
2125 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2127 fn into_iter(self) -> Self::IntoIter {
2132 /// Iterator over components; see `Projections::iter` for more
2135 /// N.B., this is not a *true* Rust iterator -- the code above just
2136 /// manually invokes `next`. This is because we (sometimes) want to
2137 /// keep executing even after `None` has been returned.
2138 pub struct ProjectionsIter<'p, 'tcx: 'p> {
2139 pub value: &'p Projections<'p, 'tcx>,
2142 impl<'p, 'tcx> Iterator for ProjectionsIter<'p, 'tcx> {
2143 type Item = &'p Projection<'tcx>;
2145 fn next(&mut self) -> Option<Self::Item> {
2146 if let &Projections::List { projection, next } = self.value {
2155 impl<'p, 'tcx> FusedIterator for ProjectionsIter<'p, 'tcx> {}
2157 impl<'tcx> Debug for Place<'tcx> {
2158 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2159 self.iterate(|_place_base, place_projections| {
2160 // FIXME: remove this collect once we have migrated to slices
2161 let projs_vec: Vec<_> = place_projections.collect();
2162 for projection in projs_vec.iter().rev() {
2163 match projection.elem {
2164 ProjectionElem::Downcast(_, _) |
2165 ProjectionElem::Field(_, _) => {
2166 write!(fmt, "(").unwrap();
2168 ProjectionElem::Deref => {
2169 write!(fmt, "(*").unwrap();
2171 ProjectionElem::Index(_) |
2172 ProjectionElem::ConstantIndex { .. } |
2173 ProjectionElem::Subslice { .. } => {}
2178 self.iterate(|place_base, place_projections| {
2180 PlaceBase::Local(id) => {
2181 write!(fmt, "{:?}", id)?;
2183 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2187 ty::tls::with(|tcx| tcx.def_path_str(*def_id)),
2192 box self::Static { ty, kind: StaticKind::Promoted(promoted) }
2203 for projection in place_projections {
2204 match projection.elem {
2205 ProjectionElem::Downcast(Some(name), _index) => {
2206 write!(fmt, " as {})", name)?;
2208 ProjectionElem::Downcast(None, index) => {
2209 write!(fmt, " as variant#{:?})", index)?;
2211 ProjectionElem::Deref => {
2214 ProjectionElem::Field(field, ty) => {
2215 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2217 ProjectionElem::Index(ref index) => {
2218 write!(fmt, "[{:?}]", index)?;
2220 ProjectionElem::ConstantIndex {
2225 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2227 ProjectionElem::ConstantIndex {
2232 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2234 ProjectionElem::Subslice { from, to } if to == 0 => {
2235 write!(fmt, "[{:?}:]", from)?;
2237 ProjectionElem::Subslice { from, to } if from == 0 => {
2238 write!(fmt, "[:-{:?}]", to)?;
2240 ProjectionElem::Subslice { from, to } => {
2241 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2251 ///////////////////////////////////////////////////////////////////////////
2255 pub struct SourceScope {
2257 DEBUG_FORMAT = "scope[{}]",
2258 const OUTERMOST_SOURCE_SCOPE = 0,
2262 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2263 pub struct SourceScopeData {
2265 pub parent_scope: Option<SourceScope>,
2268 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2269 pub struct SourceScopeLocalData {
2270 /// A HirId with lint levels equivalent to this scope's lint levels.
2271 pub lint_root: hir::HirId,
2272 /// The unsafe block that contains this node.
2276 ///////////////////////////////////////////////////////////////////////////
2279 /// These are values that can appear inside an rvalue. They are intentionally
2280 /// limited to prevent rvalues from being nested in one another.
2281 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2282 pub enum Operand<'tcx> {
2283 /// Copy: The value must be available for use afterwards.
2285 /// This implies that the type of the place must be `Copy`; this is true
2286 /// by construction during build, but also checked by the MIR type checker.
2289 /// Move: The value (including old borrows of it) will not be used again.
2291 /// Safe for values of all types (modulo future developments towards `?Move`).
2292 /// Correct usage patterns are enforced by the borrow checker for safe code.
2293 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2296 /// Synthesizes a constant value.
2297 Constant(Box<Constant<'tcx>>),
2300 impl<'tcx> Debug for Operand<'tcx> {
2301 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2302 use self::Operand::*;
2304 Constant(ref a) => write!(fmt, "{:?}", a),
2305 Copy(ref place) => write!(fmt, "{:?}", place),
2306 Move(ref place) => write!(fmt, "move {:?}", place),
2311 impl<'tcx> Operand<'tcx> {
2312 /// Convenience helper to make a constant that refers to the fn
2313 /// with given `DefId` and substs. Since this is used to synthesize
2314 /// MIR, assumes `user_ty` is None.
2315 pub fn function_handle<'a>(
2316 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2318 substs: SubstsRef<'tcx>,
2321 let ty = tcx.type_of(def_id).subst(tcx, substs);
2322 Operand::Constant(box Constant {
2326 literal: ty::Const::zero_sized(tcx, ty),
2330 pub fn to_copy(&self) -> Self {
2332 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2333 Operand::Move(ref place) => Operand::Copy(place.clone()),
2338 ///////////////////////////////////////////////////////////////////////////
2341 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2342 pub enum Rvalue<'tcx> {
2343 /// x (either a move or copy, depending on type of x)
2347 Repeat(Operand<'tcx>, u64),
2350 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2352 /// length of a [X] or [X;n] value
2355 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2357 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2358 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2360 NullaryOp(NullOp, Ty<'tcx>),
2361 UnaryOp(UnOp, Operand<'tcx>),
2363 /// Read the discriminant of an ADT.
2365 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2366 /// be defined to return, say, a 0) if ADT is not an enum.
2367 Discriminant(Place<'tcx>),
2369 /// Creates an aggregate value, like a tuple or struct. This is
2370 /// only needed because we want to distinguish `dest = Foo { x:
2371 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2372 /// that `Foo` has a destructor. These rvalues can be optimized
2373 /// away after type-checking and before lowering.
2374 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2378 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2381 Pointer(PointerCast),
2384 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2385 pub enum AggregateKind<'tcx> {
2386 /// The type is of the element
2390 /// The second field is the variant index. It's equal to 0 for struct
2391 /// and union expressions. The fourth field is
2392 /// active field number and is present only for union expressions
2393 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2394 /// active field index would identity the field `c`
2399 Option<UserTypeAnnotationIndex>,
2403 Closure(DefId, ClosureSubsts<'tcx>),
2404 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2407 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2409 /// The `+` operator (addition)
2411 /// The `-` operator (subtraction)
2413 /// The `*` operator (multiplication)
2415 /// The `/` operator (division)
2417 /// The `%` operator (modulus)
2419 /// The `^` operator (bitwise xor)
2421 /// The `&` operator (bitwise and)
2423 /// The `|` operator (bitwise or)
2425 /// The `<<` operator (shift left)
2427 /// The `>>` operator (shift right)
2429 /// The `==` operator (equality)
2431 /// The `<` operator (less than)
2433 /// The `<=` operator (less than or equal to)
2435 /// The `!=` operator (not equal to)
2437 /// The `>=` operator (greater than or equal to)
2439 /// The `>` operator (greater than)
2441 /// The `ptr.offset` operator
2446 pub fn is_checkable(self) -> bool {
2449 Add | Sub | Mul | Shl | Shr => true,
2455 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2457 /// Returns the size of a value of that type
2459 /// Creates a new uninitialized box for a value of that type
2463 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2465 /// The `!` operator for logical inversion
2467 /// The `-` operator for negation
2471 impl<'tcx> Debug for Rvalue<'tcx> {
2472 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2473 use self::Rvalue::*;
2476 Use(ref place) => write!(fmt, "{:?}", place),
2477 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2478 Len(ref a) => write!(fmt, "Len({:?})", a),
2479 Cast(ref kind, ref place, ref ty) => {
2480 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2482 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2483 CheckedBinaryOp(ref op, ref a, ref b) => {
2484 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2486 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2487 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2488 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2489 Ref(region, borrow_kind, ref place) => {
2490 let kind_str = match borrow_kind {
2491 BorrowKind::Shared => "",
2492 BorrowKind::Shallow => "shallow ",
2493 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2496 // When printing regions, add trailing space if necessary.
2497 let print_region = ty::tls::with(|tcx| {
2498 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2500 let region = if print_region {
2501 let mut region = region.to_string();
2502 if region.len() > 0 {
2507 // Do not even print 'static
2510 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2513 Aggregate(ref kind, ref places) => {
2514 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2515 let mut tuple_fmt = fmt.debug_tuple("");
2516 for place in places {
2517 tuple_fmt.field(place);
2523 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2525 AggregateKind::Tuple => match places.len() {
2526 0 => write!(fmt, "()"),
2527 1 => write!(fmt, "({:?},)", places[0]),
2528 _ => fmt_tuple(fmt, places),
2531 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2532 let variant_def = &adt_def.variants[variant];
2535 ty::tls::with(|tcx| {
2536 let substs = tcx.lift(&substs).expect("could not lift for printing");
2537 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2538 .print_def_path(variant_def.def_id, substs)?;
2542 match variant_def.ctor_kind {
2543 CtorKind::Const => Ok(()),
2544 CtorKind::Fn => fmt_tuple(fmt, places),
2545 CtorKind::Fictive => {
2546 let mut struct_fmt = fmt.debug_struct("");
2547 for (field, place) in variant_def.fields.iter().zip(places) {
2548 struct_fmt.field(&field.ident.as_str(), place);
2555 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2556 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2557 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2558 format!("[closure@{:?}]", hir_id)
2560 format!("[closure@{:?}]", tcx.hir().span_by_hir_id(hir_id))
2562 let mut struct_fmt = fmt.debug_struct(&name);
2564 if let Some(upvars) = tcx.upvars(def_id) {
2565 for (upvar, place) in upvars.iter().zip(places) {
2566 let var_name = tcx.hir().name_by_hir_id(upvar.var_id);
2567 struct_fmt.field(&var_name.as_str(), place);
2573 write!(fmt, "[closure]")
2577 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2578 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2579 let name = format!("[generator@{:?}]",
2580 tcx.hir().span_by_hir_id(hir_id));
2581 let mut struct_fmt = fmt.debug_struct(&name);
2583 if let Some(upvars) = tcx.upvars(def_id) {
2584 for (upvar, place) in upvars.iter().zip(places) {
2585 let var_name = tcx.hir().name_by_hir_id(upvar.var_id);
2586 struct_fmt.field(&var_name.as_str(), place);
2592 write!(fmt, "[generator]")
2601 ///////////////////////////////////////////////////////////////////////////
2604 /// Two constants are equal if they are the same constant. Note that
2605 /// this does not necessarily mean that they are "==" in Rust -- in
2606 /// particular one must be wary of `NaN`!
2608 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2609 pub struct Constant<'tcx> {
2613 /// Optional user-given type: for something like
2614 /// `collect::<Vec<_>>`, this would be present and would
2615 /// indicate that `Vec<_>` was explicitly specified.
2617 /// Needed for NLL to impose user-given type constraints.
2618 pub user_ty: Option<UserTypeAnnotationIndex>,
2620 pub literal: &'tcx ty::Const<'tcx>,
2623 /// A collection of projections into user types.
2625 /// They are projections because a binding can occur a part of a
2626 /// parent pattern that has been ascribed a type.
2628 /// Its a collection because there can be multiple type ascriptions on
2629 /// the path from the root of the pattern down to the binding itself.
2634 /// struct S<'a>((i32, &'a str), String);
2635 /// let S((_, w): (i32, &'static str), _): S = ...;
2636 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2637 /// // --------------------------------- ^ (2)
2640 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2641 /// ascribed the type `(i32, &'static str)`.
2643 /// The highlights labelled `(2)` show the whole pattern being
2644 /// ascribed the type `S`.
2646 /// In this example, when we descend to `w`, we will have built up the
2647 /// following two projected types:
2649 /// * base: `S`, projection: `(base.0).1`
2650 /// * base: `(i32, &'static str)`, projection: `base.1`
2652 /// The first will lead to the constraint `w: &'1 str` (for some
2653 /// inferred region `'1`). The second will lead to the constraint `w:
2655 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2656 pub struct UserTypeProjections {
2657 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2660 BraceStructTypeFoldableImpl! {
2661 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2666 impl<'tcx> UserTypeProjections {
2667 pub fn none() -> Self {
2668 UserTypeProjections { contents: vec![] }
2671 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection, Span)>) -> Self {
2672 UserTypeProjections { contents: projs.collect() }
2675 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection, Span)> {
2676 self.contents.iter()
2679 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection> {
2680 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2683 pub fn push_projection(
2685 user_ty: &UserTypeProjection,
2688 self.contents.push((user_ty.clone(), span));
2694 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection
2696 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2700 pub fn index(self) -> Self {
2701 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2704 pub fn subslice(self, from: u32, to: u32) -> Self {
2705 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2708 pub fn deref(self) -> Self {
2709 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2712 pub fn leaf(self, field: Field) -> Self {
2713 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2718 adt_def: &'tcx AdtDef,
2719 variant_index: VariantIdx,
2722 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2726 /// Encodes the effect of a user-supplied type annotation on the
2727 /// subcomponents of a pattern. The effect is determined by applying the
2728 /// given list of proejctions to some underlying base type. Often,
2729 /// the projection element list `projs` is empty, in which case this
2730 /// directly encodes a type in `base`. But in the case of complex patterns with
2731 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2732 /// in which case the `projs` vector is used.
2736 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2738 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2739 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2740 /// determined by finding the type of the `.0` field from `T`.
2741 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2742 pub struct UserTypeProjection {
2743 pub base: UserTypeAnnotationIndex,
2744 pub projs: Vec<ProjectionKind>,
2747 impl Copy for ProjectionKind { }
2749 impl UserTypeProjection {
2750 pub(crate) fn index(mut self) -> Self {
2751 self.projs.push(ProjectionElem::Index(()));
2755 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2756 self.projs.push(ProjectionElem::Subslice { from, to });
2760 pub(crate) fn deref(mut self) -> Self {
2761 self.projs.push(ProjectionElem::Deref);
2765 pub(crate) fn leaf(mut self, field: Field) -> Self {
2766 self.projs.push(ProjectionElem::Field(field, ()));
2770 pub(crate) fn variant(
2772 adt_def: &'tcx AdtDef,
2773 variant_index: VariantIdx,
2776 self.projs.push(ProjectionElem::Downcast(
2777 Some(adt_def.variants[variant_index].ident.name),
2779 self.projs.push(ProjectionElem::Field(field, ()));
2784 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2786 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2787 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2788 use crate::mir::ProjectionElem::*;
2790 let base = self.base.fold_with(folder);
2791 let projs: Vec<_> = self.projs
2796 Field(f, ()) => Field(f.clone(), ()),
2797 Index(()) => Index(()),
2798 elem => elem.clone(),
2802 UserTypeProjection { base, projs }
2805 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2806 self.base.visit_with(visitor)
2807 // Note: there's nothing in `self.proj` to visit.
2812 pub struct Promoted {
2814 DEBUG_FORMAT = "promoted[{}]"
2818 impl<'tcx> Debug for Constant<'tcx> {
2819 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2820 write!(fmt, "{}", self)
2824 impl<'tcx> Display for Constant<'tcx> {
2825 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2826 write!(fmt, "const ")?;
2827 write!(fmt, "{}", self.literal)
2831 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2832 type Node = BasicBlock;
2835 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2836 fn num_nodes(&self) -> usize {
2837 self.basic_blocks.len()
2841 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2842 fn start_node(&self) -> Self::Node {
2847 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2848 fn predecessors<'graph>(
2851 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2852 self.predecessors_for(node).clone().into_iter()
2856 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2857 fn successors<'graph>(
2860 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2861 self.basic_blocks[node].terminator().successors().cloned()
2865 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2866 type Item = BasicBlock;
2867 type Iter = IntoIter<BasicBlock>;
2870 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2871 type Item = BasicBlock;
2872 type Iter = iter::Cloned<Successors<'b>>;
2875 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2876 pub struct Location {
2877 /// the location is within this block
2878 pub block: BasicBlock,
2880 /// the location is the start of the statement; or, if `statement_index`
2881 /// == num-statements, then the start of the terminator.
2882 pub statement_index: usize,
2885 impl fmt::Debug for Location {
2886 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2887 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2892 pub const START: Location = Location {
2897 /// Returns the location immediately after this one within the enclosing block.
2899 /// Note that if this location represents a terminator, then the
2900 /// resulting location would be out of bounds and invalid.
2901 pub fn successor_within_block(&self) -> Location {
2904 statement_index: self.statement_index + 1,
2908 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2909 pub fn is_predecessor_of<'tcx>(&self, other: Location, mir: &Body<'tcx>) -> bool {
2910 // If we are in the same block as the other location and are an earlier statement
2911 // then we are a predecessor of `other`.
2912 if self.block == other.block && self.statement_index < other.statement_index {
2916 // If we're in another block, then we want to check that block is a predecessor of `other`.
2917 let mut queue: Vec<BasicBlock> = mir.predecessors_for(other.block).clone();
2918 let mut visited = FxHashSet::default();
2920 while let Some(block) = queue.pop() {
2921 // If we haven't visited this block before, then make sure we visit it's predecessors.
2922 if visited.insert(block) {
2923 queue.append(&mut mir.predecessors_for(block).clone());
2928 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2929 // we found that block by looking at the predecessors of `other`).
2930 if self.block == block {
2938 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2939 if self.block == other.block {
2940 self.statement_index <= other.statement_index
2942 dominators.is_dominated_by(other.block, self.block)
2947 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2948 pub enum UnsafetyViolationKind {
2950 /// Permitted in const fn and regular fns.
2952 ExternStatic(hir::HirId),
2953 BorrowPacked(hir::HirId),
2956 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2957 pub struct UnsafetyViolation {
2958 pub source_info: SourceInfo,
2959 pub description: InternedString,
2960 pub details: InternedString,
2961 pub kind: UnsafetyViolationKind,
2964 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2965 pub struct UnsafetyCheckResult {
2966 /// Violations that are propagated *upwards* from this function
2967 pub violations: Lrc<[UnsafetyViolation]>,
2968 /// unsafe blocks in this function, along with whether they are used. This is
2969 /// used for the "unused_unsafe" lint.
2970 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2974 pub struct GeneratorSavedLocal {
2976 DEBUG_FORMAT = "_{}",
2980 /// The layout of generator state
2981 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2982 pub struct GeneratorLayout<'tcx> {
2983 /// The type of every local stored inside the generator.
2984 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2986 /// Which of the above fields are in each variant. Note that one field may
2987 /// be stored in multiple variants.
2988 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2990 /// Names and scopes of all the stored generator locals.
2991 /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
2992 /// debuginfo generation, and will be removed at some point.
2993 /// Do **NOT** use it for anything else, local information should not be
2994 /// in the MIR, please rely on local crate HIR or other side-channels.
2995 pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
2998 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2999 pub struct BorrowCheckResult<'gcx> {
3000 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
3001 pub used_mut_upvars: SmallVec<[Field; 8]>,
3004 /// After we borrow check a closure, we are left with various
3005 /// requirements that we have inferred between the free regions that
3006 /// appear in the closure's signature or on its field types. These
3007 /// requirements are then verified and proved by the closure's
3008 /// creating function. This struct encodes those requirements.
3010 /// The requirements are listed as being between various
3011 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
3012 /// vids refer to the free regions that appear in the closure (or
3013 /// generator's) type, in order of appearance. (This numbering is
3014 /// actually defined by the `UniversalRegions` struct in the NLL
3015 /// region checker. See for example
3016 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
3017 /// regions in the closure's type "as if" they were erased, so their
3018 /// precise identity is not important, only their position.
3020 /// Example: If type check produces a closure with the closure substs:
3023 /// ClosureSubsts = [
3024 /// i8, // the "closure kind"
3025 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
3026 /// &'a String, // some upvar
3030 /// here, there is one unique free region (`'a`) but it appears
3031 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
3034 /// ClosureSubsts = [
3035 /// i8, // the "closure kind"
3036 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
3037 /// &'2 String, // some upvar
3041 /// Now the code might impose a requirement like `'1: '2`. When an
3042 /// instance of the closure is created, the corresponding free regions
3043 /// can be extracted from its type and constrained to have the given
3044 /// outlives relationship.
3046 /// In some cases, we have to record outlives requirements between
3047 /// types and regions as well. In that case, if those types include
3048 /// any regions, those regions are recorded as `ReClosureBound`
3049 /// instances assigned one of these same indices. Those regions will
3050 /// be substituted away by the creator. We use `ReClosureBound` in
3051 /// that case because the regions must be allocated in the global
3052 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
3053 /// internally within the rest of the NLL code).
3054 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3055 pub struct ClosureRegionRequirements<'gcx> {
3056 /// The number of external regions defined on the closure. In our
3057 /// example above, it would be 3 -- one for `'static`, then `'1`
3058 /// and `'2`. This is just used for a sanity check later on, to
3059 /// make sure that the number of regions we see at the callsite
3061 pub num_external_vids: usize,
3063 /// Requirements between the various free regions defined in
3065 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
3068 /// Indicates an outlives constraint between a type or between two
3069 /// free-regions declared on the closure.
3070 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3071 pub struct ClosureOutlivesRequirement<'tcx> {
3072 // This region or type ...
3073 pub subject: ClosureOutlivesSubject<'tcx>,
3075 // ... must outlive this one.
3076 pub outlived_free_region: ty::RegionVid,
3078 // If not, report an error here ...
3079 pub blame_span: Span,
3081 // ... due to this reason.
3082 pub category: ConstraintCategory,
3085 /// Outlives constraints can be categorized to determine whether and why they
3086 /// are interesting (for error reporting). Order of variants indicates sort
3087 /// order of the category, thereby influencing diagnostic output.
3089 /// See also [rustc_mir::borrow_check::nll::constraints]
3090 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
3091 Hash, RustcEncodable, RustcDecodable, HashStable)]
3092 pub enum ConstraintCategory {
3100 /// A constraint that came from checking the body of a closure.
3102 /// We try to get the category that the closure used when reporting this.
3110 /// A "boring" constraint (caused by the given location) is one that
3111 /// the user probably doesn't want to see described in diagnostics,
3112 /// because it is kind of an artifact of the type system setup.
3113 /// Example: `x = Foo { field: y }` technically creates
3114 /// intermediate regions representing the "type of `Foo { field: y
3115 /// }`", and data flows from `y` into those variables, but they
3116 /// are not very interesting. The assignment into `x` on the other
3119 // Boring and applicable everywhere.
3122 /// A constraint that doesn't correspond to anything the user sees.
3126 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
3127 /// that must outlive some region.
3128 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3129 pub enum ClosureOutlivesSubject<'tcx> {
3130 /// Subject is a type, typically a type parameter, but could also
3131 /// be a projection. Indicates a requirement like `T: 'a` being
3132 /// passed to the caller, where the type here is `T`.
3134 /// The type here is guaranteed not to contain any free regions at
3138 /// Subject is a free region from the closure. Indicates a requirement
3139 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3140 Region(ty::RegionVid),
3144 * TypeFoldable implementations for MIR types
3147 CloneTypeFoldableAndLiftImpls! {
3157 SourceScopeLocalData,
3158 UserTypeAnnotationIndex,
3161 BraceStructTypeFoldableImpl! {
3162 impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
3166 source_scope_local_data,
3172 user_type_annotations,
3174 __upvar_debuginfo_codegen_only_do_not_use,
3176 control_flow_destroyed,
3182 BraceStructTypeFoldableImpl! {
3183 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3186 __local_debuginfo_codegen_only_do_not_use,
3190 BraceStructTypeFoldableImpl! {
3191 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3204 BraceStructTypeFoldableImpl! {
3205 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3212 BraceStructTypeFoldableImpl! {
3213 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3218 EnumTypeFoldableImpl! {
3219 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3220 (StatementKind::Assign)(a, b),
3221 (StatementKind::FakeRead)(cause, place),
3222 (StatementKind::SetDiscriminant) { place, variant_index },
3223 (StatementKind::StorageLive)(a),
3224 (StatementKind::StorageDead)(a),
3225 (StatementKind::InlineAsm)(a),
3226 (StatementKind::Retag)(kind, place),
3227 (StatementKind::AscribeUserType)(a, v, b),
3228 (StatementKind::Nop),
3232 BraceStructTypeFoldableImpl! {
3233 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3240 EnumTypeFoldableImpl! {
3241 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3242 (ClearCrossCrate::Clear),
3243 (ClearCrossCrate::Set)(a),
3244 } where T: TypeFoldable<'tcx>
3247 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3248 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3249 use crate::mir::TerminatorKind::*;
3251 let kind = match self.kind {
3252 Goto { target } => Goto { target },
3259 discr: discr.fold_with(folder),
3260 switch_ty: switch_ty.fold_with(folder),
3261 values: values.clone(),
3262 targets: targets.clone(),
3269 location: location.fold_with(folder),
3278 } => DropAndReplace {
3279 location: location.fold_with(folder),
3280 value: value.fold_with(folder),
3289 value: value.fold_with(folder),
3300 let dest = destination
3302 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3305 func: func.fold_with(folder),
3306 args: args.fold_with(folder),
3319 let msg = if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3320 InterpError::BoundsCheck {
3321 len: len.fold_with(folder),
3322 index: index.fold_with(folder),
3328 cond: cond.fold_with(folder),
3335 GeneratorDrop => GeneratorDrop,
3339 Unreachable => Unreachable,
3342 ref imaginary_targets,
3345 imaginary_targets: imaginary_targets.clone(),
3356 source_info: self.source_info,
3361 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3362 use crate::mir::TerminatorKind::*;
3369 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3370 Drop { ref location, .. } => location.visit_with(visitor),
3375 } => location.visit_with(visitor) || value.visit_with(visitor),
3376 Yield { ref value, .. } => value.visit_with(visitor),
3383 let dest = if let Some((ref loc, _)) = *destination {
3384 loc.visit_with(visitor)
3388 dest || func.visit_with(visitor) || args.visit_with(visitor)
3391 ref cond, ref msg, ..
3393 if cond.visit_with(visitor) {
3394 if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3395 len.visit_with(visitor) || index.visit_with(visitor)
3410 | FalseUnwind { .. } => false,
3415 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3416 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3418 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3423 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3424 if let &Place::Projection(ref p) = self {
3425 p.visit_with(visitor)
3432 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3433 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3434 use crate::mir::Rvalue::*;
3436 Use(ref op) => Use(op.fold_with(folder)),
3437 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3438 Ref(region, bk, ref place) => {
3439 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3441 Len(ref place) => Len(place.fold_with(folder)),
3442 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3443 BinaryOp(op, ref rhs, ref lhs) => {
3444 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3446 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3447 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3449 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3450 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3451 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3452 Aggregate(ref kind, ref fields) => {
3453 let kind = box match **kind {
3454 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3455 AggregateKind::Tuple => AggregateKind::Tuple,
3456 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3459 substs.fold_with(folder),
3460 user_ty.fold_with(folder),
3463 AggregateKind::Closure(id, substs) => {
3464 AggregateKind::Closure(id, substs.fold_with(folder))
3466 AggregateKind::Generator(id, substs, movablity) => {
3467 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3470 Aggregate(kind, fields.fold_with(folder))
3475 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3476 use crate::mir::Rvalue::*;
3478 Use(ref op) => op.visit_with(visitor),
3479 Repeat(ref op, _) => op.visit_with(visitor),
3480 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3481 Len(ref place) => place.visit_with(visitor),
3482 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3483 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3484 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3486 UnaryOp(_, ref val) => val.visit_with(visitor),
3487 Discriminant(ref place) => place.visit_with(visitor),
3488 NullaryOp(_, ty) => ty.visit_with(visitor),
3489 Aggregate(ref kind, ref fields) => {
3491 AggregateKind::Array(ty) => ty.visit_with(visitor),
3492 AggregateKind::Tuple => false,
3493 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3494 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3496 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3497 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3498 }) || fields.visit_with(visitor)
3504 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3505 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3507 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3508 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3509 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3513 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3515 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3516 Operand::Constant(ref c) => c.visit_with(visitor),
3521 impl<'tcx> TypeFoldable<'tcx> for Projection<'tcx> {
3522 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3523 use crate::mir::ProjectionElem::*;
3525 let base = self.base.fold_with(folder);
3526 let elem = match self.elem {
3528 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3529 Index(ref v) => Index(v.fold_with(folder)),
3530 ref elem => elem.clone(),
3533 Projection { base, elem }
3536 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3537 use crate::mir::ProjectionElem::*;
3539 self.base.visit_with(visitor) || match self.elem {
3540 Field(_, ref ty) => ty.visit_with(visitor),
3541 Index(ref v) => v.visit_with(visitor),
3547 impl<'tcx> TypeFoldable<'tcx> for Field {
3548 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3551 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3556 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3557 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3560 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3565 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3566 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3568 span: self.span.clone(),
3569 ty: self.ty.fold_with(folder),
3570 user_ty: self.user_ty.fold_with(folder),
3571 literal: self.literal.fold_with(folder),
3574 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3575 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)