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, Dominators};
25 use rustc_data_structures::graph::{self, GraphPredecessors, 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};
33 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use std::{iter, mem, option, u32};
37 use syntax::ast::Name;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, DUMMY_SP};
41 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.
156 /// A cache for various calculations.
157 predecessors_cache: Option<IndexVec<BasicBlock, Vec<BasicBlock>>>,
160 impl<'tcx> Body<'tcx> {
162 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
163 source_scopes: IndexVec<SourceScope, SourceScopeData>,
164 local_decls: LocalDecls<'tcx>,
165 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
167 var_debug_info: Vec<VarDebugInfo<'tcx>>,
169 control_flow_destroyed: Vec<(Span, String)>,
170 generator_kind : Option<GeneratorKind>,
172 // We need `arg_count` locals, and one for the return place.
174 local_decls.len() >= arg_count + 1,
175 "expected at least {} locals, got {}",
181 phase: MirPhase::Build,
185 generator_drop: None,
186 generator_layout: None,
189 user_type_annotations,
194 predecessors_cache: None,
195 control_flow_destroyed,
200 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
205 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
206 &mut self.basic_blocks
209 pub fn basic_block_terminator_opt_mut(&mut self, bb: BasicBlock) -> &mut Option<Terminator<'tcx>> {
210 // FIXME we should look into improving the cache invalidation
211 self.predecessors_cache = None;
212 &mut self.basic_blocks[bb].terminator
215 pub fn basic_block_terminator_mut(&mut self, bb: BasicBlock) -> &mut Terminator<'tcx> {
216 // FIXME we should look into improving the cache invalidation
217 self.predecessors_cache = None;
218 self.basic_blocks[bb].terminator_mut()
222 pub fn basic_blocks_and_local_decls_mut(
224 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
225 (&mut self.basic_blocks, &mut self.local_decls)
229 pub fn unwrap_predecessors(&self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
230 assert!(self.predecessors_cache.is_some());
231 self.predecessors_cache.as_ref().unwrap()
235 /// This will recompute the predecessors cache if it is not available
236 pub fn predecessors(&mut self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
237 if self.predecessors_cache.is_none() {
238 self.predecessors_cache = Some(self.calculate_predecessors())
241 self.predecessors_cache.as_ref().unwrap()
244 fn calculate_predecessors(&self) -> IndexVec<BasicBlock, Vec<BasicBlock>> {
245 let mut result = IndexVec::from_elem(vec![], self.basic_blocks());
246 for (bb, data) in self.basic_blocks().iter_enumerated() {
247 if let Some(ref term) = data.terminator {
248 for &tgt in term.successors() {
249 result[tgt].push(bb);
258 pub fn predecessors_for(&self, bb: BasicBlock) -> &[BasicBlock] {
259 // TODO(nashenas88) could this be predecessors sometimes too?
260 &self.unwrap_predecessors()[bb]
264 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
265 let if_zero_locations = if loc.statement_index == 0 {
266 let predecessor_blocks = self.predecessors_for(loc.block);
267 let num_predecessor_blocks = predecessor_blocks.len();
269 (0..num_predecessor_blocks)
270 .map(move |i| predecessor_blocks[i])
271 .map(move |bb| self.terminator_loc(bb)),
277 let if_not_zero_locations = if loc.statement_index == 0 {
280 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
283 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
287 pub fn dominators(&self) -> Dominators<BasicBlock> {
291 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
293 pub fn is_cfg_cyclic(&self) -> bool {
294 graph::is_cyclic(self)
298 pub fn local_kind(&self, local: Local) -> LocalKind {
299 let index = local.as_usize();
302 self.local_decls[local].mutability == Mutability::Mut,
303 "return place should be mutable"
306 LocalKind::ReturnPointer
307 } else if index < self.arg_count + 1 {
309 } else if self.local_decls[local].is_user_variable() {
316 /// Returns an iterator over all temporaries.
318 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
319 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
320 let local = Local::new(index);
321 if self.local_decls[local].is_user_variable() {
329 /// Returns an iterator over all user-declared locals.
331 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
332 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
333 let local = Local::new(index);
334 if self.local_decls[local].is_user_variable() {
342 /// Returns an iterator over all user-declared mutable locals.
344 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
345 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
346 let local = Local::new(index);
347 let decl = &self.local_decls[local];
348 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
356 /// Returns an iterator over all user-declared mutable arguments and locals.
358 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
359 (1..self.local_decls.len()).filter_map(move |index| {
360 let local = Local::new(index);
361 let decl = &self.local_decls[local];
362 if (decl.is_user_variable() || index < self.arg_count + 1)
363 && decl.mutability == Mutability::Mut
372 /// Returns an iterator over all function arguments.
374 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
375 let arg_count = self.arg_count;
376 (1..=arg_count).map(Local::new)
379 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
380 /// locals that are neither arguments nor the return place).
382 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
383 let arg_count = self.arg_count;
384 let local_count = self.local_decls.len();
385 (arg_count + 1..local_count).map(Local::new)
388 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
389 /// invalidating statement indices in `Location`s.
390 pub fn make_statement_nop(&mut self, location: Location) {
391 let block = &mut self[location.block];
392 debug_assert!(location.statement_index < block.statements.len());
393 block.statements[location.statement_index].make_nop()
396 /// Returns the source info associated with `location`.
397 pub fn source_info(&self, location: Location) -> &SourceInfo {
398 let block = &self[location.block];
399 let stmts = &block.statements;
400 let idx = location.statement_index;
401 if idx < stmts.len() {
402 &stmts[idx].source_info
404 assert_eq!(idx, stmts.len());
405 &block.terminator().source_info
409 /// Checks if `sub` is a sub scope of `sup`
410 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
412 match self.source_scopes[sub].parent_scope {
413 None => return false,
420 /// Returns the return type; it always return first element from `local_decls` array.
421 pub fn return_ty(&self) -> Ty<'tcx> {
422 self.local_decls[RETURN_PLACE].ty
425 /// Gets the location of the terminator for the given block.
426 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
427 Location { block: bb, statement_index: self[bb].statements.len() }
431 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
434 /// Unsafe because of a PushUnsafeBlock
436 /// Unsafe because of an unsafe fn
438 /// Unsafe because of an `unsafe` block
439 ExplicitUnsafe(hir::HirId),
442 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
443 type Output = BasicBlockData<'tcx>;
446 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
447 &self.basic_blocks()[index]
451 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
453 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
454 &mut self.basic_blocks_mut()[index]
458 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
459 pub enum ClearCrossCrate<T> {
464 impl<T> ClearCrossCrate<T> {
465 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
467 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
468 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
472 pub fn assert_crate_local(self) -> T {
474 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
475 ClearCrossCrate::Set(v) => v,
480 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
481 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
483 /// Grouped information about the source code origin of a MIR entity.
484 /// Intended to be inspected by diagnostics and debuginfo.
485 /// Most passes can work with it as a whole, within a single function.
486 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
487 // `Hash`. Please ping @bjorn3 if removing them.
488 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
489 pub struct SourceInfo {
490 /// The source span for the AST pertaining to this MIR entity.
493 /// The source scope, keeping track of which bindings can be
494 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
495 pub scope: SourceScope,
498 ///////////////////////////////////////////////////////////////////////////
499 // Mutability and borrow kinds
501 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
502 pub enum Mutability {
507 impl From<Mutability> for hir::Mutability {
508 fn from(m: Mutability) -> Self {
510 Mutability::Mut => hir::Mutability::Mutable,
511 Mutability::Not => hir::Mutability::Immutable,
517 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
519 pub enum BorrowKind {
520 /// Data must be immutable and is aliasable.
523 /// The immediately borrowed place must be immutable, but projections from
524 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
525 /// conflict with a mutable borrow of `a.b.c`.
527 /// This is used when lowering matches: when matching on a place we want to
528 /// ensure that place have the same value from the start of the match until
529 /// an arm is selected. This prevents this code from compiling:
531 /// let mut x = &Some(0);
534 /// Some(_) if { x = &None; false } => (),
538 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
539 /// should not prevent `if let None = x { ... }`, for example, because the
540 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
541 /// We can also report errors with this kind of borrow differently.
544 /// Data must be immutable but not aliasable. This kind of borrow
545 /// cannot currently be expressed by the user and is used only in
546 /// implicit closure bindings. It is needed when the closure is
547 /// borrowing or mutating a mutable referent, e.g.:
549 /// let x: &mut isize = ...;
550 /// let y = || *x += 5;
552 /// If we were to try to translate this closure into a more explicit
553 /// form, we'd encounter an error with the code as written:
555 /// struct Env { x: & &mut isize }
556 /// let x: &mut isize = ...;
557 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
558 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
560 /// This is then illegal because you cannot mutate an `&mut` found
561 /// in an aliasable location. To solve, you'd have to translate with
562 /// an `&mut` borrow:
564 /// struct Env { x: & &mut isize }
565 /// let x: &mut isize = ...;
566 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
567 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
569 /// Now the assignment to `**env.x` is legal, but creating a
570 /// mutable pointer to `x` is not because `x` is not mutable. We
571 /// could fix this by declaring `x` as `let mut x`. This is ok in
572 /// user code, if awkward, but extra weird for closures, since the
573 /// borrow is hidden.
575 /// So we introduce a "unique imm" borrow -- the referent is
576 /// immutable, but not aliasable. This solves the problem. For
577 /// simplicity, we don't give users the way to express this
578 /// borrow, it's just used when translating closures.
581 /// Data is mutable and not aliasable.
583 /// `true` if this borrow arose from method-call auto-ref
584 /// (i.e., `adjustment::Adjust::Borrow`).
585 allow_two_phase_borrow: bool,
590 pub fn allows_two_phase_borrow(&self) -> bool {
592 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
593 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
598 ///////////////////////////////////////////////////////////////////////////
599 // Variables and temps
601 rustc_index::newtype_index! {
604 DEBUG_FORMAT = "_{}",
605 const RETURN_PLACE = 0,
609 impl Atom for Local {
610 fn index(self) -> usize {
615 /// Classifies locals into categories. See `Body::local_kind`.
616 #[derive(PartialEq, Eq, Debug, HashStable)]
618 /// User-declared variable binding.
620 /// Compiler-introduced temporary.
622 /// Function argument.
624 /// Location of function's return value.
628 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
629 pub struct VarBindingForm<'tcx> {
630 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
631 pub binding_mode: ty::BindingMode,
632 /// If an explicit type was provided for this variable binding,
633 /// this holds the source Span of that type.
635 /// NOTE: if you want to change this to a `HirId`, be wary that
636 /// doing so breaks incremental compilation (as of this writing),
637 /// while a `Span` does not cause our tests to fail.
638 pub opt_ty_info: Option<Span>,
639 /// Place of the RHS of the =, or the subject of the `match` where this
640 /// variable is initialized. None in the case of `let PATTERN;`.
641 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
642 /// (a) the right-hand side isn't evaluated as a place expression.
643 /// (b) it gives a way to separate this case from the remaining cases
645 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
646 /// The span of the pattern in which this variable was bound.
650 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
651 pub enum BindingForm<'tcx> {
652 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
653 Var(VarBindingForm<'tcx>),
654 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
655 ImplicitSelf(ImplicitSelfKind),
656 /// Reference used in a guard expression to ensure immutability.
660 /// Represents what type of implicit self a function has, if any.
661 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
662 pub enum ImplicitSelfKind {
663 /// Represents a `fn x(self);`.
665 /// Represents a `fn x(mut self);`.
667 /// Represents a `fn x(&self);`.
669 /// Represents a `fn x(&mut self);`.
671 /// Represents when a function does not have a self argument or
672 /// when a function has a `self: X` argument.
676 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
678 mod binding_form_impl {
679 use crate::ich::StableHashingContext;
680 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
682 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
683 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
684 use super::BindingForm::*;
685 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
688 Var(binding) => binding.hash_stable(hcx, hasher),
689 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
696 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
697 /// created during evaluation of expressions in a block tail
698 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
700 /// It is used to improve diagnostics when such temporaries are
701 /// involved in borrow_check errors, e.g., explanations of where the
702 /// temporaries come from, when their destructors are run, and/or how
703 /// one might revise the code to satisfy the borrow checker's rules.
704 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
705 pub struct BlockTailInfo {
706 /// If `true`, then the value resulting from evaluating this tail
707 /// expression is ignored by the block's expression context.
709 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
710 /// but not e.g., `let _x = { ...; tail };`
711 pub tail_result_is_ignored: bool,
716 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
717 /// argument, or the return place.
718 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
719 pub struct LocalDecl<'tcx> {
720 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
722 /// Temporaries and the return place are always mutable.
723 pub mutability: Mutability,
725 // FIXME(matthewjasper) Don't store in this in `Body`
726 pub local_info: LocalInfo<'tcx>,
728 /// `true` if this is an internal local.
730 /// These locals are not based on types in the source code and are only used
731 /// for a few desugarings at the moment.
733 /// The generator transformation will sanity check the locals which are live
734 /// across a suspension point against the type components of the generator
735 /// which type checking knows are live across a suspension point. We need to
736 /// flag drop flags to avoid triggering this check as they are introduced
739 /// Unsafety checking will also ignore dereferences of these locals,
740 /// so they can be used for raw pointers only used in a desugaring.
742 /// This should be sound because the drop flags are fully algebraic, and
743 /// therefore don't affect the OIBIT or outlives properties of the
747 /// If this local is a temporary and `is_block_tail` is `Some`,
748 /// then it is a temporary created for evaluation of some
749 /// subexpression of some block's tail expression (with no
750 /// intervening statement context).
751 // FIXME(matthewjasper) Don't store in this in `Body`
752 pub is_block_tail: Option<BlockTailInfo>,
754 /// The type of this local.
757 /// If the user manually ascribed a type to this variable,
758 /// e.g., via `let x: T`, then we carry that type here. The MIR
759 /// borrow checker needs this information since it can affect
760 /// region inference.
761 // FIXME(matthewjasper) Don't store in this in `Body`
762 pub user_ty: UserTypeProjections,
764 /// The *syntactic* (i.e., not visibility) source scope the local is defined
765 /// in. If the local was defined in a let-statement, this
766 /// is *within* the let-statement, rather than outside
769 /// This is needed because the visibility source scope of locals within
770 /// a let-statement is weird.
772 /// The reason is that we want the local to be *within* the let-statement
773 /// for lint purposes, but we want the local to be *after* the let-statement
774 /// for names-in-scope purposes.
776 /// That's it, if we have a let-statement like the one in this
780 /// fn foo(x: &str) {
781 /// #[allow(unused_mut)]
782 /// let mut x: u32 = { // <- one unused mut
783 /// let mut y: u32 = x.parse().unwrap();
790 /// Then, from a lint point of view, the declaration of `x: u32`
791 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
792 /// lint scopes are the same as the AST/HIR nesting.
794 /// However, from a name lookup point of view, the scopes look more like
795 /// as if the let-statements were `match` expressions:
798 /// fn foo(x: &str) {
800 /// match x.parse().unwrap() {
809 /// We care about the name-lookup scopes for debuginfo - if the
810 /// debuginfo instruction pointer is at the call to `x.parse()`, we
811 /// want `x` to refer to `x: &str`, but if it is at the call to
812 /// `drop(x)`, we want it to refer to `x: u32`.
814 /// To allow both uses to work, we need to have more than a single scope
815 /// for a local. We have the `source_info.scope` represent the "syntactic"
816 /// lint scope (with a variable being under its let block) while the
817 /// `var_debug_info.source_info.scope` represents the "local variable"
818 /// scope (where the "rest" of a block is under all prior let-statements).
820 /// The end result looks like this:
824 /// │{ argument x: &str }
826 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
827 /// │ │ // in practice because I'm lazy.
829 /// │ │← x.source_info.scope
830 /// │ │← `x.parse().unwrap()`
832 /// │ │ │← y.source_info.scope
834 /// │ │ │{ let y: u32 }
836 /// │ │ │← y.var_debug_info.source_info.scope
839 /// │ │{ let x: u32 }
840 /// │ │← x.var_debug_info.source_info.scope
841 /// │ │← `drop(x)` // This accesses `x: u32`.
843 pub source_info: SourceInfo,
846 /// Extra information about a local that's used for diagnostics.
847 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
848 pub enum LocalInfo<'tcx> {
849 /// A user-defined local variable or function parameter
851 /// The `BindingForm` is solely used for local diagnostics when generating
852 /// warnings/errors when compiling the current crate, and therefore it need
853 /// not be visible across crates.
854 User(ClearCrossCrate<BindingForm<'tcx>>),
855 /// A temporary created that references the static with the given `DefId`.
856 StaticRef { def_id: DefId, is_thread_local: bool },
857 /// Any other temporary, the return place, or an anonymous function parameter.
861 impl<'tcx> LocalDecl<'tcx> {
862 /// Returns `true` only if local is a binding that can itself be
863 /// made mutable via the addition of the `mut` keyword, namely
864 /// something like the occurrences of `x` in:
865 /// - `fn foo(x: Type) { ... }`,
867 /// - or `match ... { C(x) => ... }`
868 pub fn can_be_made_mutable(&self) -> bool {
869 match self.local_info {
870 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
871 binding_mode: ty::BindingMode::BindByValue(_),
878 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
885 /// Returns `true` if local is definitely not a `ref ident` or
886 /// `ref mut ident` binding. (Such bindings cannot be made into
887 /// mutable bindings, but the inverse does not necessarily hold).
888 pub fn is_nonref_binding(&self) -> bool {
889 match self.local_info {
890 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
891 binding_mode: ty::BindingMode::BindByValue(_),
897 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
903 /// Returns `true` if this variable is a named variable or function
904 /// parameter declared by the user.
906 pub fn is_user_variable(&self) -> bool {
907 match self.local_info {
908 LocalInfo::User(_) => true,
913 /// Returns `true` if this is a reference to a variable bound in a `match`
914 /// expression that is used to access said variable for the guard of the
916 pub fn is_ref_for_guard(&self) -> bool {
917 match self.local_info {
918 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
923 /// Returns `Some` if this is a reference to a static item that is used to
924 /// access that static
925 pub fn is_ref_to_static(&self) -> bool {
926 match self.local_info {
927 LocalInfo::StaticRef { .. } => true,
932 /// Returns `Some` if this is a reference to a static item that is used to
933 /// access that static
934 pub fn is_ref_to_thread_local(&self) -> bool {
935 match self.local_info {
936 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
941 /// Returns `true` is the local is from a compiler desugaring, e.g.,
942 /// `__next` from a `for` loop.
944 pub fn from_compiler_desugaring(&self) -> bool {
945 self.source_info.span.desugaring_kind().is_some()
948 /// Creates a new `LocalDecl` for a temporary.
950 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
951 Self::new_local(ty, Mutability::Mut, false, span)
954 /// Converts `self` into same `LocalDecl` except tagged as immutable.
956 pub fn immutable(mut self) -> Self {
957 self.mutability = Mutability::Not;
961 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
963 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
964 assert!(self.is_block_tail.is_none());
965 self.is_block_tail = Some(info);
969 /// Creates a new `LocalDecl` for a internal temporary.
971 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
972 Self::new_local(ty, Mutability::Mut, true, span)
976 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
980 user_ty: UserTypeProjections::none(),
981 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
983 local_info: LocalInfo::Other,
988 /// Builds a `LocalDecl` for the return place.
990 /// This must be inserted into the `local_decls` list as the first local.
992 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
994 mutability: Mutability::Mut,
996 user_ty: UserTypeProjections::none(),
997 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
1000 local_info: LocalInfo::Other,
1005 /// Debug information pertaining to a user variable.
1006 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1007 pub struct VarDebugInfo<'tcx> {
1010 /// Source info of the user variable, including the scope
1011 /// within which the variable is visible (to debuginfo)
1012 /// (see `LocalDecl`'s `source_info` field for more details).
1013 pub source_info: SourceInfo,
1015 /// Where the data for this user variable is to be found.
1016 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1017 /// based on a `Local`, not a `Static`, and contains no indexing.
1018 pub place: Place<'tcx>,
1021 ///////////////////////////////////////////////////////////////////////////
1024 rustc_index::newtype_index! {
1025 pub struct BasicBlock {
1027 DEBUG_FORMAT = "bb{}",
1028 const START_BLOCK = 0,
1033 pub fn start_location(self) -> Location {
1034 Location { block: self, statement_index: 0 }
1038 CloneTypeFoldableAndLiftImpls!{ BasicBlock, }
1040 ///////////////////////////////////////////////////////////////////////////
1041 // BasicBlockData and Terminator
1043 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1044 pub struct BasicBlockData<'tcx> {
1045 /// List of statements in this block.
1046 pub statements: Vec<Statement<'tcx>>,
1048 /// Terminator for this block.
1050 /// N.B., this should generally ONLY be `None` during construction.
1051 /// Therefore, you should generally access it via the
1052 /// `terminator()` or `terminator_mut()` methods. The only
1053 /// exception is that certain passes, such as `simplify_cfg`, swap
1054 /// out the terminator temporarily with `None` while they continue
1055 /// to recurse over the set of basic blocks.
1056 pub terminator: Option<Terminator<'tcx>>,
1058 /// If true, this block lies on an unwind path. This is used
1059 /// during codegen where distinct kinds of basic blocks may be
1060 /// generated (particularly for MSVC cleanup). Unwind blocks must
1061 /// only branch to other unwind blocks.
1062 pub is_cleanup: bool,
1065 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1066 pub struct Terminator<'tcx> {
1067 pub source_info: SourceInfo,
1068 pub kind: TerminatorKind<'tcx>,
1071 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1072 pub enum TerminatorKind<'tcx> {
1073 /// Block should have one successor in the graph; we jump there.
1074 Goto { target: BasicBlock },
1076 /// Operand evaluates to an integer; jump depending on its value
1077 /// to one of the targets, and otherwise fallback to `otherwise`.
1079 /// The discriminant value being tested.
1080 discr: Operand<'tcx>,
1082 /// The type of value being tested.
1083 switch_ty: Ty<'tcx>,
1085 /// Possible values. The locations to branch to in each case
1086 /// are found in the corresponding indices from the `targets` vector.
1087 values: Cow<'tcx, [u128]>,
1089 /// Possible branch sites. The last element of this vector is used
1090 /// for the otherwise branch, so targets.len() == values.len() + 1
1093 // This invariant is quite non-obvious and also could be improved.
1094 // One way to make this invariant is to have something like this instead:
1096 // branches: Vec<(ConstInt, BasicBlock)>,
1097 // otherwise: Option<BasicBlock> // exhaustive if None
1099 // However we’ve decided to keep this as-is until we figure a case
1100 // where some other approach seems to be strictly better than other.
1101 targets: Vec<BasicBlock>,
1104 /// Indicates that the landing pad is finished and unwinding should
1105 /// continue. Emitted by `build::scope::diverge_cleanup`.
1108 /// Indicates that the landing pad is finished and that the process
1109 /// should abort. Used to prevent unwinding for foreign items.
1112 /// Indicates a normal return. The return place should have
1113 /// been filled in by now. This should occur at most once.
1116 /// Indicates a terminator that can never be reached.
1119 /// Drop the `Place`.
1120 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1122 /// Drop the `Place` and assign the new value over it. This ensures
1123 /// that the assignment to `P` occurs *even if* the destructor for
1124 /// place unwinds. Its semantics are best explained by the
1129 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1137 /// Drop(P, goto BB1, unwind BB2)
1140 /// // P is now uninitialized
1144 /// // P is now uninitialized -- its dtor panicked
1149 location: Place<'tcx>,
1150 value: Operand<'tcx>,
1152 unwind: Option<BasicBlock>,
1155 /// Block ends with a call of a converging function.
1157 /// The function that’s being called.
1158 func: Operand<'tcx>,
1159 /// Arguments the function is called with.
1160 /// These are owned by the callee, which is free to modify them.
1161 /// This allows the memory occupied by "by-value" arguments to be
1162 /// reused across function calls without duplicating the contents.
1163 args: Vec<Operand<'tcx>>,
1164 /// Destination for the return value. If some, the call is converging.
1165 destination: Option<(Place<'tcx>, BasicBlock)>,
1166 /// Cleanups to be done if the call unwinds.
1167 cleanup: Option<BasicBlock>,
1168 /// `true` if this is from a call in HIR rather than from an overloaded
1169 /// operator. True for overloaded function call.
1170 from_hir_call: bool,
1173 /// Jump to the target if the condition has the expected value,
1174 /// otherwise panic with a message and a cleanup target.
1176 cond: Operand<'tcx>,
1178 msg: AssertMessage<'tcx>,
1180 cleanup: Option<BasicBlock>,
1183 /// A suspend point.
1185 /// The value to return.
1186 value: Operand<'tcx>,
1187 /// Where to resume to.
1189 /// Cleanup to be done if the generator is dropped at this suspend point.
1190 drop: Option<BasicBlock>,
1193 /// Indicates the end of the dropping of a generator.
1196 /// A block where control flow only ever takes one real path, but borrowck
1197 /// needs to be more conservative.
1199 /// The target normal control flow will take.
1200 real_target: BasicBlock,
1201 /// A block control flow could conceptually jump to, but won't in
1203 imaginary_target: BasicBlock,
1205 /// A terminator for blocks that only take one path in reality, but where we
1206 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1207 /// This can arise in infinite loops with no function calls for example.
1209 /// The target normal control flow will take.
1210 real_target: BasicBlock,
1211 /// The imaginary cleanup block link. This particular path will never be taken
1212 /// in practice, but in order to avoid fragility we want to always
1213 /// consider it in borrowck. We don't want to accept programs which
1214 /// pass borrowck only when `panic=abort` or some assertions are disabled
1215 /// due to release vs. debug mode builds. This needs to be an `Option` because
1216 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1217 unwind: Option<BasicBlock>,
1221 pub type Successors<'a> =
1222 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1223 pub type SuccessorsMut<'a> =
1224 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1226 impl<'tcx> Terminator<'tcx> {
1227 pub fn successors(&self) -> Successors<'_> {
1228 self.kind.successors()
1231 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1232 self.kind.successors_mut()
1235 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1239 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1240 self.kind.unwind_mut()
1244 impl<'tcx> TerminatorKind<'tcx> {
1247 cond: Operand<'tcx>,
1250 ) -> TerminatorKind<'tcx> {
1251 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1252 TerminatorKind::SwitchInt {
1254 switch_ty: tcx.types.bool,
1255 values: From::from(BOOL_SWITCH_FALSE),
1256 targets: vec![f, t],
1260 pub fn successors(&self) -> Successors<'_> {
1261 use self::TerminatorKind::*;
1268 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1269 Goto { target: ref t }
1270 | Call { destination: None, cleanup: Some(ref t), .. }
1271 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1272 | Yield { resume: ref t, drop: None, .. }
1273 | DropAndReplace { target: ref t, unwind: None, .. }
1274 | Drop { target: ref t, unwind: None, .. }
1275 | Assert { target: ref t, cleanup: None, .. }
1276 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1277 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1278 | Yield { resume: ref t, drop: Some(ref u), .. }
1279 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1280 | Drop { target: ref t, unwind: Some(ref u), .. }
1281 | Assert { target: ref t, cleanup: Some(ref u), .. }
1282 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1283 Some(t).into_iter().chain(slice::from_ref(u))
1285 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1286 FalseEdges { ref real_target, ref imaginary_target } => {
1287 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1292 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1293 use self::TerminatorKind::*;
1300 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1301 Goto { target: ref mut t }
1302 | Call { destination: None, cleanup: Some(ref mut t), .. }
1303 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1304 | Yield { resume: ref mut t, drop: None, .. }
1305 | DropAndReplace { target: ref mut t, unwind: None, .. }
1306 | Drop { target: ref mut t, unwind: None, .. }
1307 | Assert { target: ref mut t, cleanup: None, .. }
1308 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1309 Some(t).into_iter().chain(&mut [])
1311 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1312 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1313 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1314 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1315 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1316 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1317 Some(t).into_iter().chain(slice::from_mut(u))
1319 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1320 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1321 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1326 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1328 TerminatorKind::Goto { .. }
1329 | TerminatorKind::Resume
1330 | TerminatorKind::Abort
1331 | TerminatorKind::Return
1332 | TerminatorKind::Unreachable
1333 | TerminatorKind::GeneratorDrop
1334 | TerminatorKind::Yield { .. }
1335 | TerminatorKind::SwitchInt { .. }
1336 | TerminatorKind::FalseEdges { .. } => None,
1337 TerminatorKind::Call { cleanup: ref unwind, .. }
1338 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1339 | TerminatorKind::DropAndReplace { ref unwind, .. }
1340 | TerminatorKind::Drop { ref unwind, .. }
1341 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1345 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1347 TerminatorKind::Goto { .. }
1348 | TerminatorKind::Resume
1349 | TerminatorKind::Abort
1350 | TerminatorKind::Return
1351 | TerminatorKind::Unreachable
1352 | TerminatorKind::GeneratorDrop
1353 | TerminatorKind::Yield { .. }
1354 | TerminatorKind::SwitchInt { .. }
1355 | TerminatorKind::FalseEdges { .. } => None,
1356 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1357 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1358 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1359 | TerminatorKind::Drop { ref mut unwind, .. }
1360 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1365 impl<'tcx> BasicBlockData<'tcx> {
1366 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1367 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1370 pub fn terminator_opt(&self) -> &Option<Terminator<'tcx>> {
1374 /// Accessor for terminator.
1376 /// Terminator may not be None after construction of the basic block is complete. This accessor
1377 /// provides a convenience way to reach the terminator.
1378 pub fn terminator(&self) -> &Terminator<'tcx> {
1379 self.terminator.as_ref().expect("invalid terminator state")
1382 // This cannot be public since changing the terminator will break the predecessors cache in Body
1383 // To do so outside of this module, use Body::basic_block_terminator_mut(BasicBlock)
1384 fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1385 self.terminator.as_mut().expect("invalid terminator state")
1388 // This can be public since changing the kind will not break the predecessors cache in Body
1389 pub fn terminator_kind_mut(&mut self) -> &mut TerminatorKind<'tcx> {
1390 &mut self.terminator_mut().kind
1393 pub fn retain_statements<F>(&mut self, mut f: F)
1395 F: FnMut(&mut Statement<'_>) -> bool,
1397 for s in &mut self.statements {
1404 pub fn expand_statements<F, I>(&mut self, mut f: F)
1406 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1407 I: iter::TrustedLen<Item = Statement<'tcx>>,
1409 // Gather all the iterators we'll need to splice in, and their positions.
1410 let mut splices: Vec<(usize, I)> = vec![];
1411 let mut extra_stmts = 0;
1412 for (i, s) in self.statements.iter_mut().enumerate() {
1413 if let Some(mut new_stmts) = f(s) {
1414 if let Some(first) = new_stmts.next() {
1415 // We can already store the first new statement.
1418 // Save the other statements for optimized splicing.
1419 let remaining = new_stmts.size_hint().0;
1421 splices.push((i + 1 + extra_stmts, new_stmts));
1422 extra_stmts += remaining;
1430 // Splice in the new statements, from the end of the block.
1431 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1432 // where a range of elements ("gap") is left uninitialized, with
1433 // splicing adding new elements to the end of that gap and moving
1434 // existing elements from before the gap to the end of the gap.
1435 // For now, this is safe code, emulating a gap but initializing it.
1436 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1437 self.statements.resize(
1440 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1441 kind: StatementKind::Nop,
1444 for (splice_start, new_stmts) in splices.into_iter().rev() {
1445 let splice_end = splice_start + new_stmts.size_hint().0;
1446 while gap.end > splice_end {
1449 self.statements.swap(gap.start, gap.end);
1451 self.statements.splice(splice_start..splice_end, new_stmts);
1452 gap.end = splice_start;
1456 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1457 if index < self.statements.len() {
1458 &self.statements[index]
1465 impl<'tcx> Debug for TerminatorKind<'tcx> {
1466 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1467 self.fmt_head(fmt)?;
1468 let successor_count = self.successors().count();
1469 let labels = self.fmt_successor_labels();
1470 assert_eq!(successor_count, labels.len());
1472 match successor_count {
1475 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1478 write!(fmt, " -> [")?;
1479 for (i, target) in self.successors().enumerate() {
1483 write!(fmt, "{}: {:?}", labels[i], target)?;
1491 impl<'tcx> TerminatorKind<'tcx> {
1492 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1493 /// successor basic block, if any. The only information not included is the list of possible
1494 /// successors, which may be rendered differently between the text and the graphviz format.
1495 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1496 use self::TerminatorKind::*;
1498 Goto { .. } => write!(fmt, "goto"),
1499 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1500 Return => write!(fmt, "return"),
1501 GeneratorDrop => write!(fmt, "generator_drop"),
1502 Resume => write!(fmt, "resume"),
1503 Abort => write!(fmt, "abort"),
1504 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1505 Unreachable => write!(fmt, "unreachable"),
1506 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1507 DropAndReplace { ref location, ref value, .. } => {
1508 write!(fmt, "replace({:?} <- {:?})", location, value)
1510 Call { ref func, ref args, ref destination, .. } => {
1511 if let Some((ref destination, _)) = *destination {
1512 write!(fmt, "{:?} = ", destination)?;
1514 write!(fmt, "{:?}(", func)?;
1515 for (index, arg) in args.iter().enumerate() {
1519 write!(fmt, "{:?}", arg)?;
1523 Assert { ref cond, expected, ref msg, .. } => {
1524 write!(fmt, "assert(")?;
1528 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1530 FalseEdges { .. } => write!(fmt, "falseEdges"),
1531 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1535 /// Returns the list of labels for the edges to the successor basic blocks.
1536 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1537 use self::TerminatorKind::*;
1539 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1540 Goto { .. } => vec!["".into()],
1541 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1542 let param_env = ty::ParamEnv::empty();
1543 let switch_ty = tcx.lift(&switch_ty).unwrap();
1544 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1548 ty::Const::from_scalar(
1550 Scalar::from_uint(u, size).into(),
1556 .chain(iter::once("otherwise".into()))
1559 Call { destination: Some(_), cleanup: Some(_), .. } => {
1560 vec!["return".into(), "unwind".into()]
1562 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1563 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1564 Call { destination: None, cleanup: None, .. } => vec![],
1565 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1566 Yield { drop: None, .. } => vec!["resume".into()],
1567 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1568 vec!["return".into()]
1570 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1571 vec!["return".into(), "unwind".into()]
1573 Assert { cleanup: None, .. } => vec!["".into()],
1574 Assert { .. } => vec!["success".into(), "unwind".into()],
1575 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1576 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1577 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1582 ///////////////////////////////////////////////////////////////////////////
1585 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1586 pub struct Statement<'tcx> {
1587 pub source_info: SourceInfo,
1588 pub kind: StatementKind<'tcx>,
1591 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1592 #[cfg(target_arch = "x86_64")]
1593 static_assert_size!(Statement<'_>, 32);
1595 impl Statement<'_> {
1596 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1597 /// invalidating statement indices in `Location`s.
1598 pub fn make_nop(&mut self) {
1599 self.kind = StatementKind::Nop
1602 /// Changes a statement to a nop and returns the original statement.
1603 pub fn replace_nop(&mut self) -> Self {
1605 source_info: self.source_info,
1606 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1611 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1612 pub enum StatementKind<'tcx> {
1613 /// Write the RHS Rvalue to the LHS Place.
1614 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1616 /// This represents all the reading that a pattern match may do
1617 /// (e.g., inspecting constants and discriminant values), and the
1618 /// kind of pattern it comes from. This is in order to adapt potential
1619 /// error messages to these specific patterns.
1621 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1622 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1623 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1625 /// Write the discriminant for a variant to the enum Place.
1626 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1628 /// Start a live range for the storage of the local.
1631 /// End the current live range for the storage of the local.
1634 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1635 /// of `StatementKind` low.
1636 InlineAsm(Box<InlineAsm<'tcx>>),
1638 /// Retag references in the given place, ensuring they got fresh tags. This is
1639 /// part of the Stacked Borrows model. These statements are currently only interpreted
1640 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1641 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1642 /// for more details.
1643 Retag(RetagKind, Box<Place<'tcx>>),
1645 /// Encodes a user's type ascription. These need to be preserved
1646 /// intact so that NLL can respect them. For example:
1650 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1651 /// to the user-given type `T`. The effect depends on the specified variance:
1653 /// - `Covariant` -- requires that `T_y <: T`
1654 /// - `Contravariant` -- requires that `T_y :> T`
1655 /// - `Invariant` -- requires that `T_y == T`
1656 /// - `Bivariant` -- no effect
1657 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1659 /// No-op. Useful for deleting instructions without affecting statement indices.
1663 /// Describes what kind of retag is to be performed.
1664 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1665 pub enum RetagKind {
1666 /// The initial retag when entering a function.
1668 /// Retag preparing for a two-phase borrow.
1670 /// Retagging raw pointers.
1672 /// A "normal" retag.
1676 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1677 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1678 pub enum FakeReadCause {
1679 /// Inject a fake read of the borrowed input at the end of each guards
1682 /// This should ensure that you cannot change the variant for an enum while
1683 /// you are in the midst of matching on it.
1686 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1687 /// generate a read of x to check that it is initialized and safe.
1690 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1691 /// in a match guard to ensure that it's value hasn't change by the time
1692 /// we create the OutsideGuard version.
1695 /// Officially, the semantics of
1697 /// `let pattern = <expr>;`
1699 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1700 /// into the pattern.
1702 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1703 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1704 /// but in some cases it can affect the borrow checker, as in #53695.
1705 /// Therefore, we insert a "fake read" here to ensure that we get
1706 /// appropriate errors.
1709 /// If we have an index expression like
1711 /// (*x)[1][{ x = y; 4}]
1713 /// then the first bounds check is invalidated when we evaluate the second
1714 /// index expression. Thus we create a fake borrow of `x` across the second
1715 /// indexer, which will cause a borrow check error.
1719 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1720 pub struct InlineAsm<'tcx> {
1721 pub asm: hir::InlineAsmInner,
1722 pub outputs: Box<[Place<'tcx>]>,
1723 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1726 impl Debug for Statement<'_> {
1727 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1728 use self::StatementKind::*;
1730 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1731 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1732 Retag(ref kind, ref place) => write!(
1736 RetagKind::FnEntry => "[fn entry] ",
1737 RetagKind::TwoPhase => "[2phase] ",
1738 RetagKind::Raw => "[raw] ",
1739 RetagKind::Default => "",
1743 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1744 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1745 SetDiscriminant { ref place, variant_index } => {
1746 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1748 InlineAsm(ref asm) => {
1749 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1751 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1752 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1754 Nop => write!(fmt, "nop"),
1759 ///////////////////////////////////////////////////////////////////////////
1762 /// A path to a value; something that can be evaluated without
1763 /// changing or disturbing program state.
1765 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1767 pub struct Place<'tcx> {
1768 pub base: PlaceBase<'tcx>,
1770 /// projection out of a place (access a field, deref a pointer, etc)
1771 pub projection: &'tcx List<PlaceElem<'tcx>>,
1774 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1777 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1779 pub enum PlaceBase<'tcx> {
1783 /// static or static mut variable
1784 Static(Box<Static<'tcx>>),
1787 /// We store the normalized type to avoid requiring normalization when reading MIR
1788 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1789 RustcEncodable, RustcDecodable, HashStable)]
1790 pub struct Static<'tcx> {
1792 pub kind: StaticKind<'tcx>,
1793 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1794 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1795 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1796 /// into the calling frame.
1801 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1803 pub enum StaticKind<'tcx> {
1804 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1805 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1806 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1807 Promoted(Promoted, SubstsRef<'tcx>),
1811 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1812 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1813 pub enum ProjectionElem<V, T> {
1818 /// These indices are generated by slice patterns. Easiest to explain
1822 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1823 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1824 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1825 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1828 /// index or -index (in Python terms), depending on from_end
1830 /// thing being indexed must be at least this long
1832 /// counting backwards from end?
1836 /// These indices are generated by slice patterns.
1838 /// slice[from:-to] in Python terms.
1844 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1845 /// this for ADTs with more than one variant. It may be better to
1846 /// just introduce it always, or always for enums.
1848 /// The included Symbol is the name of the variant, used for printing MIR.
1849 Downcast(Option<Symbol>, VariantIdx),
1852 impl<V, T> ProjectionElem<V, T> {
1853 /// Returns `true` if the target of this projection may refer to a different region of memory
1855 fn is_indirect(&self) -> bool {
1857 Self::Deref => true,
1861 | Self::ConstantIndex { .. }
1862 | Self::Subslice { .. }
1863 | Self::Downcast(_, _)
1869 /// Alias for projections as they appear in places, where the base is a place
1870 /// and the index is a local.
1871 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1873 impl<'tcx> Copy for PlaceElem<'tcx> { }
1875 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1876 #[cfg(target_arch = "x86_64")]
1877 static_assert_size!(PlaceElem<'_>, 16);
1879 /// Alias for projections as they appear in `UserTypeProjection`, where we
1880 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1881 pub type ProjectionKind = ProjectionElem<(), ()>;
1883 rustc_index::newtype_index! {
1886 DEBUG_FORMAT = "field[{}]"
1890 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1891 pub struct PlaceRef<'a, 'tcx> {
1892 pub base: &'a PlaceBase<'tcx>,
1893 pub projection: &'a [PlaceElem<'tcx>],
1896 impl<'tcx> Place<'tcx> {
1897 // FIXME change this to a const fn by also making List::empty a const fn.
1898 pub fn return_place() -> Place<'tcx> {
1900 base: PlaceBase::Local(RETURN_PLACE),
1901 projection: List::empty(),
1905 /// Returns `true` if this `Place` contains a `Deref` projection.
1907 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1908 /// same region of memory as its base.
1909 pub fn is_indirect(&self) -> bool {
1910 self.projection.iter().any(|elem| elem.is_indirect())
1913 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1914 /// a single deref of a local.
1916 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1917 pub fn local_or_deref_local(&self) -> Option<Local> {
1918 match self.as_ref() {
1920 base: &PlaceBase::Local(local),
1924 base: &PlaceBase::Local(local),
1925 projection: &[ProjectionElem::Deref],
1931 /// If this place represents a local variable like `_X` with no
1932 /// projections, return `Some(_X)`.
1933 pub fn as_local(&self) -> Option<Local> {
1934 self.as_ref().as_local()
1937 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1940 projection: &self.projection,
1945 impl From<Local> for Place<'_> {
1946 fn from(local: Local) -> Self {
1949 projection: List::empty(),
1954 impl From<Local> for PlaceBase<'_> {
1955 fn from(local: Local) -> Self {
1956 PlaceBase::Local(local)
1960 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1961 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1962 /// a single deref of a local.
1964 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1965 pub fn local_or_deref_local(&self) -> Option<Local> {
1968 base: PlaceBase::Local(local),
1972 base: PlaceBase::Local(local),
1973 projection: [ProjectionElem::Deref],
1979 /// If this place represents a local variable like `_X` with no
1980 /// projections, return `Some(_X)`.
1981 pub fn as_local(&self) -> Option<Local> {
1983 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1989 impl Debug for Place<'_> {
1990 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1991 for elem in self.projection.iter().rev() {
1993 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1994 write!(fmt, "(").unwrap();
1996 ProjectionElem::Deref => {
1997 write!(fmt, "(*").unwrap();
1999 ProjectionElem::Index(_)
2000 | ProjectionElem::ConstantIndex { .. }
2001 | ProjectionElem::Subslice { .. } => {}
2005 write!(fmt, "{:?}", self.base)?;
2007 for elem in self.projection.iter() {
2009 ProjectionElem::Downcast(Some(name), _index) => {
2010 write!(fmt, " as {})", name)?;
2012 ProjectionElem::Downcast(None, index) => {
2013 write!(fmt, " as variant#{:?})", index)?;
2015 ProjectionElem::Deref => {
2018 ProjectionElem::Field(field, ty) => {
2019 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2021 ProjectionElem::Index(ref index) => {
2022 write!(fmt, "[{:?}]", index)?;
2024 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2025 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2027 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2028 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2030 ProjectionElem::Subslice { from, to } if *to == 0 => {
2031 write!(fmt, "[{:?}:]", from)?;
2033 ProjectionElem::Subslice { from, to } if *from == 0 => {
2034 write!(fmt, "[:-{:?}]", to)?;
2036 ProjectionElem::Subslice { from, to } => {
2037 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2046 impl Debug for PlaceBase<'_> {
2047 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2049 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2050 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
2051 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2053 PlaceBase::Static(box self::Static {
2054 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
2056 write!(fmt, "({:?}: {:?})", promoted, ty)
2062 ///////////////////////////////////////////////////////////////////////////
2065 rustc_index::newtype_index! {
2066 pub struct SourceScope {
2068 DEBUG_FORMAT = "scope[{}]",
2069 const OUTERMOST_SOURCE_SCOPE = 0,
2073 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2074 pub struct SourceScopeData {
2076 pub parent_scope: Option<SourceScope>,
2078 /// Crate-local information for this source scope, that can't (and
2079 /// needn't) be tracked across crates.
2080 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2083 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2084 pub struct SourceScopeLocalData {
2085 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2086 pub lint_root: hir::HirId,
2087 /// The unsafe block that contains this node.
2091 ///////////////////////////////////////////////////////////////////////////
2094 /// These are values that can appear inside an rvalue. They are intentionally
2095 /// limited to prevent rvalues from being nested in one another.
2096 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2097 pub enum Operand<'tcx> {
2098 /// Copy: The value must be available for use afterwards.
2100 /// This implies that the type of the place must be `Copy`; this is true
2101 /// by construction during build, but also checked by the MIR type checker.
2104 /// Move: The value (including old borrows of it) will not be used again.
2106 /// Safe for values of all types (modulo future developments towards `?Move`).
2107 /// Correct usage patterns are enforced by the borrow checker for safe code.
2108 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2111 /// Synthesizes a constant value.
2112 Constant(Box<Constant<'tcx>>),
2115 impl<'tcx> Debug for Operand<'tcx> {
2116 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2117 use self::Operand::*;
2119 Constant(ref a) => write!(fmt, "{:?}", a),
2120 Copy(ref place) => write!(fmt, "{:?}", place),
2121 Move(ref place) => write!(fmt, "move {:?}", place),
2126 impl<'tcx> Operand<'tcx> {
2127 /// Convenience helper to make a constant that refers to the fn
2128 /// with given `DefId` and substs. Since this is used to synthesize
2129 /// MIR, assumes `user_ty` is None.
2130 pub fn function_handle(
2133 substs: SubstsRef<'tcx>,
2136 let ty = tcx.type_of(def_id).subst(tcx, substs);
2137 Operand::Constant(box Constant {
2140 literal: ty::Const::zero_sized(tcx, ty),
2144 pub fn to_copy(&self) -> Self {
2146 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2147 Operand::Move(ref place) => Operand::Copy(place.clone()),
2152 ///////////////////////////////////////////////////////////////////////////
2155 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2156 pub enum Rvalue<'tcx> {
2157 /// x (either a move or copy, depending on type of x)
2161 Repeat(Operand<'tcx>, u64),
2164 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2166 /// length of a [X] or [X;n] value
2169 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2171 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2172 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2174 NullaryOp(NullOp, Ty<'tcx>),
2175 UnaryOp(UnOp, Operand<'tcx>),
2177 /// Read the discriminant of an ADT.
2179 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2180 /// be defined to return, say, a 0) if ADT is not an enum.
2181 Discriminant(Place<'tcx>),
2183 /// Creates an aggregate value, like a tuple or struct. This is
2184 /// only needed because we want to distinguish `dest = Foo { x:
2185 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2186 /// that `Foo` has a destructor. These rvalues can be optimized
2187 /// away after type-checking and before lowering.
2188 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2191 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2194 Pointer(PointerCast),
2197 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2198 pub enum AggregateKind<'tcx> {
2199 /// The type is of the element
2203 /// The second field is the variant index. It's equal to 0 for struct
2204 /// and union expressions. The fourth field is
2205 /// active field number and is present only for union expressions
2206 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2207 /// active field index would identity the field `c`
2208 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2210 Closure(DefId, SubstsRef<'tcx>),
2211 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2214 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2216 /// The `+` operator (addition)
2218 /// The `-` operator (subtraction)
2220 /// The `*` operator (multiplication)
2222 /// The `/` operator (division)
2224 /// The `%` operator (modulus)
2226 /// The `^` operator (bitwise xor)
2228 /// The `&` operator (bitwise and)
2230 /// The `|` operator (bitwise or)
2232 /// The `<<` operator (shift left)
2234 /// The `>>` operator (shift right)
2236 /// The `==` operator (equality)
2238 /// The `<` operator (less than)
2240 /// The `<=` operator (less than or equal to)
2242 /// The `!=` operator (not equal to)
2244 /// The `>=` operator (greater than or equal to)
2246 /// The `>` operator (greater than)
2248 /// The `ptr.offset` operator
2253 pub fn is_checkable(self) -> bool {
2256 Add | Sub | Mul | Shl | Shr => true,
2262 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2264 /// Returns the size of a value of that type
2266 /// Creates a new uninitialized box for a value of that type
2270 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2272 /// The `!` operator for logical inversion
2274 /// The `-` operator for negation
2278 impl<'tcx> Debug for Rvalue<'tcx> {
2279 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2280 use self::Rvalue::*;
2283 Use(ref place) => write!(fmt, "{:?}", place),
2284 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2285 Len(ref a) => write!(fmt, "Len({:?})", a),
2286 Cast(ref kind, ref place, ref ty) => {
2287 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2289 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2290 CheckedBinaryOp(ref op, ref a, ref b) => {
2291 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2293 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2294 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2295 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2296 Ref(region, borrow_kind, ref place) => {
2297 let kind_str = match borrow_kind {
2298 BorrowKind::Shared => "",
2299 BorrowKind::Shallow => "shallow ",
2300 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2303 // When printing regions, add trailing space if necessary.
2304 let print_region = ty::tls::with(|tcx| {
2305 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2307 let region = if print_region {
2308 let mut region = region.to_string();
2309 if region.len() > 0 {
2314 // Do not even print 'static
2317 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2320 Aggregate(ref kind, ref places) => {
2321 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2322 let mut tuple_fmt = fmt.debug_tuple("");
2323 for place in places {
2324 tuple_fmt.field(place);
2330 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2332 AggregateKind::Tuple => match places.len() {
2333 0 => write!(fmt, "()"),
2334 1 => write!(fmt, "({:?},)", places[0]),
2335 _ => fmt_tuple(fmt, places),
2338 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2339 let variant_def = &adt_def.variants[variant];
2342 ty::tls::with(|tcx| {
2343 let substs = tcx.lift(&substs).expect("could not lift for printing");
2344 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2345 .print_def_path(variant_def.def_id, substs)?;
2349 match variant_def.ctor_kind {
2350 CtorKind::Const => Ok(()),
2351 CtorKind::Fn => fmt_tuple(fmt, places),
2352 CtorKind::Fictive => {
2353 let mut struct_fmt = fmt.debug_struct("");
2354 for (field, place) in variant_def.fields.iter().zip(places) {
2355 struct_fmt.field(&field.ident.as_str(), place);
2362 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2363 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2364 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2365 let substs = tcx.lift(&substs).unwrap();
2368 tcx.def_path_str_with_substs(def_id, substs),
2371 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2373 let mut struct_fmt = fmt.debug_struct(&name);
2375 if let Some(upvars) = tcx.upvars(def_id) {
2376 for (&var_id, place) in upvars.keys().zip(places) {
2377 let var_name = tcx.hir().name(var_id);
2378 struct_fmt.field(&var_name.as_str(), place);
2384 write!(fmt, "[closure]")
2388 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2389 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2390 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2391 let mut struct_fmt = fmt.debug_struct(&name);
2393 if let Some(upvars) = tcx.upvars(def_id) {
2394 for (&var_id, place) in upvars.keys().zip(places) {
2395 let var_name = tcx.hir().name(var_id);
2396 struct_fmt.field(&var_name.as_str(), place);
2402 write!(fmt, "[generator]")
2411 ///////////////////////////////////////////////////////////////////////////
2414 /// Two constants are equal if they are the same constant. Note that
2415 /// this does not necessarily mean that they are "==" in Rust -- in
2416 /// particular one must be wary of `NaN`!
2418 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2419 pub struct Constant<'tcx> {
2422 /// Optional user-given type: for something like
2423 /// `collect::<Vec<_>>`, this would be present and would
2424 /// indicate that `Vec<_>` was explicitly specified.
2426 /// Needed for NLL to impose user-given type constraints.
2427 pub user_ty: Option<UserTypeAnnotationIndex>,
2429 pub literal: &'tcx ty::Const<'tcx>,
2432 impl Constant<'tcx> {
2433 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2434 match self.literal.val.try_to_scalar() {
2435 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2436 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2439 tcx.sess.delay_span_bug(
2440 DUMMY_SP, "MIR cannot contain dangling const pointers",
2450 /// A collection of projections into user types.
2452 /// They are projections because a binding can occur a part of a
2453 /// parent pattern that has been ascribed a type.
2455 /// Its a collection because there can be multiple type ascriptions on
2456 /// the path from the root of the pattern down to the binding itself.
2461 /// struct S<'a>((i32, &'a str), String);
2462 /// let S((_, w): (i32, &'static str), _): S = ...;
2463 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2464 /// // --------------------------------- ^ (2)
2467 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2468 /// ascribed the type `(i32, &'static str)`.
2470 /// The highlights labelled `(2)` show the whole pattern being
2471 /// ascribed the type `S`.
2473 /// In this example, when we descend to `w`, we will have built up the
2474 /// following two projected types:
2476 /// * base: `S`, projection: `(base.0).1`
2477 /// * base: `(i32, &'static str)`, projection: `base.1`
2479 /// The first will lead to the constraint `w: &'1 str` (for some
2480 /// inferred region `'1`). The second will lead to the constraint `w:
2482 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2483 pub struct UserTypeProjections {
2484 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2487 impl<'tcx> UserTypeProjections {
2488 pub fn none() -> Self {
2489 UserTypeProjections { contents: vec![] }
2492 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2493 UserTypeProjections { contents: projs.collect() }
2496 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2497 self.contents.iter()
2500 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2501 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2504 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2505 self.contents.push((user_ty.clone(), span));
2511 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2513 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2517 pub fn index(self) -> Self {
2518 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2521 pub fn subslice(self, from: u32, to: u32) -> Self {
2522 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2525 pub fn deref(self) -> Self {
2526 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2529 pub fn leaf(self, field: Field) -> Self {
2530 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2533 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2534 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2538 /// Encodes the effect of a user-supplied type annotation on the
2539 /// subcomponents of a pattern. The effect is determined by applying the
2540 /// given list of proejctions to some underlying base type. Often,
2541 /// the projection element list `projs` is empty, in which case this
2542 /// directly encodes a type in `base`. But in the case of complex patterns with
2543 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2544 /// in which case the `projs` vector is used.
2548 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2550 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2551 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2552 /// determined by finding the type of the `.0` field from `T`.
2553 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2554 pub struct UserTypeProjection {
2555 pub base: UserTypeAnnotationIndex,
2556 pub projs: Vec<ProjectionKind>,
2559 impl Copy for ProjectionKind {}
2561 impl UserTypeProjection {
2562 pub(crate) fn index(mut self) -> Self {
2563 self.projs.push(ProjectionElem::Index(()));
2567 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2568 self.projs.push(ProjectionElem::Subslice { from, to });
2572 pub(crate) fn deref(mut self) -> Self {
2573 self.projs.push(ProjectionElem::Deref);
2577 pub(crate) fn leaf(mut self, field: Field) -> Self {
2578 self.projs.push(ProjectionElem::Field(field, ()));
2582 pub(crate) fn variant(
2584 adt_def: &'tcx AdtDef,
2585 variant_index: VariantIdx,
2588 self.projs.push(ProjectionElem::Downcast(
2589 Some(adt_def.variants[variant_index].ident.name),
2592 self.projs.push(ProjectionElem::Field(field, ()));
2597 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2599 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2600 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2601 use crate::mir::ProjectionElem::*;
2603 let base = self.base.fold_with(folder);
2604 let projs: Vec<_> = self
2607 .map(|elem| match elem {
2609 Field(f, ()) => Field(f.clone(), ()),
2610 Index(()) => Index(()),
2611 elem => elem.clone(),
2615 UserTypeProjection { base, projs }
2618 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2619 self.base.visit_with(visitor)
2620 // Note: there's nothing in `self.proj` to visit.
2624 rustc_index::newtype_index! {
2625 pub struct Promoted {
2627 DEBUG_FORMAT = "promoted[{}]"
2631 impl<'tcx> Debug for Constant<'tcx> {
2632 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2633 write!(fmt, "{}", self)
2637 impl<'tcx> Display for Constant<'tcx> {
2638 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2639 write!(fmt, "const ")?;
2640 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2641 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2642 // detailed and just not '{pointer}'.
2643 if let ty::RawPtr(_) = self.literal.ty.kind {
2644 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2646 write!(fmt, "{}", self.literal)
2651 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2652 type Node = BasicBlock;
2655 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2656 fn num_nodes(&self) -> usize {
2657 self.basic_blocks.len()
2661 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2662 fn start_node(&self) -> Self::Node {
2667 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2671 ) -> <Self as GraphPredecessors<'_>>::Iter {
2672 self.predecessors_for(node).to_vec().into_iter()
2676 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2680 ) -> <Self as GraphSuccessors<'_>>::Iter {
2681 self.basic_blocks[node].terminator().successors().cloned()
2685 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2686 type Item = BasicBlock;
2687 type Iter = IntoIter<BasicBlock>;
2690 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2691 type Item = BasicBlock;
2692 type Iter = iter::Cloned<Successors<'b>>;
2695 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2696 pub struct Location {
2697 /// The block that the location is within.
2698 pub block: BasicBlock,
2700 /// The location is the position of the start of the statement; or, if
2701 /// `statement_index` equals the number of statements, then the start of the
2703 pub statement_index: usize,
2706 impl fmt::Debug for Location {
2707 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2708 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2713 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2715 /// Returns the location immediately after this one within the enclosing block.
2717 /// Note that if this location represents a terminator, then the
2718 /// resulting location would be out of bounds and invalid.
2719 pub fn successor_within_block(&self) -> Location {
2720 Location { block: self.block, statement_index: self.statement_index + 1 }
2723 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2724 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2725 // If we are in the same block as the other location and are an earlier statement
2726 // then we are a predecessor of `other`.
2727 if self.block == other.block && self.statement_index < other.statement_index {
2731 // If we're in another block, then we want to check that block is a predecessor of `other`.
2732 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2733 let mut visited = FxHashSet::default();
2735 while let Some(block) = queue.pop() {
2736 // If we haven't visited this block before, then make sure we visit it's predecessors.
2737 if visited.insert(block) {
2738 queue.extend(body.predecessors_for(block).iter().cloned());
2743 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2744 // we found that block by looking at the predecessors of `other`).
2745 if self.block == block {
2753 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2754 if self.block == other.block {
2755 self.statement_index <= other.statement_index
2757 dominators.is_dominated_by(other.block, self.block)
2762 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2763 pub enum UnsafetyViolationKind {
2765 /// Permitted both in `const fn`s and regular `fn`s.
2767 BorrowPacked(hir::HirId),
2770 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2771 pub struct UnsafetyViolation {
2772 pub source_info: SourceInfo,
2773 pub description: Symbol,
2774 pub details: Symbol,
2775 pub kind: UnsafetyViolationKind,
2778 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2779 pub struct UnsafetyCheckResult {
2780 /// Violations that are propagated *upwards* from this function.
2781 pub violations: Lrc<[UnsafetyViolation]>,
2782 /// `unsafe` blocks in this function, along with whether they are used. This is
2783 /// used for the "unused_unsafe" lint.
2784 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2787 rustc_index::newtype_index! {
2788 pub struct GeneratorSavedLocal {
2790 DEBUG_FORMAT = "_{}",
2794 /// The layout of generator state.
2795 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2796 pub struct GeneratorLayout<'tcx> {
2797 /// The type of every local stored inside the generator.
2798 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2800 /// Which of the above fields are in each variant. Note that one field may
2801 /// be stored in multiple variants.
2802 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2804 /// Which saved locals are storage-live at the same time. Locals that do not
2805 /// have conflicts with each other are allowed to overlap in the computed
2807 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2810 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2811 pub struct BorrowCheckResult<'tcx> {
2812 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2813 pub used_mut_upvars: SmallVec<[Field; 8]>,
2816 /// The result of the `mir_const_qualif` query.
2818 /// Each field corresponds to an implementer of the `Qualif` trait in
2819 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2821 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2822 pub struct ConstQualifs {
2823 pub has_mut_interior: bool,
2824 pub needs_drop: bool,
2827 /// After we borrow check a closure, we are left with various
2828 /// requirements that we have inferred between the free regions that
2829 /// appear in the closure's signature or on its field types. These
2830 /// requirements are then verified and proved by the closure's
2831 /// creating function. This struct encodes those requirements.
2833 /// The requirements are listed as being between various
2834 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2835 /// vids refer to the free regions that appear in the closure (or
2836 /// generator's) type, in order of appearance. (This numbering is
2837 /// actually defined by the `UniversalRegions` struct in the NLL
2838 /// region checker. See for example
2839 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2840 /// regions in the closure's type "as if" they were erased, so their
2841 /// precise identity is not important, only their position.
2843 /// Example: If type check produces a closure with the closure substs:
2846 /// ClosureSubsts = [
2847 /// i8, // the "closure kind"
2848 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2849 /// &'a String, // some upvar
2853 /// here, there is one unique free region (`'a`) but it appears
2854 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2857 /// ClosureSubsts = [
2858 /// i8, // the "closure kind"
2859 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2860 /// &'2 String, // some upvar
2864 /// Now the code might impose a requirement like `'1: '2`. When an
2865 /// instance of the closure is created, the corresponding free regions
2866 /// can be extracted from its type and constrained to have the given
2867 /// outlives relationship.
2869 /// In some cases, we have to record outlives requirements between
2870 /// types and regions as well. In that case, if those types include
2871 /// any regions, those regions are recorded as `ReClosureBound`
2872 /// instances assigned one of these same indices. Those regions will
2873 /// be substituted away by the creator. We use `ReClosureBound` in
2874 /// that case because the regions must be allocated in the global
2875 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2876 /// internally within the rest of the NLL code).
2877 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2878 pub struct ClosureRegionRequirements<'tcx> {
2879 /// The number of external regions defined on the closure. In our
2880 /// example above, it would be 3 -- one for `'static`, then `'1`
2881 /// and `'2`. This is just used for a sanity check later on, to
2882 /// make sure that the number of regions we see at the callsite
2884 pub num_external_vids: usize,
2886 /// Requirements between the various free regions defined in
2888 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2891 /// Indicates an outlives-constraint between a type or between two
2892 /// free regions declared on the closure.
2893 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2894 pub struct ClosureOutlivesRequirement<'tcx> {
2895 // This region or type ...
2896 pub subject: ClosureOutlivesSubject<'tcx>,
2898 // ... must outlive this one.
2899 pub outlived_free_region: ty::RegionVid,
2901 // If not, report an error here ...
2902 pub blame_span: Span,
2904 // ... due to this reason.
2905 pub category: ConstraintCategory,
2908 /// Outlives-constraints can be categorized to determine whether and why they
2909 /// are interesting (for error reporting). Order of variants indicates sort
2910 /// order of the category, thereby influencing diagnostic output.
2912 /// See also [rustc_mir::borrow_check::nll::constraints].
2926 pub enum ConstraintCategory {
2934 /// A constraint that came from checking the body of a closure.
2936 /// We try to get the category that the closure used when reporting this.
2944 /// A "boring" constraint (caused by the given location) is one that
2945 /// the user probably doesn't want to see described in diagnostics,
2946 /// because it is kind of an artifact of the type system setup.
2947 /// Example: `x = Foo { field: y }` technically creates
2948 /// intermediate regions representing the "type of `Foo { field: y
2949 /// }`", and data flows from `y` into those variables, but they
2950 /// are not very interesting. The assignment into `x` on the other
2953 // Boring and applicable everywhere.
2956 /// A constraint that doesn't correspond to anything the user sees.
2960 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2961 /// that must outlive some region.
2962 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2963 pub enum ClosureOutlivesSubject<'tcx> {
2964 /// Subject is a type, typically a type parameter, but could also
2965 /// be a projection. Indicates a requirement like `T: 'a` being
2966 /// passed to the caller, where the type here is `T`.
2968 /// The type here is guaranteed not to contain any free regions at
2972 /// Subject is a free region from the closure. Indicates a requirement
2973 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2974 Region(ty::RegionVid),
2978 * `TypeFoldable` implementations for MIR types
2981 CloneTypeFoldableAndLiftImpls! {
2990 SourceScopeLocalData,
2991 UserTypeAnnotationIndex,
2994 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2995 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2996 use crate::mir::TerminatorKind::*;
2998 let kind = match self.kind {
2999 Goto { target } => Goto { target },
3000 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
3001 discr: discr.fold_with(folder),
3002 switch_ty: switch_ty.fold_with(folder),
3003 values: values.clone(),
3004 targets: targets.clone(),
3006 Drop { ref location, target, unwind } => {
3007 Drop { location: location.fold_with(folder), target, unwind }
3009 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
3010 location: location.fold_with(folder),
3011 value: value.fold_with(folder),
3015 Yield { ref value, resume, drop } => {
3016 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3018 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3020 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3023 func: func.fold_with(folder),
3024 args: args.fold_with(folder),
3030 Assert { ref cond, expected, ref msg, target, cleanup } => {
3032 let msg = match msg {
3033 BoundsCheck { ref len, ref index } =>
3035 len: len.fold_with(folder),
3036 index: index.fold_with(folder),
3038 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3039 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3042 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3044 GeneratorDrop => GeneratorDrop,
3048 Unreachable => Unreachable,
3049 FalseEdges { real_target, imaginary_target } => {
3050 FalseEdges { real_target, imaginary_target }
3052 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3054 Terminator { source_info: self.source_info, kind }
3057 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3058 use crate::mir::TerminatorKind::*;
3061 SwitchInt { ref discr, switch_ty, .. } => {
3062 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3064 Drop { ref location, .. } => location.visit_with(visitor),
3065 DropAndReplace { ref location, ref value, .. } => {
3066 location.visit_with(visitor) || value.visit_with(visitor)
3068 Yield { ref value, .. } => value.visit_with(visitor),
3069 Call { ref func, ref args, ref destination, .. } => {
3070 let dest = if let Some((ref loc, _)) = *destination {
3071 loc.visit_with(visitor)
3075 dest || func.visit_with(visitor) || args.visit_with(visitor)
3077 Assert { ref cond, ref msg, .. } => {
3078 if cond.visit_with(visitor) {
3081 BoundsCheck { ref len, ref index } =>
3082 len.visit_with(visitor) || index.visit_with(visitor),
3083 Panic { .. } | Overflow(_) | OverflowNeg |
3084 DivisionByZero | RemainderByZero |
3085 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3099 | FalseUnwind { .. } => false,
3104 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
3105 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3109 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3114 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3115 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3117 base: self.base.fold_with(folder),
3118 projection: self.projection.fold_with(folder),
3122 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3123 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3127 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3128 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3130 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3131 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3135 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3137 PlaceBase::Local(local) => local.visit_with(visitor),
3138 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3143 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3144 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3145 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3146 folder.tcx().intern_place_elems(&v)
3149 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3150 self.iter().any(|t| t.visit_with(visitor))
3154 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3155 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3157 ty: self.ty.fold_with(folder),
3158 kind: self.kind.fold_with(folder),
3159 def_id: self.def_id,
3163 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3164 let Static { ty, kind, def_id: _ } = self;
3166 ty.visit_with(visitor) || kind.visit_with(visitor)
3170 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3171 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3173 StaticKind::Promoted(promoted, substs) =>
3174 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3175 StaticKind::Static => StaticKind::Static
3179 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3181 StaticKind::Promoted(promoted, substs) =>
3182 promoted.visit_with(visitor) || substs.visit_with(visitor),
3183 StaticKind::Static => { false }
3188 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3189 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3190 use crate::mir::Rvalue::*;
3192 Use(ref op) => Use(op.fold_with(folder)),
3193 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3194 Ref(region, bk, ref place) => {
3195 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3197 Len(ref place) => Len(place.fold_with(folder)),
3198 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3199 BinaryOp(op, ref rhs, ref lhs) => {
3200 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3202 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3203 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3205 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3206 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3207 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3208 Aggregate(ref kind, ref fields) => {
3209 let kind = box match **kind {
3210 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3211 AggregateKind::Tuple => AggregateKind::Tuple,
3212 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3215 substs.fold_with(folder),
3216 user_ty.fold_with(folder),
3219 AggregateKind::Closure(id, substs) => {
3220 AggregateKind::Closure(id, substs.fold_with(folder))
3222 AggregateKind::Generator(id, substs, movablity) => {
3223 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3226 Aggregate(kind, fields.fold_with(folder))
3231 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3232 use crate::mir::Rvalue::*;
3234 Use(ref op) => op.visit_with(visitor),
3235 Repeat(ref op, _) => op.visit_with(visitor),
3236 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3237 Len(ref place) => place.visit_with(visitor),
3238 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3239 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3240 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3242 UnaryOp(_, ref val) => val.visit_with(visitor),
3243 Discriminant(ref place) => place.visit_with(visitor),
3244 NullaryOp(_, ty) => ty.visit_with(visitor),
3245 Aggregate(ref kind, ref fields) => {
3247 AggregateKind::Array(ty) => ty.visit_with(visitor),
3248 AggregateKind::Tuple => false,
3249 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3250 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3252 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3253 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3254 }) || fields.visit_with(visitor)
3260 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3261 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3263 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3264 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3265 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3269 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3271 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3272 Operand::Constant(ref c) => c.visit_with(visitor),
3277 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3278 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3279 use crate::mir::ProjectionElem::*;
3283 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3284 Index(v) => Index(v.fold_with(folder)),
3285 elem => elem.clone(),
3289 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3290 use crate::mir::ProjectionElem::*;
3293 Field(_, ty) => ty.visit_with(visitor),
3294 Index(v) => v.visit_with(visitor),
3300 impl<'tcx> TypeFoldable<'tcx> for Field {
3301 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3304 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3309 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3310 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3313 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3318 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3319 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3322 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3327 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3328 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3330 span: self.span.clone(),
3331 user_ty: self.user_ty.fold_with(folder),
3332 literal: self.literal.fold_with(folder),
3335 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3336 self.literal.visit_with(visitor)