1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
5 use crate::mir::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{Allocation, ConstValue, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{Subst, SubstsRef};
14 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
17 use rustc_hir::def::{CtorKind, Namespace};
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::{self, GeneratorKind};
20 use rustc_target::abi::VariantIdx;
22 use polonius_engine::Atom;
23 pub use rustc_ast::Mutability;
24 use rustc_data_structures::fx::FxHashSet;
25 use rustc_data_structures::graph::dominators::{dominators, Dominators};
26 use rustc_data_structures::graph::{self, GraphSuccessors};
27 use rustc_index::bit_set::BitMatrix;
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_serialize::{Decodable, Encodable};
30 use rustc_span::symbol::Symbol;
31 use rustc_span::{Span, DUMMY_SP};
32 use rustc_target::abi;
33 use rustc_target::asm::InlineAsmRegOrRegClass;
35 use std::fmt::{self, Debug, Display, Formatter, Write};
36 use std::ops::{Index, IndexMut};
38 use std::{iter, mem, option};
40 use self::predecessors::{PredecessorCache, Predecessors};
41 pub use self::query::*;
50 pub use terminator::*;
56 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
58 pub trait HasLocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx>;
62 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
63 fn local_decls(&self) -> &LocalDecls<'tcx> {
68 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
69 fn local_decls(&self) -> &LocalDecls<'tcx> {
74 /// The various "big phases" that MIR goes through.
76 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
77 /// dialects forbid certain variants or values in certain phases.
79 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
80 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
82 /// Warning: ordering of variants is significant.
83 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
87 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
88 // We used to have this for pre-miri MIR based const eval.
90 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
91 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
92 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
96 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
97 /// * `DropAndReplace` is gone for good
98 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
99 /// means that the auto-generated drop glue will be invoked.
101 /// After this phase, generators are explicit state machines (no more `Yield`).
102 /// `AggregateKind::Generator` is gone for good.
103 GeneratorLowering = 4,
108 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
109 pub fn phase_index(&self) -> usize {
114 /// The lowered representation of a single function.
115 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
116 pub struct Body<'tcx> {
117 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
118 /// that indexes into this vector.
119 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
121 /// Records how far through the "desugaring and optimization" process this particular
122 /// MIR has traversed. This is particularly useful when inlining, since in that context
123 /// we instantiate the promoted constants and add them to our promoted vector -- but those
124 /// promoted items have already been optimized, whereas ours have not. This field allows
125 /// us to see the difference and forego optimization on the inlined promoted items.
128 /// A list of source scopes; these are referenced by statements
129 /// and used for debuginfo. Indexed by a `SourceScope`.
130 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
132 /// The yield type of the function, if it is a generator.
133 pub yield_ty: Option<Ty<'tcx>>,
135 /// Generator drop glue.
136 pub generator_drop: Option<Box<Body<'tcx>>>,
138 /// The layout of a generator. Produced by the state transformation.
139 pub generator_layout: Option<GeneratorLayout<'tcx>>,
141 /// If this is a generator then record the type of source expression that caused this generator
143 pub generator_kind: Option<GeneratorKind>,
145 /// Declarations of locals.
147 /// The first local is the return value pointer, followed by `arg_count`
148 /// locals for the function arguments, followed by any user-declared
149 /// variables and temporaries.
150 pub local_decls: LocalDecls<'tcx>,
152 /// User type annotations.
153 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
155 /// The number of arguments this function takes.
157 /// Starting at local 1, `arg_count` locals will be provided by the caller
158 /// and can be assumed to be initialized.
160 /// If this MIR was built for a constant, this will be 0.
161 pub arg_count: usize,
163 /// Mark an argument local (which must be a tuple) as getting passed as
164 /// its individual components at the LLVM level.
166 /// This is used for the "rust-call" ABI.
167 pub spread_arg: Option<Local>,
169 /// Debug information pertaining to user variables, including captures.
170 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
172 /// A span representing this MIR, for error reporting.
175 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
176 /// We hold in this field all the constants we are not able to evaluate yet.
177 pub required_consts: Vec<Constant<'tcx>>,
179 /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
180 /// we'd statically know that no thing with interior mutability will ever be available to the
181 /// user without some serious unsafe code. Now this means that our promoted is actually
182 /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
183 /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
184 /// interior mutability. This flag just makes this situation very obvious where the previous
185 /// implementation without the flag hid this situation silently.
186 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
187 pub ignore_interior_mut_in_const_validation: bool,
189 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
191 /// Note that this does not actually mean that this body is not computable right now.
192 /// The repeat count in the following example is polymorphic, but can still be evaluated
193 /// without knowing anything about the type parameter `T`.
197 /// let _ = [0; std::mem::size_of::<*mut T>()];
201 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
202 /// removed the last mention of all generic params. We do not want to rely on optimizations and
203 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
204 pub is_polymorphic: bool,
206 predecessor_cache: PredecessorCache,
209 impl<'tcx> Body<'tcx> {
211 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
212 source_scopes: IndexVec<SourceScope, SourceScopeData>,
213 local_decls: LocalDecls<'tcx>,
214 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
216 var_debug_info: Vec<VarDebugInfo<'tcx>>,
218 generator_kind: Option<GeneratorKind>,
220 // We need `arg_count` locals, and one for the return place.
222 local_decls.len() > arg_count,
223 "expected at least {} locals, got {}",
228 let mut body = Body {
229 phase: MirPhase::Build,
233 generator_drop: None,
234 generator_layout: None,
237 user_type_annotations,
242 required_consts: Vec::new(),
243 ignore_interior_mut_in_const_validation: false,
244 is_polymorphic: false,
245 predecessor_cache: PredecessorCache::new(),
247 body.is_polymorphic = body.has_param_types_or_consts();
251 /// Returns a partially initialized MIR body containing only a list of basic blocks.
253 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
254 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
256 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
257 let mut body = Body {
258 phase: MirPhase::Build,
260 source_scopes: IndexVec::new(),
262 generator_drop: None,
263 generator_layout: None,
264 local_decls: IndexVec::new(),
265 user_type_annotations: IndexVec::new(),
269 required_consts: Vec::new(),
270 generator_kind: None,
271 var_debug_info: Vec::new(),
272 ignore_interior_mut_in_const_validation: false,
273 is_polymorphic: false,
274 predecessor_cache: PredecessorCache::new(),
276 body.is_polymorphic = body.has_param_types_or_consts();
281 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
286 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
287 // Because the user could mutate basic block terminators via this reference, we need to
288 // invalidate the predecessor cache.
290 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
291 // invalidate the predecessor cache.
292 self.predecessor_cache.invalidate();
293 &mut self.basic_blocks
297 pub fn basic_blocks_and_local_decls_mut(
299 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
300 self.predecessor_cache.invalidate();
301 (&mut self.basic_blocks, &mut self.local_decls)
305 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
308 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
309 &mut LocalDecls<'tcx>,
310 &mut Vec<VarDebugInfo<'tcx>>,
312 self.predecessor_cache.invalidate();
313 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
316 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
318 pub fn is_cfg_cyclic(&self) -> bool {
319 graph::is_cyclic(self)
323 pub fn local_kind(&self, local: Local) -> LocalKind {
324 let index = local.as_usize();
327 self.local_decls[local].mutability == Mutability::Mut,
328 "return place should be mutable"
331 LocalKind::ReturnPointer
332 } else if index < self.arg_count + 1 {
334 } else if self.local_decls[local].is_user_variable() {
341 /// Returns an iterator over all temporaries.
343 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
344 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
345 let local = Local::new(index);
346 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
350 /// Returns an iterator over all user-declared locals.
352 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
353 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
354 let local = Local::new(index);
355 self.local_decls[local].is_user_variable().then_some(local)
359 /// Returns an iterator over all user-declared mutable locals.
361 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
362 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
363 let local = Local::new(index);
364 let decl = &self.local_decls[local];
365 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
373 /// Returns an iterator over all user-declared mutable arguments and locals.
375 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
376 (1..self.local_decls.len()).filter_map(move |index| {
377 let local = Local::new(index);
378 let decl = &self.local_decls[local];
379 if (decl.is_user_variable() || index < self.arg_count + 1)
380 && decl.mutability == Mutability::Mut
389 /// Returns an iterator over all function arguments.
391 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
392 let arg_count = self.arg_count;
393 (1..arg_count + 1).map(Local::new)
396 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
397 /// locals that are neither arguments nor the return place).
399 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
400 let arg_count = self.arg_count;
401 let local_count = self.local_decls.len();
402 (arg_count + 1..local_count).map(Local::new)
405 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
406 /// invalidating statement indices in `Location`s.
407 pub fn make_statement_nop(&mut self, location: Location) {
408 let block = &mut self.basic_blocks[location.block];
409 debug_assert!(location.statement_index < block.statements.len());
410 block.statements[location.statement_index].make_nop()
413 /// Returns the source info associated with `location`.
414 pub fn source_info(&self, location: Location) -> &SourceInfo {
415 let block = &self[location.block];
416 let stmts = &block.statements;
417 let idx = location.statement_index;
418 if idx < stmts.len() {
419 &stmts[idx].source_info
421 assert_eq!(idx, stmts.len());
422 &block.terminator().source_info
426 /// Checks if `sub` is a sub scope of `sup`
427 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
429 match self.source_scopes[sub].parent_scope {
430 None => return false,
437 /// Returns the return type; it always return first element from `local_decls` array.
439 pub fn return_ty(&self) -> Ty<'tcx> {
440 self.local_decls[RETURN_PLACE].ty
443 /// Gets the location of the terminator for the given block.
445 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
446 Location { block: bb, statement_index: self[bb].statements.len() }
450 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
451 self.predecessor_cache.compute(&self.basic_blocks)
455 pub fn dominators(&self) -> Dominators<BasicBlock> {
460 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
463 /// Unsafe because of a PushUnsafeBlock
465 /// Unsafe because of an unsafe fn
467 /// Unsafe because of an `unsafe` block
468 ExplicitUnsafe(hir::HirId),
471 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
472 type Output = BasicBlockData<'tcx>;
475 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
476 &self.basic_blocks()[index]
480 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
482 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
483 &mut self.basic_blocks_mut()[index]
487 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
488 pub enum ClearCrossCrate<T> {
493 impl<T> ClearCrossCrate<T> {
494 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
496 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
497 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
501 pub fn assert_crate_local(self) -> T {
503 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
504 ClearCrossCrate::Set(v) => v,
509 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
510 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
512 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
514 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
515 if E::CLEAR_CROSS_CRATE {
520 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
521 ClearCrossCrate::Set(ref val) => {
522 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
528 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
530 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
531 if D::CLEAR_CROSS_CRATE {
532 return Ok(ClearCrossCrate::Clear);
535 let discr = u8::decode(d)?;
538 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
539 TAG_CLEAR_CROSS_CRATE_SET => {
540 let val = T::decode(d)?;
541 Ok(ClearCrossCrate::Set(val))
543 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
548 /// Grouped information about the source code origin of a MIR entity.
549 /// Intended to be inspected by diagnostics and debuginfo.
550 /// Most passes can work with it as a whole, within a single function.
551 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
552 // `Hash`. Please ping @bjorn3 if removing them.
553 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
554 pub struct SourceInfo {
555 /// The source span for the AST pertaining to this MIR entity.
558 /// The source scope, keeping track of which bindings can be
559 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
560 pub scope: SourceScope,
565 pub fn outermost(span: Span) -> Self {
566 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
570 ///////////////////////////////////////////////////////////////////////////
573 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
574 #[derive(HashStable)]
575 pub enum BorrowKind {
576 /// Data must be immutable and is aliasable.
579 /// The immediately borrowed place must be immutable, but projections from
580 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
581 /// conflict with a mutable borrow of `a.b.c`.
583 /// This is used when lowering matches: when matching on a place we want to
584 /// ensure that place have the same value from the start of the match until
585 /// an arm is selected. This prevents this code from compiling:
587 /// let mut x = &Some(0);
590 /// Some(_) if { x = &None; false } => (),
594 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
595 /// should not prevent `if let None = x { ... }`, for example, because the
596 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
597 /// We can also report errors with this kind of borrow differently.
600 /// Data must be immutable but not aliasable. This kind of borrow
601 /// cannot currently be expressed by the user and is used only in
602 /// implicit closure bindings. It is needed when the closure is
603 /// borrowing or mutating a mutable referent, e.g.:
605 /// let x: &mut isize = ...;
606 /// let y = || *x += 5;
608 /// If we were to try to translate this closure into a more explicit
609 /// form, we'd encounter an error with the code as written:
611 /// struct Env { x: & &mut isize }
612 /// let x: &mut isize = ...;
613 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
614 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
616 /// This is then illegal because you cannot mutate an `&mut` found
617 /// in an aliasable location. To solve, you'd have to translate with
618 /// an `&mut` borrow:
620 /// struct Env { x: & &mut isize }
621 /// let x: &mut isize = ...;
622 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
623 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
625 /// Now the assignment to `**env.x` is legal, but creating a
626 /// mutable pointer to `x` is not because `x` is not mutable. We
627 /// could fix this by declaring `x` as `let mut x`. This is ok in
628 /// user code, if awkward, but extra weird for closures, since the
629 /// borrow is hidden.
631 /// So we introduce a "unique imm" borrow -- the referent is
632 /// immutable, but not aliasable. This solves the problem. For
633 /// simplicity, we don't give users the way to express this
634 /// borrow, it's just used when translating closures.
637 /// Data is mutable and not aliasable.
639 /// `true` if this borrow arose from method-call auto-ref
640 /// (i.e., `adjustment::Adjust::Borrow`).
641 allow_two_phase_borrow: bool,
646 pub fn allows_two_phase_borrow(&self) -> bool {
648 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
649 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
654 ///////////////////////////////////////////////////////////////////////////
655 // Variables and temps
657 rustc_index::newtype_index! {
660 DEBUG_FORMAT = "_{}",
661 const RETURN_PLACE = 0,
665 impl Atom for Local {
666 fn index(self) -> usize {
671 /// Classifies locals into categories. See `Body::local_kind`.
672 #[derive(PartialEq, Eq, Debug, HashStable)]
674 /// User-declared variable binding.
676 /// Compiler-introduced temporary.
678 /// Function argument.
680 /// Location of function's return value.
684 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
685 pub struct VarBindingForm<'tcx> {
686 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
687 pub binding_mode: ty::BindingMode,
688 /// If an explicit type was provided for this variable binding,
689 /// this holds the source Span of that type.
691 /// NOTE: if you want to change this to a `HirId`, be wary that
692 /// doing so breaks incremental compilation (as of this writing),
693 /// while a `Span` does not cause our tests to fail.
694 pub opt_ty_info: Option<Span>,
695 /// Place of the RHS of the =, or the subject of the `match` where this
696 /// variable is initialized. None in the case of `let PATTERN;`.
697 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
698 /// (a) the right-hand side isn't evaluated as a place expression.
699 /// (b) it gives a way to separate this case from the remaining cases
701 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
702 /// The span of the pattern in which this variable was bound.
706 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
707 pub enum BindingForm<'tcx> {
708 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
709 Var(VarBindingForm<'tcx>),
710 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
711 ImplicitSelf(ImplicitSelfKind),
712 /// Reference used in a guard expression to ensure immutability.
716 /// Represents what type of implicit self a function has, if any.
717 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
718 pub enum ImplicitSelfKind {
719 /// Represents a `fn x(self);`.
721 /// Represents a `fn x(mut self);`.
723 /// Represents a `fn x(&self);`.
725 /// Represents a `fn x(&mut self);`.
727 /// Represents when a function does not have a self argument or
728 /// when a function has a `self: X` argument.
732 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
734 mod binding_form_impl {
735 use crate::ich::StableHashingContext;
736 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
738 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
739 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
740 use super::BindingForm::*;
741 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
744 Var(binding) => binding.hash_stable(hcx, hasher),
745 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
752 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
753 /// created during evaluation of expressions in a block tail
754 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
756 /// It is used to improve diagnostics when such temporaries are
757 /// involved in borrow_check errors, e.g., explanations of where the
758 /// temporaries come from, when their destructors are run, and/or how
759 /// one might revise the code to satisfy the borrow checker's rules.
760 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
761 pub struct BlockTailInfo {
762 /// If `true`, then the value resulting from evaluating this tail
763 /// expression is ignored by the block's expression context.
765 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
766 /// but not e.g., `let _x = { ...; tail };`
767 pub tail_result_is_ignored: bool,
769 /// `Span` of the tail expression.
775 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
776 /// argument, or the return place.
777 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
778 pub struct LocalDecl<'tcx> {
779 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
781 /// Temporaries and the return place are always mutable.
782 pub mutability: Mutability,
784 // FIXME(matthewjasper) Don't store in this in `Body`
785 pub local_info: Option<Box<LocalInfo<'tcx>>>,
787 /// `true` if this is an internal local.
789 /// These locals are not based on types in the source code and are only used
790 /// for a few desugarings at the moment.
792 /// The generator transformation will sanity check the locals which are live
793 /// across a suspension point against the type components of the generator
794 /// which type checking knows are live across a suspension point. We need to
795 /// flag drop flags to avoid triggering this check as they are introduced
798 /// Unsafety checking will also ignore dereferences of these locals,
799 /// so they can be used for raw pointers only used in a desugaring.
801 /// This should be sound because the drop flags are fully algebraic, and
802 /// therefore don't affect the OIBIT or outlives properties of the
806 /// If this local is a temporary and `is_block_tail` is `Some`,
807 /// then it is a temporary created for evaluation of some
808 /// subexpression of some block's tail expression (with no
809 /// intervening statement context).
810 // FIXME(matthewjasper) Don't store in this in `Body`
811 pub is_block_tail: Option<BlockTailInfo>,
813 /// The type of this local.
816 /// If the user manually ascribed a type to this variable,
817 /// e.g., via `let x: T`, then we carry that type here. The MIR
818 /// borrow checker needs this information since it can affect
819 /// region inference.
820 // FIXME(matthewjasper) Don't store in this in `Body`
821 pub user_ty: Option<Box<UserTypeProjections>>,
823 /// The *syntactic* (i.e., not visibility) source scope the local is defined
824 /// in. If the local was defined in a let-statement, this
825 /// is *within* the let-statement, rather than outside
828 /// This is needed because the visibility source scope of locals within
829 /// a let-statement is weird.
831 /// The reason is that we want the local to be *within* the let-statement
832 /// for lint purposes, but we want the local to be *after* the let-statement
833 /// for names-in-scope purposes.
835 /// That's it, if we have a let-statement like the one in this
839 /// fn foo(x: &str) {
840 /// #[allow(unused_mut)]
841 /// let mut x: u32 = { // <- one unused mut
842 /// let mut y: u32 = x.parse().unwrap();
849 /// Then, from a lint point of view, the declaration of `x: u32`
850 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
851 /// lint scopes are the same as the AST/HIR nesting.
853 /// However, from a name lookup point of view, the scopes look more like
854 /// as if the let-statements were `match` expressions:
857 /// fn foo(x: &str) {
859 /// match x.parse().unwrap() {
868 /// We care about the name-lookup scopes for debuginfo - if the
869 /// debuginfo instruction pointer is at the call to `x.parse()`, we
870 /// want `x` to refer to `x: &str`, but if it is at the call to
871 /// `drop(x)`, we want it to refer to `x: u32`.
873 /// To allow both uses to work, we need to have more than a single scope
874 /// for a local. We have the `source_info.scope` represent the "syntactic"
875 /// lint scope (with a variable being under its let block) while the
876 /// `var_debug_info.source_info.scope` represents the "local variable"
877 /// scope (where the "rest" of a block is under all prior let-statements).
879 /// The end result looks like this:
883 /// │{ argument x: &str }
885 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
886 /// │ │ // in practice because I'm lazy.
888 /// │ │← x.source_info.scope
889 /// │ │← `x.parse().unwrap()`
891 /// │ │ │← y.source_info.scope
893 /// │ │ │{ let y: u32 }
895 /// │ │ │← y.var_debug_info.source_info.scope
898 /// │ │{ let x: u32 }
899 /// │ │← x.var_debug_info.source_info.scope
900 /// │ │← `drop(x)` // This accesses `x: u32`.
902 pub source_info: SourceInfo,
905 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
906 #[cfg(target_arch = "x86_64")]
907 static_assert_size!(LocalDecl<'_>, 56);
909 /// Extra information about a some locals that's used for diagnostics and for
910 /// classifying variables into local variables, statics, etc, which is needed e.g.
911 /// for unsafety checking.
913 /// Not used for non-StaticRef temporaries, the return place, or anonymous
914 /// function parameters.
915 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
916 pub enum LocalInfo<'tcx> {
917 /// A user-defined local variable or function parameter
919 /// The `BindingForm` is solely used for local diagnostics when generating
920 /// warnings/errors when compiling the current crate, and therefore it need
921 /// not be visible across crates.
922 User(ClearCrossCrate<BindingForm<'tcx>>),
923 /// A temporary created that references the static with the given `DefId`.
924 StaticRef { def_id: DefId, is_thread_local: bool },
925 /// A temporary created that references the const with the given `DefId`
926 ConstRef { def_id: DefId },
929 impl<'tcx> LocalDecl<'tcx> {
930 /// Returns `true` only if local is a binding that can itself be
931 /// made mutable via the addition of the `mut` keyword, namely
932 /// something like the occurrences of `x` in:
933 /// - `fn foo(x: Type) { ... }`,
935 /// - or `match ... { C(x) => ... }`
936 pub fn can_be_made_mutable(&self) -> bool {
937 match self.local_info {
938 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
939 binding_mode: ty::BindingMode::BindByValue(_),
945 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
946 ImplicitSelfKind::Imm,
953 /// Returns `true` if local is definitely not a `ref ident` or
954 /// `ref mut ident` binding. (Such bindings cannot be made into
955 /// mutable bindings, but the inverse does not necessarily hold).
956 pub fn is_nonref_binding(&self) -> bool {
957 match self.local_info {
958 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
959 binding_mode: ty::BindingMode::BindByValue(_),
965 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
971 /// Returns `true` if this variable is a named variable or function
972 /// parameter declared by the user.
974 pub fn is_user_variable(&self) -> bool {
975 match self.local_info {
976 Some(box LocalInfo::User(_)) => true,
981 /// Returns `true` if this is a reference to a variable bound in a `match`
982 /// expression that is used to access said variable for the guard of the
984 pub fn is_ref_for_guard(&self) -> bool {
985 match self.local_info {
986 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
991 /// Returns `Some` if this is a reference to a static item that is used to
992 /// access that static
993 pub fn is_ref_to_static(&self) -> bool {
994 match self.local_info {
995 Some(box LocalInfo::StaticRef { .. }) => true,
1000 /// Returns `Some` if this is a reference to a static item that is used to
1001 /// access that static
1002 pub fn is_ref_to_thread_local(&self) -> bool {
1003 match self.local_info {
1004 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1009 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1010 /// `__next` from a `for` loop.
1012 pub fn from_compiler_desugaring(&self) -> bool {
1013 self.source_info.span.desugaring_kind().is_some()
1016 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1018 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1019 Self::with_source_info(ty, SourceInfo::outermost(span))
1022 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1024 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1026 mutability: Mutability::Mut,
1029 is_block_tail: None,
1036 /// Converts `self` into same `LocalDecl` except tagged as internal.
1038 pub fn internal(mut self) -> Self {
1039 self.internal = true;
1043 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1045 pub fn immutable(mut self) -> Self {
1046 self.mutability = Mutability::Not;
1050 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1052 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1053 assert!(self.is_block_tail.is_none());
1054 self.is_block_tail = Some(info);
1059 /// Debug information pertaining to a user variable.
1060 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1061 pub struct VarDebugInfo<'tcx> {
1064 /// Source info of the user variable, including the scope
1065 /// within which the variable is visible (to debuginfo)
1066 /// (see `LocalDecl`'s `source_info` field for more details).
1067 pub source_info: SourceInfo,
1069 /// Where the data for this user variable is to be found.
1070 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1071 /// based on a `Local`, not a `Static`, and contains no indexing.
1072 pub place: Place<'tcx>,
1075 ///////////////////////////////////////////////////////////////////////////
1078 rustc_index::newtype_index! {
1079 /// The unit of the MIR [control-flow graph][CFG].
1081 /// There is no branching (e.g., `if`s, function calls, etc.) within a basic block, which makes
1082 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1083 /// as an edge in a graph between basic blocks.
1085 /// Basic blocks consist of a series of [statements][`Statement`], ending with a
1086 /// [terminator][`Terminator`]. Basic blocks can have multiple predecessors and successors.
1088 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1090 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1091 /// [data-flow analyses]:
1092 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1093 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1094 pub struct BasicBlock {
1096 DEBUG_FORMAT = "bb{}",
1097 const START_BLOCK = 0,
1102 pub fn start_location(self) -> Location {
1103 Location { block: self, statement_index: 0 }
1107 ///////////////////////////////////////////////////////////////////////////
1108 // BasicBlockData and Terminator
1110 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1111 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1112 pub struct BasicBlockData<'tcx> {
1113 /// List of statements in this block.
1114 pub statements: Vec<Statement<'tcx>>,
1116 /// Terminator for this block.
1118 /// N.B., this should generally ONLY be `None` during construction.
1119 /// Therefore, you should generally access it via the
1120 /// `terminator()` or `terminator_mut()` methods. The only
1121 /// exception is that certain passes, such as `simplify_cfg`, swap
1122 /// out the terminator temporarily with `None` while they continue
1123 /// to recurse over the set of basic blocks.
1124 pub terminator: Option<Terminator<'tcx>>,
1126 /// If true, this block lies on an unwind path. This is used
1127 /// during codegen where distinct kinds of basic blocks may be
1128 /// generated (particularly for MSVC cleanup). Unwind blocks must
1129 /// only branch to other unwind blocks.
1130 pub is_cleanup: bool,
1133 /// Information about an assertion failure.
1134 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1135 pub enum AssertKind<O> {
1136 BoundsCheck { len: O, index: O },
1137 Overflow(BinOp, O, O),
1141 ResumedAfterReturn(GeneratorKind),
1142 ResumedAfterPanic(GeneratorKind),
1145 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1146 pub enum InlineAsmOperand<'tcx> {
1148 reg: InlineAsmRegOrRegClass,
1149 value: Operand<'tcx>,
1152 reg: InlineAsmRegOrRegClass,
1154 place: Option<Place<'tcx>>,
1157 reg: InlineAsmRegOrRegClass,
1159 in_value: Operand<'tcx>,
1160 out_place: Option<Place<'tcx>>,
1163 value: Operand<'tcx>,
1166 value: Box<Constant<'tcx>>,
1173 /// Type for MIR `Assert` terminator error messages.
1174 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1176 pub type Successors<'a> =
1177 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1178 pub type SuccessorsMut<'a> =
1179 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1181 impl<'tcx> BasicBlockData<'tcx> {
1182 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1183 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1186 /// Accessor for terminator.
1188 /// Terminator may not be None after construction of the basic block is complete. This accessor
1189 /// provides a convenience way to reach the terminator.
1190 pub fn terminator(&self) -> &Terminator<'tcx> {
1191 self.terminator.as_ref().expect("invalid terminator state")
1194 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1195 self.terminator.as_mut().expect("invalid terminator state")
1198 pub fn retain_statements<F>(&mut self, mut f: F)
1200 F: FnMut(&mut Statement<'_>) -> bool,
1202 for s in &mut self.statements {
1209 pub fn expand_statements<F, I>(&mut self, mut f: F)
1211 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1212 I: iter::TrustedLen<Item = Statement<'tcx>>,
1214 // Gather all the iterators we'll need to splice in, and their positions.
1215 let mut splices: Vec<(usize, I)> = vec![];
1216 let mut extra_stmts = 0;
1217 for (i, s) in self.statements.iter_mut().enumerate() {
1218 if let Some(mut new_stmts) = f(s) {
1219 if let Some(first) = new_stmts.next() {
1220 // We can already store the first new statement.
1223 // Save the other statements for optimized splicing.
1224 let remaining = new_stmts.size_hint().0;
1226 splices.push((i + 1 + extra_stmts, new_stmts));
1227 extra_stmts += remaining;
1235 // Splice in the new statements, from the end of the block.
1236 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1237 // where a range of elements ("gap") is left uninitialized, with
1238 // splicing adding new elements to the end of that gap and moving
1239 // existing elements from before the gap to the end of the gap.
1240 // For now, this is safe code, emulating a gap but initializing it.
1241 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1242 self.statements.resize(
1244 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1246 for (splice_start, new_stmts) in splices.into_iter().rev() {
1247 let splice_end = splice_start + new_stmts.size_hint().0;
1248 while gap.end > splice_end {
1251 self.statements.swap(gap.start, gap.end);
1253 self.statements.splice(splice_start..splice_end, new_stmts);
1254 gap.end = splice_start;
1258 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1259 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1263 impl<O> AssertKind<O> {
1264 /// Getting a description does not require `O` to be printable, and does not
1265 /// require allocation.
1266 /// The caller is expected to handle `BoundsCheck` separately.
1267 pub fn description(&self) -> &'static str {
1270 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1271 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1272 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1273 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1274 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1275 OverflowNeg(_) => "attempt to negate with overflow",
1276 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1277 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1278 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1279 DivisionByZero(_) => "attempt to divide by zero",
1280 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1281 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1282 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1283 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1284 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1285 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1289 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1290 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1296 BoundsCheck { ref len, ref index } => write!(
1298 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1302 OverflowNeg(op) => {
1303 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1305 DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1306 RemainderByZero(op) => write!(
1308 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1311 Overflow(BinOp::Add, l, r) => write!(
1313 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1316 Overflow(BinOp::Sub, l, r) => write!(
1318 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1321 Overflow(BinOp::Mul, l, r) => write!(
1323 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1326 Overflow(BinOp::Div, l, r) => write!(
1328 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1331 Overflow(BinOp::Rem, l, r) => write!(
1333 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1336 Overflow(BinOp::Shr, _, r) => {
1337 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1339 Overflow(BinOp::Shl, _, r) => {
1340 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1342 _ => write!(f, "\"{}\"", self.description()),
1347 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1351 BoundsCheck { ref len, ref index } => {
1352 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1354 OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1355 DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1356 RemainderByZero(op) => {
1357 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1359 Overflow(BinOp::Add, l, r) => {
1360 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1362 Overflow(BinOp::Sub, l, r) => {
1363 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1365 Overflow(BinOp::Mul, l, r) => {
1366 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1368 Overflow(BinOp::Div, l, r) => {
1369 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1371 Overflow(BinOp::Rem, l, r) => write!(
1373 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1376 Overflow(BinOp::Shr, _, r) => {
1377 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1379 Overflow(BinOp::Shl, _, r) => {
1380 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1382 _ => write!(f, "{}", self.description()),
1387 ///////////////////////////////////////////////////////////////////////////
1390 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1391 pub struct Statement<'tcx> {
1392 pub source_info: SourceInfo,
1393 pub kind: StatementKind<'tcx>,
1396 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1397 #[cfg(target_arch = "x86_64")]
1398 static_assert_size!(Statement<'_>, 32);
1400 impl Statement<'_> {
1401 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1402 /// invalidating statement indices in `Location`s.
1403 pub fn make_nop(&mut self) {
1404 self.kind = StatementKind::Nop
1407 /// Changes a statement to a nop and returns the original statement.
1408 pub fn replace_nop(&mut self) -> Self {
1410 source_info: self.source_info,
1411 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1416 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1417 pub enum StatementKind<'tcx> {
1418 /// Write the RHS Rvalue to the LHS Place.
1419 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1421 /// This represents all the reading that a pattern match may do
1422 /// (e.g., inspecting constants and discriminant values), and the
1423 /// kind of pattern it comes from. This is in order to adapt potential
1424 /// error messages to these specific patterns.
1426 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1427 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1428 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1430 /// Write the discriminant for a variant to the enum Place.
1431 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1433 /// Start a live range for the storage of the local.
1436 /// End the current live range for the storage of the local.
1439 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1440 /// of `StatementKind` low.
1441 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1443 /// Retag references in the given place, ensuring they got fresh tags. This is
1444 /// part of the Stacked Borrows model. These statements are currently only interpreted
1445 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1446 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1447 /// for more details.
1448 Retag(RetagKind, Box<Place<'tcx>>),
1450 /// Encodes a user's type ascription. These need to be preserved
1451 /// intact so that NLL can respect them. For example:
1455 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1456 /// to the user-given type `T`. The effect depends on the specified variance:
1458 /// - `Covariant` -- requires that `T_y <: T`
1459 /// - `Contravariant` -- requires that `T_y :> T`
1460 /// - `Invariant` -- requires that `T_y == T`
1461 /// - `Bivariant` -- no effect
1462 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1464 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1465 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1466 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1467 /// counter varible at runtime, each time the code region is executed.
1468 Coverage(Box<Coverage>),
1470 /// No-op. Useful for deleting instructions without affecting statement indices.
1474 impl<'tcx> StatementKind<'tcx> {
1475 pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1477 StatementKind::Assign(x) => Some(x),
1483 /// Describes what kind of retag is to be performed.
1484 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1485 pub enum RetagKind {
1486 /// The initial retag when entering a function.
1488 /// Retag preparing for a two-phase borrow.
1490 /// Retagging raw pointers.
1492 /// A "normal" retag.
1496 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1497 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1498 pub enum FakeReadCause {
1499 /// Inject a fake read of the borrowed input at the end of each guards
1502 /// This should ensure that you cannot change the variant for an enum while
1503 /// you are in the midst of matching on it.
1506 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1507 /// generate a read of x to check that it is initialized and safe.
1510 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1511 /// in a match guard to ensure that it's value hasn't change by the time
1512 /// we create the OutsideGuard version.
1515 /// Officially, the semantics of
1517 /// `let pattern = <expr>;`
1519 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1520 /// into the pattern.
1522 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1523 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1524 /// but in some cases it can affect the borrow checker, as in #53695.
1525 /// Therefore, we insert a "fake read" here to ensure that we get
1526 /// appropriate errors.
1529 /// If we have an index expression like
1531 /// (*x)[1][{ x = y; 4}]
1533 /// then the first bounds check is invalidated when we evaluate the second
1534 /// index expression. Thus we create a fake borrow of `x` across the second
1535 /// indexer, which will cause a borrow check error.
1539 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1540 pub struct LlvmInlineAsm<'tcx> {
1541 pub asm: hir::LlvmInlineAsmInner,
1542 pub outputs: Box<[Place<'tcx>]>,
1543 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1546 impl Debug for Statement<'_> {
1547 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1548 use self::StatementKind::*;
1550 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1551 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1552 Retag(ref kind, ref place) => write!(
1556 RetagKind::FnEntry => "[fn entry] ",
1557 RetagKind::TwoPhase => "[2phase] ",
1558 RetagKind::Raw => "[raw] ",
1559 RetagKind::Default => "",
1563 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1564 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1565 SetDiscriminant { ref place, variant_index } => {
1566 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1568 LlvmInlineAsm(ref asm) => {
1569 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1571 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1572 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1574 Coverage(box ref coverage) => {
1575 let rgn = &coverage.code_region;
1576 match coverage.kind {
1577 CoverageKind::Counter { id, .. } => {
1578 write!(fmt, "Coverage::Counter({:?}) for {:?}", id.index(), rgn)
1580 CoverageKind::Expression { id, lhs, op, rhs } => write!(
1582 "Coverage::Expression({:?}) = {} {} {} for {:?}",
1585 if op == coverage::Op::Add { "+" } else { "-" },
1589 CoverageKind::Unreachable => write!(fmt, "Coverage::Unreachable for {:?}", rgn),
1592 Nop => write!(fmt, "nop"),
1597 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1598 pub struct Coverage {
1599 pub kind: CoverageKind,
1600 pub code_region: CodeRegion,
1603 ///////////////////////////////////////////////////////////////////////////
1606 /// A path to a value; something that can be evaluated without
1607 /// changing or disturbing program state.
1608 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1609 pub struct Place<'tcx> {
1612 /// projection out of a place (access a field, deref a pointer, etc)
1613 pub projection: &'tcx List<PlaceElem<'tcx>>,
1616 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1617 #[derive(TyEncodable, TyDecodable, HashStable)]
1618 pub enum ProjectionElem<V, T> {
1623 /// These indices are generated by slice patterns. Easiest to explain
1627 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1628 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1629 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1630 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1633 /// index or -index (in Python terms), depending on from_end
1635 /// The thing being indexed must be at least this long. For arrays this
1636 /// is always the exact length.
1638 /// Counting backwards from end? This is always false when indexing an
1643 /// These indices are generated by slice patterns.
1645 /// If `from_end` is true `slice[from..slice.len() - to]`.
1646 /// Otherwise `array[from..to]`.
1650 /// Whether `to` counts from the start or end of the array/slice.
1651 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1652 /// For `ProjectionKind`, this can also be `true` for arrays.
1656 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1657 /// this for ADTs with more than one variant. It may be better to
1658 /// just introduce it always, or always for enums.
1660 /// The included Symbol is the name of the variant, used for printing MIR.
1661 Downcast(Option<Symbol>, VariantIdx),
1664 impl<V, T> ProjectionElem<V, T> {
1665 /// Returns `true` if the target of this projection may refer to a different region of memory
1667 fn is_indirect(&self) -> bool {
1669 Self::Deref => true,
1673 | Self::ConstantIndex { .. }
1674 | Self::Subslice { .. }
1675 | Self::Downcast(_, _) => false,
1680 /// Alias for projections as they appear in places, where the base is a place
1681 /// and the index is a local.
1682 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1684 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1685 #[cfg(target_arch = "x86_64")]
1686 static_assert_size!(PlaceElem<'_>, 24);
1688 /// Alias for projections as they appear in `UserTypeProjection`, where we
1689 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1690 pub type ProjectionKind = ProjectionElem<(), ()>;
1692 rustc_index::newtype_index! {
1695 DEBUG_FORMAT = "field[{}]"
1699 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1700 pub struct PlaceRef<'tcx> {
1702 pub projection: &'tcx [PlaceElem<'tcx>],
1705 impl<'tcx> Place<'tcx> {
1706 // FIXME change this to a const fn by also making List::empty a const fn.
1707 pub fn return_place() -> Place<'tcx> {
1708 Place { local: RETURN_PLACE, projection: List::empty() }
1711 /// Returns `true` if this `Place` contains a `Deref` projection.
1713 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1714 /// same region of memory as its base.
1715 pub fn is_indirect(&self) -> bool {
1716 self.projection.iter().any(|elem| elem.is_indirect())
1719 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1720 /// a single deref of a local.
1722 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1723 pub fn local_or_deref_local(&self) -> Option<Local> {
1724 match self.as_ref() {
1725 PlaceRef { local, projection: [] }
1726 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1731 /// If this place represents a local variable like `_X` with no
1732 /// projections, return `Some(_X)`.
1733 pub fn as_local(&self) -> Option<Local> {
1734 self.as_ref().as_local()
1737 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1738 PlaceRef { local: self.local, projection: &self.projection }
1742 impl From<Local> for Place<'_> {
1743 fn from(local: Local) -> Self {
1744 Place { local, projection: List::empty() }
1748 impl<'tcx> PlaceRef<'tcx> {
1749 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1750 /// a single deref of a local.
1752 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1753 pub fn local_or_deref_local(&self) -> Option<Local> {
1755 PlaceRef { local, projection: [] }
1756 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1761 /// If this place represents a local variable like `_X` with no
1762 /// projections, return `Some(_X)`.
1763 pub fn as_local(&self) -> Option<Local> {
1765 PlaceRef { local, projection: [] } => Some(local),
1771 impl Debug for Place<'_> {
1772 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1773 for elem in self.projection.iter().rev() {
1775 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1776 write!(fmt, "(").unwrap();
1778 ProjectionElem::Deref => {
1779 write!(fmt, "(*").unwrap();
1781 ProjectionElem::Index(_)
1782 | ProjectionElem::ConstantIndex { .. }
1783 | ProjectionElem::Subslice { .. } => {}
1787 write!(fmt, "{:?}", self.local)?;
1789 for elem in self.projection.iter() {
1791 ProjectionElem::Downcast(Some(name), _index) => {
1792 write!(fmt, " as {})", name)?;
1794 ProjectionElem::Downcast(None, index) => {
1795 write!(fmt, " as variant#{:?})", index)?;
1797 ProjectionElem::Deref => {
1800 ProjectionElem::Field(field, ty) => {
1801 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1803 ProjectionElem::Index(ref index) => {
1804 write!(fmt, "[{:?}]", index)?;
1806 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1807 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1809 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1810 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1812 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1813 write!(fmt, "[{:?}:]", from)?;
1815 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1816 write!(fmt, "[:-{:?}]", to)?;
1818 ProjectionElem::Subslice { from, to, from_end: true } => {
1819 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1821 ProjectionElem::Subslice { from, to, from_end: false } => {
1822 write!(fmt, "[{:?}..{:?}]", from, to)?;
1831 ///////////////////////////////////////////////////////////////////////////
1834 rustc_index::newtype_index! {
1835 pub struct SourceScope {
1837 DEBUG_FORMAT = "scope[{}]",
1838 const OUTERMOST_SOURCE_SCOPE = 0,
1842 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1843 pub struct SourceScopeData {
1845 pub parent_scope: Option<SourceScope>,
1847 /// Crate-local information for this source scope, that can't (and
1848 /// needn't) be tracked across crates.
1849 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1852 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1853 pub struct SourceScopeLocalData {
1854 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1855 pub lint_root: hir::HirId,
1856 /// The unsafe block that contains this node.
1860 ///////////////////////////////////////////////////////////////////////////
1863 /// These are values that can appear inside an rvalue. They are intentionally
1864 /// limited to prevent rvalues from being nested in one another.
1865 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1866 pub enum Operand<'tcx> {
1867 /// Copy: The value must be available for use afterwards.
1869 /// This implies that the type of the place must be `Copy`; this is true
1870 /// by construction during build, but also checked by the MIR type checker.
1873 /// Move: The value (including old borrows of it) will not be used again.
1875 /// Safe for values of all types (modulo future developments towards `?Move`).
1876 /// Correct usage patterns are enforced by the borrow checker for safe code.
1877 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1880 /// Synthesizes a constant value.
1881 Constant(Box<Constant<'tcx>>),
1884 impl<'tcx> Debug for Operand<'tcx> {
1885 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1886 use self::Operand::*;
1888 Constant(ref a) => write!(fmt, "{:?}", a),
1889 Copy(ref place) => write!(fmt, "{:?}", place),
1890 Move(ref place) => write!(fmt, "move {:?}", place),
1895 impl<'tcx> Operand<'tcx> {
1896 /// Convenience helper to make a constant that refers to the fn
1897 /// with given `DefId` and substs. Since this is used to synthesize
1898 /// MIR, assumes `user_ty` is None.
1899 pub fn function_handle(
1902 substs: SubstsRef<'tcx>,
1905 let ty = tcx.type_of(def_id).subst(tcx, substs);
1906 Operand::Constant(box Constant {
1909 literal: ty::Const::zero_sized(tcx, ty),
1913 pub fn is_move(&self) -> bool {
1914 matches!(self, Operand::Move(..))
1917 /// Convenience helper to make a literal-like constant from a given scalar value.
1918 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1919 pub fn const_from_scalar(
1924 ) -> Operand<'tcx> {
1926 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1928 .layout_of(param_env_and_ty)
1929 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1931 let scalar_size = abi::Size::from_bytes(match val {
1932 Scalar::Raw { size, .. } => size,
1933 _ => panic!("Invalid scalar type {:?}", val),
1935 scalar_size == type_size
1937 Operand::Constant(box Constant {
1940 literal: ty::Const::from_scalar(tcx, val, ty),
1944 /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1945 /// wraps a constant literal value. Panics if this is not the case.
1946 pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1948 Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1949 Some(scalar) => scalar,
1950 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1952 _ => panic!("{:?}: Constant expected", operand),
1956 /// Convenience helper to make a literal-like constant from a given `&str` slice.
1957 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1958 pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1960 let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1961 let allocation = tcx.intern_const_alloc(allocation);
1962 let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1963 let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1964 Operand::Constant(box Constant {
1967 literal: ty::Const::from_value(tcx, const_val, ty),
1971 /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1972 /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1973 pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1975 Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1976 Some(const_value) => const_value,
1977 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1979 _ => panic!("{:?}: Constant expected", operand),
1983 pub fn to_copy(&self) -> Self {
1985 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1986 Operand::Move(place) => Operand::Copy(place),
1990 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1992 pub fn place(&self) -> Option<Place<'tcx>> {
1994 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1995 Operand::Constant(_) => None,
1999 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2001 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2003 Operand::Constant(x) => Some(&**x),
2004 Operand::Copy(_) | Operand::Move(_) => None,
2009 ///////////////////////////////////////////////////////////////////////////
2012 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
2013 pub enum Rvalue<'tcx> {
2014 /// x (either a move or copy, depending on type of x)
2018 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2021 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2023 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2024 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2026 ThreadLocalRef(DefId),
2028 /// Create a raw pointer to the given place
2029 /// Can be generated by raw address of expressions (`&raw const x`),
2030 /// or when casting a reference to a raw pointer.
2031 AddressOf(Mutability, Place<'tcx>),
2033 /// length of a `[X]` or `[X;n]` value
2036 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2038 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2039 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2041 NullaryOp(NullOp, Ty<'tcx>),
2042 UnaryOp(UnOp, Operand<'tcx>),
2044 /// Read the discriminant of an ADT.
2046 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2047 /// be defined to return, say, a 0) if ADT is not an enum.
2048 Discriminant(Place<'tcx>),
2050 /// Creates an aggregate value, like a tuple or struct. This is
2051 /// only needed because we want to distinguish `dest = Foo { x:
2052 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2053 /// that `Foo` has a destructor. These rvalues can be optimized
2054 /// away after type-checking and before lowering.
2055 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2058 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2061 Pointer(PointerCast),
2064 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2065 pub enum AggregateKind<'tcx> {
2066 /// The type is of the element
2070 /// The second field is the variant index. It's equal to 0 for struct
2071 /// and union expressions. The fourth field is
2072 /// active field number and is present only for union expressions
2073 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2074 /// active field index would identity the field `c`
2075 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2077 Closure(DefId, SubstsRef<'tcx>),
2078 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2081 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2083 /// The `+` operator (addition)
2085 /// The `-` operator (subtraction)
2087 /// The `*` operator (multiplication)
2089 /// The `/` operator (division)
2091 /// The `%` operator (modulus)
2093 /// The `^` operator (bitwise xor)
2095 /// The `&` operator (bitwise and)
2097 /// The `|` operator (bitwise or)
2099 /// The `<<` operator (shift left)
2101 /// The `>>` operator (shift right)
2103 /// The `==` operator (equality)
2105 /// The `<` operator (less than)
2107 /// The `<=` operator (less than or equal to)
2109 /// The `!=` operator (not equal to)
2111 /// The `>=` operator (greater than or equal to)
2113 /// The `>` operator (greater than)
2115 /// The `ptr.offset` operator
2120 pub fn is_checkable(self) -> bool {
2123 Add | Sub | Mul | Shl | Shr => true,
2129 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2131 /// Returns the size of a value of that type
2133 /// Creates a new uninitialized box for a value of that type
2137 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2139 /// The `!` operator for logical inversion
2141 /// The `-` operator for negation
2145 impl<'tcx> Debug for Rvalue<'tcx> {
2146 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2147 use self::Rvalue::*;
2150 Use(ref place) => write!(fmt, "{:?}", place),
2151 Repeat(ref a, ref b) => {
2152 write!(fmt, "[{:?}; ", a)?;
2153 pretty_print_const(b, fmt, false)?;
2156 Len(ref a) => write!(fmt, "Len({:?})", a),
2157 Cast(ref kind, ref place, ref ty) => {
2158 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2160 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2161 CheckedBinaryOp(ref op, ref a, ref b) => {
2162 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2164 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2165 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2166 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2167 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2168 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2169 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2171 Ref(region, borrow_kind, ref place) => {
2172 let kind_str = match borrow_kind {
2173 BorrowKind::Shared => "",
2174 BorrowKind::Shallow => "shallow ",
2175 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2178 // When printing regions, add trailing space if necessary.
2179 let print_region = ty::tls::with(|tcx| {
2180 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2182 let region = if print_region {
2183 let mut region = region.to_string();
2184 if !region.is_empty() {
2189 // Do not even print 'static
2192 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2195 AddressOf(mutability, ref place) => {
2196 let kind_str = match mutability {
2197 Mutability::Mut => "mut",
2198 Mutability::Not => "const",
2201 write!(fmt, "&raw {} {:?}", kind_str, place)
2204 Aggregate(ref kind, ref places) => {
2205 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2206 let mut tuple_fmt = fmt.debug_tuple(name);
2207 for place in places {
2208 tuple_fmt.field(place);
2214 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2216 AggregateKind::Tuple => {
2217 if places.is_empty() {
2224 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2225 let variant_def = &adt_def.variants[variant];
2227 let name = ty::tls::with(|tcx| {
2228 let mut name = String::new();
2229 let substs = tcx.lift(&substs).expect("could not lift for printing");
2230 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2231 .print_def_path(variant_def.def_id, substs)?;
2235 match variant_def.ctor_kind {
2236 CtorKind::Const => fmt.write_str(&name),
2237 CtorKind::Fn => fmt_tuple(fmt, &name),
2238 CtorKind::Fictive => {
2239 let mut struct_fmt = fmt.debug_struct(&name);
2240 for (field, place) in variant_def.fields.iter().zip(places) {
2241 struct_fmt.field(&field.ident.as_str(), place);
2248 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2249 if let Some(def_id) = def_id.as_local() {
2250 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2251 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2252 let substs = tcx.lift(&substs).unwrap();
2255 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2258 let span = tcx.hir().span(hir_id);
2259 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2261 let mut struct_fmt = fmt.debug_struct(&name);
2263 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2264 for (&var_id, place) in upvars.keys().zip(places) {
2265 let var_name = tcx.hir().name(var_id);
2266 struct_fmt.field(&var_name.as_str(), place);
2272 write!(fmt, "[closure]")
2276 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2277 if let Some(def_id) = def_id.as_local() {
2278 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2279 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2280 let mut struct_fmt = fmt.debug_struct(&name);
2282 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2283 for (&var_id, place) in upvars.keys().zip(places) {
2284 let var_name = tcx.hir().name(var_id);
2285 struct_fmt.field(&var_name.as_str(), place);
2291 write!(fmt, "[generator]")
2300 ///////////////////////////////////////////////////////////////////////////
2303 /// Two constants are equal if they are the same constant. Note that
2304 /// this does not necessarily mean that they are "==" in Rust -- in
2305 /// particular one must be wary of `NaN`!
2307 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2308 pub struct Constant<'tcx> {
2311 /// Optional user-given type: for something like
2312 /// `collect::<Vec<_>>`, this would be present and would
2313 /// indicate that `Vec<_>` was explicitly specified.
2315 /// Needed for NLL to impose user-given type constraints.
2316 pub user_ty: Option<UserTypeAnnotationIndex>,
2318 pub literal: &'tcx ty::Const<'tcx>,
2321 impl Constant<'tcx> {
2322 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2323 match self.literal.val.try_to_scalar() {
2324 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2325 GlobalAlloc::Static(def_id) => {
2326 assert!(!tcx.is_thread_local_static(def_id));
2336 /// A collection of projections into user types.
2338 /// They are projections because a binding can occur a part of a
2339 /// parent pattern that has been ascribed a type.
2341 /// Its a collection because there can be multiple type ascriptions on
2342 /// the path from the root of the pattern down to the binding itself.
2347 /// struct S<'a>((i32, &'a str), String);
2348 /// let S((_, w): (i32, &'static str), _): S = ...;
2349 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2350 /// // --------------------------------- ^ (2)
2353 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2354 /// ascribed the type `(i32, &'static str)`.
2356 /// The highlights labelled `(2)` show the whole pattern being
2357 /// ascribed the type `S`.
2359 /// In this example, when we descend to `w`, we will have built up the
2360 /// following two projected types:
2362 /// * base: `S`, projection: `(base.0).1`
2363 /// * base: `(i32, &'static str)`, projection: `base.1`
2365 /// The first will lead to the constraint `w: &'1 str` (for some
2366 /// inferred region `'1`). The second will lead to the constraint `w:
2368 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2369 pub struct UserTypeProjections {
2370 pub contents: Vec<(UserTypeProjection, Span)>,
2373 impl<'tcx> UserTypeProjections {
2374 pub fn none() -> Self {
2375 UserTypeProjections { contents: vec![] }
2378 pub fn is_empty(&self) -> bool {
2379 self.contents.is_empty()
2382 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2383 UserTypeProjections { contents: projs.collect() }
2386 pub fn projections_and_spans(
2388 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2389 self.contents.iter()
2392 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2393 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2396 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2397 self.contents.push((user_ty.clone(), span));
2403 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2405 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2409 pub fn index(self) -> Self {
2410 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2413 pub fn subslice(self, from: u64, to: u64) -> Self {
2414 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2417 pub fn deref(self) -> Self {
2418 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2421 pub fn leaf(self, field: Field) -> Self {
2422 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2425 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2426 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2430 /// Encodes the effect of a user-supplied type annotation on the
2431 /// subcomponents of a pattern. The effect is determined by applying the
2432 /// given list of proejctions to some underlying base type. Often,
2433 /// the projection element list `projs` is empty, in which case this
2434 /// directly encodes a type in `base`. But in the case of complex patterns with
2435 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2436 /// in which case the `projs` vector is used.
2440 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2442 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2443 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2444 /// determined by finding the type of the `.0` field from `T`.
2445 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2446 pub struct UserTypeProjection {
2447 pub base: UserTypeAnnotationIndex,
2448 pub projs: Vec<ProjectionKind>,
2451 impl Copy for ProjectionKind {}
2453 impl UserTypeProjection {
2454 pub(crate) fn index(mut self) -> Self {
2455 self.projs.push(ProjectionElem::Index(()));
2459 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2460 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2464 pub(crate) fn deref(mut self) -> Self {
2465 self.projs.push(ProjectionElem::Deref);
2469 pub(crate) fn leaf(mut self, field: Field) -> Self {
2470 self.projs.push(ProjectionElem::Field(field, ()));
2474 pub(crate) fn variant(
2477 variant_index: VariantIdx,
2480 self.projs.push(ProjectionElem::Downcast(
2481 Some(adt_def.variants[variant_index].ident.name),
2484 self.projs.push(ProjectionElem::Field(field, ()));
2489 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2491 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2492 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2493 use crate::mir::ProjectionElem::*;
2495 let base = self.base.fold_with(folder);
2496 let projs: Vec<_> = self
2499 .map(|&elem| match elem {
2501 Field(f, ()) => Field(f, ()),
2502 Index(()) => Index(()),
2503 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2504 ConstantIndex { offset, min_length, from_end } => {
2505 ConstantIndex { offset, min_length, from_end }
2507 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2511 UserTypeProjection { base, projs }
2514 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2515 self.base.visit_with(visitor)
2516 // Note: there's nothing in `self.proj` to visit.
2520 rustc_index::newtype_index! {
2521 pub struct Promoted {
2523 DEBUG_FORMAT = "promoted[{}]"
2527 impl<'tcx> Debug for Constant<'tcx> {
2528 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2529 write!(fmt, "{}", self)
2533 impl<'tcx> Display for Constant<'tcx> {
2534 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2535 match self.literal.ty.kind() {
2537 _ => write!(fmt, "const ")?,
2539 pretty_print_const(self.literal, fmt, true)
2543 fn pretty_print_const(
2544 c: &ty::Const<'tcx>,
2545 fmt: &mut Formatter<'_>,
2548 use crate::ty::print::PrettyPrinter;
2549 ty::tls::with(|tcx| {
2550 let literal = tcx.lift(&c).unwrap();
2551 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2552 cx.print_alloc_ids = true;
2553 cx.pretty_print_const(literal, print_types)?;
2558 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2559 type Node = BasicBlock;
2562 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2564 fn num_nodes(&self) -> usize {
2565 self.basic_blocks.len()
2569 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2571 fn start_node(&self) -> Self::Node {
2576 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2578 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2579 self.basic_blocks[node].terminator().successors().cloned()
2583 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2584 type Item = BasicBlock;
2585 type Iter = iter::Cloned<Successors<'b>>;
2588 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2589 type Item = BasicBlock;
2590 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2593 impl graph::WithPredecessors for Body<'tcx> {
2595 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2596 self.predecessors()[node].clone().into_iter()
2600 /// `Location` represents the position of the start of the statement; or, if
2601 /// `statement_index` equals the number of statements, then the start of the
2603 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2604 pub struct Location {
2605 /// The block that the location is within.
2606 pub block: BasicBlock,
2608 pub statement_index: usize,
2611 impl fmt::Debug for Location {
2612 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2613 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2618 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2620 /// Returns the location immediately after this one within the enclosing block.
2622 /// Note that if this location represents a terminator, then the
2623 /// resulting location would be out of bounds and invalid.
2624 pub fn successor_within_block(&self) -> Location {
2625 Location { block: self.block, statement_index: self.statement_index + 1 }
2628 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2629 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2630 // If we are in the same block as the other location and are an earlier statement
2631 // then we are a predecessor of `other`.
2632 if self.block == other.block && self.statement_index < other.statement_index {
2636 let predecessors = body.predecessors();
2638 // If we're in another block, then we want to check that block is a predecessor of `other`.
2639 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2640 let mut visited = FxHashSet::default();
2642 while let Some(block) = queue.pop() {
2643 // If we haven't visited this block before, then make sure we visit it's predecessors.
2644 if visited.insert(block) {
2645 queue.extend(predecessors[block].iter().cloned());
2650 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2651 // we found that block by looking at the predecessors of `other`).
2652 if self.block == block {
2660 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2661 if self.block == other.block {
2662 self.statement_index <= other.statement_index
2664 dominators.is_dominated_by(other.block, self.block)