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, PanicInfo, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use crate::ty::adjustment::PointerCast;
13 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 use crate::ty::layout::VariantIdx;
15 use crate::ty::print::{FmtPrinter, Printer};
16 use crate::ty::subst::{Subst, SubstsRef};
18 self, AdtDef, CanonicalUserTypeAnnotations, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt,
19 UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_data_structures::bit_set::BitMatrix;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
26 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_data_structures::sync::MappedReadGuard;
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Encodable, Decodable};
31 use smallvec::SmallVec;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::iter::FusedIterator;
35 use std::ops::{Index, IndexMut};
37 use std::vec::IntoIter;
38 use std::{iter, mem, option, u32};
39 use syntax::ast::Name;
40 use syntax::symbol::{InternedString, Symbol};
41 use syntax_pos::{Span, DUMMY_SP};
43 pub use crate::mir::interpret::AssertMessage;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// The various "big phases" that MIR goes through.
73 /// Warning: ordering of variants is significant
74 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
83 /// Gets the index of the current MirPhase within the set of all MirPhases.
84 pub fn phase_index(&self) -> usize {
89 /// Lowered representation of a single function.
90 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
91 pub struct Body<'tcx> {
92 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
93 /// that indexes into this vector.
94 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
96 /// Records how far through the "desugaring and optimization" process this particular
97 /// MIR has traversed. This is particularly useful when inlining, since in that context
98 /// we instantiate the promoted constants and add them to our promoted vector -- but those
99 /// promoted items have already been optimized, whereas ours have not. This field allows
100 /// us to see the difference and forego optimization on the inlined promoted items.
103 /// List of source scopes; these are referenced by statements
104 /// and used for debuginfo. Indexed by a `SourceScope`.
105 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
107 /// Crate-local information for each source scope, that can't (and
108 /// needn't) be tracked across crates.
109 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
111 /// Rvalues promoted from this function, such as borrows of constants.
112 /// Each of them is the Body of a constant with the fn's type parameters
113 /// in scope, but a separate set of locals.
114 pub promoted: IndexVec<Promoted, Body<'tcx>>,
116 /// Yields type of the function, if it is a generator.
117 pub yield_ty: Option<Ty<'tcx>>,
119 /// Generator drop glue
120 pub generator_drop: Option<Box<Body<'tcx>>>,
122 /// The layout of a generator. Produced by the state transformation.
123 pub generator_layout: Option<GeneratorLayout<'tcx>>,
125 /// Declarations of locals.
127 /// The first local is the return value pointer, followed by `arg_count`
128 /// locals for the function arguments, followed by any user-declared
129 /// variables and temporaries.
130 pub local_decls: LocalDecls<'tcx>,
132 /// User type annotations
133 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
135 /// Number of arguments this function takes.
137 /// Starting at local 1, `arg_count` locals will be provided by the caller
138 /// and can be assumed to be initialized.
140 /// If this MIR was built for a constant, this will be 0.
141 pub arg_count: usize,
143 /// Mark an argument local (which must be a tuple) as getting passed as
144 /// its individual components at the LLVM level.
146 /// This is used for the "rust-call" ABI.
147 pub spread_arg: Option<Local>,
149 /// Names and capture modes of all the closure upvars, assuming
150 /// the first argument is either the closure or a reference to it.
151 // NOTE(eddyb) This is *strictly* a temporary hack for codegen
152 // debuginfo generation, and will be removed at some point.
153 // Do **NOT** use it for anything else, upvar information should not be
154 // in the MIR, please rely on local crate HIR or other side-channels.
155 pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
157 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
158 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
159 /// this conversion from happening and use short circuiting, we will cause the following code
160 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
162 /// List of places where control flow was destroyed. Used for error reporting.
163 pub control_flow_destroyed: Vec<(Span, String)>,
165 /// A span representing this MIR, for error reporting
168 /// A cache for various calculations
172 impl<'tcx> Body<'tcx> {
174 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
175 source_scopes: IndexVec<SourceScope, SourceScopeData>,
176 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
177 promoted: IndexVec<Promoted, Body<'tcx>>,
178 yield_ty: Option<Ty<'tcx>>,
179 local_decls: LocalDecls<'tcx>,
180 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
182 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
184 control_flow_destroyed: Vec<(Span, String)>,
186 // We need `arg_count` locals, and one for the return place
188 local_decls.len() >= arg_count + 1,
189 "expected at least {} locals, got {}",
195 phase: MirPhase::Build,
198 source_scope_local_data,
201 generator_drop: None,
202 generator_layout: None,
204 user_type_annotations,
206 __upvar_debuginfo_codegen_only_do_not_use,
209 cache: cache::Cache::new(),
210 control_flow_destroyed,
215 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
220 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
221 self.cache.invalidate();
222 &mut self.basic_blocks
226 pub fn basic_blocks_and_local_decls_mut(
228 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
229 self.cache.invalidate();
230 (&mut self.basic_blocks, &mut self.local_decls)
234 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
235 self.cache.predecessors(self)
239 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
240 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
244 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
245 let if_zero_locations = if loc.statement_index == 0 {
246 let predecessor_blocks = self.predecessors_for(loc.block);
247 let num_predecessor_blocks = predecessor_blocks.len();
249 (0..num_predecessor_blocks)
250 .map(move |i| predecessor_blocks[i])
251 .map(move |bb| self.terminator_loc(bb)),
257 let if_not_zero_locations = if loc.statement_index == 0 {
260 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
263 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
267 pub fn dominators(&self) -> Dominators<BasicBlock> {
272 pub fn local_kind(&self, local: Local) -> LocalKind {
273 let index = local.as_usize();
276 self.local_decls[local].mutability == Mutability::Mut,
277 "return place should be mutable"
280 LocalKind::ReturnPointer
281 } else if index < self.arg_count + 1 {
283 } else if self.local_decls[local].name.is_some() {
290 /// Returns an iterator over all temporaries.
292 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
293 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
294 let local = Local::new(index);
295 if self.local_decls[local].is_user_variable.is_some() {
303 /// Returns an iterator over all user-declared locals.
305 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
306 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
307 let local = Local::new(index);
308 if self.local_decls[local].is_user_variable.is_some() {
316 /// Returns an iterator over all user-declared mutable locals.
318 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
319 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
320 let local = Local::new(index);
321 let decl = &self.local_decls[local];
322 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
330 /// Returns an iterator over all user-declared mutable arguments and locals.
332 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
333 (1..self.local_decls.len()).filter_map(move |index| {
334 let local = Local::new(index);
335 let decl = &self.local_decls[local];
336 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
337 && decl.mutability == Mutability::Mut
346 /// Returns an iterator over all function arguments.
348 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
349 let arg_count = self.arg_count;
350 (1..=arg_count).map(Local::new)
353 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
354 /// locals that are neither arguments nor the return place).
356 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
357 let arg_count = self.arg_count;
358 let local_count = self.local_decls.len();
359 (arg_count + 1..local_count).map(Local::new)
362 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
363 /// invalidating statement indices in `Location`s.
364 pub fn make_statement_nop(&mut self, location: Location) {
365 let block = &mut self[location.block];
366 debug_assert!(location.statement_index < block.statements.len());
367 block.statements[location.statement_index].make_nop()
370 /// Returns the source info associated with `location`.
371 pub fn source_info(&self, location: Location) -> &SourceInfo {
372 let block = &self[location.block];
373 let stmts = &block.statements;
374 let idx = location.statement_index;
375 if idx < stmts.len() {
376 &stmts[idx].source_info
378 assert_eq!(idx, stmts.len());
379 &block.terminator().source_info
383 /// Checks if `sub` is a sub scope of `sup`
384 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
386 match self.source_scopes[sub].parent_scope {
387 None => return false,
394 /// Returns the return type, it always return first element from `local_decls` array
395 pub fn return_ty(&self) -> Ty<'tcx> {
396 self.local_decls[RETURN_PLACE].ty
399 /// Gets the location of the terminator for the given block
400 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
401 Location { block: bb, statement_index: self[bb].statements.len() }
405 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
408 /// Unsafe because of a PushUnsafeBlock
410 /// Unsafe because of an unsafe fn
412 /// Unsafe because of an `unsafe` block
413 ExplicitUnsafe(hir::HirId),
416 impl_stable_hash_for!(struct Body<'tcx> {
420 source_scope_local_data,
426 user_type_annotations,
428 __upvar_debuginfo_codegen_only_do_not_use,
430 control_flow_destroyed,
435 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
436 type Output = BasicBlockData<'tcx>;
439 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
440 &self.basic_blocks()[index]
444 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
446 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
447 &mut self.basic_blocks_mut()[index]
451 #[derive(Copy, Clone, Debug, HashStable)]
452 pub enum ClearCrossCrate<T> {
457 impl<T> ClearCrossCrate<T> {
458 pub fn assert_crate_local(self) -> T {
460 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
461 ClearCrossCrate::Set(v) => v,
466 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
467 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
469 /// Grouped information about the source code origin of a MIR entity.
470 /// Intended to be inspected by diagnostics and debuginfo.
471 /// Most passes can work with it as a whole, within a single function.
472 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, HashStable)]
473 pub struct SourceInfo {
474 /// Source span for the AST pertaining to this MIR entity.
477 /// The source scope, keeping track of which bindings can be
478 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
479 pub scope: SourceScope,
482 ///////////////////////////////////////////////////////////////////////////
483 // Mutability and borrow kinds
485 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
486 pub enum Mutability {
491 impl From<Mutability> for hir::Mutability {
492 fn from(m: Mutability) -> Self {
494 Mutability::Mut => hir::MutMutable,
495 Mutability::Not => hir::MutImmutable,
501 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
503 pub enum BorrowKind {
504 /// Data must be immutable and is aliasable.
507 /// The immediately borrowed place must be immutable, but projections from
508 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
509 /// conflict with a mutable borrow of `a.b.c`.
511 /// This is used when lowering matches: when matching on a place we want to
512 /// ensure that place have the same value from the start of the match until
513 /// an arm is selected. This prevents this code from compiling:
515 /// let mut x = &Some(0);
518 /// Some(_) if { x = &None; false } => (),
522 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
523 /// should not prevent `if let None = x { ... }`, for example, because the
524 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
525 /// We can also report errors with this kind of borrow differently.
528 /// Data must be immutable but not aliasable. This kind of borrow
529 /// cannot currently be expressed by the user and is used only in
530 /// implicit closure bindings. It is needed when the closure is
531 /// borrowing or mutating a mutable referent, e.g.:
533 /// let x: &mut isize = ...;
534 /// let y = || *x += 5;
536 /// If we were to try to translate this closure into a more explicit
537 /// form, we'd encounter an error with the code as written:
539 /// struct Env { x: & &mut isize }
540 /// let x: &mut isize = ...;
541 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
542 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
544 /// This is then illegal because you cannot mutate an `&mut` found
545 /// in an aliasable location. To solve, you'd have to translate with
546 /// an `&mut` borrow:
548 /// struct Env { x: & &mut isize }
549 /// let x: &mut isize = ...;
550 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
551 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
553 /// Now the assignment to `**env.x` is legal, but creating a
554 /// mutable pointer to `x` is not because `x` is not mutable. We
555 /// could fix this by declaring `x` as `let mut x`. This is ok in
556 /// user code, if awkward, but extra weird for closures, since the
557 /// borrow is hidden.
559 /// So we introduce a "unique imm" borrow -- the referent is
560 /// immutable, but not aliasable. This solves the problem. For
561 /// simplicity, we don't give users the way to express this
562 /// borrow, it's just used when translating closures.
565 /// Data is mutable and not aliasable.
567 /// `true` if this borrow arose from method-call auto-ref
568 /// (i.e., `adjustment::Adjust::Borrow`).
569 allow_two_phase_borrow: bool,
574 pub fn allows_two_phase_borrow(&self) -> bool {
576 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
577 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
582 ///////////////////////////////////////////////////////////////////////////
583 // Variables and temps
588 DEBUG_FORMAT = "_{}",
589 const RETURN_PLACE = 0,
593 impl Atom for Local {
594 fn index(self) -> usize {
599 /// Classifies locals into categories. See `Body::local_kind`.
600 #[derive(PartialEq, Eq, Debug, HashStable)]
602 /// User-declared variable binding
604 /// Compiler-introduced temporary
606 /// Function argument
608 /// Location of function's return value
612 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
613 pub struct VarBindingForm<'tcx> {
614 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
615 pub binding_mode: ty::BindingMode,
616 /// If an explicit type was provided for this variable binding,
617 /// this holds the source Span of that type.
619 /// NOTE: if you want to change this to a `HirId`, be wary that
620 /// doing so breaks incremental compilation (as of this writing),
621 /// while a `Span` does not cause our tests to fail.
622 pub opt_ty_info: Option<Span>,
623 /// Place of the RHS of the =, or the subject of the `match` where this
624 /// variable is initialized. None in the case of `let PATTERN;`.
625 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
626 /// (a) the right-hand side isn't evaluated as a place expression.
627 /// (b) it gives a way to separate this case from the remaining cases
629 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
630 /// Span of the pattern in which this variable was bound.
634 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
635 pub enum BindingForm<'tcx> {
636 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
637 Var(VarBindingForm<'tcx>),
638 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
639 ImplicitSelf(ImplicitSelfKind),
640 /// Reference used in a guard expression to ensure immutability.
644 /// Represents what type of implicit self a function has, if any.
645 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
646 pub enum ImplicitSelfKind {
647 /// Represents a `fn x(self);`.
649 /// Represents a `fn x(mut self);`.
651 /// Represents a `fn x(&self);`.
653 /// Represents a `fn x(&mut self);`.
655 /// Represents when a function does not have a self argument or
656 /// when a function has a `self: X` argument.
660 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
662 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
669 impl_stable_hash_for!(enum self::ImplicitSelfKind {
677 impl_stable_hash_for!(enum self::MirPhase {
684 mod binding_form_impl {
685 use crate::ich::StableHashingContext;
686 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
688 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
689 fn hash_stable<W: StableHasherResult>(
691 hcx: &mut StableHashingContext<'a>,
692 hasher: &mut StableHasher<W>,
694 use super::BindingForm::*;
695 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
698 Var(binding) => binding.hash_stable(hcx, hasher),
699 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
706 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
707 /// created during evaluation of expressions in a block tail
708 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
710 /// It is used to improve diagnostics when such temporaries are
711 /// involved in borrow_check errors, e.g., explanations of where the
712 /// temporaries come from, when their destructors are run, and/or how
713 /// one might revise the code to satisfy the borrow checker's rules.
714 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
715 pub struct BlockTailInfo {
716 /// If `true`, then the value resulting from evaluating this tail
717 /// expression is ignored by the block's expression context.
719 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
720 /// but not e.g., `let _x = { ...; tail };`
721 pub tail_result_is_ignored: bool,
724 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
728 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
729 /// argument, or the return place.
730 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
731 pub struct LocalDecl<'tcx> {
732 /// `let mut x` vs `let x`.
734 /// Temporaries and the return place are always mutable.
735 pub mutability: Mutability,
737 /// Some(binding_mode) if this corresponds to a user-declared local variable.
739 /// This is solely used for local diagnostics when generating
740 /// warnings/errors when compiling the current crate, and
741 /// therefore it need not be visible across crates. pnkfelix
742 /// currently hypothesized we *need* to wrap this in a
743 /// `ClearCrossCrate` as long as it carries as `HirId`.
744 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
746 /// `true` if this is an internal local.
748 /// These locals are not based on types in the source code and are only used
749 /// for a few desugarings at the moment.
751 /// The generator transformation will sanity check the locals which are live
752 /// across a suspension point against the type components of the generator
753 /// which type checking knows are live across a suspension point. We need to
754 /// flag drop flags to avoid triggering this check as they are introduced
757 /// Unsafety checking will also ignore dereferences of these locals,
758 /// so they can be used for raw pointers only used in a desugaring.
760 /// This should be sound because the drop flags are fully algebraic, and
761 /// therefore don't affect the OIBIT or outlives properties of the
765 /// If this local is a temporary and `is_block_tail` is `Some`,
766 /// then it is a temporary created for evaluation of some
767 /// subexpression of some block's tail expression (with no
768 /// intervening statement context).
769 pub is_block_tail: Option<BlockTailInfo>,
771 /// Type of this local.
774 /// If the user manually ascribed a type to this variable,
775 /// e.g., via `let x: T`, then we carry that type here. The MIR
776 /// borrow checker needs this information since it can affect
777 /// region inference.
778 pub user_ty: UserTypeProjections,
780 /// Name of the local, used in debuginfo and pretty-printing.
782 /// Note that function arguments can also have this set to `Some(_)`
783 /// to generate better debuginfo.
784 pub name: Option<Name>,
786 /// The *syntactic* (i.e., not visibility) source scope the local is defined
787 /// in. If the local was defined in a let-statement, this
788 /// is *within* the let-statement, rather than outside
791 /// This is needed because the visibility source scope of locals within
792 /// a let-statement is weird.
794 /// The reason is that we want the local to be *within* the let-statement
795 /// for lint purposes, but we want the local to be *after* the let-statement
796 /// for names-in-scope purposes.
798 /// That's it, if we have a let-statement like the one in this
802 /// fn foo(x: &str) {
803 /// #[allow(unused_mut)]
804 /// let mut x: u32 = { // <- one unused mut
805 /// let mut y: u32 = x.parse().unwrap();
812 /// Then, from a lint point of view, the declaration of `x: u32`
813 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
814 /// lint scopes are the same as the AST/HIR nesting.
816 /// However, from a name lookup point of view, the scopes look more like
817 /// as if the let-statements were `match` expressions:
820 /// fn foo(x: &str) {
822 /// match x.parse().unwrap() {
831 /// We care about the name-lookup scopes for debuginfo - if the
832 /// debuginfo instruction pointer is at the call to `x.parse()`, we
833 /// want `x` to refer to `x: &str`, but if it is at the call to
834 /// `drop(x)`, we want it to refer to `x: u32`.
836 /// To allow both uses to work, we need to have more than a single scope
837 /// for a local. We have the `source_info.scope` represent the
838 /// "syntactic" lint scope (with a variable being under its let
839 /// block) while the `visibility_scope` represents the "local variable"
840 /// scope (where the "rest" of a block is under all prior let-statements).
842 /// The end result looks like this:
846 /// │{ argument x: &str }
848 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
849 /// │ │ // in practice because I'm lazy.
851 /// │ │← x.source_info.scope
852 /// │ │← `x.parse().unwrap()`
854 /// │ │ │← y.source_info.scope
856 /// │ │ │{ let y: u32 }
858 /// │ │ │← y.visibility_scope
861 /// │ │{ let x: u32 }
862 /// │ │← x.visibility_scope
863 /// │ │← `drop(x)` // this accesses `x: u32`
865 pub source_info: SourceInfo,
867 /// Source scope within which the local is visible (for debuginfo)
868 /// (see `source_info` for more details).
869 pub visibility_scope: SourceScope,
872 impl<'tcx> LocalDecl<'tcx> {
873 /// Returns `true` only if local is a binding that can itself be
874 /// made mutable via the addition of the `mut` keyword, namely
875 /// something like the occurrences of `x` in:
876 /// - `fn foo(x: Type) { ... }`,
878 /// - or `match ... { C(x) => ... }`
879 pub fn can_be_made_mutable(&self) -> bool {
880 match self.is_user_variable {
881 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
882 binding_mode: ty::BindingMode::BindByValue(_),
888 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm))) => true,
894 /// Returns `true` if local is definitely not a `ref ident` or
895 /// `ref mut ident` binding. (Such bindings cannot be made into
896 /// mutable bindings, but the inverse does not necessarily hold).
897 pub fn is_nonref_binding(&self) -> bool {
898 match self.is_user_variable {
899 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
900 binding_mode: ty::BindingMode::BindByValue(_),
906 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
912 /// Returns `true` if this is a reference to a variable bound in a `match`
913 /// expression that is used to access said variable for the guard of the
915 pub fn is_ref_for_guard(&self) -> bool {
916 match self.is_user_variable {
917 Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
922 /// Returns `true` is the local is from a compiler desugaring, e.g.,
923 /// `__next` from a `for` loop.
925 pub fn from_compiler_desugaring(&self) -> bool {
926 self.source_info.span.desugaring_kind().is_some()
929 /// Creates a new `LocalDecl` for a temporary.
931 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
932 Self::new_local(ty, Mutability::Mut, false, span)
935 /// Converts `self` into same `LocalDecl` except tagged as immutable.
937 pub fn immutable(mut self) -> Self {
938 self.mutability = Mutability::Not;
942 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
944 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
945 assert!(self.is_block_tail.is_none());
946 self.is_block_tail = Some(info);
950 /// Creates a new `LocalDecl` for a internal temporary.
952 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
953 Self::new_local(ty, Mutability::Mut, true, span)
957 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
961 user_ty: UserTypeProjections::none(),
963 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
964 visibility_scope: OUTERMOST_SOURCE_SCOPE,
966 is_user_variable: None,
971 /// Builds a `LocalDecl` for the return place.
973 /// This must be inserted into the `local_decls` list as the first local.
975 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
977 mutability: Mutability::Mut,
979 user_ty: UserTypeProjections::none(),
980 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
981 visibility_scope: OUTERMOST_SOURCE_SCOPE,
984 name: None, // FIXME maybe we do want some name here?
985 is_user_variable: None,
990 /// A closure capture, with its name and mode.
991 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
992 pub struct UpvarDebuginfo {
993 pub debug_name: Name,
995 /// If true, the capture is behind a reference.
999 ///////////////////////////////////////////////////////////////////////////
1003 pub struct BasicBlock {
1005 DEBUG_FORMAT = "bb{}",
1006 const START_BLOCK = 0,
1011 pub fn start_location(self) -> Location {
1012 Location { block: self, statement_index: 0 }
1016 ///////////////////////////////////////////////////////////////////////////
1017 // BasicBlockData and Terminator
1019 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1020 pub struct BasicBlockData<'tcx> {
1021 /// List of statements in this block.
1022 pub statements: Vec<Statement<'tcx>>,
1024 /// Terminator for this block.
1026 /// N.B., this should generally ONLY be `None` during construction.
1027 /// Therefore, you should generally access it via the
1028 /// `terminator()` or `terminator_mut()` methods. The only
1029 /// exception is that certain passes, such as `simplify_cfg`, swap
1030 /// out the terminator temporarily with `None` while they continue
1031 /// to recurse over the set of basic blocks.
1032 pub terminator: Option<Terminator<'tcx>>,
1034 /// If true, this block lies on an unwind path. This is used
1035 /// during codegen where distinct kinds of basic blocks may be
1036 /// generated (particularly for MSVC cleanup). Unwind blocks must
1037 /// only branch to other unwind blocks.
1038 pub is_cleanup: bool,
1041 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1042 pub struct Terminator<'tcx> {
1043 pub source_info: SourceInfo,
1044 pub kind: TerminatorKind<'tcx>,
1047 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1048 pub enum TerminatorKind<'tcx> {
1049 /// block should have one successor in the graph; we jump there
1050 Goto { target: BasicBlock },
1052 /// operand evaluates to an integer; jump depending on its value
1053 /// to one of the targets, and otherwise fallback to `otherwise`
1055 /// discriminant value being tested
1056 discr: Operand<'tcx>,
1058 /// type of value being tested
1059 switch_ty: Ty<'tcx>,
1061 /// Possible values. The locations to branch to in each case
1062 /// are found in the corresponding indices from the `targets` vector.
1063 values: Cow<'tcx, [u128]>,
1065 /// Possible branch sites. The last element of this vector is used
1066 /// for the otherwise branch, so targets.len() == values.len() + 1
1068 // This invariant is quite non-obvious and also could be improved.
1069 // One way to make this invariant is to have something like this instead:
1071 // branches: Vec<(ConstInt, BasicBlock)>,
1072 // otherwise: Option<BasicBlock> // exhaustive if None
1074 // However we’ve decided to keep this as-is until we figure a case
1075 // where some other approach seems to be strictly better than other.
1076 targets: Vec<BasicBlock>,
1079 /// Indicates that the landing pad is finished and unwinding should
1080 /// continue. Emitted by build::scope::diverge_cleanup.
1083 /// Indicates that the landing pad is finished and that the process
1084 /// should abort. Used to prevent unwinding for foreign items.
1087 /// Indicates a normal return. The return place should have
1088 /// been filled in by now. This should occur at most once.
1091 /// Indicates a terminator that can never be reached.
1095 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1097 /// Drop the Place and assign the new value over it. This ensures
1098 /// that the assignment to `P` occurs *even if* the destructor for
1099 /// place unwinds. Its semantics are best explained by the
1104 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1112 /// Drop(P, goto BB1, unwind BB2)
1115 /// // P is now uninitialized
1119 /// // P is now uninitialized -- its dtor panicked
1124 location: Place<'tcx>,
1125 value: Operand<'tcx>,
1127 unwind: Option<BasicBlock>,
1130 /// Block ends with a call of a converging function
1132 /// The function that’s being called
1133 func: Operand<'tcx>,
1134 /// Arguments the function is called with.
1135 /// These are owned by the callee, which is free to modify them.
1136 /// This allows the memory occupied by "by-value" arguments to be
1137 /// reused across function calls without duplicating the contents.
1138 args: Vec<Operand<'tcx>>,
1139 /// Destination for the return value. If some, the call is converging.
1140 destination: Option<(Place<'tcx>, BasicBlock)>,
1141 /// Cleanups to be done if the call unwinds.
1142 cleanup: Option<BasicBlock>,
1143 /// Whether this is from a call in HIR, rather than from an overloaded
1144 /// operator. True for overloaded function call.
1145 from_hir_call: bool,
1148 /// Jump to the target if the condition has the expected value,
1149 /// otherwise panic with a message and a cleanup target.
1151 cond: Operand<'tcx>,
1153 msg: AssertMessage<'tcx>,
1155 cleanup: Option<BasicBlock>,
1160 /// The value to return
1161 value: Operand<'tcx>,
1162 /// Where to resume to
1164 /// Cleanup to be done if the generator is dropped at this suspend point
1165 drop: Option<BasicBlock>,
1168 /// Indicates the end of the dropping of a generator
1171 /// A block where control flow only ever takes one real path, but borrowck
1172 /// needs to be more conservative.
1174 /// The target normal control flow will take
1175 real_target: BasicBlock,
1176 /// A block control flow could conceptually jump to, but won't in
1178 imaginary_target: BasicBlock,
1180 /// A terminator for blocks that only take one path in reality, but where we
1181 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1182 /// This can arise in infinite loops with no function calls for example.
1184 /// The target normal control flow will take
1185 real_target: BasicBlock,
1186 /// The imaginary cleanup block link. This particular path will never be taken
1187 /// in practice, but in order to avoid fragility we want to always
1188 /// consider it in borrowck. We don't want to accept programs which
1189 /// pass borrowck only when panic=abort or some assertions are disabled
1190 /// due to release vs. debug mode builds. This needs to be an Option because
1191 /// of the remove_noop_landing_pads and no_landing_pads passes
1192 unwind: Option<BasicBlock>,
1196 pub type Successors<'a> =
1197 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1198 pub type SuccessorsMut<'a> =
1199 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1201 impl<'tcx> Terminator<'tcx> {
1202 pub fn successors(&self) -> Successors<'_> {
1203 self.kind.successors()
1206 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1207 self.kind.successors_mut()
1210 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1214 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1215 self.kind.unwind_mut()
1219 impl<'tcx> TerminatorKind<'tcx> {
1222 cond: Operand<'tcx>,
1225 ) -> TerminatorKind<'tcx> {
1226 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1227 TerminatorKind::SwitchInt {
1229 switch_ty: tcx.types.bool,
1230 values: From::from(BOOL_SWITCH_FALSE),
1231 targets: vec![f, t],
1235 pub fn successors(&self) -> Successors<'_> {
1236 use self::TerminatorKind::*;
1243 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1244 Goto { target: ref t }
1245 | Call { destination: None, cleanup: Some(ref t), .. }
1246 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1247 | Yield { resume: ref t, drop: None, .. }
1248 | DropAndReplace { target: ref t, unwind: None, .. }
1249 | Drop { target: ref t, unwind: None, .. }
1250 | Assert { target: ref t, cleanup: None, .. }
1251 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1252 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1253 | Yield { resume: ref t, drop: Some(ref u), .. }
1254 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1255 | Drop { target: ref t, unwind: Some(ref u), .. }
1256 | Assert { target: ref t, cleanup: Some(ref u), .. }
1257 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1258 Some(t).into_iter().chain(slice::from_ref(u))
1260 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1261 FalseEdges { ref real_target, ref imaginary_target } => {
1262 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1267 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1268 use self::TerminatorKind::*;
1275 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1276 Goto { target: ref mut t }
1277 | Call { destination: None, cleanup: Some(ref mut t), .. }
1278 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1279 | Yield { resume: ref mut t, drop: None, .. }
1280 | DropAndReplace { target: ref mut t, unwind: None, .. }
1281 | Drop { target: ref mut t, unwind: None, .. }
1282 | Assert { target: ref mut t, cleanup: None, .. }
1283 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1284 Some(t).into_iter().chain(&mut [])
1286 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1287 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1288 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1289 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1290 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1291 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1292 Some(t).into_iter().chain(slice::from_mut(u))
1294 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1295 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1296 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1301 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1303 TerminatorKind::Goto { .. }
1304 | TerminatorKind::Resume
1305 | TerminatorKind::Abort
1306 | TerminatorKind::Return
1307 | TerminatorKind::Unreachable
1308 | TerminatorKind::GeneratorDrop
1309 | TerminatorKind::Yield { .. }
1310 | TerminatorKind::SwitchInt { .. }
1311 | TerminatorKind::FalseEdges { .. } => None,
1312 TerminatorKind::Call { cleanup: ref unwind, .. }
1313 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1314 | TerminatorKind::DropAndReplace { ref unwind, .. }
1315 | TerminatorKind::Drop { ref unwind, .. }
1316 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1320 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1322 TerminatorKind::Goto { .. }
1323 | TerminatorKind::Resume
1324 | TerminatorKind::Abort
1325 | TerminatorKind::Return
1326 | TerminatorKind::Unreachable
1327 | TerminatorKind::GeneratorDrop
1328 | TerminatorKind::Yield { .. }
1329 | TerminatorKind::SwitchInt { .. }
1330 | TerminatorKind::FalseEdges { .. } => None,
1331 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1332 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1333 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1334 | TerminatorKind::Drop { ref mut unwind, .. }
1335 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1340 impl<'tcx> BasicBlockData<'tcx> {
1341 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1342 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1345 /// Accessor for terminator.
1347 /// Terminator may not be None after construction of the basic block is complete. This accessor
1348 /// provides a convenience way to reach the terminator.
1349 pub fn terminator(&self) -> &Terminator<'tcx> {
1350 self.terminator.as_ref().expect("invalid terminator state")
1353 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1354 self.terminator.as_mut().expect("invalid terminator state")
1357 pub fn retain_statements<F>(&mut self, mut f: F)
1359 F: FnMut(&mut Statement<'_>) -> bool,
1361 for s in &mut self.statements {
1368 pub fn expand_statements<F, I>(&mut self, mut f: F)
1370 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1371 I: iter::TrustedLen<Item = Statement<'tcx>>,
1373 // Gather all the iterators we'll need to splice in, and their positions.
1374 let mut splices: Vec<(usize, I)> = vec![];
1375 let mut extra_stmts = 0;
1376 for (i, s) in self.statements.iter_mut().enumerate() {
1377 if let Some(mut new_stmts) = f(s) {
1378 if let Some(first) = new_stmts.next() {
1379 // We can already store the first new statement.
1382 // Save the other statements for optimized splicing.
1383 let remaining = new_stmts.size_hint().0;
1385 splices.push((i + 1 + extra_stmts, new_stmts));
1386 extra_stmts += remaining;
1394 // Splice in the new statements, from the end of the block.
1395 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1396 // where a range of elements ("gap") is left uninitialized, with
1397 // splicing adding new elements to the end of that gap and moving
1398 // existing elements from before the gap to the end of the gap.
1399 // For now, this is safe code, emulating a gap but initializing it.
1400 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1401 self.statements.resize(
1404 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1405 kind: StatementKind::Nop,
1408 for (splice_start, new_stmts) in splices.into_iter().rev() {
1409 let splice_end = splice_start + new_stmts.size_hint().0;
1410 while gap.end > splice_end {
1413 self.statements.swap(gap.start, gap.end);
1415 self.statements.splice(splice_start..splice_end, new_stmts);
1416 gap.end = splice_start;
1420 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1421 if index < self.statements.len() {
1422 &self.statements[index]
1429 impl<'tcx> Debug for TerminatorKind<'tcx> {
1430 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1431 self.fmt_head(fmt)?;
1432 let successor_count = self.successors().count();
1433 let labels = self.fmt_successor_labels();
1434 assert_eq!(successor_count, labels.len());
1436 match successor_count {
1439 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1442 write!(fmt, " -> [")?;
1443 for (i, target) in self.successors().enumerate() {
1447 write!(fmt, "{}: {:?}", labels[i], target)?;
1455 impl<'tcx> TerminatorKind<'tcx> {
1456 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1457 /// successor basic block, if any. The only information not included is the list of possible
1458 /// successors, which may be rendered differently between the text and the graphviz format.
1459 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1460 use self::TerminatorKind::*;
1462 Goto { .. } => write!(fmt, "goto"),
1463 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1464 Return => write!(fmt, "return"),
1465 GeneratorDrop => write!(fmt, "generator_drop"),
1466 Resume => write!(fmt, "resume"),
1467 Abort => write!(fmt, "abort"),
1468 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1469 Unreachable => write!(fmt, "unreachable"),
1470 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1471 DropAndReplace { ref location, ref value, .. } => {
1472 write!(fmt, "replace({:?} <- {:?})", location, value)
1474 Call { ref func, ref args, ref destination, .. } => {
1475 if let Some((ref destination, _)) = *destination {
1476 write!(fmt, "{:?} = ", destination)?;
1478 write!(fmt, "{:?}(", func)?;
1479 for (index, arg) in args.iter().enumerate() {
1483 write!(fmt, "{:?}", arg)?;
1487 Assert { ref cond, expected, ref msg, .. } => {
1488 write!(fmt, "assert(")?;
1492 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1494 FalseEdges { .. } => write!(fmt, "falseEdges"),
1495 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1499 /// Returns the list of labels for the edges to the successor basic blocks.
1500 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1501 use self::TerminatorKind::*;
1503 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1504 Goto { .. } => vec!["".into()],
1505 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1506 let param_env = ty::ParamEnv::empty();
1507 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1508 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1512 tcx.mk_const(ty::Const {
1513 val: ConstValue::Scalar(Scalar::from_uint(u, size).into()),
1519 .chain(iter::once("otherwise".into()))
1522 Call { destination: Some(_), cleanup: Some(_), .. } => {
1523 vec!["return".into(), "unwind".into()]
1525 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1526 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1527 Call { destination: None, cleanup: None, .. } => vec![],
1528 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1529 Yield { drop: None, .. } => vec!["resume".into()],
1530 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1531 vec!["return".into()]
1533 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1534 vec!["return".into(), "unwind".into()]
1536 Assert { cleanup: None, .. } => vec!["".into()],
1537 Assert { .. } => vec!["success".into(), "unwind".into()],
1538 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1539 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1540 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1545 ///////////////////////////////////////////////////////////////////////////
1548 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1549 pub struct Statement<'tcx> {
1550 pub source_info: SourceInfo,
1551 pub kind: StatementKind<'tcx>,
1554 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1555 #[cfg(target_arch = "x86_64")]
1556 static_assert_size!(Statement<'_>, 56);
1558 impl<'tcx> Statement<'tcx> {
1559 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1560 /// invalidating statement indices in `Location`s.
1561 pub fn make_nop(&mut self) {
1562 self.kind = StatementKind::Nop
1565 /// Changes a statement to a nop and returns the original statement.
1566 pub fn replace_nop(&mut self) -> Self {
1568 source_info: self.source_info,
1569 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1574 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1575 pub enum StatementKind<'tcx> {
1576 /// Write the RHS Rvalue to the LHS Place.
1577 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1579 /// This represents all the reading that a pattern match may do
1580 /// (e.g., inspecting constants and discriminant values), and the
1581 /// kind of pattern it comes from. This is in order to adapt potential
1582 /// error messages to these specific patterns.
1584 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1585 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1586 FakeRead(FakeReadCause, Place<'tcx>),
1588 /// Write the discriminant for a variant to the enum Place.
1589 SetDiscriminant { place: Place<'tcx>, variant_index: VariantIdx },
1591 /// Start a live range for the storage of the local.
1594 /// End the current live range for the storage of the local.
1597 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1598 /// of `StatementKind` low.
1599 InlineAsm(Box<InlineAsm<'tcx>>),
1601 /// Retag references in the given place, ensuring they got fresh tags. This is
1602 /// part of the Stacked Borrows model. These statements are currently only interpreted
1603 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1604 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1605 /// for more details.
1606 Retag(RetagKind, Place<'tcx>),
1608 /// Encodes a user's type ascription. These need to be preserved
1609 /// intact so that NLL can respect them. For example:
1613 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1614 /// to the user-given type `T`. The effect depends on the specified variance:
1616 /// - `Covariant` -- requires that `T_y <: T`
1617 /// - `Contravariant` -- requires that `T_y :> T`
1618 /// - `Invariant` -- requires that `T_y == T`
1619 /// - `Bivariant` -- no effect
1620 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection>),
1622 /// No-op. Useful for deleting instructions without affecting statement indices.
1626 /// `RetagKind` describes what kind of retag is to be performed.
1627 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1628 pub enum RetagKind {
1629 /// The initial retag when entering a function
1631 /// Retag preparing for a two-phase borrow
1633 /// Retagging raw pointers
1635 /// A "normal" retag
1639 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1640 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1641 pub enum FakeReadCause {
1642 /// Inject a fake read of the borrowed input at the end of each guards
1645 /// This should ensure that you cannot change the variant for an enum while
1646 /// you are in the midst of matching on it.
1649 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1650 /// generate a read of x to check that it is initialized and safe.
1653 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1654 /// in a match guard to ensure that it's value hasn't change by the time
1655 /// we create the OutsideGuard version.
1658 /// Officially, the semantics of
1660 /// `let pattern = <expr>;`
1662 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1663 /// into the pattern.
1665 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1666 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1667 /// but in some cases it can affect the borrow checker, as in #53695.
1668 /// Therefore, we insert a "fake read" here to ensure that we get
1669 /// appropriate errors.
1673 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1674 pub struct InlineAsm<'tcx> {
1675 pub asm: HirInlineAsm,
1676 pub outputs: Box<[Place<'tcx>]>,
1677 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1680 impl<'tcx> Debug for Statement<'tcx> {
1681 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1682 use self::StatementKind::*;
1684 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1685 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1686 Retag(ref kind, ref place) => write!(
1690 RetagKind::FnEntry => "[fn entry] ",
1691 RetagKind::TwoPhase => "[2phase] ",
1692 RetagKind::Raw => "[raw] ",
1693 RetagKind::Default => "",
1697 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1698 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1699 SetDiscriminant { ref place, variant_index } => {
1700 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1702 InlineAsm(ref asm) => {
1703 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1705 AscribeUserType(ref place, ref variance, ref c_ty) => {
1706 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1708 Nop => write!(fmt, "nop"),
1713 ///////////////////////////////////////////////////////////////////////////
1716 /// A path to a value; something that can be evaluated without
1717 /// changing or disturbing program state.
1719 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1721 pub struct Place<'tcx> {
1722 pub base: PlaceBase<'tcx>,
1724 /// projection out of a place (access a field, deref a pointer, etc)
1725 pub projection: Option<Box<Projection<'tcx>>>,
1729 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1731 pub enum PlaceBase<'tcx> {
1735 /// static or static mut variable
1736 Static(Box<Static<'tcx>>),
1739 /// We store the normalized type to avoid requiring normalization when reading MIR
1740 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1741 pub struct Static<'tcx> {
1743 pub kind: StaticKind,
1747 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1749 pub enum StaticKind {
1754 impl_stable_hash_for!(struct Static<'tcx> {
1759 /// The `Projection` data structure defines things of the form `base.x`, `*b` or `b[index]`.
1761 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1763 pub struct Projection<'tcx> {
1764 pub base: Option<Box<Projection<'tcx>>>,
1765 pub elem: PlaceElem<'tcx>,
1769 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1771 pub enum ProjectionElem<V, T> {
1776 /// These indices are generated by slice patterns. Easiest to explain
1780 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1781 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1782 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1783 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1786 /// index or -index (in Python terms), depending on from_end
1788 /// thing being indexed must be at least this long
1790 /// counting backwards from end?
1794 /// These indices are generated by slice patterns.
1796 /// slice[from:-to] in Python terms.
1802 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1803 /// this for ADTs with more than one variant. It may be better to
1804 /// just introduce it always, or always for enums.
1806 /// The included Symbol is the name of the variant, used for printing MIR.
1807 Downcast(Option<Symbol>, VariantIdx),
1810 /// Alias for projections as they appear in places, where the base is a place
1811 /// and the index is a local.
1812 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1814 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1815 #[cfg(target_arch = "x86_64")]
1816 static_assert_size!(PlaceElem<'_>, 16);
1818 /// Alias for projections as they appear in `UserTypeProjection`, where we
1819 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1820 pub type ProjectionKind = ProjectionElem<(), ()>;
1825 DEBUG_FORMAT = "field[{}]"
1829 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1830 pub struct PlaceRef<'a, 'tcx> {
1831 pub base: &'a PlaceBase<'tcx>,
1832 pub projection: &'a Option<Box<Projection<'tcx>>>,
1835 impl<'tcx> Place<'tcx> {
1836 pub const RETURN_PLACE: Place<'tcx> = Place {
1837 base: PlaceBase::Local(RETURN_PLACE),
1841 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1842 self.elem(ProjectionElem::Field(f, ty))
1845 pub fn deref(self) -> Place<'tcx> {
1846 self.elem(ProjectionElem::Deref)
1849 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
1850 self.elem(ProjectionElem::Downcast(
1851 Some(adt_def.variants[variant_index].ident.name),
1856 pub fn downcast_unnamed(self, variant_index: VariantIdx) -> Place<'tcx> {
1857 self.elem(ProjectionElem::Downcast(None, variant_index))
1860 pub fn index(self, index: Local) -> Place<'tcx> {
1861 self.elem(ProjectionElem::Index(index))
1864 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1867 projection: Some(Box::new(Projection { base: self.projection, elem })),
1871 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1872 /// a single deref of a local.
1874 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1875 pub fn local_or_deref_local(&self) -> Option<Local> {
1878 base: PlaceBase::Local(local),
1882 base: PlaceBase::Local(local),
1883 projection: Some(box Projection {
1885 elem: ProjectionElem::Deref,
1892 /// Recursively "iterates" over place components, generating a `PlaceBase` and
1893 /// `Projections` list and invoking `op` with a `ProjectionsIter`.
1896 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1898 Place::iterate_over(&self.base, &self.projection, op)
1901 pub fn iterate_over<R>(
1902 place_base: &PlaceBase<'tcx>,
1903 place_projection: &Option<Box<Projection<'tcx>>>,
1904 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1906 fn iterate_over2<'tcx, R>(
1907 place_base: &PlaceBase<'tcx>,
1908 place_projection: &Option<Box<Projection<'tcx>>>,
1909 next: &Projections<'_, 'tcx>,
1910 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1912 match place_projection {
1914 op(place_base, next.iter())
1921 &Projections::List {
1922 projection: interior,
1931 iterate_over2(place_base, place_projection, &Projections::Empty, op)
1934 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1937 projection: &self.projection,
1942 impl From<Local> for Place<'_> {
1943 fn from(local: Local) -> Self {
1951 impl From<Local> for PlaceBase<'_> {
1952 fn from(local: Local) -> Self {
1953 PlaceBase::Local(local)
1957 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1960 op: impl FnOnce(&PlaceBase<'tcx>, ProjectionsIter<'_, 'tcx>) -> R,
1962 Place::iterate_over(self.base, self.projection, op)
1965 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1966 /// a single deref of a local.
1968 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1969 pub fn local_or_deref_local(&self) -> Option<Local> {
1972 base: PlaceBase::Local(local),
1976 base: PlaceBase::Local(local),
1977 projection: Some(box Projection {
1979 elem: ProjectionElem::Deref,
1987 /// A linked list of projections running up the stack; begins with the
1988 /// innermost projection and extends to the outermost (e.g., `a.b.c`
1989 /// would have the place `b` with a "next" pointer to `b.c`).
1990 /// Created by `Place::iterate`.
1992 /// N.B., this particular impl strategy is not the most obvious. It was
1993 /// chosen because it makes a measurable difference to NLL
1994 /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot.
1995 pub enum Projections<'p, 'tcx> {
1998 List { projection: &'p Projection<'tcx>, next: &'p Projections<'p, 'tcx> },
2001 impl<'p, 'tcx> Projections<'p, 'tcx> {
2002 fn iter(&self) -> ProjectionsIter<'_, 'tcx> {
2003 ProjectionsIter { value: self }
2007 impl<'p, 'tcx> IntoIterator for &'p Projections<'p, 'tcx> {
2008 type Item = &'p Projection<'tcx>;
2009 type IntoIter = ProjectionsIter<'p, 'tcx>;
2011 /// Converts a list of `Projection` components into an iterator;
2012 /// this iterator yields up a never-ending stream of `Option<&Place>`.
2013 /// These begin with the "innermost" projection and then with each
2014 /// projection therefrom. So given a place like `a.b.c` it would
2018 /// Some(`a`), Some(`a.b`), Some(`a.b.c`), None, None, ...
2020 fn into_iter(self) -> Self::IntoIter {
2025 /// Iterator over components; see `Projections::iter` for more
2028 /// N.B., this is not a *true* Rust iterator -- the code above just
2029 /// manually invokes `next`. This is because we (sometimes) want to
2030 /// keep executing even after `None` has been returned.
2031 pub struct ProjectionsIter<'p, 'tcx> {
2032 pub value: &'p Projections<'p, 'tcx>,
2035 impl<'p, 'tcx> Iterator for ProjectionsIter<'p, 'tcx> {
2036 type Item = &'p Projection<'tcx>;
2038 fn next(&mut self) -> Option<Self::Item> {
2039 if let &Projections::List { projection, next } = self.value {
2048 impl<'p, 'tcx> FusedIterator for ProjectionsIter<'p, 'tcx> {}
2050 impl<'tcx> Debug for Place<'tcx> {
2051 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2052 self.iterate(|_place_base, place_projections| {
2053 // FIXME: remove this collect once we have migrated to slices
2054 let projs_vec: Vec<_> = place_projections.collect();
2055 for projection in projs_vec.iter().rev() {
2056 match projection.elem {
2057 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
2058 write!(fmt, "(").unwrap();
2060 ProjectionElem::Deref => {
2061 write!(fmt, "(*").unwrap();
2063 ProjectionElem::Index(_)
2064 | ProjectionElem::ConstantIndex { .. }
2065 | ProjectionElem::Subslice { .. } => {}
2070 self.iterate(|place_base, place_projections| {
2071 write!(fmt, "{:?}", place_base)?;
2073 for projection in place_projections {
2074 match projection.elem {
2075 ProjectionElem::Downcast(Some(name), _index) => {
2076 write!(fmt, " as {})", name)?;
2078 ProjectionElem::Downcast(None, index) => {
2079 write!(fmt, " as variant#{:?})", index)?;
2081 ProjectionElem::Deref => {
2084 ProjectionElem::Field(field, ty) => {
2085 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2087 ProjectionElem::Index(ref index) => {
2088 write!(fmt, "[{:?}]", index)?;
2090 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2091 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2093 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2094 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2096 ProjectionElem::Subslice { from, to } if to == 0 => {
2097 write!(fmt, "[{:?}:]", from)?;
2099 ProjectionElem::Subslice { from, to } if from == 0 => {
2100 write!(fmt, "[:-{:?}]", to)?;
2102 ProjectionElem::Subslice { from, to } => {
2103 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2113 impl Debug for PlaceBase<'_> {
2114 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2116 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2117 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static(def_id) }) => {
2118 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2120 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Promoted(promoted) }) => {
2121 write!(fmt, "({:?}: {:?})", promoted, ty)
2127 ///////////////////////////////////////////////////////////////////////////
2131 pub struct SourceScope {
2133 DEBUG_FORMAT = "scope[{}]",
2134 const OUTERMOST_SOURCE_SCOPE = 0,
2138 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2139 pub struct SourceScopeData {
2141 pub parent_scope: Option<SourceScope>,
2144 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2145 pub struct SourceScopeLocalData {
2146 /// A HirId with lint levels equivalent to this scope's lint levels.
2147 pub lint_root: hir::HirId,
2148 /// The unsafe block that contains this node.
2152 ///////////////////////////////////////////////////////////////////////////
2155 /// These are values that can appear inside an rvalue. They are intentionally
2156 /// limited to prevent rvalues from being nested in one another.
2157 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2158 pub enum Operand<'tcx> {
2159 /// Copy: The value must be available for use afterwards.
2161 /// This implies that the type of the place must be `Copy`; this is true
2162 /// by construction during build, but also checked by the MIR type checker.
2165 /// Move: The value (including old borrows of it) will not be used again.
2167 /// Safe for values of all types (modulo future developments towards `?Move`).
2168 /// Correct usage patterns are enforced by the borrow checker for safe code.
2169 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2172 /// Synthesizes a constant value.
2173 Constant(Box<Constant<'tcx>>),
2176 impl<'tcx> Debug for Operand<'tcx> {
2177 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2178 use self::Operand::*;
2180 Constant(ref a) => write!(fmt, "{:?}", a),
2181 Copy(ref place) => write!(fmt, "{:?}", place),
2182 Move(ref place) => write!(fmt, "move {:?}", place),
2187 impl<'tcx> Operand<'tcx> {
2188 /// Convenience helper to make a constant that refers to the fn
2189 /// with given `DefId` and substs. Since this is used to synthesize
2190 /// MIR, assumes `user_ty` is None.
2191 pub fn function_handle(
2194 substs: SubstsRef<'tcx>,
2197 let ty = tcx.type_of(def_id).subst(tcx, substs);
2198 Operand::Constant(box Constant {
2202 literal: ty::Const::zero_sized(tcx, ty),
2206 pub fn to_copy(&self) -> Self {
2208 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2209 Operand::Move(ref place) => Operand::Copy(place.clone()),
2214 ///////////////////////////////////////////////////////////////////////////
2217 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2218 pub enum Rvalue<'tcx> {
2219 /// x (either a move or copy, depending on type of x)
2223 Repeat(Operand<'tcx>, u64),
2226 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2228 /// length of a [X] or [X;n] value
2231 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2233 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2234 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2236 NullaryOp(NullOp, Ty<'tcx>),
2237 UnaryOp(UnOp, Operand<'tcx>),
2239 /// Read the discriminant of an ADT.
2241 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2242 /// be defined to return, say, a 0) if ADT is not an enum.
2243 Discriminant(Place<'tcx>),
2245 /// Creates an aggregate value, like a tuple or struct. This is
2246 /// only needed because we want to distinguish `dest = Foo { x:
2247 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2248 /// that `Foo` has a destructor. These rvalues can be optimized
2249 /// away after type-checking and before lowering.
2250 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2253 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2256 Pointer(PointerCast),
2259 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2260 pub enum AggregateKind<'tcx> {
2261 /// The type is of the element
2265 /// The second field is the variant index. It's equal to 0 for struct
2266 /// and union expressions. The fourth field is
2267 /// active field number and is present only for union expressions
2268 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2269 /// active field index would identity the field `c`
2270 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2272 Closure(DefId, ClosureSubsts<'tcx>),
2273 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2276 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2278 /// The `+` operator (addition)
2280 /// The `-` operator (subtraction)
2282 /// The `*` operator (multiplication)
2284 /// The `/` operator (division)
2286 /// The `%` operator (modulus)
2288 /// The `^` operator (bitwise xor)
2290 /// The `&` operator (bitwise and)
2292 /// The `|` operator (bitwise or)
2294 /// The `<<` operator (shift left)
2296 /// The `>>` operator (shift right)
2298 /// The `==` operator (equality)
2300 /// The `<` operator (less than)
2302 /// The `<=` operator (less than or equal to)
2304 /// The `!=` operator (not equal to)
2306 /// The `>=` operator (greater than or equal to)
2308 /// The `>` operator (greater than)
2310 /// The `ptr.offset` operator
2315 pub fn is_checkable(self) -> bool {
2318 Add | Sub | Mul | Shl | Shr => true,
2324 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2326 /// Returns the size of a value of that type
2328 /// Creates a new uninitialized box for a value of that type
2332 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2334 /// The `!` operator for logical inversion
2336 /// The `-` operator for negation
2340 impl<'tcx> Debug for Rvalue<'tcx> {
2341 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2342 use self::Rvalue::*;
2345 Use(ref place) => write!(fmt, "{:?}", place),
2346 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2347 Len(ref a) => write!(fmt, "Len({:?})", a),
2348 Cast(ref kind, ref place, ref ty) => {
2349 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2351 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2352 CheckedBinaryOp(ref op, ref a, ref b) => {
2353 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2355 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2356 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2357 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2358 Ref(region, borrow_kind, ref place) => {
2359 let kind_str = match borrow_kind {
2360 BorrowKind::Shared => "",
2361 BorrowKind::Shallow => "shallow ",
2362 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2365 // When printing regions, add trailing space if necessary.
2366 let print_region = ty::tls::with(|tcx| {
2367 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2369 let region = if print_region {
2370 let mut region = region.to_string();
2371 if region.len() > 0 {
2376 // Do not even print 'static
2379 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2382 Aggregate(ref kind, ref places) => {
2383 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2384 let mut tuple_fmt = fmt.debug_tuple("");
2385 for place in places {
2386 tuple_fmt.field(place);
2392 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2394 AggregateKind::Tuple => match places.len() {
2395 0 => write!(fmt, "()"),
2396 1 => write!(fmt, "({:?},)", places[0]),
2397 _ => fmt_tuple(fmt, places),
2400 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2401 let variant_def = &adt_def.variants[variant];
2404 ty::tls::with(|tcx| {
2405 let substs = tcx.lift(&substs).expect("could not lift for printing");
2406 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2407 .print_def_path(variant_def.def_id, substs)?;
2411 match variant_def.ctor_kind {
2412 CtorKind::Const => Ok(()),
2413 CtorKind::Fn => fmt_tuple(fmt, places),
2414 CtorKind::Fictive => {
2415 let mut struct_fmt = fmt.debug_struct("");
2416 for (field, place) in variant_def.fields.iter().zip(places) {
2417 struct_fmt.field(&field.ident.as_str(), place);
2424 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2425 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2426 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2427 format!("[closure@{:?}]", hir_id)
2429 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2431 let mut struct_fmt = fmt.debug_struct(&name);
2433 if let Some(upvars) = tcx.upvars(def_id) {
2434 for (&var_id, place) in upvars.keys().zip(places) {
2435 let var_name = tcx.hir().name(var_id);
2436 struct_fmt.field(&var_name.as_str(), place);
2442 write!(fmt, "[closure]")
2446 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2447 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2448 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2449 let mut struct_fmt = fmt.debug_struct(&name);
2451 if let Some(upvars) = tcx.upvars(def_id) {
2452 for (&var_id, place) in upvars.keys().zip(places) {
2453 let var_name = tcx.hir().name(var_id);
2454 struct_fmt.field(&var_name.as_str(), place);
2460 write!(fmt, "[generator]")
2469 ///////////////////////////////////////////////////////////////////////////
2472 /// Two constants are equal if they are the same constant. Note that
2473 /// this does not necessarily mean that they are "==" in Rust -- in
2474 /// particular one must be wary of `NaN`!
2476 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2477 pub struct Constant<'tcx> {
2481 /// Optional user-given type: for something like
2482 /// `collect::<Vec<_>>`, this would be present and would
2483 /// indicate that `Vec<_>` was explicitly specified.
2485 /// Needed for NLL to impose user-given type constraints.
2486 pub user_ty: Option<UserTypeAnnotationIndex>,
2488 pub literal: &'tcx ty::Const<'tcx>,
2491 /// A collection of projections into user types.
2493 /// They are projections because a binding can occur a part of a
2494 /// parent pattern that has been ascribed a type.
2496 /// Its a collection because there can be multiple type ascriptions on
2497 /// the path from the root of the pattern down to the binding itself.
2502 /// struct S<'a>((i32, &'a str), String);
2503 /// let S((_, w): (i32, &'static str), _): S = ...;
2504 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2505 /// // --------------------------------- ^ (2)
2508 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2509 /// ascribed the type `(i32, &'static str)`.
2511 /// The highlights labelled `(2)` show the whole pattern being
2512 /// ascribed the type `S`.
2514 /// In this example, when we descend to `w`, we will have built up the
2515 /// following two projected types:
2517 /// * base: `S`, projection: `(base.0).1`
2518 /// * base: `(i32, &'static str)`, projection: `base.1`
2520 /// The first will lead to the constraint `w: &'1 str` (for some
2521 /// inferred region `'1`). The second will lead to the constraint `w:
2523 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2524 pub struct UserTypeProjections {
2525 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2528 BraceStructTypeFoldableImpl! {
2529 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2534 impl<'tcx> UserTypeProjections {
2535 pub fn none() -> Self {
2536 UserTypeProjections { contents: vec![] }
2539 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2540 UserTypeProjections { contents: projs.collect() }
2543 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2544 self.contents.iter()
2547 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2548 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2551 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2552 self.contents.push((user_ty.clone(), span));
2558 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2560 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2564 pub fn index(self) -> Self {
2565 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2568 pub fn subslice(self, from: u32, to: u32) -> Self {
2569 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2572 pub fn deref(self) -> Self {
2573 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2576 pub fn leaf(self, field: Field) -> Self {
2577 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2580 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2581 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2585 /// Encodes the effect of a user-supplied type annotation on the
2586 /// subcomponents of a pattern. The effect is determined by applying the
2587 /// given list of proejctions to some underlying base type. Often,
2588 /// the projection element list `projs` is empty, in which case this
2589 /// directly encodes a type in `base`. But in the case of complex patterns with
2590 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2591 /// in which case the `projs` vector is used.
2595 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2597 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2598 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2599 /// determined by finding the type of the `.0` field from `T`.
2600 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2601 pub struct UserTypeProjection {
2602 pub base: UserTypeAnnotationIndex,
2603 pub projs: Vec<ProjectionKind>,
2606 impl Copy for ProjectionKind {}
2608 impl UserTypeProjection {
2609 pub(crate) fn index(mut self) -> Self {
2610 self.projs.push(ProjectionElem::Index(()));
2614 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2615 self.projs.push(ProjectionElem::Subslice { from, to });
2619 pub(crate) fn deref(mut self) -> Self {
2620 self.projs.push(ProjectionElem::Deref);
2624 pub(crate) fn leaf(mut self, field: Field) -> Self {
2625 self.projs.push(ProjectionElem::Field(field, ()));
2629 pub(crate) fn variant(
2631 adt_def: &'tcx AdtDef,
2632 variant_index: VariantIdx,
2635 self.projs.push(ProjectionElem::Downcast(
2636 Some(adt_def.variants[variant_index].ident.name),
2639 self.projs.push(ProjectionElem::Field(field, ()));
2644 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2646 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2647 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2648 use crate::mir::ProjectionElem::*;
2650 let base = self.base.fold_with(folder);
2651 let projs: Vec<_> = self
2654 .map(|elem| match elem {
2656 Field(f, ()) => Field(f.clone(), ()),
2657 Index(()) => Index(()),
2658 elem => elem.clone(),
2662 UserTypeProjection { base, projs }
2665 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2666 self.base.visit_with(visitor)
2667 // Note: there's nothing in `self.proj` to visit.
2672 pub struct Promoted {
2674 DEBUG_FORMAT = "promoted[{}]"
2678 impl<'tcx> Debug for Constant<'tcx> {
2679 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2680 write!(fmt, "{}", self)
2684 impl<'tcx> Display for Constant<'tcx> {
2685 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2686 write!(fmt, "const ")?;
2687 write!(fmt, "{}", self.literal)
2691 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2692 type Node = BasicBlock;
2695 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2696 fn num_nodes(&self) -> usize {
2697 self.basic_blocks.len()
2701 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2702 fn start_node(&self) -> Self::Node {
2707 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2711 ) -> <Self as GraphPredecessors<'_>>::Iter {
2712 self.predecessors_for(node).clone().into_iter()
2716 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2720 ) -> <Self as GraphSuccessors<'_>>::Iter {
2721 self.basic_blocks[node].terminator().successors().cloned()
2725 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2726 type Item = BasicBlock;
2727 type Iter = IntoIter<BasicBlock>;
2730 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2731 type Item = BasicBlock;
2732 type Iter = iter::Cloned<Successors<'b>>;
2735 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2736 pub struct Location {
2737 /// the location is within this block
2738 pub block: BasicBlock,
2740 /// the location is the start of the statement; or, if `statement_index`
2741 /// == num-statements, then the start of the terminator.
2742 pub statement_index: usize,
2745 impl fmt::Debug for Location {
2746 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2747 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2752 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2754 /// Returns the location immediately after this one within the enclosing block.
2756 /// Note that if this location represents a terminator, then the
2757 /// resulting location would be out of bounds and invalid.
2758 pub fn successor_within_block(&self) -> Location {
2759 Location { block: self.block, statement_index: self.statement_index + 1 }
2762 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2763 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2764 // If we are in the same block as the other location and are an earlier statement
2765 // then we are a predecessor of `other`.
2766 if self.block == other.block && self.statement_index < other.statement_index {
2770 // If we're in another block, then we want to check that block is a predecessor of `other`.
2771 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2772 let mut visited = FxHashSet::default();
2774 while let Some(block) = queue.pop() {
2775 // If we haven't visited this block before, then make sure we visit it's predecessors.
2776 if visited.insert(block) {
2777 queue.append(&mut body.predecessors_for(block).clone());
2782 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2783 // we found that block by looking at the predecessors of `other`).
2784 if self.block == block {
2792 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2793 if self.block == other.block {
2794 self.statement_index <= other.statement_index
2796 dominators.is_dominated_by(other.block, self.block)
2801 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2802 pub enum UnsafetyViolationKind {
2804 /// Permitted in const fn and regular fns.
2806 ExternStatic(hir::HirId),
2807 BorrowPacked(hir::HirId),
2810 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2811 pub struct UnsafetyViolation {
2812 pub source_info: SourceInfo,
2813 pub description: InternedString,
2814 pub details: InternedString,
2815 pub kind: UnsafetyViolationKind,
2818 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
2819 pub struct UnsafetyCheckResult {
2820 /// Violations that are propagated *upwards* from this function
2821 pub violations: Lrc<[UnsafetyViolation]>,
2822 /// unsafe blocks in this function, along with whether they are used. This is
2823 /// used for the "unused_unsafe" lint.
2824 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2828 pub struct GeneratorSavedLocal {
2830 DEBUG_FORMAT = "_{}",
2834 /// The layout of generator state
2835 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2836 pub struct GeneratorLayout<'tcx> {
2837 /// The type of every local stored inside the generator.
2838 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2840 /// Which of the above fields are in each variant. Note that one field may
2841 /// be stored in multiple variants.
2842 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2844 /// Which saved locals are storage-live at the same time. Locals that do not
2845 /// have conflicts with each other are allowed to overlap in the computed
2847 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2849 /// Names and scopes of all the stored generator locals.
2850 /// NOTE(tmandry) This is *strictly* a temporary hack for codegen
2851 /// debuginfo generation, and will be removed at some point.
2852 /// Do **NOT** use it for anything else, local information should not be
2853 /// in the MIR, please rely on local crate HIR or other side-channels.
2854 pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
2857 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2858 pub struct BorrowCheckResult<'tcx> {
2859 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2860 pub used_mut_upvars: SmallVec<[Field; 8]>,
2863 /// After we borrow check a closure, we are left with various
2864 /// requirements that we have inferred between the free regions that
2865 /// appear in the closure's signature or on its field types. These
2866 /// requirements are then verified and proved by the closure's
2867 /// creating function. This struct encodes those requirements.
2869 /// The requirements are listed as being between various
2870 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2871 /// vids refer to the free regions that appear in the closure (or
2872 /// generator's) type, in order of appearance. (This numbering is
2873 /// actually defined by the `UniversalRegions` struct in the NLL
2874 /// region checker. See for example
2875 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2876 /// regions in the closure's type "as if" they were erased, so their
2877 /// precise identity is not important, only their position.
2879 /// Example: If type check produces a closure with the closure substs:
2882 /// ClosureSubsts = [
2883 /// i8, // the "closure kind"
2884 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2885 /// &'a String, // some upvar
2889 /// here, there is one unique free region (`'a`) but it appears
2890 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2893 /// ClosureSubsts = [
2894 /// i8, // the "closure kind"
2895 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2896 /// &'2 String, // some upvar
2900 /// Now the code might impose a requirement like `'1: '2`. When an
2901 /// instance of the closure is created, the corresponding free regions
2902 /// can be extracted from its type and constrained to have the given
2903 /// outlives relationship.
2905 /// In some cases, we have to record outlives requirements between
2906 /// types and regions as well. In that case, if those types include
2907 /// any regions, those regions are recorded as `ReClosureBound`
2908 /// instances assigned one of these same indices. Those regions will
2909 /// be substituted away by the creator. We use `ReClosureBound` in
2910 /// that case because the regions must be allocated in the global
2911 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2912 /// internally within the rest of the NLL code).
2913 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2914 pub struct ClosureRegionRequirements<'tcx> {
2915 /// The number of external regions defined on the closure. In our
2916 /// example above, it would be 3 -- one for `'static`, then `'1`
2917 /// and `'2`. This is just used for a sanity check later on, to
2918 /// make sure that the number of regions we see at the callsite
2920 pub num_external_vids: usize,
2922 /// Requirements between the various free regions defined in
2924 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2927 /// Indicates an outlives constraint between a type or between two
2928 /// free-regions declared on the closure.
2929 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2930 pub struct ClosureOutlivesRequirement<'tcx> {
2931 // This region or type ...
2932 pub subject: ClosureOutlivesSubject<'tcx>,
2934 // ... must outlive this one.
2935 pub outlived_free_region: ty::RegionVid,
2937 // If not, report an error here ...
2938 pub blame_span: Span,
2940 // ... due to this reason.
2941 pub category: ConstraintCategory,
2944 /// Outlives constraints can be categorized to determine whether and why they
2945 /// are interesting (for error reporting). Order of variants indicates sort
2946 /// order of the category, thereby influencing diagnostic output.
2948 /// See also [rustc_mir::borrow_check::nll::constraints]
2962 pub enum ConstraintCategory {
2970 /// A constraint that came from checking the body of a closure.
2972 /// We try to get the category that the closure used when reporting this.
2980 /// A "boring" constraint (caused by the given location) is one that
2981 /// the user probably doesn't want to see described in diagnostics,
2982 /// because it is kind of an artifact of the type system setup.
2983 /// Example: `x = Foo { field: y }` technically creates
2984 /// intermediate regions representing the "type of `Foo { field: y
2985 /// }`", and data flows from `y` into those variables, but they
2986 /// are not very interesting. The assignment into `x` on the other
2989 // Boring and applicable everywhere.
2992 /// A constraint that doesn't correspond to anything the user sees.
2996 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2997 /// that must outlive some region.
2998 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2999 pub enum ClosureOutlivesSubject<'tcx> {
3000 /// Subject is a type, typically a type parameter, but could also
3001 /// be a projection. Indicates a requirement like `T: 'a` being
3002 /// passed to the caller, where the type here is `T`.
3004 /// The type here is guaranteed not to contain any free regions at
3008 /// Subject is a free region from the closure. Indicates a requirement
3009 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
3010 Region(ty::RegionVid),
3014 * TypeFoldable implementations for MIR types
3017 CloneTypeFoldableAndLiftImpls! {
3027 SourceScopeLocalData,
3028 UserTypeAnnotationIndex,
3031 BraceStructTypeFoldableImpl! {
3032 impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
3036 source_scope_local_data,
3042 user_type_annotations,
3044 __upvar_debuginfo_codegen_only_do_not_use,
3046 control_flow_destroyed,
3052 BraceStructTypeFoldableImpl! {
3053 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3057 __local_debuginfo_codegen_only_do_not_use,
3061 BraceStructTypeFoldableImpl! {
3062 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3075 BraceStructTypeFoldableImpl! {
3076 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3083 BraceStructTypeFoldableImpl! {
3084 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3089 EnumTypeFoldableImpl! {
3090 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3091 (StatementKind::Assign)(a, b),
3092 (StatementKind::FakeRead)(cause, place),
3093 (StatementKind::SetDiscriminant) { place, variant_index },
3094 (StatementKind::StorageLive)(a),
3095 (StatementKind::StorageDead)(a),
3096 (StatementKind::InlineAsm)(a),
3097 (StatementKind::Retag)(kind, place),
3098 (StatementKind::AscribeUserType)(a, v, b),
3099 (StatementKind::Nop),
3103 BraceStructTypeFoldableImpl! {
3104 impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3111 EnumTypeFoldableImpl! {
3112 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3113 (ClearCrossCrate::Clear),
3114 (ClearCrossCrate::Set)(a),
3115 } where T: TypeFoldable<'tcx>
3118 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3119 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3120 use crate::mir::TerminatorKind::*;
3122 let kind = match self.kind {
3123 Goto { target } => Goto { target },
3124 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
3125 discr: discr.fold_with(folder),
3126 switch_ty: switch_ty.fold_with(folder),
3127 values: values.clone(),
3128 targets: targets.clone(),
3130 Drop { ref location, target, unwind } => {
3131 Drop { location: location.fold_with(folder), target, unwind }
3133 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
3134 location: location.fold_with(folder),
3135 value: value.fold_with(folder),
3139 Yield { ref value, resume, drop } => {
3140 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3142 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3144 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3147 func: func.fold_with(folder),
3148 args: args.fold_with(folder),
3154 Assert { ref cond, expected, ref msg, target, cleanup } => {
3156 let msg = match msg {
3157 BoundsCheck { ref len, ref index } =>
3159 len: len.fold_with(folder),
3160 index: index.fold_with(folder),
3162 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3163 GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3166 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3168 GeneratorDrop => GeneratorDrop,
3172 Unreachable => Unreachable,
3173 FalseEdges { real_target, imaginary_target } => {
3174 FalseEdges { real_target, imaginary_target }
3176 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3178 Terminator { source_info: self.source_info, kind }
3181 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3182 use crate::mir::TerminatorKind::*;
3185 SwitchInt { ref discr, switch_ty, .. } => {
3186 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3188 Drop { ref location, .. } => location.visit_with(visitor),
3189 DropAndReplace { ref location, ref value, .. } => {
3190 location.visit_with(visitor) || value.visit_with(visitor)
3192 Yield { ref value, .. } => value.visit_with(visitor),
3193 Call { ref func, ref args, ref destination, .. } => {
3194 let dest = if let Some((ref loc, _)) = *destination {
3195 loc.visit_with(visitor)
3199 dest || func.visit_with(visitor) || args.visit_with(visitor)
3201 Assert { ref cond, ref msg, .. } => {
3202 if cond.visit_with(visitor) {
3205 BoundsCheck { ref len, ref index } =>
3206 len.visit_with(visitor) || index.visit_with(visitor),
3207 Panic { .. } | Overflow(_) | OverflowNeg |
3208 DivisionByZero | RemainderByZero |
3209 GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3223 | FalseUnwind { .. } => false,
3228 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3229 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3231 base: self.base.clone(),
3232 projection: self.projection.fold_with(folder),
3236 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3237 self.projection.visit_with(visitor)
3241 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3242 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3243 use crate::mir::Rvalue::*;
3245 Use(ref op) => Use(op.fold_with(folder)),
3246 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3247 Ref(region, bk, ref place) => {
3248 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3250 Len(ref place) => Len(place.fold_with(folder)),
3251 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3252 BinaryOp(op, ref rhs, ref lhs) => {
3253 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3255 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3256 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3258 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3259 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3260 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3261 Aggregate(ref kind, ref fields) => {
3262 let kind = box match **kind {
3263 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3264 AggregateKind::Tuple => AggregateKind::Tuple,
3265 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3268 substs.fold_with(folder),
3269 user_ty.fold_with(folder),
3272 AggregateKind::Closure(id, substs) => {
3273 AggregateKind::Closure(id, substs.fold_with(folder))
3275 AggregateKind::Generator(id, substs, movablity) => {
3276 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3279 Aggregate(kind, fields.fold_with(folder))
3284 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3285 use crate::mir::Rvalue::*;
3287 Use(ref op) => op.visit_with(visitor),
3288 Repeat(ref op, _) => op.visit_with(visitor),
3289 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3290 Len(ref place) => place.visit_with(visitor),
3291 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3292 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3293 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3295 UnaryOp(_, ref val) => val.visit_with(visitor),
3296 Discriminant(ref place) => place.visit_with(visitor),
3297 NullaryOp(_, ty) => ty.visit_with(visitor),
3298 Aggregate(ref kind, ref fields) => {
3300 AggregateKind::Array(ty) => ty.visit_with(visitor),
3301 AggregateKind::Tuple => false,
3302 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3303 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3305 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3306 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3307 }) || fields.visit_with(visitor)
3313 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3314 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3316 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3317 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3318 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3322 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3324 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3325 Operand::Constant(ref c) => c.visit_with(visitor),
3330 impl<'tcx> TypeFoldable<'tcx> for Projection<'tcx> {
3331 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3332 use crate::mir::ProjectionElem::*;
3334 let base = self.base.fold_with(folder);
3335 let elem = match self.elem {
3337 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3338 Index(ref v) => Index(v.fold_with(folder)),
3339 ref elem => elem.clone(),
3342 Projection { base, elem }
3345 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3346 use crate::mir::ProjectionElem::*;
3348 self.base.visit_with(visitor)
3349 || match self.elem {
3350 Field(_, ref ty) => ty.visit_with(visitor),
3351 Index(ref v) => v.visit_with(visitor),
3357 impl<'tcx> TypeFoldable<'tcx> for Field {
3358 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3361 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3366 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3367 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3370 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3375 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3376 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3379 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3384 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3385 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3387 span: self.span.clone(),
3388 ty: self.ty.fold_with(folder),
3389 user_ty: self.user_ty.fold_with(folder),
3390 literal: self.literal.fold_with(folder),
3393 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3394 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)