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, GeneratorKind};
10 use crate::mir::interpret::{GlobalAlloc, 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, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_index::bit_set::BitMatrix;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::Dominators;
25 use rustc_data_structures::graph::{self, GraphSuccessors};
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_macros::HashStable;
29 use rustc_serialize::{Encodable, Decodable};
30 use smallvec::SmallVec;
32 use std::fmt::{self, Debug, Display, Formatter, Write};
35 use std::{iter, mem, option, u32};
36 use syntax::ast::Name;
37 use syntax::symbol::Symbol;
38 use syntax_pos::{Span, DUMMY_SP};
40 pub use crate::mir::interpret::AssertMessage;
50 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
52 pub trait HasLocalDecls<'tcx> {
53 fn local_decls(&self) -> &LocalDecls<'tcx>;
56 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx> {
62 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
63 fn local_decls(&self) -> &LocalDecls<'tcx> {
68 /// The various "big phases" that MIR goes through.
70 /// Warning: ordering of variants is significant.
71 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable,
72 Debug, PartialEq, Eq, PartialOrd, Ord)]
81 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
82 pub fn phase_index(&self) -> usize {
87 /// The lowered representation of a single function.
88 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
89 pub struct Body<'tcx> {
90 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
91 /// that indexes into this vector.
92 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
94 /// Records how far through the "desugaring and optimization" process this particular
95 /// MIR has traversed. This is particularly useful when inlining, since in that context
96 /// we instantiate the promoted constants and add them to our promoted vector -- but those
97 /// promoted items have already been optimized, whereas ours have not. This field allows
98 /// us to see the difference and forego optimization on the inlined promoted items.
101 /// A list of source scopes; these are referenced by statements
102 /// and used for debuginfo. Indexed by a `SourceScope`.
103 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
105 /// The yield type of the function, if it is a generator.
106 pub yield_ty: Option<Ty<'tcx>>,
108 /// Generator drop glue.
109 pub generator_drop: Option<Box<Body<'tcx>>>,
111 /// The layout of a generator. Produced by the state transformation.
112 pub generator_layout: Option<GeneratorLayout<'tcx>>,
114 /// If this is a generator then record the type of source expression that caused this generator
116 pub generator_kind: Option<GeneratorKind>,
118 /// Declarations of locals.
120 /// The first local is the return value pointer, followed by `arg_count`
121 /// locals for the function arguments, followed by any user-declared
122 /// variables and temporaries.
123 pub local_decls: LocalDecls<'tcx>,
125 /// User type annotations.
126 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
128 /// The number of arguments this function takes.
130 /// Starting at local 1, `arg_count` locals will be provided by the caller
131 /// and can be assumed to be initialized.
133 /// If this MIR was built for a constant, this will be 0.
134 pub arg_count: usize,
136 /// Mark an argument local (which must be a tuple) as getting passed as
137 /// its individual components at the LLVM level.
139 /// This is used for the "rust-call" ABI.
140 pub spread_arg: Option<Local>,
142 /// Debug information pertaining to user variables, including captures.
143 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
145 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
146 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
147 /// this conversion from happening and use short circuiting, we will cause the following code
148 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
150 /// List of places where control flow was destroyed. Used for error reporting.
151 pub control_flow_destroyed: Vec<(Span, String)>,
153 /// A span representing this MIR, for error reporting.
157 impl<'tcx> Body<'tcx> {
159 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
160 source_scopes: IndexVec<SourceScope, SourceScopeData>,
161 local_decls: LocalDecls<'tcx>,
162 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
164 var_debug_info: Vec<VarDebugInfo<'tcx>>,
166 control_flow_destroyed: Vec<(Span, String)>,
167 generator_kind : Option<GeneratorKind>,
169 // We need `arg_count` locals, and one for the return place.
171 local_decls.len() >= arg_count + 1,
172 "expected at least {} locals, got {}",
178 phase: MirPhase::Build,
182 generator_drop: None,
183 generator_layout: None,
186 user_type_annotations,
191 control_flow_destroyed,
196 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
200 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
202 pub fn is_cfg_cyclic(&self) -> bool {
203 graph::is_cyclic(self)
207 pub fn local_kind(&self, local: Local) -> LocalKind {
208 let index = local.as_usize();
211 self.local_decls[local].mutability == Mutability::Mut,
212 "return place should be mutable"
215 LocalKind::ReturnPointer
216 } else if index < self.arg_count + 1 {
218 } else if self.local_decls[local].is_user_variable() {
225 /// Returns an iterator over all temporaries.
227 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
228 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
229 let local = Local::new(index);
230 if self.local_decls[local].is_user_variable() {
238 /// Returns an iterator over all user-declared locals.
240 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
241 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
242 let local = Local::new(index);
243 if self.local_decls[local].is_user_variable() {
251 /// Returns an iterator over all user-declared mutable locals.
253 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
254 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
255 let local = Local::new(index);
256 let decl = &self.local_decls[local];
257 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
265 /// Returns an iterator over all user-declared mutable arguments and locals.
267 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
268 (1..self.local_decls.len()).filter_map(move |index| {
269 let local = Local::new(index);
270 let decl = &self.local_decls[local];
271 if (decl.is_user_variable() || index < self.arg_count + 1)
272 && decl.mutability == Mutability::Mut
281 /// Returns an iterator over all function arguments.
283 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
284 let arg_count = self.arg_count;
285 (1..=arg_count).map(Local::new)
288 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
289 /// locals that are neither arguments nor the return place).
291 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
292 let arg_count = self.arg_count;
293 let local_count = self.local_decls.len();
294 (arg_count + 1..local_count).map(Local::new)
297 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
298 /// invalidating statement indices in `Location`s.
299 pub fn make_statement_nop(&mut self, location: Location) {
300 let block = &mut self.basic_blocks[location.block];
301 debug_assert!(location.statement_index < block.statements.len());
302 block.statements[location.statement_index].make_nop()
305 /// Returns the source info associated with `location`.
306 pub fn source_info(&self, location: Location) -> &SourceInfo {
307 let block = &self[location.block];
308 let stmts = &block.statements;
309 let idx = location.statement_index;
310 if idx < stmts.len() {
311 &stmts[idx].source_info
313 assert_eq!(idx, stmts.len());
314 &block.terminator().source_info
318 /// Checks if `sub` is a sub scope of `sup`
319 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
321 match self.source_scopes[sub].parent_scope {
322 None => return false,
329 /// Returns the return type; it always return first element from `local_decls` array.
330 pub fn return_ty(&self) -> Ty<'tcx> {
331 self.local_decls[RETURN_PLACE].ty
334 /// Gets the location of the terminator for the given block.
335 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
336 Location { block: bb, statement_index: self[bb].statements.len() }
340 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
343 /// Unsafe because of a PushUnsafeBlock
345 /// Unsafe because of an unsafe fn
347 /// Unsafe because of an `unsafe` block
348 ExplicitUnsafe(hir::HirId),
351 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
352 type Output = BasicBlockData<'tcx>;
355 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
356 &self.basic_blocks()[index]
360 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
361 pub enum ClearCrossCrate<T> {
366 impl<T> ClearCrossCrate<T> {
367 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
369 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
370 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
374 pub fn assert_crate_local(self) -> T {
376 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
377 ClearCrossCrate::Set(v) => v,
382 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
383 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
385 /// Grouped information about the source code origin of a MIR entity.
386 /// Intended to be inspected by diagnostics and debuginfo.
387 /// Most passes can work with it as a whole, within a single function.
388 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
389 // `Hash`. Please ping @bjorn3 if removing them.
390 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
391 pub struct SourceInfo {
392 /// The source span for the AST pertaining to this MIR entity.
395 /// The source scope, keeping track of which bindings can be
396 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
397 pub scope: SourceScope,
400 ///////////////////////////////////////////////////////////////////////////
401 // Mutability and borrow kinds
403 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
404 pub enum Mutability {
409 impl From<Mutability> for hir::Mutability {
410 fn from(m: Mutability) -> Self {
412 Mutability::Mut => hir::Mutability::Mutable,
413 Mutability::Not => hir::Mutability::Immutable,
419 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
421 pub enum BorrowKind {
422 /// Data must be immutable and is aliasable.
425 /// The immediately borrowed place must be immutable, but projections from
426 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
427 /// conflict with a mutable borrow of `a.b.c`.
429 /// This is used when lowering matches: when matching on a place we want to
430 /// ensure that place have the same value from the start of the match until
431 /// an arm is selected. This prevents this code from compiling:
433 /// let mut x = &Some(0);
436 /// Some(_) if { x = &None; false } => (),
440 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
441 /// should not prevent `if let None = x { ... }`, for example, because the
442 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
443 /// We can also report errors with this kind of borrow differently.
446 /// Data must be immutable but not aliasable. This kind of borrow
447 /// cannot currently be expressed by the user and is used only in
448 /// implicit closure bindings. It is needed when the closure is
449 /// borrowing or mutating a mutable referent, e.g.:
451 /// let x: &mut isize = ...;
452 /// let y = || *x += 5;
454 /// If we were to try to translate this closure into a more explicit
455 /// form, we'd encounter an error with the code as written:
457 /// struct Env { x: & &mut isize }
458 /// let x: &mut isize = ...;
459 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
460 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
462 /// This is then illegal because you cannot mutate an `&mut` found
463 /// in an aliasable location. To solve, you'd have to translate with
464 /// an `&mut` borrow:
466 /// struct Env { x: & &mut isize }
467 /// let x: &mut isize = ...;
468 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
469 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
471 /// Now the assignment to `**env.x` is legal, but creating a
472 /// mutable pointer to `x` is not because `x` is not mutable. We
473 /// could fix this by declaring `x` as `let mut x`. This is ok in
474 /// user code, if awkward, but extra weird for closures, since the
475 /// borrow is hidden.
477 /// So we introduce a "unique imm" borrow -- the referent is
478 /// immutable, but not aliasable. This solves the problem. For
479 /// simplicity, we don't give users the way to express this
480 /// borrow, it's just used when translating closures.
483 /// Data is mutable and not aliasable.
485 /// `true` if this borrow arose from method-call auto-ref
486 /// (i.e., `adjustment::Adjust::Borrow`).
487 allow_two_phase_borrow: bool,
492 pub fn allows_two_phase_borrow(&self) -> bool {
494 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
495 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
500 ///////////////////////////////////////////////////////////////////////////
501 // Variables and temps
503 rustc_index::newtype_index! {
506 DEBUG_FORMAT = "_{}",
507 const RETURN_PLACE = 0,
511 impl Atom for Local {
512 fn index(self) -> usize {
517 /// Classifies locals into categories. See `Body::local_kind`.
518 #[derive(PartialEq, Eq, Debug, HashStable)]
520 /// User-declared variable binding.
522 /// Compiler-introduced temporary.
524 /// Function argument.
526 /// Location of function's return value.
530 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
531 pub struct VarBindingForm<'tcx> {
532 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
533 pub binding_mode: ty::BindingMode,
534 /// If an explicit type was provided for this variable binding,
535 /// this holds the source Span of that type.
537 /// NOTE: if you want to change this to a `HirId`, be wary that
538 /// doing so breaks incremental compilation (as of this writing),
539 /// while a `Span` does not cause our tests to fail.
540 pub opt_ty_info: Option<Span>,
541 /// Place of the RHS of the =, or the subject of the `match` where this
542 /// variable is initialized. None in the case of `let PATTERN;`.
543 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
544 /// (a) the right-hand side isn't evaluated as a place expression.
545 /// (b) it gives a way to separate this case from the remaining cases
547 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
548 /// The span of the pattern in which this variable was bound.
552 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
553 pub enum BindingForm<'tcx> {
554 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
555 Var(VarBindingForm<'tcx>),
556 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
557 ImplicitSelf(ImplicitSelfKind),
558 /// Reference used in a guard expression to ensure immutability.
562 /// Represents what type of implicit self a function has, if any.
563 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
564 pub enum ImplicitSelfKind {
565 /// Represents a `fn x(self);`.
567 /// Represents a `fn x(mut self);`.
569 /// Represents a `fn x(&self);`.
571 /// Represents a `fn x(&mut self);`.
573 /// Represents when a function does not have a self argument or
574 /// when a function has a `self: X` argument.
578 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
580 mod binding_form_impl {
581 use crate::ich::StableHashingContext;
582 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
584 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
585 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
586 use super::BindingForm::*;
587 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
590 Var(binding) => binding.hash_stable(hcx, hasher),
591 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
598 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
599 /// created during evaluation of expressions in a block tail
600 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
602 /// It is used to improve diagnostics when such temporaries are
603 /// involved in borrow_check errors, e.g., explanations of where the
604 /// temporaries come from, when their destructors are run, and/or how
605 /// one might revise the code to satisfy the borrow checker's rules.
606 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
607 pub struct BlockTailInfo {
608 /// If `true`, then the value resulting from evaluating this tail
609 /// expression is ignored by the block's expression context.
611 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
612 /// but not e.g., `let _x = { ...; tail };`
613 pub tail_result_is_ignored: bool,
618 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
619 /// argument, or the return place.
620 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
621 pub struct LocalDecl<'tcx> {
622 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
624 /// Temporaries and the return place are always mutable.
625 pub mutability: Mutability,
627 // FIXME(matthewjasper) Don't store in this in `Body`
628 pub local_info: LocalInfo<'tcx>,
630 /// `true` if this is an internal local.
632 /// These locals are not based on types in the source code and are only used
633 /// for a few desugarings at the moment.
635 /// The generator transformation will sanity check the locals which are live
636 /// across a suspension point against the type components of the generator
637 /// which type checking knows are live across a suspension point. We need to
638 /// flag drop flags to avoid triggering this check as they are introduced
641 /// Unsafety checking will also ignore dereferences of these locals,
642 /// so they can be used for raw pointers only used in a desugaring.
644 /// This should be sound because the drop flags are fully algebraic, and
645 /// therefore don't affect the OIBIT or outlives properties of the
649 /// If this local is a temporary and `is_block_tail` is `Some`,
650 /// then it is a temporary created for evaluation of some
651 /// subexpression of some block's tail expression (with no
652 /// intervening statement context).
653 // FIXME(matthewjasper) Don't store in this in `Body`
654 pub is_block_tail: Option<BlockTailInfo>,
656 /// The type of this local.
659 /// If the user manually ascribed a type to this variable,
660 /// e.g., via `let x: T`, then we carry that type here. The MIR
661 /// borrow checker needs this information since it can affect
662 /// region inference.
663 // FIXME(matthewjasper) Don't store in this in `Body`
664 pub user_ty: UserTypeProjections,
666 /// The *syntactic* (i.e., not visibility) source scope the local is defined
667 /// in. If the local was defined in a let-statement, this
668 /// is *within* the let-statement, rather than outside
671 /// This is needed because the visibility source scope of locals within
672 /// a let-statement is weird.
674 /// The reason is that we want the local to be *within* the let-statement
675 /// for lint purposes, but we want the local to be *after* the let-statement
676 /// for names-in-scope purposes.
678 /// That's it, if we have a let-statement like the one in this
682 /// fn foo(x: &str) {
683 /// #[allow(unused_mut)]
684 /// let mut x: u32 = { // <- one unused mut
685 /// let mut y: u32 = x.parse().unwrap();
692 /// Then, from a lint point of view, the declaration of `x: u32`
693 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
694 /// lint scopes are the same as the AST/HIR nesting.
696 /// However, from a name lookup point of view, the scopes look more like
697 /// as if the let-statements were `match` expressions:
700 /// fn foo(x: &str) {
702 /// match x.parse().unwrap() {
711 /// We care about the name-lookup scopes for debuginfo - if the
712 /// debuginfo instruction pointer is at the call to `x.parse()`, we
713 /// want `x` to refer to `x: &str`, but if it is at the call to
714 /// `drop(x)`, we want it to refer to `x: u32`.
716 /// To allow both uses to work, we need to have more than a single scope
717 /// for a local. We have the `source_info.scope` represent the "syntactic"
718 /// lint scope (with a variable being under its let block) while the
719 /// `var_debug_info.source_info.scope` represents the "local variable"
720 /// scope (where the "rest" of a block is under all prior let-statements).
722 /// The end result looks like this:
726 /// │{ argument x: &str }
728 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
729 /// │ │ // in practice because I'm lazy.
731 /// │ │← x.source_info.scope
732 /// │ │← `x.parse().unwrap()`
734 /// │ │ │← y.source_info.scope
736 /// │ │ │{ let y: u32 }
738 /// │ │ │← y.var_debug_info.source_info.scope
741 /// │ │{ let x: u32 }
742 /// │ │← x.var_debug_info.source_info.scope
743 /// │ │← `drop(x)` // This accesses `x: u32`.
745 pub source_info: SourceInfo,
748 /// Extra information about a local that's used for diagnostics.
749 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
750 pub enum LocalInfo<'tcx> {
751 /// A user-defined local variable or function parameter
753 /// The `BindingForm` is solely used for local diagnostics when generating
754 /// warnings/errors when compiling the current crate, and therefore it need
755 /// not be visible across crates.
756 User(ClearCrossCrate<BindingForm<'tcx>>),
757 /// A temporary created that references the static with the given `DefId`.
758 StaticRef { def_id: DefId, is_thread_local: bool },
759 /// Any other temporary, the return place, or an anonymous function parameter.
763 impl<'tcx> LocalDecl<'tcx> {
764 /// Returns `true` only if local is a binding that can itself be
765 /// made mutable via the addition of the `mut` keyword, namely
766 /// something like the occurrences of `x` in:
767 /// - `fn foo(x: Type) { ... }`,
769 /// - or `match ... { C(x) => ... }`
770 pub fn can_be_made_mutable(&self) -> bool {
771 match self.local_info {
772 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
773 binding_mode: ty::BindingMode::BindByValue(_),
780 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
787 /// Returns `true` if local is definitely not a `ref ident` or
788 /// `ref mut ident` binding. (Such bindings cannot be made into
789 /// mutable bindings, but the inverse does not necessarily hold).
790 pub fn is_nonref_binding(&self) -> bool {
791 match self.local_info {
792 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
793 binding_mode: ty::BindingMode::BindByValue(_),
799 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
805 /// Returns `true` if this variable is a named variable or function
806 /// parameter declared by the user.
808 pub fn is_user_variable(&self) -> bool {
809 match self.local_info {
810 LocalInfo::User(_) => true,
815 /// Returns `true` if this is a reference to a variable bound in a `match`
816 /// expression that is used to access said variable for the guard of the
818 pub fn is_ref_for_guard(&self) -> bool {
819 match self.local_info {
820 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
825 /// Returns `Some` if this is a reference to a static item that is used to
826 /// access that static
827 pub fn is_ref_to_static(&self) -> bool {
828 match self.local_info {
829 LocalInfo::StaticRef { .. } => true,
834 /// Returns `Some` if this is a reference to a static item that is used to
835 /// access that static
836 pub fn is_ref_to_thread_local(&self) -> bool {
837 match self.local_info {
838 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
843 /// Returns `true` is the local is from a compiler desugaring, e.g.,
844 /// `__next` from a `for` loop.
846 pub fn from_compiler_desugaring(&self) -> bool {
847 self.source_info.span.desugaring_kind().is_some()
850 /// Creates a new `LocalDecl` for a temporary.
852 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
853 Self::new_local(ty, Mutability::Mut, false, span)
856 /// Converts `self` into same `LocalDecl` except tagged as immutable.
858 pub fn immutable(mut self) -> Self {
859 self.mutability = Mutability::Not;
863 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
865 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
866 assert!(self.is_block_tail.is_none());
867 self.is_block_tail = Some(info);
871 /// Creates a new `LocalDecl` for a internal temporary.
873 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
874 Self::new_local(ty, Mutability::Mut, true, span)
878 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
882 user_ty: UserTypeProjections::none(),
883 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
885 local_info: LocalInfo::Other,
890 /// Builds a `LocalDecl` for the return place.
892 /// This must be inserted into the `local_decls` list as the first local.
894 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
896 mutability: Mutability::Mut,
898 user_ty: UserTypeProjections::none(),
899 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
902 local_info: LocalInfo::Other,
907 /// Debug information pertaining to a user variable.
908 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
909 pub struct VarDebugInfo<'tcx> {
912 /// Source info of the user variable, including the scope
913 /// within which the variable is visible (to debuginfo)
914 /// (see `LocalDecl`'s `source_info` field for more details).
915 pub source_info: SourceInfo,
917 /// Where the data for this user variable is to be found.
918 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
919 /// based on a `Local`, not a `Static`, and contains no indexing.
920 pub place: Place<'tcx>,
923 ///////////////////////////////////////////////////////////////////////////
926 rustc_index::newtype_index! {
927 pub struct BasicBlock {
929 DEBUG_FORMAT = "bb{}",
930 const START_BLOCK = 0,
935 pub fn start_location(self) -> Location {
936 Location { block: self, statement_index: 0 }
940 ///////////////////////////////////////////////////////////////////////////
941 // BasicBlockData and Terminator
943 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
944 pub struct BasicBlockData<'tcx> {
945 /// List of statements in this block.
946 pub statements: Vec<Statement<'tcx>>,
948 /// Terminator for this block.
950 /// N.B., this should generally ONLY be `None` during construction.
951 /// Therefore, you should generally access it via the
952 /// `terminator()` or `terminator_mut()` methods. The only
953 /// exception is that certain passes, such as `simplify_cfg`, swap
954 /// out the terminator temporarily with `None` while they continue
955 /// to recurse over the set of basic blocks.
956 pub terminator: Option<Terminator<'tcx>>,
958 /// If true, this block lies on an unwind path. This is used
959 /// during codegen where distinct kinds of basic blocks may be
960 /// generated (particularly for MSVC cleanup). Unwind blocks must
961 /// only branch to other unwind blocks.
962 pub is_cleanup: bool,
965 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
966 pub struct Terminator<'tcx> {
967 pub source_info: SourceInfo,
968 pub kind: TerminatorKind<'tcx>,
971 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
972 pub enum TerminatorKind<'tcx> {
973 /// Block should have one successor in the graph; we jump there.
974 Goto { target: BasicBlock },
976 /// Operand evaluates to an integer; jump depending on its value
977 /// to one of the targets, and otherwise fallback to `otherwise`.
979 /// The discriminant value being tested.
980 discr: Operand<'tcx>,
982 /// The type of value being tested.
985 /// Possible values. The locations to branch to in each case
986 /// are found in the corresponding indices from the `targets` vector.
987 values: Cow<'tcx, [u128]>,
989 /// Possible branch sites. The last element of this vector is used
990 /// for the otherwise branch, so targets.len() == values.len() + 1
993 // This invariant is quite non-obvious and also could be improved.
994 // One way to make this invariant is to have something like this instead:
996 // branches: Vec<(ConstInt, BasicBlock)>,
997 // otherwise: Option<BasicBlock> // exhaustive if None
999 // However we’ve decided to keep this as-is until we figure a case
1000 // where some other approach seems to be strictly better than other.
1001 targets: Vec<BasicBlock>,
1004 /// Indicates that the landing pad is finished and unwinding should
1005 /// continue. Emitted by `build::scope::diverge_cleanup`.
1008 /// Indicates that the landing pad is finished and that the process
1009 /// should abort. Used to prevent unwinding for foreign items.
1012 /// Indicates a normal return. The return place should have
1013 /// been filled in by now. This should occur at most once.
1016 /// Indicates a terminator that can never be reached.
1019 /// Drop the `Place`.
1020 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1022 /// Drop the `Place` and assign the new value over it. This ensures
1023 /// that the assignment to `P` occurs *even if* the destructor for
1024 /// place unwinds. Its semantics are best explained by the
1029 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1037 /// Drop(P, goto BB1, unwind BB2)
1040 /// // P is now uninitialized
1044 /// // P is now uninitialized -- its dtor panicked
1049 location: Place<'tcx>,
1050 value: Operand<'tcx>,
1052 unwind: Option<BasicBlock>,
1055 /// Block ends with a call of a converging function.
1057 /// The function that’s being called.
1058 func: Operand<'tcx>,
1059 /// Arguments the function is called with.
1060 /// These are owned by the callee, which is free to modify them.
1061 /// This allows the memory occupied by "by-value" arguments to be
1062 /// reused across function calls without duplicating the contents.
1063 args: Vec<Operand<'tcx>>,
1064 /// Destination for the return value. If some, the call is converging.
1065 destination: Option<(Place<'tcx>, BasicBlock)>,
1066 /// Cleanups to be done if the call unwinds.
1067 cleanup: Option<BasicBlock>,
1068 /// `true` if this is from a call in HIR rather than from an overloaded
1069 /// operator. True for overloaded function call.
1070 from_hir_call: bool,
1073 /// Jump to the target if the condition has the expected value,
1074 /// otherwise panic with a message and a cleanup target.
1076 cond: Operand<'tcx>,
1078 msg: AssertMessage<'tcx>,
1080 cleanup: Option<BasicBlock>,
1083 /// A suspend point.
1085 /// The value to return.
1086 value: Operand<'tcx>,
1087 /// Where to resume to.
1089 /// Cleanup to be done if the generator is dropped at this suspend point.
1090 drop: Option<BasicBlock>,
1093 /// Indicates the end of the dropping of a generator.
1096 /// A block where control flow only ever takes one real path, but borrowck
1097 /// needs to be more conservative.
1099 /// The target normal control flow will take.
1100 real_target: BasicBlock,
1101 /// A block control flow could conceptually jump to, but won't in
1103 imaginary_target: BasicBlock,
1105 /// A terminator for blocks that only take one path in reality, but where we
1106 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1107 /// This can arise in infinite loops with no function calls for example.
1109 /// The target normal control flow will take.
1110 real_target: BasicBlock,
1111 /// The imaginary cleanup block link. This particular path will never be taken
1112 /// in practice, but in order to avoid fragility we want to always
1113 /// consider it in borrowck. We don't want to accept programs which
1114 /// pass borrowck only when `panic=abort` or some assertions are disabled
1115 /// due to release vs. debug mode builds. This needs to be an `Option` because
1116 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1117 unwind: Option<BasicBlock>,
1121 pub type Successors<'a> =
1122 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1123 pub type SuccessorsMut<'a> =
1124 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1126 impl<'tcx> Terminator<'tcx> {
1127 pub fn successors(&self) -> Successors<'_> {
1128 self.kind.successors()
1131 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1132 self.kind.successors_mut()
1135 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1139 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1140 self.kind.unwind_mut()
1144 impl<'tcx> TerminatorKind<'tcx> {
1147 cond: Operand<'tcx>,
1150 ) -> TerminatorKind<'tcx> {
1151 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1152 TerminatorKind::SwitchInt {
1154 switch_ty: tcx.types.bool,
1155 values: From::from(BOOL_SWITCH_FALSE),
1156 targets: vec![f, t],
1160 pub fn successors(&self) -> Successors<'_> {
1161 use self::TerminatorKind::*;
1168 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1169 Goto { target: ref t }
1170 | Call { destination: None, cleanup: Some(ref t), .. }
1171 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1172 | Yield { resume: ref t, drop: None, .. }
1173 | DropAndReplace { target: ref t, unwind: None, .. }
1174 | Drop { target: ref t, unwind: None, .. }
1175 | Assert { target: ref t, cleanup: None, .. }
1176 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1177 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1178 | Yield { resume: ref t, drop: Some(ref u), .. }
1179 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1180 | Drop { target: ref t, unwind: Some(ref u), .. }
1181 | Assert { target: ref t, cleanup: Some(ref u), .. }
1182 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1183 Some(t).into_iter().chain(slice::from_ref(u))
1185 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1186 FalseEdges { ref real_target, ref imaginary_target } => {
1187 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1192 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1193 use self::TerminatorKind::*;
1200 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1201 Goto { target: ref mut t }
1202 | Call { destination: None, cleanup: Some(ref mut t), .. }
1203 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1204 | Yield { resume: ref mut t, drop: None, .. }
1205 | DropAndReplace { target: ref mut t, unwind: None, .. }
1206 | Drop { target: ref mut t, unwind: None, .. }
1207 | Assert { target: ref mut t, cleanup: None, .. }
1208 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1209 Some(t).into_iter().chain(&mut [])
1211 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1212 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1213 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1214 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1215 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1216 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1217 Some(t).into_iter().chain(slice::from_mut(u))
1219 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1220 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1221 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1226 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1228 TerminatorKind::Goto { .. }
1229 | TerminatorKind::Resume
1230 | TerminatorKind::Abort
1231 | TerminatorKind::Return
1232 | TerminatorKind::Unreachable
1233 | TerminatorKind::GeneratorDrop
1234 | TerminatorKind::Yield { .. }
1235 | TerminatorKind::SwitchInt { .. }
1236 | TerminatorKind::FalseEdges { .. } => None,
1237 TerminatorKind::Call { cleanup: ref unwind, .. }
1238 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1239 | TerminatorKind::DropAndReplace { ref unwind, .. }
1240 | TerminatorKind::Drop { ref unwind, .. }
1241 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1245 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1247 TerminatorKind::Goto { .. }
1248 | TerminatorKind::Resume
1249 | TerminatorKind::Abort
1250 | TerminatorKind::Return
1251 | TerminatorKind::Unreachable
1252 | TerminatorKind::GeneratorDrop
1253 | TerminatorKind::Yield { .. }
1254 | TerminatorKind::SwitchInt { .. }
1255 | TerminatorKind::FalseEdges { .. } => None,
1256 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1257 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1258 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1259 | TerminatorKind::Drop { ref mut unwind, .. }
1260 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1265 impl<'tcx> BasicBlockData<'tcx> {
1266 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1267 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1270 /// Accessor for terminator.
1272 /// Terminator may not be None after construction of the basic block is complete. This accessor
1273 /// provides a convenience way to reach the terminator.
1274 pub fn terminator(&self) -> &Terminator<'tcx> {
1275 self.terminator.as_ref().expect("invalid terminator state")
1278 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1279 self.terminator.as_mut().expect("invalid terminator state")
1282 pub fn retain_statements<F>(&mut self, mut f: F)
1284 F: FnMut(&mut Statement<'_>) -> bool,
1286 for s in &mut self.statements {
1293 pub fn expand_statements<F, I>(&mut self, mut f: F)
1295 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1296 I: iter::TrustedLen<Item = Statement<'tcx>>,
1298 // Gather all the iterators we'll need to splice in, and their positions.
1299 let mut splices: Vec<(usize, I)> = vec![];
1300 let mut extra_stmts = 0;
1301 for (i, s) in self.statements.iter_mut().enumerate() {
1302 if let Some(mut new_stmts) = f(s) {
1303 if let Some(first) = new_stmts.next() {
1304 // We can already store the first new statement.
1307 // Save the other statements for optimized splicing.
1308 let remaining = new_stmts.size_hint().0;
1310 splices.push((i + 1 + extra_stmts, new_stmts));
1311 extra_stmts += remaining;
1319 // Splice in the new statements, from the end of the block.
1320 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1321 // where a range of elements ("gap") is left uninitialized, with
1322 // splicing adding new elements to the end of that gap and moving
1323 // existing elements from before the gap to the end of the gap.
1324 // For now, this is safe code, emulating a gap but initializing it.
1325 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1326 self.statements.resize(
1329 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1330 kind: StatementKind::Nop,
1333 for (splice_start, new_stmts) in splices.into_iter().rev() {
1334 let splice_end = splice_start + new_stmts.size_hint().0;
1335 while gap.end > splice_end {
1338 self.statements.swap(gap.start, gap.end);
1340 self.statements.splice(splice_start..splice_end, new_stmts);
1341 gap.end = splice_start;
1345 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1346 if index < self.statements.len() {
1347 &self.statements[index]
1354 impl<'tcx> Debug for TerminatorKind<'tcx> {
1355 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1356 self.fmt_head(fmt)?;
1357 let successor_count = self.successors().count();
1358 let labels = self.fmt_successor_labels();
1359 assert_eq!(successor_count, labels.len());
1361 match successor_count {
1364 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1367 write!(fmt, " -> [")?;
1368 for (i, target) in self.successors().enumerate() {
1372 write!(fmt, "{}: {:?}", labels[i], target)?;
1380 impl<'tcx> TerminatorKind<'tcx> {
1381 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1382 /// successor basic block, if any. The only information not included is the list of possible
1383 /// successors, which may be rendered differently between the text and the graphviz format.
1384 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1385 use self::TerminatorKind::*;
1387 Goto { .. } => write!(fmt, "goto"),
1388 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1389 Return => write!(fmt, "return"),
1390 GeneratorDrop => write!(fmt, "generator_drop"),
1391 Resume => write!(fmt, "resume"),
1392 Abort => write!(fmt, "abort"),
1393 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1394 Unreachable => write!(fmt, "unreachable"),
1395 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1396 DropAndReplace { ref location, ref value, .. } => {
1397 write!(fmt, "replace({:?} <- {:?})", location, value)
1399 Call { ref func, ref args, ref destination, .. } => {
1400 if let Some((ref destination, _)) = *destination {
1401 write!(fmt, "{:?} = ", destination)?;
1403 write!(fmt, "{:?}(", func)?;
1404 for (index, arg) in args.iter().enumerate() {
1408 write!(fmt, "{:?}", arg)?;
1412 Assert { ref cond, expected, ref msg, .. } => {
1413 write!(fmt, "assert(")?;
1417 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1419 FalseEdges { .. } => write!(fmt, "falseEdges"),
1420 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1424 /// Returns the list of labels for the edges to the successor basic blocks.
1425 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1426 use self::TerminatorKind::*;
1428 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1429 Goto { .. } => vec!["".into()],
1430 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1431 let param_env = ty::ParamEnv::empty();
1432 let switch_ty = tcx.lift(&switch_ty).unwrap();
1433 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1437 ty::Const::from_scalar(
1439 Scalar::from_uint(u, size).into(),
1445 .chain(iter::once("otherwise".into()))
1448 Call { destination: Some(_), cleanup: Some(_), .. } => {
1449 vec!["return".into(), "unwind".into()]
1451 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1452 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1453 Call { destination: None, cleanup: None, .. } => vec![],
1454 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1455 Yield { drop: None, .. } => vec!["resume".into()],
1456 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1457 vec!["return".into()]
1459 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1460 vec!["return".into(), "unwind".into()]
1462 Assert { cleanup: None, .. } => vec!["".into()],
1463 Assert { .. } => vec!["success".into(), "unwind".into()],
1464 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1465 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1466 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1471 ///////////////////////////////////////////////////////////////////////////
1474 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1475 pub struct Statement<'tcx> {
1476 pub source_info: SourceInfo,
1477 pub kind: StatementKind<'tcx>,
1480 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1481 #[cfg(target_arch = "x86_64")]
1482 static_assert_size!(Statement<'_>, 32);
1484 impl Statement<'_> {
1485 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1486 /// invalidating statement indices in `Location`s.
1487 pub fn make_nop(&mut self) {
1488 self.kind = StatementKind::Nop
1491 /// Changes a statement to a nop and returns the original statement.
1492 pub fn replace_nop(&mut self) -> Self {
1494 source_info: self.source_info,
1495 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1500 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1501 pub enum StatementKind<'tcx> {
1502 /// Write the RHS Rvalue to the LHS Place.
1503 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1505 /// This represents all the reading that a pattern match may do
1506 /// (e.g., inspecting constants and discriminant values), and the
1507 /// kind of pattern it comes from. This is in order to adapt potential
1508 /// error messages to these specific patterns.
1510 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1511 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1512 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1514 /// Write the discriminant for a variant to the enum Place.
1515 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1517 /// Start a live range for the storage of the local.
1520 /// End the current live range for the storage of the local.
1523 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1524 /// of `StatementKind` low.
1525 InlineAsm(Box<InlineAsm<'tcx>>),
1527 /// Retag references in the given place, ensuring they got fresh tags. This is
1528 /// part of the Stacked Borrows model. These statements are currently only interpreted
1529 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1530 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1531 /// for more details.
1532 Retag(RetagKind, Box<Place<'tcx>>),
1534 /// Encodes a user's type ascription. These need to be preserved
1535 /// intact so that NLL can respect them. For example:
1539 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1540 /// to the user-given type `T`. The effect depends on the specified variance:
1542 /// - `Covariant` -- requires that `T_y <: T`
1543 /// - `Contravariant` -- requires that `T_y :> T`
1544 /// - `Invariant` -- requires that `T_y == T`
1545 /// - `Bivariant` -- no effect
1546 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1548 /// No-op. Useful for deleting instructions without affecting statement indices.
1552 /// Describes what kind of retag is to be performed.
1553 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1554 pub enum RetagKind {
1555 /// The initial retag when entering a function.
1557 /// Retag preparing for a two-phase borrow.
1559 /// Retagging raw pointers.
1561 /// A "normal" retag.
1565 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1566 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1567 pub enum FakeReadCause {
1568 /// Inject a fake read of the borrowed input at the end of each guards
1571 /// This should ensure that you cannot change the variant for an enum while
1572 /// you are in the midst of matching on it.
1575 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1576 /// generate a read of x to check that it is initialized and safe.
1579 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1580 /// in a match guard to ensure that it's value hasn't change by the time
1581 /// we create the OutsideGuard version.
1584 /// Officially, the semantics of
1586 /// `let pattern = <expr>;`
1588 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1589 /// into the pattern.
1591 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1592 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1593 /// but in some cases it can affect the borrow checker, as in #53695.
1594 /// Therefore, we insert a "fake read" here to ensure that we get
1595 /// appropriate errors.
1598 /// If we have an index expression like
1600 /// (*x)[1][{ x = y; 4}]
1602 /// then the first bounds check is invalidated when we evaluate the second
1603 /// index expression. Thus we create a fake borrow of `x` across the second
1604 /// indexer, which will cause a borrow check error.
1608 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1609 pub struct InlineAsm<'tcx> {
1610 pub asm: hir::InlineAsmInner,
1611 pub outputs: Box<[Place<'tcx>]>,
1612 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1615 impl Debug for Statement<'_> {
1616 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1617 use self::StatementKind::*;
1619 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1620 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1621 Retag(ref kind, ref place) => write!(
1625 RetagKind::FnEntry => "[fn entry] ",
1626 RetagKind::TwoPhase => "[2phase] ",
1627 RetagKind::Raw => "[raw] ",
1628 RetagKind::Default => "",
1632 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1633 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1634 SetDiscriminant { ref place, variant_index } => {
1635 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1637 InlineAsm(ref asm) => {
1638 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1640 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1641 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1643 Nop => write!(fmt, "nop"),
1648 ///////////////////////////////////////////////////////////////////////////
1651 /// A path to a value; something that can be evaluated without
1652 /// changing or disturbing program state.
1654 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1656 pub struct Place<'tcx> {
1657 pub base: PlaceBase<'tcx>,
1659 /// projection out of a place (access a field, deref a pointer, etc)
1660 pub projection: &'tcx List<PlaceElem<'tcx>>,
1663 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1666 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1668 pub enum PlaceBase<'tcx> {
1672 /// static or static mut variable
1673 Static(Box<Static<'tcx>>),
1676 /// We store the normalized type to avoid requiring normalization when reading MIR
1677 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1678 RustcEncodable, RustcDecodable, HashStable)]
1679 pub struct Static<'tcx> {
1681 pub kind: StaticKind<'tcx>,
1682 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1683 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1684 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1685 /// into the calling frame.
1690 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1692 pub enum StaticKind<'tcx> {
1693 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1694 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1695 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1696 Promoted(Promoted, SubstsRef<'tcx>),
1700 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1701 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1702 pub enum ProjectionElem<V, T> {
1707 /// These indices are generated by slice patterns. Easiest to explain
1711 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1712 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1713 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1714 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1717 /// index or -index (in Python terms), depending on from_end
1719 /// thing being indexed must be at least this long
1721 /// counting backwards from end?
1725 /// These indices are generated by slice patterns.
1727 /// slice[from:-to] in Python terms.
1733 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1734 /// this for ADTs with more than one variant. It may be better to
1735 /// just introduce it always, or always for enums.
1737 /// The included Symbol is the name of the variant, used for printing MIR.
1738 Downcast(Option<Symbol>, VariantIdx),
1741 impl<V, T> ProjectionElem<V, T> {
1742 /// Returns `true` if the target of this projection may refer to a different region of memory
1744 fn is_indirect(&self) -> bool {
1746 Self::Deref => true,
1750 | Self::ConstantIndex { .. }
1751 | Self::Subslice { .. }
1752 | Self::Downcast(_, _)
1758 /// Alias for projections as they appear in places, where the base is a place
1759 /// and the index is a local.
1760 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1762 impl<'tcx> Copy for PlaceElem<'tcx> { }
1764 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1765 #[cfg(target_arch = "x86_64")]
1766 static_assert_size!(PlaceElem<'_>, 16);
1768 /// Alias for projections as they appear in `UserTypeProjection`, where we
1769 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1770 pub type ProjectionKind = ProjectionElem<(), ()>;
1772 rustc_index::newtype_index! {
1775 DEBUG_FORMAT = "field[{}]"
1779 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1780 pub struct PlaceRef<'a, 'tcx> {
1781 pub base: &'a PlaceBase<'tcx>,
1782 pub projection: &'a [PlaceElem<'tcx>],
1785 impl<'tcx> Place<'tcx> {
1786 // FIXME change this to a const fn by also making List::empty a const fn.
1787 pub fn return_place() -> Place<'tcx> {
1789 base: PlaceBase::Local(RETURN_PLACE),
1790 projection: List::empty(),
1794 /// Returns `true` if this `Place` contains a `Deref` projection.
1796 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1797 /// same region of memory as its base.
1798 pub fn is_indirect(&self) -> bool {
1799 self.projection.iter().any(|elem| elem.is_indirect())
1802 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1803 /// a single deref of a local.
1805 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1806 pub fn local_or_deref_local(&self) -> Option<Local> {
1807 match self.as_ref() {
1809 base: &PlaceBase::Local(local),
1813 base: &PlaceBase::Local(local),
1814 projection: &[ProjectionElem::Deref],
1820 /// If this place represents a local variable like `_X` with no
1821 /// projections, return `Some(_X)`.
1822 pub fn as_local(&self) -> Option<Local> {
1823 self.as_ref().as_local()
1826 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1829 projection: &self.projection,
1834 impl From<Local> for Place<'_> {
1835 fn from(local: Local) -> Self {
1838 projection: List::empty(),
1843 impl From<Local> for PlaceBase<'_> {
1844 fn from(local: Local) -> Self {
1845 PlaceBase::Local(local)
1849 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1850 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1851 /// a single deref of a local.
1853 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1854 pub fn local_or_deref_local(&self) -> Option<Local> {
1857 base: PlaceBase::Local(local),
1861 base: PlaceBase::Local(local),
1862 projection: [ProjectionElem::Deref],
1868 /// If this place represents a local variable like `_X` with no
1869 /// projections, return `Some(_X)`.
1870 pub fn as_local(&self) -> Option<Local> {
1872 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1878 impl Debug for Place<'_> {
1879 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1880 for elem in self.projection.iter().rev() {
1882 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1883 write!(fmt, "(").unwrap();
1885 ProjectionElem::Deref => {
1886 write!(fmt, "(*").unwrap();
1888 ProjectionElem::Index(_)
1889 | ProjectionElem::ConstantIndex { .. }
1890 | ProjectionElem::Subslice { .. } => {}
1894 write!(fmt, "{:?}", self.base)?;
1896 for elem in self.projection.iter() {
1898 ProjectionElem::Downcast(Some(name), _index) => {
1899 write!(fmt, " as {})", name)?;
1901 ProjectionElem::Downcast(None, index) => {
1902 write!(fmt, " as variant#{:?})", index)?;
1904 ProjectionElem::Deref => {
1907 ProjectionElem::Field(field, ty) => {
1908 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1910 ProjectionElem::Index(ref index) => {
1911 write!(fmt, "[{:?}]", index)?;
1913 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1914 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1916 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1917 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1919 ProjectionElem::Subslice { from, to } if *to == 0 => {
1920 write!(fmt, "[{:?}:]", from)?;
1922 ProjectionElem::Subslice { from, to } if *from == 0 => {
1923 write!(fmt, "[:-{:?}]", to)?;
1925 ProjectionElem::Subslice { from, to } => {
1926 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1935 impl Debug for PlaceBase<'_> {
1936 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1938 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
1939 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
1940 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
1942 PlaceBase::Static(box self::Static {
1943 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
1945 write!(fmt, "({:?}: {:?})", promoted, ty)
1951 ///////////////////////////////////////////////////////////////////////////
1954 rustc_index::newtype_index! {
1955 pub struct SourceScope {
1957 DEBUG_FORMAT = "scope[{}]",
1958 const OUTERMOST_SOURCE_SCOPE = 0,
1962 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1963 pub struct SourceScopeData {
1965 pub parent_scope: Option<SourceScope>,
1967 /// Crate-local information for this source scope, that can't (and
1968 /// needn't) be tracked across crates.
1969 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1972 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1973 pub struct SourceScopeLocalData {
1974 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1975 pub lint_root: hir::HirId,
1976 /// The unsafe block that contains this node.
1980 ///////////////////////////////////////////////////////////////////////////
1983 /// These are values that can appear inside an rvalue. They are intentionally
1984 /// limited to prevent rvalues from being nested in one another.
1985 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1986 pub enum Operand<'tcx> {
1987 /// Copy: The value must be available for use afterwards.
1989 /// This implies that the type of the place must be `Copy`; this is true
1990 /// by construction during build, but also checked by the MIR type checker.
1993 /// Move: The value (including old borrows of it) will not be used again.
1995 /// Safe for values of all types (modulo future developments towards `?Move`).
1996 /// Correct usage patterns are enforced by the borrow checker for safe code.
1997 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2000 /// Synthesizes a constant value.
2001 Constant(Box<Constant<'tcx>>),
2004 impl<'tcx> Debug for Operand<'tcx> {
2005 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2006 use self::Operand::*;
2008 Constant(ref a) => write!(fmt, "{:?}", a),
2009 Copy(ref place) => write!(fmt, "{:?}", place),
2010 Move(ref place) => write!(fmt, "move {:?}", place),
2015 impl<'tcx> Operand<'tcx> {
2016 /// Convenience helper to make a constant that refers to the fn
2017 /// with given `DefId` and substs. Since this is used to synthesize
2018 /// MIR, assumes `user_ty` is None.
2019 pub fn function_handle(
2022 substs: SubstsRef<'tcx>,
2025 let ty = tcx.type_of(def_id).subst(tcx, substs);
2026 Operand::Constant(box Constant {
2029 literal: ty::Const::zero_sized(tcx, ty),
2033 pub fn to_copy(&self) -> Self {
2035 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2036 Operand::Move(ref place) => Operand::Copy(place.clone()),
2041 ///////////////////////////////////////////////////////////////////////////
2044 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2045 pub enum Rvalue<'tcx> {
2046 /// x (either a move or copy, depending on type of x)
2050 Repeat(Operand<'tcx>, u64),
2053 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2055 /// length of a [X] or [X;n] value
2058 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2060 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2061 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2063 NullaryOp(NullOp, Ty<'tcx>),
2064 UnaryOp(UnOp, Operand<'tcx>),
2066 /// Read the discriminant of an ADT.
2068 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2069 /// be defined to return, say, a 0) if ADT is not an enum.
2070 Discriminant(Place<'tcx>),
2072 /// Creates an aggregate value, like a tuple or struct. This is
2073 /// only needed because we want to distinguish `dest = Foo { x:
2074 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2075 /// that `Foo` has a destructor. These rvalues can be optimized
2076 /// away after type-checking and before lowering.
2077 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2080 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2083 Pointer(PointerCast),
2086 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2087 pub enum AggregateKind<'tcx> {
2088 /// The type is of the element
2092 /// The second field is the variant index. It's equal to 0 for struct
2093 /// and union expressions. The fourth field is
2094 /// active field number and is present only for union expressions
2095 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2096 /// active field index would identity the field `c`
2097 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2099 Closure(DefId, SubstsRef<'tcx>),
2100 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2103 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2105 /// The `+` operator (addition)
2107 /// The `-` operator (subtraction)
2109 /// The `*` operator (multiplication)
2111 /// The `/` operator (division)
2113 /// The `%` operator (modulus)
2115 /// The `^` operator (bitwise xor)
2117 /// The `&` operator (bitwise and)
2119 /// The `|` operator (bitwise or)
2121 /// The `<<` operator (shift left)
2123 /// The `>>` operator (shift right)
2125 /// The `==` operator (equality)
2127 /// The `<` operator (less than)
2129 /// The `<=` operator (less than or equal to)
2131 /// The `!=` operator (not equal to)
2133 /// The `>=` operator (greater than or equal to)
2135 /// The `>` operator (greater than)
2137 /// The `ptr.offset` operator
2142 pub fn is_checkable(self) -> bool {
2145 Add | Sub | Mul | Shl | Shr => true,
2151 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2153 /// Returns the size of a value of that type
2155 /// Creates a new uninitialized box for a value of that type
2159 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2161 /// The `!` operator for logical inversion
2163 /// The `-` operator for negation
2167 impl<'tcx> Debug for Rvalue<'tcx> {
2168 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2169 use self::Rvalue::*;
2172 Use(ref place) => write!(fmt, "{:?}", place),
2173 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2174 Len(ref a) => write!(fmt, "Len({:?})", a),
2175 Cast(ref kind, ref place, ref ty) => {
2176 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2178 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2179 CheckedBinaryOp(ref op, ref a, ref b) => {
2180 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2182 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2183 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2184 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2185 Ref(region, borrow_kind, ref place) => {
2186 let kind_str = match borrow_kind {
2187 BorrowKind::Shared => "",
2188 BorrowKind::Shallow => "shallow ",
2189 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2192 // When printing regions, add trailing space if necessary.
2193 let print_region = ty::tls::with(|tcx| {
2194 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2196 let region = if print_region {
2197 let mut region = region.to_string();
2198 if region.len() > 0 {
2203 // Do not even print 'static
2206 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2209 Aggregate(ref kind, ref places) => {
2210 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2211 let mut tuple_fmt = fmt.debug_tuple("");
2212 for place in places {
2213 tuple_fmt.field(place);
2219 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2221 AggregateKind::Tuple => match places.len() {
2222 0 => write!(fmt, "()"),
2223 1 => write!(fmt, "({:?},)", places[0]),
2224 _ => fmt_tuple(fmt, places),
2227 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2228 let variant_def = &adt_def.variants[variant];
2231 ty::tls::with(|tcx| {
2232 let substs = tcx.lift(&substs).expect("could not lift for printing");
2233 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2234 .print_def_path(variant_def.def_id, substs)?;
2238 match variant_def.ctor_kind {
2239 CtorKind::Const => Ok(()),
2240 CtorKind::Fn => fmt_tuple(fmt, places),
2241 CtorKind::Fictive => {
2242 let mut struct_fmt = fmt.debug_struct("");
2243 for (field, place) in variant_def.fields.iter().zip(places) {
2244 struct_fmt.field(&field.ident.as_str(), place);
2251 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2252 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2253 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2254 let substs = tcx.lift(&substs).unwrap();
2257 tcx.def_path_str_with_substs(def_id, substs),
2260 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2262 let mut struct_fmt = fmt.debug_struct(&name);
2264 if let Some(upvars) = tcx.upvars(def_id) {
2265 for (&var_id, place) in upvars.keys().zip(places) {
2266 let var_name = tcx.hir().name(var_id);
2267 struct_fmt.field(&var_name.as_str(), place);
2273 write!(fmt, "[closure]")
2277 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2278 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2279 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2280 let mut struct_fmt = fmt.debug_struct(&name);
2282 if let Some(upvars) = tcx.upvars(def_id) {
2283 for (&var_id, place) in upvars.keys().zip(places) {
2284 let var_name = tcx.hir().name(var_id);
2285 struct_fmt.field(&var_name.as_str(), place);
2291 write!(fmt, "[generator]")
2300 ///////////////////////////////////////////////////////////////////////////
2303 /// Two constants are equal if they are the same constant. Note that
2304 /// this does not necessarily mean that they are "==" in Rust -- in
2305 /// particular one must be wary of `NaN`!
2307 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2308 pub struct Constant<'tcx> {
2311 /// Optional user-given type: for something like
2312 /// `collect::<Vec<_>>`, this would be present and would
2313 /// indicate that `Vec<_>` was explicitly specified.
2315 /// Needed for NLL to impose user-given type constraints.
2316 pub user_ty: Option<UserTypeAnnotationIndex>,
2318 pub literal: &'tcx ty::Const<'tcx>,
2321 impl Constant<'tcx> {
2322 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2323 match self.literal.val.try_to_scalar() {
2324 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2325 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2328 tcx.sess.delay_span_bug(
2329 DUMMY_SP, "MIR cannot contain dangling const pointers",
2339 /// A collection of projections into user types.
2341 /// They are projections because a binding can occur a part of a
2342 /// parent pattern that has been ascribed a type.
2344 /// Its a collection because there can be multiple type ascriptions on
2345 /// the path from the root of the pattern down to the binding itself.
2350 /// struct S<'a>((i32, &'a str), String);
2351 /// let S((_, w): (i32, &'static str), _): S = ...;
2352 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2353 /// // --------------------------------- ^ (2)
2356 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2357 /// ascribed the type `(i32, &'static str)`.
2359 /// The highlights labelled `(2)` show the whole pattern being
2360 /// ascribed the type `S`.
2362 /// In this example, when we descend to `w`, we will have built up the
2363 /// following two projected types:
2365 /// * base: `S`, projection: `(base.0).1`
2366 /// * base: `(i32, &'static str)`, projection: `base.1`
2368 /// The first will lead to the constraint `w: &'1 str` (for some
2369 /// inferred region `'1`). The second will lead to the constraint `w:
2371 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2372 pub struct UserTypeProjections {
2373 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2376 impl<'tcx> UserTypeProjections {
2377 pub fn none() -> Self {
2378 UserTypeProjections { contents: vec![] }
2381 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2382 UserTypeProjections { contents: projs.collect() }
2385 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2386 self.contents.iter()
2389 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2390 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2393 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2394 self.contents.push((user_ty.clone(), span));
2400 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2402 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2406 pub fn index(self) -> Self {
2407 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2410 pub fn subslice(self, from: u32, to: u32) -> Self {
2411 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2414 pub fn deref(self) -> Self {
2415 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2418 pub fn leaf(self, field: Field) -> Self {
2419 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2422 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2423 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2427 /// Encodes the effect of a user-supplied type annotation on the
2428 /// subcomponents of a pattern. The effect is determined by applying the
2429 /// given list of proejctions to some underlying base type. Often,
2430 /// the projection element list `projs` is empty, in which case this
2431 /// directly encodes a type in `base`. But in the case of complex patterns with
2432 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2433 /// in which case the `projs` vector is used.
2437 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2439 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2440 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2441 /// determined by finding the type of the `.0` field from `T`.
2442 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2443 pub struct UserTypeProjection {
2444 pub base: UserTypeAnnotationIndex,
2445 pub projs: Vec<ProjectionKind>,
2448 impl Copy for ProjectionKind {}
2450 impl UserTypeProjection {
2451 pub(crate) fn index(mut self) -> Self {
2452 self.projs.push(ProjectionElem::Index(()));
2456 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2457 self.projs.push(ProjectionElem::Subslice { from, to });
2461 pub(crate) fn deref(mut self) -> Self {
2462 self.projs.push(ProjectionElem::Deref);
2466 pub(crate) fn leaf(mut self, field: Field) -> Self {
2467 self.projs.push(ProjectionElem::Field(field, ()));
2471 pub(crate) fn variant(
2473 adt_def: &'tcx AdtDef,
2474 variant_index: VariantIdx,
2477 self.projs.push(ProjectionElem::Downcast(
2478 Some(adt_def.variants[variant_index].ident.name),
2481 self.projs.push(ProjectionElem::Field(field, ()));
2486 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2488 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2489 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2490 use crate::mir::ProjectionElem::*;
2492 let base = self.base.fold_with(folder);
2493 let projs: Vec<_> = self
2496 .map(|elem| match elem {
2498 Field(f, ()) => Field(f.clone(), ()),
2499 Index(()) => Index(()),
2500 elem => elem.clone(),
2504 UserTypeProjection { base, projs }
2507 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2508 self.base.visit_with(visitor)
2509 // Note: there's nothing in `self.proj` to visit.
2513 rustc_index::newtype_index! {
2514 pub struct Promoted {
2516 DEBUG_FORMAT = "promoted[{}]"
2520 impl<'tcx> Debug for Constant<'tcx> {
2521 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2522 write!(fmt, "{}", self)
2526 impl<'tcx> Display for Constant<'tcx> {
2527 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2528 write!(fmt, "const ")?;
2529 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2530 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2531 // detailed and just not '{pointer}'.
2532 if let ty::RawPtr(_) = self.literal.ty.kind {
2533 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2535 write!(fmt, "{}", self.literal)
2540 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2541 type Node = BasicBlock;
2544 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2545 fn num_nodes(&self) -> usize {
2546 self.basic_blocks.len()
2550 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2551 fn start_node(&self) -> Self::Node {
2556 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2560 ) -> <Self as GraphSuccessors<'_>>::Iter {
2561 self.basic_blocks[node].terminator().successors().cloned()
2565 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2566 type Item = BasicBlock;
2567 type Iter = iter::Cloned<Successors<'b>>;
2570 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2571 pub struct Location {
2572 /// The block that the location is within.
2573 pub block: BasicBlock,
2575 /// The location is the position of the start of the statement; or, if
2576 /// `statement_index` equals the number of statements, then the start of the
2578 pub statement_index: usize,
2581 impl fmt::Debug for Location {
2582 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2583 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2588 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2590 /// Returns the location immediately after this one within the enclosing block.
2592 /// Note that if this location represents a terminator, then the
2593 /// resulting location would be out of bounds and invalid.
2594 pub fn successor_within_block(&self) -> Location {
2595 Location { block: self.block, statement_index: self.statement_index + 1 }
2598 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2599 pub fn is_predecessor_of<'tcx>(&self, other: Location, mut body_cache: cache::BorrowedCache<'_, 'tcx>) -> bool {
2600 // If we are in the same block as the other location and are an earlier statement
2601 // then we are a predecessor of `other`.
2602 if self.block == other.block && self.statement_index < other.statement_index {
2606 // If we're in another block, then we want to check that block is a predecessor of `other`.
2607 let mut queue: Vec<BasicBlock> = body_cache.predecessors_for(other.block).to_vec();
2608 let mut visited = FxHashSet::default();
2610 while let Some(block) = queue.pop() {
2611 // If we haven't visited this block before, then make sure we visit it's predecessors.
2612 if visited.insert(block) {
2613 queue.extend(body_cache.predecessors_for(block).iter().cloned());
2618 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2619 // we found that block by looking at the predecessors of `other`).
2620 if self.block == block {
2628 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2629 if self.block == other.block {
2630 self.statement_index <= other.statement_index
2632 dominators.is_dominated_by(other.block, self.block)
2637 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2638 pub enum UnsafetyViolationKind {
2640 /// Permitted both in `const fn`s and regular `fn`s.
2642 BorrowPacked(hir::HirId),
2645 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2646 pub struct UnsafetyViolation {
2647 pub source_info: SourceInfo,
2648 pub description: Symbol,
2649 pub details: Symbol,
2650 pub kind: UnsafetyViolationKind,
2653 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2654 pub struct UnsafetyCheckResult {
2655 /// Violations that are propagated *upwards* from this function.
2656 pub violations: Lrc<[UnsafetyViolation]>,
2657 /// `unsafe` blocks in this function, along with whether they are used. This is
2658 /// used for the "unused_unsafe" lint.
2659 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2662 rustc_index::newtype_index! {
2663 pub struct GeneratorSavedLocal {
2665 DEBUG_FORMAT = "_{}",
2669 /// The layout of generator state.
2670 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2671 pub struct GeneratorLayout<'tcx> {
2672 /// The type of every local stored inside the generator.
2673 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2675 /// Which of the above fields are in each variant. Note that one field may
2676 /// be stored in multiple variants.
2677 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2679 /// Which saved locals are storage-live at the same time. Locals that do not
2680 /// have conflicts with each other are allowed to overlap in the computed
2682 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2685 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2686 pub struct BorrowCheckResult<'tcx> {
2687 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2688 pub used_mut_upvars: SmallVec<[Field; 8]>,
2691 /// The result of the `mir_const_qualif` query.
2693 /// Each field corresponds to an implementer of the `Qualif` trait in
2694 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2696 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2697 pub struct ConstQualifs {
2698 pub has_mut_interior: bool,
2699 pub needs_drop: bool,
2702 /// After we borrow check a closure, we are left with various
2703 /// requirements that we have inferred between the free regions that
2704 /// appear in the closure's signature or on its field types. These
2705 /// requirements are then verified and proved by the closure's
2706 /// creating function. This struct encodes those requirements.
2708 /// The requirements are listed as being between various
2709 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2710 /// vids refer to the free regions that appear in the closure (or
2711 /// generator's) type, in order of appearance. (This numbering is
2712 /// actually defined by the `UniversalRegions` struct in the NLL
2713 /// region checker. See for example
2714 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2715 /// regions in the closure's type "as if" they were erased, so their
2716 /// precise identity is not important, only their position.
2718 /// Example: If type check produces a closure with the closure substs:
2721 /// ClosureSubsts = [
2722 /// i8, // the "closure kind"
2723 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2724 /// &'a String, // some upvar
2728 /// here, there is one unique free region (`'a`) but it appears
2729 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2732 /// ClosureSubsts = [
2733 /// i8, // the "closure kind"
2734 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2735 /// &'2 String, // some upvar
2739 /// Now the code might impose a requirement like `'1: '2`. When an
2740 /// instance of the closure is created, the corresponding free regions
2741 /// can be extracted from its type and constrained to have the given
2742 /// outlives relationship.
2744 /// In some cases, we have to record outlives requirements between
2745 /// types and regions as well. In that case, if those types include
2746 /// any regions, those regions are recorded as `ReClosureBound`
2747 /// instances assigned one of these same indices. Those regions will
2748 /// be substituted away by the creator. We use `ReClosureBound` in
2749 /// that case because the regions must be allocated in the global
2750 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2751 /// internally within the rest of the NLL code).
2752 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2753 pub struct ClosureRegionRequirements<'tcx> {
2754 /// The number of external regions defined on the closure. In our
2755 /// example above, it would be 3 -- one for `'static`, then `'1`
2756 /// and `'2`. This is just used for a sanity check later on, to
2757 /// make sure that the number of regions we see at the callsite
2759 pub num_external_vids: usize,
2761 /// Requirements between the various free regions defined in
2763 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2766 /// Indicates an outlives-constraint between a type or between two
2767 /// free regions declared on the closure.
2768 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2769 pub struct ClosureOutlivesRequirement<'tcx> {
2770 // This region or type ...
2771 pub subject: ClosureOutlivesSubject<'tcx>,
2773 // ... must outlive this one.
2774 pub outlived_free_region: ty::RegionVid,
2776 // If not, report an error here ...
2777 pub blame_span: Span,
2779 // ... due to this reason.
2780 pub category: ConstraintCategory,
2783 /// Outlives-constraints can be categorized to determine whether and why they
2784 /// are interesting (for error reporting). Order of variants indicates sort
2785 /// order of the category, thereby influencing diagnostic output.
2787 /// See also [rustc_mir::borrow_check::nll::constraints].
2801 pub enum ConstraintCategory {
2809 /// A constraint that came from checking the body of a closure.
2811 /// We try to get the category that the closure used when reporting this.
2819 /// A "boring" constraint (caused by the given location) is one that
2820 /// the user probably doesn't want to see described in diagnostics,
2821 /// because it is kind of an artifact of the type system setup.
2822 /// Example: `x = Foo { field: y }` technically creates
2823 /// intermediate regions representing the "type of `Foo { field: y
2824 /// }`", and data flows from `y` into those variables, but they
2825 /// are not very interesting. The assignment into `x` on the other
2828 // Boring and applicable everywhere.
2831 /// A constraint that doesn't correspond to anything the user sees.
2835 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2836 /// that must outlive some region.
2837 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2838 pub enum ClosureOutlivesSubject<'tcx> {
2839 /// Subject is a type, typically a type parameter, but could also
2840 /// be a projection. Indicates a requirement like `T: 'a` being
2841 /// passed to the caller, where the type here is `T`.
2843 /// The type here is guaranteed not to contain any free regions at
2847 /// Subject is a free region from the closure. Indicates a requirement
2848 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2849 Region(ty::RegionVid),
2853 * `TypeFoldable` implementations for MIR types
2856 CloneTypeFoldableAndLiftImpls! {
2865 SourceScopeLocalData,
2866 UserTypeAnnotationIndex,
2869 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2870 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2871 use crate::mir::TerminatorKind::*;
2873 let kind = match self.kind {
2874 Goto { target } => Goto { target },
2875 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2876 discr: discr.fold_with(folder),
2877 switch_ty: switch_ty.fold_with(folder),
2878 values: values.clone(),
2879 targets: targets.clone(),
2881 Drop { ref location, target, unwind } => {
2882 Drop { location: location.fold_with(folder), target, unwind }
2884 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2885 location: location.fold_with(folder),
2886 value: value.fold_with(folder),
2890 Yield { ref value, resume, drop } => {
2891 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2893 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2895 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2898 func: func.fold_with(folder),
2899 args: args.fold_with(folder),
2905 Assert { ref cond, expected, ref msg, target, cleanup } => {
2907 let msg = match msg {
2908 BoundsCheck { ref len, ref index } =>
2910 len: len.fold_with(folder),
2911 index: index.fold_with(folder),
2913 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
2914 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
2917 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2919 GeneratorDrop => GeneratorDrop,
2923 Unreachable => Unreachable,
2924 FalseEdges { real_target, imaginary_target } => {
2925 FalseEdges { real_target, imaginary_target }
2927 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2929 Terminator { source_info: self.source_info, kind }
2932 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2933 use crate::mir::TerminatorKind::*;
2936 SwitchInt { ref discr, switch_ty, .. } => {
2937 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
2939 Drop { ref location, .. } => location.visit_with(visitor),
2940 DropAndReplace { ref location, ref value, .. } => {
2941 location.visit_with(visitor) || value.visit_with(visitor)
2943 Yield { ref value, .. } => value.visit_with(visitor),
2944 Call { ref func, ref args, ref destination, .. } => {
2945 let dest = if let Some((ref loc, _)) = *destination {
2946 loc.visit_with(visitor)
2950 dest || func.visit_with(visitor) || args.visit_with(visitor)
2952 Assert { ref cond, ref msg, .. } => {
2953 if cond.visit_with(visitor) {
2956 BoundsCheck { ref len, ref index } =>
2957 len.visit_with(visitor) || index.visit_with(visitor),
2958 Panic { .. } | Overflow(_) | OverflowNeg |
2959 DivisionByZero | RemainderByZero |
2960 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
2974 | FalseUnwind { .. } => false,
2979 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
2980 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
2984 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
2989 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2990 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2992 base: self.base.fold_with(folder),
2993 projection: self.projection.fold_with(folder),
2997 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2998 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3002 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3003 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3005 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3006 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3010 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3012 PlaceBase::Local(local) => local.visit_with(visitor),
3013 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3018 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3019 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3020 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3021 folder.tcx().intern_place_elems(&v)
3024 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3025 self.iter().any(|t| t.visit_with(visitor))
3029 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3030 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3032 ty: self.ty.fold_with(folder),
3033 kind: self.kind.fold_with(folder),
3034 def_id: self.def_id,
3038 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3039 let Static { ty, kind, def_id: _ } = self;
3041 ty.visit_with(visitor) || kind.visit_with(visitor)
3045 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3046 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3048 StaticKind::Promoted(promoted, substs) =>
3049 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3050 StaticKind::Static => StaticKind::Static
3054 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3056 StaticKind::Promoted(promoted, substs) =>
3057 promoted.visit_with(visitor) || substs.visit_with(visitor),
3058 StaticKind::Static => { false }
3063 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3064 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3065 use crate::mir::Rvalue::*;
3067 Use(ref op) => Use(op.fold_with(folder)),
3068 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3069 Ref(region, bk, ref place) => {
3070 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3072 Len(ref place) => Len(place.fold_with(folder)),
3073 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3074 BinaryOp(op, ref rhs, ref lhs) => {
3075 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3077 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3078 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3080 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3081 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3082 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3083 Aggregate(ref kind, ref fields) => {
3084 let kind = box match **kind {
3085 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3086 AggregateKind::Tuple => AggregateKind::Tuple,
3087 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3090 substs.fold_with(folder),
3091 user_ty.fold_with(folder),
3094 AggregateKind::Closure(id, substs) => {
3095 AggregateKind::Closure(id, substs.fold_with(folder))
3097 AggregateKind::Generator(id, substs, movablity) => {
3098 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3101 Aggregate(kind, fields.fold_with(folder))
3106 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3107 use crate::mir::Rvalue::*;
3109 Use(ref op) => op.visit_with(visitor),
3110 Repeat(ref op, _) => op.visit_with(visitor),
3111 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3112 Len(ref place) => place.visit_with(visitor),
3113 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3114 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3115 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3117 UnaryOp(_, ref val) => val.visit_with(visitor),
3118 Discriminant(ref place) => place.visit_with(visitor),
3119 NullaryOp(_, ty) => ty.visit_with(visitor),
3120 Aggregate(ref kind, ref fields) => {
3122 AggregateKind::Array(ty) => ty.visit_with(visitor),
3123 AggregateKind::Tuple => false,
3124 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3125 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3127 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3128 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3129 }) || fields.visit_with(visitor)
3135 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3136 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3138 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3139 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3140 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3144 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3146 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3147 Operand::Constant(ref c) => c.visit_with(visitor),
3152 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3153 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3154 use crate::mir::ProjectionElem::*;
3158 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3159 Index(v) => Index(v.fold_with(folder)),
3160 elem => elem.clone(),
3164 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3165 use crate::mir::ProjectionElem::*;
3168 Field(_, ty) => ty.visit_with(visitor),
3169 Index(v) => v.visit_with(visitor),
3175 impl<'tcx> TypeFoldable<'tcx> for Field {
3176 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3179 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3184 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3185 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3188 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3193 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3194 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3197 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3202 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3203 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3205 span: self.span.clone(),
3206 user_ty: self.user_ty.fold_with(folder),
3207 literal: self.literal.fold_with(folder),
3210 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3211 self.literal.visit_with(visitor)