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::bit_set::BitMatrix;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_data_structures::graph::dominators::{dominators, Dominators};
15 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
16 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
17 use rustc_data_structures::sync::Lrc;
18 use rustc_data_structures::sync::MappedReadGuard;
19 use rustc_macros::HashStable;
20 use crate::rustc_serialize::{self as serialize};
21 use smallvec::SmallVec;
23 use std::fmt::{self, Debug, Formatter, Write, Display};
24 use std::iter::FusedIterator;
25 use std::ops::{Index, IndexMut};
27 use std::vec::IntoIter;
28 use std::{iter, mem, option, u32};
29 use syntax::ast::Name;
30 use syntax::symbol::{InternedString, Symbol};
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
33 use crate::ty::subst::{Subst, SubstsRef};
34 use crate::ty::layout::VariantIdx;
36 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
37 UserTypeAnnotationIndex,
39 use crate::ty::print::{FmtPrinter, Printer};
40 use crate::ty::adjustment::{PointerCast};
42 pub use crate::mir::interpret::AssertMessage;
52 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
54 pub trait HasLocalDecls<'tcx> {
55 fn local_decls(&self) -> &LocalDecls<'tcx>;
58 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx> {
64 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
65 fn local_decls(&self) -> &LocalDecls<'tcx> {
70 /// The various "big phases" that MIR goes through.
72 /// Warning: ordering of variants is significant
73 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
82 /// Gets the index of the current MirPhase within the set of all MirPhases.
83 pub fn phase_index(&self) -> usize {
88 /// Lowered representation of a single function.
89 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
90 pub struct Body<'tcx> {
91 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
92 /// that indexes into this vector.
93 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
95 /// Records how far through the "desugaring and optimization" process this particular
96 /// MIR has traversed. This is particularly useful when inlining, since in that context
97 /// we instantiate the promoted constants and add them to our promoted vector -- but those
98 /// promoted items have already been optimized, whereas ours have not. This field allows
99 /// us to see the difference and forego optimization on the inlined promoted items.
102 /// List of source scopes; these are referenced by statements
103 /// and used for debuginfo. Indexed by a `SourceScope`.
104 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
106 /// Crate-local information for each source scope, that can't (and
107 /// needn't) be tracked across crates.
108 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
110 /// Rvalues promoted from this function, such as borrows of constants.
111 /// Each of them is the Body of a constant with the fn's type parameters
112 /// in scope, but a separate set of locals.
113 pub promoted: IndexVec<Promoted, Body<'tcx>>,
115 /// Yields type of the function, if it is a generator.
116 pub yield_ty: Option<Ty<'tcx>>,
118 /// Generator drop glue
119 pub generator_drop: Option<Box<Body<'tcx>>>,
121 /// The layout of a generator. Produced by the state transformation.
122 pub generator_layout: Option<GeneratorLayout<'tcx>>,
124 /// Declarations of locals.
126 /// The first local is the return value pointer, followed by `arg_count`
127 /// locals for the function arguments, followed by any user-declared
128 /// variables and temporaries.
129 pub local_decls: LocalDecls<'tcx>,
131 /// User type annotations
132 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
134 /// Number of arguments this function takes.
136 /// Starting at local 1, `arg_count` locals will be provided by the caller
137 /// and can be assumed to be initialized.
139 /// If this MIR was built for a constant, this will be 0.
140 pub arg_count: usize,
142 /// Mark an argument local (which must be a tuple) as getting passed as
143 /// its individual components at the LLVM level.
145 /// This is used for the "rust-call" ABI.
146 pub spread_arg: Option<Local>,
148 /// Names and capture modes of all the closure upvars, assuming
149 /// the first argument is either the closure or a reference to it.
150 // NOTE(eddyb) This is *strictly* a temporary hack for codegen
151 // debuginfo generation, and will be removed at some point.
152 // Do **NOT** use it for anything else, upvar information should not be
153 // in the MIR, please rely on local crate HIR or other side-channels.
154 pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
156 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
157 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
158 /// this conversion from happening and use short circuiting, we will cause the following code
159 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
161 /// List of places where control flow was destroyed. Used for error reporting.
162 pub control_flow_destroyed: Vec<(Span, String)>,
164 /// A span representing this MIR, for error reporting
167 /// A cache for various calculations
171 impl<'tcx> Body<'tcx> {
173 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
174 source_scopes: IndexVec<SourceScope, SourceScopeData>,
175 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
176 promoted: IndexVec<Promoted, Body<'tcx>>,
177 yield_ty: Option<Ty<'tcx>>,
178 local_decls: LocalDecls<'tcx>,
179 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
181 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
183 control_flow_destroyed: Vec<(Span, String)>,
185 // We need `arg_count` locals, and one for the return place
187 local_decls.len() >= arg_count + 1,
188 "expected at least {} locals, got {}",
194 phase: MirPhase::Build,
197 source_scope_local_data,
200 generator_drop: None,
201 generator_layout: None,
203 user_type_annotations,
205 __upvar_debuginfo_codegen_only_do_not_use,
208 cache: cache::Cache::new(),
209 control_flow_destroyed,
214 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
219 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
220 self.cache.invalidate();
221 &mut self.basic_blocks
225 pub fn basic_blocks_and_local_decls_mut(
228 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
229 &mut LocalDecls<'tcx>,
231 self.cache.invalidate();
232 (&mut self.basic_blocks, &mut self.local_decls)
236 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
237 self.cache.predecessors(self)
241 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
242 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
246 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
247 let if_zero_locations = if loc.statement_index == 0 {
248 let predecessor_blocks = self.predecessors_for(loc.block);
249 let num_predecessor_blocks = predecessor_blocks.len();
251 (0..num_predecessor_blocks)
252 .map(move |i| predecessor_blocks[i])
253 .map(move |bb| self.terminator_loc(bb)),
259 let if_not_zero_locations = if loc.statement_index == 0 {
264 statement_index: loc.statement_index - 1,
271 .chain(if_not_zero_locations)
275 pub fn dominators(&self) -> Dominators<BasicBlock> {
280 pub fn local_kind(&self, local: Local) -> LocalKind {
281 let index = local.as_usize();
284 self.local_decls[local].mutability == Mutability::Mut,
285 "return place should be mutable"
288 LocalKind::ReturnPointer
289 } else if index < self.arg_count + 1 {
291 } else if self.local_decls[local].name.is_some() {
298 /// Returns an iterator over all temporaries.
300 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
301 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
302 let local = Local::new(index);
303 if self.local_decls[local].is_user_variable.is_some() {
311 /// Returns an iterator over all user-declared locals.
313 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
314 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
315 let local = Local::new(index);
316 if self.local_decls[local].is_user_variable.is_some() {
324 /// Returns an iterator over all user-declared mutable locals.
326 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
327 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
328 let local = Local::new(index);
329 let decl = &self.local_decls[local];
330 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
338 /// Returns an iterator over all user-declared mutable arguments and locals.
340 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
341 (1..self.local_decls.len()).filter_map(move |index| {
342 let local = Local::new(index);
343 let decl = &self.local_decls[local];
344 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
345 && decl.mutability == Mutability::Mut
354 /// Returns an iterator over all function arguments.
356 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
357 let arg_count = self.arg_count;
358 (1..=arg_count).map(Local::new)
361 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
362 /// locals that are neither arguments nor the return place).
364 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
365 let arg_count = self.arg_count;
366 let local_count = self.local_decls.len();
367 (arg_count + 1..local_count).map(Local::new)
370 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
371 /// invalidating statement indices in `Location`s.
372 pub fn make_statement_nop(&mut self, location: Location) {
373 let block = &mut self[location.block];
374 debug_assert!(location.statement_index < block.statements.len());
375 block.statements[location.statement_index].make_nop()
378 /// Returns the source info associated with `location`.
379 pub fn source_info(&self, location: Location) -> &SourceInfo {
380 let block = &self[location.block];
381 let stmts = &block.statements;
382 let idx = location.statement_index;
383 if idx < stmts.len() {
384 &stmts[idx].source_info
386 assert_eq!(idx, stmts.len());
387 &block.terminator().source_info
391 /// Checks if `sub` is a sub scope of `sup`
392 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
394 match self.source_scopes[sub].parent_scope {
395 None => return false,
402 /// Returns the return type, it always return first element from `local_decls` array
403 pub fn return_ty(&self) -> Ty<'tcx> {
404 self.local_decls[RETURN_PLACE].ty
407 /// Gets the location of the terminator for the given block
408 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
411 statement_index: self[bb].statements.len(),
416 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
419 /// Unsafe because of a PushUnsafeBlock
421 /// Unsafe because of an unsafe fn
423 /// Unsafe because of an `unsafe` block
424 ExplicitUnsafe(hir::HirId),
427 impl_stable_hash_for!(struct Body<'tcx> {
431 source_scope_local_data,
437 user_type_annotations,
439 __upvar_debuginfo_codegen_only_do_not_use,
441 control_flow_destroyed,
446 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
447 type Output = BasicBlockData<'tcx>;
450 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
451 &self.basic_blocks()[index]
455 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
457 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
458 &mut self.basic_blocks_mut()[index]
462 #[derive(Copy, Clone, Debug, HashStable)]
463 pub enum ClearCrossCrate<T> {
468 impl<T> ClearCrossCrate<T> {
469 pub fn assert_crate_local(self) -> T {
471 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
472 ClearCrossCrate::Set(v) => v,
477 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
478 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
480 /// Grouped information about the source code origin of a MIR entity.
481 /// Intended to be inspected by diagnostics and debuginfo.
482 /// Most passes can work with it as a whole, within a single function.
483 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
484 pub struct SourceInfo {
485 /// Source span for the AST pertaining to this MIR entity.
488 /// The source scope, keeping track of which bindings can be
489 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
490 pub scope: SourceScope,
493 ///////////////////////////////////////////////////////////////////////////
494 // Mutability and borrow kinds
496 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
497 pub enum Mutability {
502 impl From<Mutability> for hir::Mutability {
503 fn from(m: Mutability) -> Self {
505 Mutability::Mut => hir::MutMutable,
506 Mutability::Not => hir::MutImmutable,
511 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd,
512 Ord, RustcEncodable, RustcDecodable, HashStable)]
513 pub enum BorrowKind {
514 /// Data must be immutable and is aliasable.
517 /// The immediately borrowed place must be immutable, but projections from
518 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
519 /// conflict with a mutable borrow of `a.b.c`.
521 /// This is used when lowering matches: when matching on a place we want to
522 /// ensure that place have the same value from the start of the match until
523 /// an arm is selected. This prevents this code from compiling:
525 /// let mut x = &Some(0);
528 /// Some(_) if { x = &None; false } => (),
532 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
533 /// should not prevent `if let None = x { ... }`, for example, because the
534 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
535 /// We can also report errors with this kind of borrow differently.
538 /// Data must be immutable but not aliasable. This kind of borrow
539 /// cannot currently be expressed by the user and is used only in
540 /// implicit closure bindings. It is needed when the closure is
541 /// borrowing or mutating a mutable referent, e.g.:
543 /// let x: &mut isize = ...;
544 /// let y = || *x += 5;
546 /// If we were to try to translate this closure into a more explicit
547 /// form, we'd encounter an error with the code as written:
549 /// struct Env { x: & &mut isize }
550 /// let x: &mut isize = ...;
551 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
552 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
554 /// This is then illegal because you cannot mutate an `&mut` found
555 /// in an aliasable location. To solve, you'd have to translate with
556 /// an `&mut` borrow:
558 /// struct Env { x: & &mut isize }
559 /// let x: &mut isize = ...;
560 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
561 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
563 /// Now the assignment to `**env.x` is legal, but creating a
564 /// mutable pointer to `x` is not because `x` is not mutable. We
565 /// could fix this by declaring `x` as `let mut x`. This is ok in
566 /// user code, if awkward, but extra weird for closures, since the
567 /// borrow is hidden.
569 /// So we introduce a "unique imm" borrow -- the referent is
570 /// immutable, but not aliasable. This solves the problem. For
571 /// simplicity, we don't give users the way to express this
572 /// borrow, it's just used when translating closures.
575 /// Data is mutable and not aliasable.
577 /// `true` if this borrow arose from method-call auto-ref
578 /// (i.e., `adjustment::Adjust::Borrow`).
579 allow_two_phase_borrow: bool,
584 pub fn allows_two_phase_borrow(&self) -> bool {
586 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
587 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
592 ///////////////////////////////////////////////////////////////////////////
593 // Variables and temps
598 DEBUG_FORMAT = "_{}",
599 const RETURN_PLACE = 0,
603 /// Classifies locals into categories. See `Body::local_kind`.
604 #[derive(PartialEq, Eq, Debug, HashStable)]
606 /// User-declared variable binding
608 /// Compiler-introduced temporary
610 /// Function argument
612 /// Location of function's return value
616 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
617 pub struct VarBindingForm<'tcx> {
618 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
619 pub binding_mode: ty::BindingMode,
620 /// If an explicit type was provided for this variable binding,
621 /// this holds the source Span of that type.
623 /// NOTE: if you want to change this to a `HirId`, be wary that
624 /// doing so breaks incremental compilation (as of this writing),
625 /// while a `Span` does not cause our tests to fail.
626 pub opt_ty_info: Option<Span>,
627 /// Place of the RHS of the =, or the subject of the `match` where this
628 /// variable is initialized. None in the case of `let PATTERN;`.
629 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
630 /// (a) the right-hand side isn't evaluated as a place expression.
631 /// (b) it gives a way to separate this case from the remaining cases
633 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
634 /// Span of the pattern in which this variable was bound.
638 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
639 pub enum BindingForm<'tcx> {
640 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
641 Var(VarBindingForm<'tcx>),
642 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
643 ImplicitSelf(ImplicitSelfKind),
644 /// Reference used in a guard expression to ensure immutability.
648 /// Represents what type of implicit self a function has, if any.
649 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
650 pub enum ImplicitSelfKind {
651 /// Represents a `fn x(self);`.
653 /// Represents a `fn x(mut self);`.
655 /// Represents a `fn x(&self);`.
657 /// Represents a `fn x(&mut self);`.
659 /// Represents when a function does not have a self argument or
660 /// when a function has a `self: X` argument.
664 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
666 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
673 impl_stable_hash_for!(enum self::ImplicitSelfKind {
681 impl_stable_hash_for!(enum self::MirPhase {
688 mod binding_form_impl {
689 use crate::ich::StableHashingContext;
690 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
692 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
693 fn hash_stable<W: StableHasherResult>(
695 hcx: &mut StableHashingContext<'a>,
696 hasher: &mut StableHasher<W>,
698 use super::BindingForm::*;
699 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
702 Var(binding) => binding.hash_stable(hcx, hasher),
703 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
710 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
711 /// created during evaluation of expressions in a block tail
712 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
714 /// It is used to improve diagnostics when such temporaries are
715 /// involved in borrow_check errors, e.g., explanations of where the
716 /// temporaries come from, when their destructors are run, and/or how
717 /// one might revise the code to satisfy the borrow checker's rules.
718 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
719 pub struct BlockTailInfo {
720 /// If `true`, then the value resulting from evaluating this tail
721 /// expression is ignored by the block's expression context.
723 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
724 /// but not e.g., `let _x = { ...; tail };`
725 pub tail_result_is_ignored: bool,
728 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
732 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
733 /// argument, or the return place.
734 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
735 pub struct LocalDecl<'tcx> {
736 /// `let mut x` vs `let x`.
738 /// Temporaries and the return place are always mutable.
739 pub mutability: Mutability,
741 /// Some(binding_mode) if this corresponds to a user-declared local variable.
743 /// This is solely used for local diagnostics when generating
744 /// warnings/errors when compiling the current crate, and
745 /// therefore it need not be visible across crates. pnkfelix
746 /// currently hypothesized we *need* to wrap this in a
747 /// `ClearCrossCrate` as long as it carries as `HirId`.
748 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
750 /// `true` if this is an internal local.
752 /// These locals are not based on types in the source code and are only used
753 /// for a few desugarings at the moment.
755 /// The generator transformation will sanity check the locals which are live
756 /// across a suspension point against the type components of the generator
757 /// which type checking knows are live across a suspension point. We need to
758 /// flag drop flags to avoid triggering this check as they are introduced
761 /// Unsafety checking will also ignore dereferences of these locals,
762 /// so they can be used for raw pointers only used in a desugaring.
764 /// This should be sound because the drop flags are fully algebraic, and
765 /// therefore don't affect the OIBIT or outlives properties of the
769 /// If this local is a temporary and `is_block_tail` is `Some`,
770 /// then it is a temporary created for evaluation of some
771 /// subexpression of some block's tail expression (with no
772 /// intervening statement context).
773 pub is_block_tail: Option<BlockTailInfo>,
775 /// Type of this local.
778 /// If the user manually ascribed a type to this variable,
779 /// e.g., via `let x: T`, then we carry that type here. The MIR
780 /// borrow checker needs this information since it can affect
781 /// region inference.
782 pub user_ty: UserTypeProjections,
784 /// Name of the local, used in debuginfo and pretty-printing.
786 /// Note that function arguments can also have this set to `Some(_)`
787 /// to generate better debuginfo.
788 pub name: Option<Name>,
790 /// The *syntactic* (i.e., not visibility) source scope the local is defined
791 /// in. If the local was defined in a let-statement, this
792 /// is *within* the let-statement, rather than outside
795 /// This is needed because the visibility source scope of locals within
796 /// a let-statement is weird.
798 /// The reason is that we want the local to be *within* the let-statement
799 /// for lint purposes, but we want the local to be *after* the let-statement
800 /// for names-in-scope purposes.
802 /// That's it, if we have a let-statement like the one in this
806 /// fn foo(x: &str) {
807 /// #[allow(unused_mut)]
808 /// let mut x: u32 = { // <- one unused mut
809 /// let mut y: u32 = x.parse().unwrap();
816 /// Then, from a lint point of view, the declaration of `x: u32`
817 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
818 /// lint scopes are the same as the AST/HIR nesting.
820 /// However, from a name lookup point of view, the scopes look more like
821 /// as if the let-statements were `match` expressions:
824 /// fn foo(x: &str) {
826 /// match x.parse().unwrap() {
835 /// We care about the name-lookup scopes for debuginfo - if the
836 /// debuginfo instruction pointer is at the call to `x.parse()`, we
837 /// want `x` to refer to `x: &str`, but if it is at the call to
838 /// `drop(x)`, we want it to refer to `x: u32`.
840 /// To allow both uses to work, we need to have more than a single scope
841 /// for a local. We have the `source_info.scope` represent the
842 /// "syntactic" lint scope (with a variable being under its let
843 /// block) while the `visibility_scope` represents the "local variable"
844 /// scope (where the "rest" of a block is under all prior let-statements).
846 /// The end result looks like this:
850 /// │{ argument x: &str }
852 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
853 /// │ │ // in practice because I'm lazy.
855 /// │ │← x.source_info.scope
856 /// │ │← `x.parse().unwrap()`
858 /// │ │ │← y.source_info.scope
860 /// │ │ │{ let y: u32 }
862 /// │ │ │← y.visibility_scope
865 /// │ │{ let x: u32 }
866 /// │ │← x.visibility_scope
867 /// │ │← `drop(x)` // this accesses `x: u32`
869 pub source_info: SourceInfo,
871 /// Source scope within which the local is visible (for debuginfo)
872 /// (see `source_info` for more details).
873 pub visibility_scope: SourceScope,
876 impl<'tcx> LocalDecl<'tcx> {
877 /// Returns `true` only if local is a binding that can itself be
878 /// made mutable via the addition of the `mut` keyword, namely
879 /// something like the occurrences of `x` in:
880 /// - `fn foo(x: Type) { ... }`,
882 /// - or `match ... { C(x) => ... }`
883 pub fn can_be_made_mutable(&self) -> bool {
884 match self.is_user_variable {
885 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
886 binding_mode: ty::BindingMode::BindByValue(_),
892 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
899 /// Returns `true` if local is definitely not a `ref ident` or
900 /// `ref mut ident` binding. (Such bindings cannot be made into
901 /// mutable bindings, but the inverse does not necessarily hold).
902 pub fn is_nonref_binding(&self) -> bool {
903 match self.is_user_variable {
904 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
905 binding_mode: ty::BindingMode::BindByValue(_),
911 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
917 /// Returns `true` if this is a reference to a variable bound in a `match`
918 /// expression that is used to access said variable for the guard of the
920 pub fn is_ref_for_guard(&self) -> bool {
921 match self.is_user_variable {
922 Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
927 /// Returns `true` is the local is from a compiler desugaring, e.g.,
928 /// `__next` from a `for` loop.
930 pub fn from_compiler_desugaring(&self) -> bool {
931 self.source_info.span.compiler_desugaring_kind().is_some()
934 /// Creates a new `LocalDecl` for a temporary.
936 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
937 Self::new_local(ty, Mutability::Mut, false, span)
940 /// Converts `self` into same `LocalDecl` except tagged as immutable.
942 pub fn immutable(mut self) -> Self {
943 self.mutability = Mutability::Not;
947 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
949 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
950 assert!(self.is_block_tail.is_none());
951 self.is_block_tail = Some(info);
955 /// Creates a new `LocalDecl` for a internal temporary.
957 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
958 Self::new_local(ty, Mutability::Mut, true, span)
964 mutability: Mutability,
971 user_ty: UserTypeProjections::none(),
973 source_info: SourceInfo {
975 scope: OUTERMOST_SOURCE_SCOPE,
977 visibility_scope: OUTERMOST_SOURCE_SCOPE,
979 is_user_variable: None,
984 /// Builds a `LocalDecl` for the return place.
986 /// This must be inserted into the `local_decls` list as the first local.
988 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
990 mutability: Mutability::Mut,
992 user_ty: UserTypeProjections::none(),
993 source_info: SourceInfo {
995 scope: OUTERMOST_SOURCE_SCOPE,
997 visibility_scope: OUTERMOST_SOURCE_SCOPE,
1000 name: None, // FIXME maybe we do want some name here?
1001 is_user_variable: None,
1006 /// A closure capture, with its name and mode.
1007 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1008 pub struct UpvarDebuginfo {
1009 pub debug_name: Name,
1011 /// If true, the capture is behind a reference.
1015 ///////////////////////////////////////////////////////////////////////////
1019 pub struct BasicBlock {
1021 DEBUG_FORMAT = "bb{}",
1022 const START_BLOCK = 0,
1027 pub fn start_location(self) -> Location {
1035 ///////////////////////////////////////////////////////////////////////////
1036 // BasicBlockData and Terminator
1038 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1039 pub struct BasicBlockData<'tcx> {
1040 /// List of statements in this block.
1041 pub statements: Vec<Statement<'tcx>>,
1043 /// Terminator for this block.
1045 /// N.B., this should generally ONLY be `None` during construction.
1046 /// Therefore, you should generally access it via the
1047 /// `terminator()` or `terminator_mut()` methods. The only
1048 /// exception is that certain passes, such as `simplify_cfg`, swap
1049 /// out the terminator temporarily with `None` while they continue
1050 /// to recurse over the set of basic blocks.
1051 pub terminator: Option<Terminator<'tcx>>,
1053 /// If true, this block lies on an unwind path. This is used
1054 /// during codegen where distinct kinds of basic blocks may be
1055 /// generated (particularly for MSVC cleanup). Unwind blocks must
1056 /// only branch to other unwind blocks.
1057 pub is_cleanup: bool,
1060 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1061 pub struct Terminator<'tcx> {
1062 pub source_info: SourceInfo,
1063 pub kind: TerminatorKind<'tcx>,
1066 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1067 pub enum TerminatorKind<'tcx> {
1068 /// block should have one successor in the graph; we jump there
1069 Goto { target: BasicBlock },
1071 /// operand evaluates to an integer; jump depending on its value
1072 /// to one of the targets, and otherwise fallback to `otherwise`
1074 /// discriminant value being tested
1075 discr: Operand<'tcx>,
1077 /// type of value being tested
1078 switch_ty: Ty<'tcx>,
1080 /// Possible values. The locations to branch to in each case
1081 /// are found in the corresponding indices from the `targets` vector.
1082 values: Cow<'tcx, [u128]>,
1084 /// Possible branch sites. The last element of this vector is used
1085 /// for the otherwise branch, so targets.len() == values.len() + 1
1087 // This invariant is quite non-obvious and also could be improved.
1088 // One way to make this invariant is to have something like this instead:
1090 // branches: Vec<(ConstInt, BasicBlock)>,
1091 // otherwise: Option<BasicBlock> // exhaustive if None
1093 // However we’ve decided to keep this as-is until we figure a case
1094 // where some other approach seems to be strictly better than other.
1095 targets: Vec<BasicBlock>,
1098 /// Indicates that the landing pad is finished and unwinding should
1099 /// continue. Emitted by build::scope::diverge_cleanup.
1102 /// Indicates that the landing pad is finished and that the process
1103 /// should abort. Used to prevent unwinding for foreign items.
1106 /// Indicates a normal return. The return place should have
1107 /// been filled in by now. This should occur at most once.
1110 /// Indicates a terminator that can never be reached.
1115 location: Place<'tcx>,
1117 unwind: Option<BasicBlock>,
1120 /// Drop the Place and assign the new value over it. This ensures
1121 /// that the assignment to `P` occurs *even if* the destructor for
1122 /// place unwinds. Its semantics are best explained by the
1127 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1135 /// Drop(P, goto BB1, unwind BB2)
1138 /// // P is now uninitialized
1142 /// // P is now uninitialized -- its dtor panicked
1147 location: Place<'tcx>,
1148 value: Operand<'tcx>,
1150 unwind: Option<BasicBlock>,
1153 /// Block ends with a call of a converging function
1155 /// The function that’s being called
1156 func: Operand<'tcx>,
1157 /// Arguments the function is called with.
1158 /// These are owned by the callee, which is free to modify them.
1159 /// This allows the memory occupied by "by-value" arguments to be
1160 /// reused across function calls without duplicating the contents.
1161 args: Vec<Operand<'tcx>>,
1162 /// Destination for the return value. If some, the call is converging.
1163 destination: Option<(Place<'tcx>, BasicBlock)>,
1164 /// Cleanups to be done if the call unwinds.
1165 cleanup: Option<BasicBlock>,
1166 /// Whether this is from a call in HIR, rather than from an overloaded
1167 /// operator. True for overloaded function call.
1168 from_hir_call: bool,
1171 /// Jump to the target if the condition has the expected value,
1172 /// otherwise panic with a message and a cleanup target.
1174 cond: Operand<'tcx>,
1176 msg: AssertMessage<'tcx>,
1178 cleanup: Option<BasicBlock>,
1183 /// The value to return
1184 value: Operand<'tcx>,
1185 /// Where to resume to
1187 /// Cleanup to be done if the generator is dropped at this suspend point
1188 drop: Option<BasicBlock>,
1191 /// Indicates the end of the dropping of a generator
1194 /// A block where control flow only ever takes one real path, but borrowck
1195 /// needs to be more conservative.
1197 /// The target normal control flow will take
1198 real_target: BasicBlock,
1199 /// The list of blocks control flow could conceptually take, but won't
1201 imaginary_targets: Vec<BasicBlock>,
1203 /// A terminator for blocks that only take one path in reality, but where we
1204 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1205 /// This can arise in infinite loops with no function calls for example.
1207 /// The target normal control flow will take
1208 real_target: BasicBlock,
1209 /// The imaginary cleanup block link. This particular path will never be taken
1210 /// in practice, but in order to avoid fragility we want to always
1211 /// consider it in borrowck. We don't want to accept programs which
1212 /// pass borrowck only when panic=abort or some assertions are disabled
1213 /// due to release vs. debug mode builds. This needs to be an Option because
1214 /// of the remove_noop_landing_pads and no_landing_pads passes
1215 unwind: Option<BasicBlock>,
1219 pub type Successors<'a> =
1220 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1221 pub type SuccessorsMut<'a> =
1222 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1224 impl<'tcx> Terminator<'tcx> {
1225 pub fn successors(&self) -> Successors<'_> {
1226 self.kind.successors()
1229 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1230 self.kind.successors_mut()
1233 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1237 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1238 self.kind.unwind_mut()
1242 impl<'tcx> TerminatorKind<'tcx> {
1244 tcx: TyCtxt<'gcx, 'tcx>,
1245 cond: Operand<'tcx>,
1248 ) -> TerminatorKind<'tcx> {
1249 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1250 TerminatorKind::SwitchInt {
1252 switch_ty: tcx.types.bool,
1253 values: From::from(BOOL_SWITCH_FALSE),
1254 targets: vec![f, t],
1258 pub fn successors(&self) -> Successors<'_> {
1259 use self::TerminatorKind::*;
1270 } => None.into_iter().chain(&[]),
1271 Goto { target: ref t }
1274 cleanup: Some(ref t),
1278 destination: Some((_, ref t)),
1305 } => Some(t).into_iter().chain(&[]),
1307 destination: Some((_, ref t)),
1308 cleanup: Some(ref u),
1318 unwind: Some(ref u),
1323 unwind: Some(ref u),
1328 cleanup: Some(ref u),
1333 unwind: Some(ref u),
1334 } => Some(t).into_iter().chain(slice::from_ref(u)),
1335 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1338 ref imaginary_targets,
1339 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1343 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1344 use self::TerminatorKind::*;
1355 } => None.into_iter().chain(&mut []),
1356 Goto { target: ref mut t }
1359 cleanup: Some(ref mut t),
1363 destination: Some((_, ref mut t)),
1388 real_target: ref mut t,
1390 } => Some(t).into_iter().chain(&mut []),
1392 destination: Some((_, ref mut t)),
1393 cleanup: Some(ref mut u),
1398 drop: Some(ref mut u),
1403 unwind: Some(ref mut u),
1408 unwind: Some(ref mut u),
1413 cleanup: Some(ref mut u),
1417 real_target: ref mut t,
1418 unwind: Some(ref mut u),
1419 } => Some(t).into_iter().chain(slice::from_mut(u)),
1422 } => None.into_iter().chain(&mut targets[..]),
1424 ref mut real_target,
1425 ref mut imaginary_targets,
1426 } => Some(real_target)
1428 .chain(&mut imaginary_targets[..]),
1432 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1434 TerminatorKind::Goto { .. }
1435 | TerminatorKind::Resume
1436 | TerminatorKind::Abort
1437 | TerminatorKind::Return
1438 | TerminatorKind::Unreachable
1439 | TerminatorKind::GeneratorDrop
1440 | TerminatorKind::Yield { .. }
1441 | TerminatorKind::SwitchInt { .. }
1442 | TerminatorKind::FalseEdges { .. } => None,
1443 TerminatorKind::Call {
1444 cleanup: ref unwind,
1447 | TerminatorKind::Assert {
1448 cleanup: ref unwind,
1451 | TerminatorKind::DropAndReplace { ref unwind, .. }
1452 | TerminatorKind::Drop { ref unwind, .. }
1453 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1457 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1459 TerminatorKind::Goto { .. }
1460 | TerminatorKind::Resume
1461 | TerminatorKind::Abort
1462 | TerminatorKind::Return
1463 | TerminatorKind::Unreachable
1464 | TerminatorKind::GeneratorDrop
1465 | TerminatorKind::Yield { .. }
1466 | TerminatorKind::SwitchInt { .. }
1467 | TerminatorKind::FalseEdges { .. } => None,
1468 TerminatorKind::Call {
1469 cleanup: ref mut unwind,
1472 | TerminatorKind::Assert {
1473 cleanup: ref mut unwind,
1476 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1477 | TerminatorKind::Drop { ref mut unwind, .. }
1478 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1483 impl<'tcx> BasicBlockData<'tcx> {
1484 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1492 /// Accessor for terminator.
1494 /// Terminator may not be None after construction of the basic block is complete. This accessor
1495 /// provides a convenience way to reach the terminator.
1496 pub fn terminator(&self) -> &Terminator<'tcx> {
1497 self.terminator.as_ref().expect("invalid terminator state")
1500 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1501 self.terminator.as_mut().expect("invalid terminator state")
1504 pub fn retain_statements<F>(&mut self, mut f: F)
1506 F: FnMut(&mut Statement<'_>) -> bool,
1508 for s in &mut self.statements {
1515 pub fn expand_statements<F, I>(&mut self, mut f: F)
1517 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1518 I: iter::TrustedLen<Item = Statement<'tcx>>,
1520 // Gather all the iterators we'll need to splice in, and their positions.
1521 let mut splices: Vec<(usize, I)> = vec![];
1522 let mut extra_stmts = 0;
1523 for (i, s) in self.statements.iter_mut().enumerate() {
1524 if let Some(mut new_stmts) = f(s) {
1525 if let Some(first) = new_stmts.next() {
1526 // We can already store the first new statement.
1529 // Save the other statements for optimized splicing.
1530 let remaining = new_stmts.size_hint().0;
1532 splices.push((i + 1 + extra_stmts, new_stmts));
1533 extra_stmts += remaining;
1541 // Splice in the new statements, from the end of the block.
1542 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1543 // where a range of elements ("gap") is left uninitialized, with
1544 // splicing adding new elements to the end of that gap and moving
1545 // existing elements from before the gap to the end of the gap.
1546 // For now, this is safe code, emulating a gap but initializing it.
1547 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1548 self.statements.resize(
1551 source_info: SourceInfo {
1553 scope: OUTERMOST_SOURCE_SCOPE,
1555 kind: StatementKind::Nop,
1558 for (splice_start, new_stmts) in splices.into_iter().rev() {
1559 let splice_end = splice_start + new_stmts.size_hint().0;
1560 while gap.end > splice_end {
1563 self.statements.swap(gap.start, gap.end);
1565 self.statements.splice(splice_start..splice_end, new_stmts);
1566 gap.end = splice_start;
1570 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1571 if index < self.statements.len() {
1572 &self.statements[index]
1579 impl<'tcx> Debug for TerminatorKind<'tcx> {
1580 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1581 self.fmt_head(fmt)?;
1582 let successor_count = self.successors().count();
1583 let labels = self.fmt_successor_labels();
1584 assert_eq!(successor_count, labels.len());
1586 match successor_count {
1589 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1592 write!(fmt, " -> [")?;
1593 for (i, target) in self.successors().enumerate() {
1597 write!(fmt, "{}: {:?}", labels[i], target)?;
1605 impl<'tcx> TerminatorKind<'tcx> {
1606 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1607 /// successor basic block, if any. The only information not included is the list of possible
1608 /// successors, which may be rendered differently between the text and the graphviz format.
1609 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1610 use self::TerminatorKind::*;
1612 Goto { .. } => write!(fmt, "goto"),
1614 discr: ref place, ..
1615 } => write!(fmt, "switchInt({:?})", place),
1616 Return => write!(fmt, "return"),
1617 GeneratorDrop => write!(fmt, "generator_drop"),
1618 Resume => write!(fmt, "resume"),
1619 Abort => write!(fmt, "abort"),
1620 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1621 Unreachable => write!(fmt, "unreachable"),
1622 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1627 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1634 if let Some((ref destination, _)) = *destination {
1635 write!(fmt, "{:?} = ", destination)?;
1637 write!(fmt, "{:?}(", func)?;
1638 for (index, arg) in args.iter().enumerate() {
1642 write!(fmt, "{:?}", arg)?;
1652 write!(fmt, "assert(")?;
1656 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1658 FalseEdges { .. } => write!(fmt, "falseEdges"),
1659 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1663 /// Returns the list of labels for the edges to the successor basic blocks.
1664 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1665 use self::TerminatorKind::*;
1667 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1668 Goto { .. } => vec!["".into()],
1674 ty::tls::with(|tcx| {
1675 let param_env = ty::ParamEnv::empty();
1676 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1677 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1681 tcx.mk_const(ty::Const {
1682 val: ConstValue::Scalar(
1683 Scalar::from_uint(u, size).into(),
1686 }).to_string().into()
1687 }).chain(iter::once("otherwise".into()))
1692 destination: Some(_),
1695 } => vec!["return".into(), "unwind".into()],
1697 destination: Some(_),
1700 } => vec!["return".into()],
1705 } => vec!["unwind".into()],
1711 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1712 Yield { drop: None, .. } => vec!["resume".into()],
1713 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1714 vec!["return".into()]
1721 } => vec!["return".into(), "unwind".into()],
1722 Assert { cleanup: None, .. } => vec!["".into()],
1723 Assert { .. } => vec!["success".into(), "unwind".into()],
1725 ref imaginary_targets,
1728 let mut l = vec!["real".into()];
1729 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1734 } => vec!["real".into(), "cleanup".into()],
1735 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1740 ///////////////////////////////////////////////////////////////////////////
1743 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1744 pub struct Statement<'tcx> {
1745 pub source_info: SourceInfo,
1746 pub kind: StatementKind<'tcx>,
1749 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1750 #[cfg(target_arch = "x86_64")]
1751 static_assert_size!(Statement<'_>, 56);
1753 impl<'tcx> Statement<'tcx> {
1754 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1755 /// invalidating statement indices in `Location`s.
1756 pub fn make_nop(&mut self) {
1757 self.kind = StatementKind::Nop
1760 /// Changes a statement to a nop and returns the original statement.
1761 pub fn replace_nop(&mut self) -> Self {
1763 source_info: self.source_info,
1764 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1769 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1770 pub enum StatementKind<'tcx> {
1771 /// Write the RHS Rvalue to the LHS Place.
1772 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1774 /// This represents all the reading that a pattern match may do
1775 /// (e.g., inspecting constants and discriminant values), and the
1776 /// kind of pattern it comes from. This is in order to adapt potential
1777 /// error messages to these specific patterns.
1779 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1780 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1781 FakeRead(FakeReadCause, Place<'tcx>),
1783 /// Write the discriminant for a variant to the enum Place.
1786 variant_index: VariantIdx,
1789 /// Start a live range for the storage of the local.
1792 /// End the current live range for the storage of the local.
1795 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1796 /// of `StatementKind` low.
1797 InlineAsm(Box<InlineAsm<'tcx>>),
1799 /// Retag references in the given place, ensuring they got fresh tags. This is
1800 /// part of the Stacked Borrows model. These statements are currently only interpreted
1801 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1802 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1803 /// for more details.
1804 Retag(RetagKind, Place<'tcx>),
1806 /// Encodes a user's type ascription. These need to be preserved
1807 /// intact so that NLL can respect them. For example:
1811 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1812 /// to the user-given type `T`. The effect depends on the specified variance:
1814 /// - `Covariant` -- requires that `T_y <: T`
1815 /// - `Contravariant` -- requires that `T_y :> T`
1816 /// - `Invariant` -- requires that `T_y == T`
1817 /// - `Bivariant` -- no effect
1818 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1820 /// No-op. Useful for deleting instructions without affecting statement indices.
1824 /// `RetagKind` describes what kind of retag is to be performed.
1825 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1826 pub enum RetagKind {
1827 /// The initial retag when entering a function
1829 /// Retag preparing for a two-phase borrow
1831 /// Retagging raw pointers
1833 /// A "normal" retag
1837 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1838 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1839 pub enum FakeReadCause {
1840 /// Inject a fake read of the borrowed input at the end of each guards
1843 /// This should ensure that you cannot change the variant for an enum while
1844 /// you are in the midst of matching on it.
1847 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1848 /// generate a read of x to check that it is initialized and safe.
1851 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1852 /// in a match guard to ensure that it's value hasn't change by the time
1853 /// we create the OutsideGuard version.
1856 /// Officially, the semantics of
1858 /// `let pattern = <expr>;`
1860 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1861 /// into the pattern.
1863 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1864 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1865 /// but in some cases it can affect the borrow checker, as in #53695.
1866 /// Therefore, we insert a "fake read" here to ensure that we get
1867 /// appropriate errors.
1871 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1872 pub struct InlineAsm<'tcx> {
1873 pub asm: HirInlineAsm,
1874 pub outputs: Box<[Place<'tcx>]>,
1875 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1878 impl<'tcx> Debug for Statement<'tcx> {
1879 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1880 use self::StatementKind::*;
1882 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1883 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1884 Retag(ref kind, ref place) =>
1885 write!(fmt, "Retag({}{:?})",
1887 RetagKind::FnEntry => "[fn entry] ",
1888 RetagKind::TwoPhase => "[2phase] ",
1889 RetagKind::Raw => "[raw] ",
1890 RetagKind::Default => "",
1894 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1895 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1899 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1900 InlineAsm(ref asm) =>
1901 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs),
1902 AscribeUserType(ref place, ref variance, ref c_ty) => {
1903 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1905 Nop => write!(fmt, "nop"),
1910 ///////////////////////////////////////////////////////////////////////////
1913 /// A path to a value; something that can be evaluated without
1914 /// changing or disturbing program state.
1915 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1916 pub enum Place<'tcx> {
1917 Base(PlaceBase<'tcx>),
1919 /// projection out of a place (access a field, deref a pointer, etc)
1920 Projection(Box<Projection<'tcx>>),
1923 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1924 pub enum PlaceBase<'tcx> {
1928 /// static or static mut variable
1929 Static(Box<Static<'tcx>>),
1932 /// We store the normalized type to avoid requiring normalization when reading MIR
1933 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1934 pub struct Static<'tcx> {
1936 pub kind: StaticKind,
1939 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable)]
1940 pub enum StaticKind {
1945 impl_stable_hash_for!(struct Static<'tcx> {
1950 /// The `Projection` data structure defines things of the form `base.x`, `*b` or `b[index]`.
1951 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1952 Hash, RustcEncodable, RustcDecodable, HashStable)]
1953 pub struct Projection<'tcx> {
1954 pub base: Place<'tcx>,
1955 pub elem: PlaceElem<'tcx>,
1958 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord,
1959 Hash, RustcEncodable, RustcDecodable, HashStable)]
1960 pub enum ProjectionElem<V, T> {
1965 /// These indices are generated by slice patterns. Easiest to explain
1969 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1970 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1971 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1972 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1975 /// index or -index (in Python terms), depending on from_end
1977 /// thing being indexed must be at least this long
1979 /// counting backwards from end?
1983 /// These indices are generated by slice patterns.
1985 /// slice[from:-to] in Python terms.
1991 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1992 /// this for ADTs with more than one variant. It may be better to
1993 /// just introduce it always, or always for enums.
1995 /// The included Symbol is the name of the variant, used for printing MIR.
1996 Downcast(Option<Symbol>, VariantIdx),
1999 /// Alias for projections as they appear in places, where the base is a place
2000 /// and the index is a local.
2001 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
2003 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
2004 #[cfg(target_arch = "x86_64")]
2005 static_assert_size!(PlaceElem<'_>, 16);
2007 /// Alias for projections as they appear in `UserTypeProjection`, where we
2008 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
2009 pub type ProjectionKind = ProjectionElem<(), ()>;
2014 DEBUG_FORMAT = "field[{}]"
2018 impl<'tcx> Place<'tcx> {
2019 pub const RETURN_PLACE: Place<'tcx> = Place::Base(PlaceBase::Local(RETURN_PLACE));
2021 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
2022 self.elem(ProjectionElem::Field(f, ty))
2025 pub fn deref(self) -> Place<'tcx> {
2026 self.elem(ProjectionElem::Deref)
2029 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2030 self.elem(ProjectionElem::Downcast(
2031 Some(adt_def.variants[variant_index].ident.name),
2035 pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
2036 self.elem(ProjectionElem::Downcast(None, variant_index))
2039 pub fn index(self, index: Local) -> Place<'tcx> {
2040 self.elem(ProjectionElem::Index(index))
2043 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2044 Place::Projection(Box::new(Projection { base: self, elem }))
2047 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2048 /// a single deref of a local.
2050 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2051 pub fn local_or_deref_local(&self) -> Option<Local> {
2053 Place::Base(PlaceBase::Local(local)) |
2054 Place::Projection(box Projection {
2055 base: Place::Base(PlaceBase::Local(local)),
2056 elem: ProjectionElem::Deref,
2062 /// Finds the innermost `Local` from this `Place`.
2063 pub fn base_local(&self) -> Option<Local> {
2064 let mut place = self;
2067 Place::Projection(proj) => place = &proj.base,
2068 Place::Base(PlaceBase::Static(_)) => return None,
2069 Place::Base(PlaceBase::Local(local)) => return Some(*local),
2074 /// Recursively "iterates" over place components, generating a `PlaceBase` and
2075 /// `Projections` list and invoking `op` with a `ProjectionsIter`.
2078 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2080 self.iterate2(&Projections::Empty, op)
2085 next: &Projections<'_, 'tcx>,
2086 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
2089 Place::Projection(interior) => interior.base.iterate2(
2090 &Projections::List {
2091 projection: interior,
2097 Place::Base(base) => op(base, next.iter()),
2102 /// A linked list of projections running up the stack; begins with the
2103 /// innermost projection and extends to the outermost (e.g., `a.b.c`
2104 /// would have the place `b` with a "next" pointer to `b.c`).
2105 /// Created by `Place::iterate`.
2107 /// N.B., this particular impl strategy is not the most obvious. It was
2108 /// chosen because it makes a measurable difference to NLL
2109 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
2110 pub enum Projections<'p, 'tcx: 'p> {
2114 projection: &'p Projection<'tcx>,
2115 next: &'p Projections<'p, 'tcx>,
2119 impl<'p, 'tcx> Projections<'p, 'tcx> {
2120 fn iter(&self) -> ProjectionsIter<'_, 'tcx> {
2121 ProjectionsIter { value: self }
2125 impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
2126 type Item = &'p Projection<'tcx>;
2127 type IntoIter = ProjectionsIter<'p, 'tcx>;
2129 /// Converts a list of `Projection` components into an iterator;
2130 /// this iterator yields up a never-ending stream of `Option<&Place>`.
2131 /// These begin with the "innermost" projection and then with each
2132 /// projection therefrom. So given a place like `a.b.c` it would
2136 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2138 fn into_iter(self) -> Self::IntoIter {
2143 /// Iterator over components; see `Projections::iter` for more
2146 /// N.B., this is not a *true* Rust iterator -- the code above just
2147 /// manually invokes `next`. This is because we (sometimes) want to
2148 /// keep executing even after `None` has been returned.
2149 pub struct ProjectionsIter<'p, 'tcx: 'p> {
2150 pub value: &'p Projections<'p, 'tcx>,
2153 impl<'p, 'tcx> Iterator for ProjectionsIter<'p, 'tcx> {
2154 type Item = &'p Projection<'tcx>;
2156 fn next(&mut self) -> Option<Self::Item> {
2157 if let &Projections::List { projection, next } = self.value {
2166 impl<'p, 'tcx> FusedIterator for ProjectionsIter<'p, 'tcx> {}
2168 impl<'tcx> Debug for Place<'tcx> {
2169 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2170 self.iterate(|_place_base, place_projections| {
2171 // FIXME: remove this collect once we have migrated to slices
2172 let projs_vec: Vec<_> = place_projections.collect();
2173 for projection in projs_vec.iter().rev() {
2174 match projection.elem {
2175 ProjectionElem::Downcast(_, _) |
2176 ProjectionElem::Field(_, _) => {
2177 write!(fmt, "(").unwrap();
2179 ProjectionElem::Deref => {
2180 write!(fmt, "(*").unwrap();
2182 ProjectionElem::Index(_) |
2183 ProjectionElem::ConstantIndex { .. } |
2184 ProjectionElem::Subslice { .. } => {}
2189 self.iterate(|place_base, place_projections| {
2191 PlaceBase::Local(id) => {
2192 write!(fmt, "{:?}", id)?;
2194 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2198 ty::tls::with(|tcx| tcx.def_path_str(*def_id)),
2203 box self::Static { ty, kind: StaticKind::Promoted(promoted) }
2214 for projection in place_projections {
2215 match projection.elem {
2216 ProjectionElem::Downcast(Some(name), _index) => {
2217 write!(fmt, " as {})", name)?;
2219 ProjectionElem::Downcast(None, index) => {
2220 write!(fmt, " as variant#{:?})", index)?;
2222 ProjectionElem::Deref => {
2225 ProjectionElem::Field(field, ty) => {
2226 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2228 ProjectionElem::Index(ref index) => {
2229 write!(fmt, "[{:?}]", index)?;
2231 ProjectionElem::ConstantIndex {
2236 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2238 ProjectionElem::ConstantIndex {
2243 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2245 ProjectionElem::Subslice { from, to } if to == 0 => {
2246 write!(fmt, "[{:?}:]", from)?;
2248 ProjectionElem::Subslice { from, to } if from == 0 => {
2249 write!(fmt, "[:-{:?}]", to)?;
2251 ProjectionElem::Subslice { from, to } => {
2252 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2262 ///////////////////////////////////////////////////////////////////////////
2266 pub struct SourceScope {
2268 DEBUG_FORMAT = "scope[{}]",
2269 const OUTERMOST_SOURCE_SCOPE = 0,
2273 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2274 pub struct SourceScopeData {
2276 pub parent_scope: Option<SourceScope>,
2279 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2280 pub struct SourceScopeLocalData {
2281 /// A HirId with lint levels equivalent to this scope's lint levels.
2282 pub lint_root: hir::HirId,
2283 /// The unsafe block that contains this node.
2287 ///////////////////////////////////////////////////////////////////////////
2290 /// These are values that can appear inside an rvalue. They are intentionally
2291 /// limited to prevent rvalues from being nested in one another.
2292 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2293 pub enum Operand<'tcx> {
2294 /// Copy: The value must be available for use afterwards.
2296 /// This implies that the type of the place must be `Copy`; this is true
2297 /// by construction during build, but also checked by the MIR type checker.
2300 /// Move: The value (including old borrows of it) will not be used again.
2302 /// Safe for values of all types (modulo future developments towards `?Move`).
2303 /// Correct usage patterns are enforced by the borrow checker for safe code.
2304 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2307 /// Synthesizes a constant value.
2308 Constant(Box<Constant<'tcx>>),
2311 impl<'tcx> Debug for Operand<'tcx> {
2312 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2313 use self::Operand::*;
2315 Constant(ref a) => write!(fmt, "{:?}", a),
2316 Copy(ref place) => write!(fmt, "{:?}", place),
2317 Move(ref place) => write!(fmt, "move {:?}", place),
2322 impl<'tcx> Operand<'tcx> {
2323 /// Convenience helper to make a constant that refers to the fn
2324 /// with given `DefId` and substs. Since this is used to synthesize
2325 /// MIR, assumes `user_ty` is None.
2326 pub fn function_handle(
2327 tcx: TyCtxt<'tcx, 'tcx>,
2329 substs: SubstsRef<'tcx>,
2332 let ty = tcx.type_of(def_id).subst(tcx, substs);
2333 Operand::Constant(box Constant {
2337 literal: ty::Const::zero_sized(tcx, ty),
2341 pub fn to_copy(&self) -> Self {
2343 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2344 Operand::Move(ref place) => Operand::Copy(place.clone()),
2349 ///////////////////////////////////////////////////////////////////////////
2352 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2353 pub enum Rvalue<'tcx> {
2354 /// x (either a move or copy, depending on type of x)
2358 Repeat(Operand<'tcx>, u64),
2361 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2363 /// length of a [X] or [X;n] value
2366 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2368 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2369 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2371 NullaryOp(NullOp, Ty<'tcx>),
2372 UnaryOp(UnOp, Operand<'tcx>),
2374 /// Read the discriminant of an ADT.
2376 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2377 /// be defined to return, say, a 0) if ADT is not an enum.
2378 Discriminant(Place<'tcx>),
2380 /// Creates an aggregate value, like a tuple or struct. This is
2381 /// only needed because we want to distinguish `dest = Foo { x:
2382 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2383 /// that `Foo` has a destructor. These rvalues can be optimized
2384 /// away after type-checking and before lowering.
2385 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2389 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2392 Pointer(PointerCast),
2395 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2396 pub enum AggregateKind<'tcx> {
2397 /// The type is of the element
2401 /// The second field is the variant index. It's equal to 0 for struct
2402 /// and union expressions. The fourth field is
2403 /// active field number and is present only for union expressions
2404 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2405 /// active field index would identity the field `c`
2410 Option<UserTypeAnnotationIndex>,
2414 Closure(DefId, ClosureSubsts<'tcx>),
2415 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2418 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2420 /// The `+` operator (addition)
2422 /// The `-` operator (subtraction)
2424 /// The `*` operator (multiplication)
2426 /// The `/` operator (division)
2428 /// The `%` operator (modulus)
2430 /// The `^` operator (bitwise xor)
2432 /// The `&` operator (bitwise and)
2434 /// The `|` operator (bitwise or)
2436 /// The `<<` operator (shift left)
2438 /// The `>>` operator (shift right)
2440 /// The `==` operator (equality)
2442 /// The `<` operator (less than)
2444 /// The `<=` operator (less than or equal to)
2446 /// The `!=` operator (not equal to)
2448 /// The `>=` operator (greater than or equal to)
2450 /// The `>` operator (greater than)
2452 /// The `ptr.offset` operator
2457 pub fn is_checkable(self) -> bool {
2460 Add | Sub | Mul | Shl | Shr => true,
2466 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2468 /// Returns the size of a value of that type
2470 /// Creates a new uninitialized box for a value of that type
2474 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2476 /// The `!` operator for logical inversion
2478 /// The `-` operator for negation
2482 impl<'tcx> Debug for Rvalue<'tcx> {
2483 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2484 use self::Rvalue::*;
2487 Use(ref place) => write!(fmt, "{:?}", place),
2488 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2489 Len(ref a) => write!(fmt, "Len({:?})", a),
2490 Cast(ref kind, ref place, ref ty) => {
2491 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2493 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2494 CheckedBinaryOp(ref op, ref a, ref b) => {
2495 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2497 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2498 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2499 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2500 Ref(region, borrow_kind, ref place) => {
2501 let kind_str = match borrow_kind {
2502 BorrowKind::Shared => "",
2503 BorrowKind::Shallow => "shallow ",
2504 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2507 // When printing regions, add trailing space if necessary.
2508 let print_region = ty::tls::with(|tcx| {
2509 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2511 let region = if print_region {
2512 let mut region = region.to_string();
2513 if region.len() > 0 {
2518 // Do not even print 'static
2521 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2524 Aggregate(ref kind, ref places) => {
2525 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2526 let mut tuple_fmt = fmt.debug_tuple("");
2527 for place in places {
2528 tuple_fmt.field(place);
2534 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2536 AggregateKind::Tuple => match places.len() {
2537 0 => write!(fmt, "()"),
2538 1 => write!(fmt, "({:?},)", places[0]),
2539 _ => fmt_tuple(fmt, places),
2542 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2543 let variant_def = &adt_def.variants[variant];
2546 ty::tls::with(|tcx| {
2547 let substs = tcx.lift(&substs).expect("could not lift for printing");
2548 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2549 .print_def_path(variant_def.def_id, substs)?;
2553 match variant_def.ctor_kind {
2554 CtorKind::Const => Ok(()),
2555 CtorKind::Fn => fmt_tuple(fmt, places),
2556 CtorKind::Fictive => {
2557 let mut struct_fmt = fmt.debug_struct("");
2558 for (field, place) in variant_def.fields.iter().zip(places) {
2559 struct_fmt.field(&field.ident.as_str(), place);
2566 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2567 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2568 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2569 format!("[closure@{:?}]", hir_id)
2571 format!("[closure@{:?}]", tcx.hir().span_by_hir_id(hir_id))
2573 let mut struct_fmt = fmt.debug_struct(&name);
2575 if let Some(upvars) = tcx.upvars(def_id) {
2576 for (&var_id, place) in upvars.keys().zip(places) {
2577 let var_name = tcx.hir().name_by_hir_id(var_id);
2578 struct_fmt.field(&var_name.as_str(), place);
2584 write!(fmt, "[closure]")
2588 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2589 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2590 let name = format!("[generator@{:?}]",
2591 tcx.hir().span_by_hir_id(hir_id));
2592 let mut struct_fmt = fmt.debug_struct(&name);
2594 if let Some(upvars) = tcx.upvars(def_id) {
2595 for (&var_id, place) in upvars.keys().zip(places) {
2596 let var_name = tcx.hir().name_by_hir_id(var_id);
2597 struct_fmt.field(&var_name.as_str(), place);
2603 write!(fmt, "[generator]")
2612 ///////////////////////////////////////////////////////////////////////////
2615 /// Two constants are equal if they are the same constant. Note that
2616 /// this does not necessarily mean that they are "==" in Rust -- in
2617 /// particular one must be wary of `NaN`!
2619 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2620 pub struct Constant<'tcx> {
2624 /// Optional user-given type: for something like
2625 /// `collect::<Vec<_>>`, this would be present and would
2626 /// indicate that `Vec<_>` was explicitly specified.
2628 /// Needed for NLL to impose user-given type constraints.
2629 pub user_ty: Option<UserTypeAnnotationIndex>,
2631 pub literal: &'tcx ty::Const<'tcx>,
2634 /// A collection of projections into user types.
2636 /// They are projections because a binding can occur a part of a
2637 /// parent pattern that has been ascribed a type.
2639 /// Its a collection because there can be multiple type ascriptions on
2640 /// the path from the root of the pattern down to the binding itself.
2645 /// struct S<'a>((i32, &'a str), String);
2646 /// let S((_, w): (i32, &'static str), _): S = ...;
2647 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2648 /// // --------------------------------- ^ (2)
2651 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2652 /// ascribed the type `(i32, &'static str)`.
2654 /// The highlights labelled `(2)` show the whole pattern being
2655 /// ascribed the type `S`.
2657 /// In this example, when we descend to `w`, we will have built up the
2658 /// following two projected types:
2660 /// * base: `S`, projection: `(base.0).1`
2661 /// * base: `(i32, &'static str)`, projection: `base.1`
2663 /// The first will lead to the constraint `w: &'1 str` (for some
2664 /// inferred region `'1`). The second will lead to the constraint `w:
2666 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2667 pub struct UserTypeProjections {
2668 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2671 BraceStructTypeFoldableImpl! {
2672 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2677 impl<'tcx> UserTypeProjections {
2678 pub fn none() -> Self {
2679 UserTypeProjections { contents: vec![] }
2682 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection, Span)>) -> Self {
2683 UserTypeProjections { contents: projs.collect() }
2686 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection, Span)> {
2687 self.contents.iter()
2690 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection> {
2691 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2694 pub fn push_projection(
2696 user_ty: &UserTypeProjection,
2699 self.contents.push((user_ty.clone(), span));
2705 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection
2707 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2711 pub fn index(self) -> Self {
2712 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2715 pub fn subslice(self, from: u32, to: u32) -> Self {
2716 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2719 pub fn deref(self) -> Self {
2720 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2723 pub fn leaf(self, field: Field) -> Self {
2724 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2729 adt_def: &'tcx AdtDef,
2730 variant_index: VariantIdx,
2733 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2737 /// Encodes the effect of a user-supplied type annotation on the
2738 /// subcomponents of a pattern. The effect is determined by applying the
2739 /// given list of proejctions to some underlying base type. Often,
2740 /// the projection element list `projs` is empty, in which case this
2741 /// directly encodes a type in `base`. But in the case of complex patterns with
2742 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2743 /// in which case the `projs` vector is used.
2747 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2749 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2750 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2751 /// determined by finding the type of the `.0` field from `T`.
2752 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2753 pub struct UserTypeProjection {
2754 pub base: UserTypeAnnotationIndex,
2755 pub projs: Vec<ProjectionKind>,
2758 impl Copy for ProjectionKind { }
2760 impl UserTypeProjection {
2761 pub(crate) fn index(mut self) -> Self {
2762 self.projs.push(ProjectionElem::Index(()));
2766 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2767 self.projs.push(ProjectionElem::Subslice { from, to });
2771 pub(crate) fn deref(mut self) -> Self {
2772 self.projs.push(ProjectionElem::Deref);
2776 pub(crate) fn leaf(mut self, field: Field) -> Self {
2777 self.projs.push(ProjectionElem::Field(field, ()));
2781 pub(crate) fn variant(
2783 adt_def: &'tcx AdtDef,
2784 variant_index: VariantIdx,
2787 self.projs.push(ProjectionElem::Downcast(
2788 Some(adt_def.variants[variant_index].ident.name),
2790 self.projs.push(ProjectionElem::Field(field, ()));
2795 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2797 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2798 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2799 use crate::mir::ProjectionElem::*;
2801 let base = self.base.fold_with(folder);
2802 let projs: Vec<_> = self.projs
2807 Field(f, ()) => Field(f.clone(), ()),
2808 Index(()) => Index(()),
2809 elem => elem.clone(),
2813 UserTypeProjection { base, projs }
2816 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2817 self.base.visit_with(visitor)
2818 // Note: there's nothing in `self.proj` to visit.
2823 pub struct Promoted {
2825 DEBUG_FORMAT = "promoted[{}]"
2829 impl<'tcx> Debug for Constant<'tcx> {
2830 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2831 write!(fmt, "{}", self)
2835 impl<'tcx> Display for Constant<'tcx> {
2836 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2837 write!(fmt, "const ")?;
2838 write!(fmt, "{}", self.literal)
2842 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2843 type Node = BasicBlock;
2846 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2847 fn num_nodes(&self) -> usize {
2848 self.basic_blocks.len()
2852 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2853 fn start_node(&self) -> Self::Node {
2858 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2859 fn predecessors<'graph>(
2862 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2863 self.predecessors_for(node).clone().into_iter()
2867 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2868 fn successors<'graph>(
2871 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2872 self.basic_blocks[node].terminator().successors().cloned()
2876 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2877 type Item = BasicBlock;
2878 type Iter = IntoIter<BasicBlock>;
2881 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2882 type Item = BasicBlock;
2883 type Iter = iter::Cloned<Successors<'b>>;
2886 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2887 pub struct Location {
2888 /// the location is within this block
2889 pub block: BasicBlock,
2891 /// the location is the start of the statement; or, if `statement_index`
2892 /// == num-statements, then the start of the terminator.
2893 pub statement_index: usize,
2896 impl fmt::Debug for Location {
2897 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2898 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2903 pub const START: Location = Location {
2908 /// Returns the location immediately after this one within the enclosing block.
2910 /// Note that if this location represents a terminator, then the
2911 /// resulting location would be out of bounds and invalid.
2912 pub fn successor_within_block(&self) -> Location {
2915 statement_index: self.statement_index + 1,
2919 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2920 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2921 // If we are in the same block as the other location and are an earlier statement
2922 // then we are a predecessor of `other`.
2923 if self.block == other.block && self.statement_index < other.statement_index {
2927 // If we're in another block, then we want to check that block is a predecessor of `other`.
2928 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2929 let mut visited = FxHashSet::default();
2931 while let Some(block) = queue.pop() {
2932 // If we haven't visited this block before, then make sure we visit it's predecessors.
2933 if visited.insert(block) {
2934 queue.append(&mut body.predecessors_for(block).clone());
2939 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2940 // we found that block by looking at the predecessors of `other`).
2941 if self.block == block {
2949 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2950 if self.block == other.block {
2951 self.statement_index <= other.statement_index
2953 dominators.is_dominated_by(other.block, self.block)
2958 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2959 pub enum UnsafetyViolationKind {
2961 /// Permitted in const fn and regular fns.
2963 ExternStatic(hir::HirId),
2964 BorrowPacked(hir::HirId),
2967 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2968 pub struct UnsafetyViolation {
2969 pub source_info: SourceInfo,
2970 pub description: InternedString,
2971 pub details: InternedString,
2972 pub kind: UnsafetyViolationKind,
2975 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2976 pub struct UnsafetyCheckResult {
2977 /// Violations that are propagated *upwards* from this function
2978 pub violations: Lrc<[UnsafetyViolation]>,
2979 /// unsafe blocks in this function, along with whether they are used. This is
2980 /// used for the "unused_unsafe" lint.
2981 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2985 pub struct GeneratorSavedLocal {
2987 DEBUG_FORMAT = "_{}",
2991 /// The layout of generator state
2992 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2993 pub struct GeneratorLayout<'tcx> {
2994 /// The type of every local stored inside the generator.
2995 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2997 /// Which of the above fields are in each variant. Note that one field may
2998 /// be stored in multiple variants.
2999 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
3001 /// Which saved locals are storage-live at the same time. Locals that do not
3002 /// have conflicts with each other are allowed to overlap in the computed
3004 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
3006 /// Names and scopes of all the stored generator locals.
3007 /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
3008 /// debuginfo generation, and will be removed at some point.
3009 /// Do **NOT** use it for anything else, local information should not be
3010 /// in the MIR, please rely on local crate HIR or other side-channels.
3011 pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
3014 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3015 pub struct BorrowCheckResult<'gcx> {
3016 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
3017 pub used_mut_upvars: SmallVec<[Field; 8]>,
3020 /// After we borrow check a closure, we are left with various
3021 /// requirements that we have inferred between the free regions that
3022 /// appear in the closure's signature or on its field types. These
3023 /// requirements are then verified and proved by the closure's
3024 /// creating function. This struct encodes those requirements.
3026 /// The requirements are listed as being between various
3027 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
3028 /// vids refer to the free regions that appear in the closure (or
3029 /// generator's) type, in order of appearance. (This numbering is
3030 /// actually defined by the `UniversalRegions` struct in the NLL
3031 /// region checker. See for example
3032 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
3033 /// regions in the closure's type "as if" they were erased, so their
3034 /// precise identity is not important, only their position.
3036 /// Example: If type check produces a closure with the closure substs:
3039 /// ClosureSubsts = [
3040 /// i8, // the "closure kind"
3041 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
3042 /// &'a String, // some upvar
3046 /// here, there is one unique free region (`'a`) but it appears
3047 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
3050 /// ClosureSubsts = [
3051 /// i8, // the "closure kind"
3052 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
3053 /// &'2 String, // some upvar
3057 /// Now the code might impose a requirement like `'1: '2`. When an
3058 /// instance of the closure is created, the corresponding free regions
3059 /// can be extracted from its type and constrained to have the given
3060 /// outlives relationship.
3062 /// In some cases, we have to record outlives requirements between
3063 /// types and regions as well. In that case, if those types include
3064 /// any regions, those regions are recorded as `ReClosureBound`
3065 /// instances assigned one of these same indices. Those regions will
3066 /// be substituted away by the creator. We use `ReClosureBound` in
3067 /// that case because the regions must be allocated in the global
3068 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
3069 /// internally within the rest of the NLL code).
3070 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3071 pub struct ClosureRegionRequirements<'gcx> {
3072 /// The number of external regions defined on the closure. In our
3073 /// example above, it would be 3 -- one for `'static`, then `'1`
3074 /// and `'2`. This is just used for a sanity check later on, to
3075 /// make sure that the number of regions we see at the callsite
3077 pub num_external_vids: usize,
3079 /// Requirements between the various free regions defined in
3081 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
3084 /// Indicates an outlives constraint between a type or between two
3085 /// free-regions declared on the closure.
3086 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3087 pub struct ClosureOutlivesRequirement<'tcx> {
3088 // This region or type ...
3089 pub subject: ClosureOutlivesSubject<'tcx>,
3091 // ... must outlive this one.
3092 pub outlived_free_region: ty::RegionVid,
3094 // If not, report an error here ...
3095 pub blame_span: Span,
3097 // ... due to this reason.
3098 pub category: ConstraintCategory,
3101 /// Outlives constraints can be categorized to determine whether and why they
3102 /// are interesting (for error reporting). Order of variants indicates sort
3103 /// order of the category, thereby influencing diagnostic output.
3105 /// See also [rustc_mir::borrow_check::nll::constraints]
3106 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
3107 Hash, RustcEncodable, RustcDecodable, HashStable)]
3108 pub enum ConstraintCategory {
3116 /// A constraint that came from checking the body of a closure.
3118 /// We try to get the category that the closure used when reporting this.
3126 /// A "boring" constraint (caused by the given location) is one that
3127 /// the user probably doesn't want to see described in diagnostics,
3128 /// because it is kind of an artifact of the type system setup.
3129 /// Example: `x = Foo { field: y }` technically creates
3130 /// intermediate regions representing the "type of `Foo { field: y
3131 /// }`", and data flows from `y` into those variables, but they
3132 /// are not very interesting. The assignment into `x` on the other
3135 // Boring and applicable everywhere.
3138 /// A constraint that doesn't correspond to anything the user sees.
3142 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
3143 /// that must outlive some region.
3144 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
3145 pub enum ClosureOutlivesSubject<'tcx> {
3146 /// Subject is a type, typically a type parameter, but could also
3147 /// be a projection. Indicates a requirement like `T: 'a` being
3148 /// passed to the caller, where the type here is `T`.
3150 /// The type here is guaranteed not to contain any free regions at
3154 /// Subject is a free region from the closure. Indicates a requirement
3155 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3156 Region(ty::RegionVid),
3160 * TypeFoldable implementations for MIR types
3163 CloneTypeFoldableAndLiftImpls! {
3173 SourceScopeLocalData,
3174 UserTypeAnnotationIndex,
3177 BraceStructTypeFoldableImpl! {
3178 impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
3182 source_scope_local_data,
3188 user_type_annotations,
3190 __upvar_debuginfo_codegen_only_do_not_use,
3192 control_flow_destroyed,
3198 BraceStructTypeFoldableImpl! {
3199 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3203 __local_debuginfo_codegen_only_do_not_use,
3207 BraceStructTypeFoldableImpl! {
3208 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3221 BraceStructTypeFoldableImpl! {
3222 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3229 BraceStructTypeFoldableImpl! {
3230 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3235 EnumTypeFoldableImpl! {
3236 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3237 (StatementKind::Assign)(a, b),
3238 (StatementKind::FakeRead)(cause, place),
3239 (StatementKind::SetDiscriminant) { place, variant_index },
3240 (StatementKind::StorageLive)(a),
3241 (StatementKind::StorageDead)(a),
3242 (StatementKind::InlineAsm)(a),
3243 (StatementKind::Retag)(kind, place),
3244 (StatementKind::AscribeUserType)(a, v, b),
3245 (StatementKind::Nop),
3249 BraceStructTypeFoldableImpl! {
3250 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3257 EnumTypeFoldableImpl! {
3258 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3259 (ClearCrossCrate::Clear),
3260 (ClearCrossCrate::Set)(a),
3261 } where T: TypeFoldable<'tcx>
3264 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3265 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3266 use crate::mir::TerminatorKind::*;
3268 let kind = match self.kind {
3269 Goto { target } => Goto { target },
3276 discr: discr.fold_with(folder),
3277 switch_ty: switch_ty.fold_with(folder),
3278 values: values.clone(),
3279 targets: targets.clone(),
3286 location: location.fold_with(folder),
3295 } => DropAndReplace {
3296 location: location.fold_with(folder),
3297 value: value.fold_with(folder),
3306 value: value.fold_with(folder),
3317 let dest = destination
3319 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3322 func: func.fold_with(folder),
3323 args: args.fold_with(folder),
3336 let msg = if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3337 InterpError::BoundsCheck {
3338 len: len.fold_with(folder),
3339 index: index.fold_with(folder),
3345 cond: cond.fold_with(folder),
3352 GeneratorDrop => GeneratorDrop,
3356 Unreachable => Unreachable,
3359 ref imaginary_targets,
3362 imaginary_targets: imaginary_targets.clone(),
3373 source_info: self.source_info,
3378 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3379 use crate::mir::TerminatorKind::*;
3386 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3387 Drop { ref location, .. } => location.visit_with(visitor),
3392 } => location.visit_with(visitor) || value.visit_with(visitor),
3393 Yield { ref value, .. } => value.visit_with(visitor),
3400 let dest = if let Some((ref loc, _)) = *destination {
3401 loc.visit_with(visitor)
3405 dest || func.visit_with(visitor) || args.visit_with(visitor)
3408 ref cond, ref msg, ..
3410 if cond.visit_with(visitor) {
3411 if let InterpError::BoundsCheck { ref len, ref index } = *msg {
3412 len.visit_with(visitor) || index.visit_with(visitor)
3427 | FalseUnwind { .. } => false,
3432 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3433 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3435 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3440 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3441 if let &Place::Projection(ref p) = self {
3442 p.visit_with(visitor)
3449 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3450 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3451 use crate::mir::Rvalue::*;
3453 Use(ref op) => Use(op.fold_with(folder)),
3454 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3455 Ref(region, bk, ref place) => {
3456 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3458 Len(ref place) => Len(place.fold_with(folder)),
3459 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3460 BinaryOp(op, ref rhs, ref lhs) => {
3461 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3463 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3464 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3466 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3467 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3468 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3469 Aggregate(ref kind, ref fields) => {
3470 let kind = box match **kind {
3471 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3472 AggregateKind::Tuple => AggregateKind::Tuple,
3473 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3476 substs.fold_with(folder),
3477 user_ty.fold_with(folder),
3480 AggregateKind::Closure(id, substs) => {
3481 AggregateKind::Closure(id, substs.fold_with(folder))
3483 AggregateKind::Generator(id, substs, movablity) => {
3484 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3487 Aggregate(kind, fields.fold_with(folder))
3492 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3493 use crate::mir::Rvalue::*;
3495 Use(ref op) => op.visit_with(visitor),
3496 Repeat(ref op, _) => op.visit_with(visitor),
3497 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3498 Len(ref place) => place.visit_with(visitor),
3499 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3500 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3501 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3503 UnaryOp(_, ref val) => val.visit_with(visitor),
3504 Discriminant(ref place) => place.visit_with(visitor),
3505 NullaryOp(_, ty) => ty.visit_with(visitor),
3506 Aggregate(ref kind, ref fields) => {
3508 AggregateKind::Array(ty) => ty.visit_with(visitor),
3509 AggregateKind::Tuple => false,
3510 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3511 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3513 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3514 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3515 }) || fields.visit_with(visitor)
3521 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3522 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3524 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3525 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3526 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3530 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3532 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3533 Operand::Constant(ref c) => c.visit_with(visitor),
3538 impl<'tcx> TypeFoldable<'tcx> for Projection<'tcx> {
3539 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3540 use crate::mir::ProjectionElem::*;
3542 let base = self.base.fold_with(folder);
3543 let elem = match self.elem {
3545 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3546 Index(ref v) => Index(v.fold_with(folder)),
3547 ref elem => elem.clone(),
3550 Projection { base, elem }
3553 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3554 use crate::mir::ProjectionElem::*;
3556 self.base.visit_with(visitor) || match self.elem {
3557 Field(_, ref ty) => ty.visit_with(visitor),
3558 Index(ref v) => v.visit_with(visitor),
3564 impl<'tcx> TypeFoldable<'tcx> for Field {
3565 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3568 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3573 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3574 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3577 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3582 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3583 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3586 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3591 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3592 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3594 span: self.span.clone(),
3595 ty: self.ty.fold_with(folder),
3596 user_ty: self.user_ty.fold_with(folder),
3597 literal: self.literal.fold_with(folder),
3600 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3601 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)