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::*;
43 pub mod abstract_const;
51 pub use terminator::*;
57 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
59 pub trait HasLocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx>;
63 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
64 fn local_decls(&self) -> &LocalDecls<'tcx> {
69 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
70 fn local_decls(&self) -> &LocalDecls<'tcx> {
75 /// The various "big phases" that MIR goes through.
77 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
78 /// dialects forbid certain variants or values in certain phases.
80 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
81 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
83 /// Warning: ordering of variants is significant.
84 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
88 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
89 // We used to have this for pre-miri MIR based const eval.
91 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
92 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
93 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
97 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
98 /// * `DropAndReplace` is gone for good
99 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
100 /// means that the auto-generated drop glue will be invoked.
102 /// After this phase, generators are explicit state machines (no more `Yield`).
103 /// `AggregateKind::Generator` is gone for good.
104 GeneratorLowering = 4,
109 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
110 pub fn phase_index(&self) -> usize {
115 /// The lowered representation of a single function.
116 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
117 pub struct Body<'tcx> {
118 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
119 /// that indexes into this vector.
120 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
122 /// Records how far through the "desugaring and optimization" process this particular
123 /// MIR has traversed. This is particularly useful when inlining, since in that context
124 /// we instantiate the promoted constants and add them to our promoted vector -- but those
125 /// promoted items have already been optimized, whereas ours have not. This field allows
126 /// us to see the difference and forego optimization on the inlined promoted items.
129 /// A list of source scopes; these are referenced by statements
130 /// and used for debuginfo. Indexed by a `SourceScope`.
131 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
133 /// The yield type of the function, if it is a generator.
134 pub yield_ty: Option<Ty<'tcx>>,
136 /// Generator drop glue.
137 pub generator_drop: Option<Box<Body<'tcx>>>,
139 /// The layout of a generator. Produced by the state transformation.
140 pub generator_layout: Option<GeneratorLayout<'tcx>>,
142 /// If this is a generator then record the type of source expression that caused this generator
144 pub generator_kind: Option<GeneratorKind>,
146 /// Declarations of locals.
148 /// The first local is the return value pointer, followed by `arg_count`
149 /// locals for the function arguments, followed by any user-declared
150 /// variables and temporaries.
151 pub local_decls: LocalDecls<'tcx>,
153 /// User type annotations.
154 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
156 /// The number of arguments this function takes.
158 /// Starting at local 1, `arg_count` locals will be provided by the caller
159 /// and can be assumed to be initialized.
161 /// If this MIR was built for a constant, this will be 0.
162 pub arg_count: usize,
164 /// Mark an argument local (which must be a tuple) as getting passed as
165 /// its individual components at the LLVM level.
167 /// This is used for the "rust-call" ABI.
168 pub spread_arg: Option<Local>,
170 /// Debug information pertaining to user variables, including captures.
171 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
173 /// A span representing this MIR, for error reporting.
176 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
177 /// We hold in this field all the constants we are not able to evaluate yet.
178 pub required_consts: Vec<Constant<'tcx>>,
180 /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
181 /// we'd statically know that no thing with interior mutability will ever be available to the
182 /// user without some serious unsafe code. Now this means that our promoted is actually
183 /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
184 /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
185 /// interior mutability. This flag just makes this situation very obvious where the previous
186 /// implementation without the flag hid this situation silently.
187 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
188 pub ignore_interior_mut_in_const_validation: bool,
190 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
192 /// Note that this does not actually mean that this body is not computable right now.
193 /// The repeat count in the following example is polymorphic, but can still be evaluated
194 /// without knowing anything about the type parameter `T`.
198 /// let _ = [0; std::mem::size_of::<*mut T>()];
202 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
203 /// removed the last mention of all generic params. We do not want to rely on optimizations and
204 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
205 pub is_polymorphic: bool,
207 predecessor_cache: PredecessorCache,
210 impl<'tcx> Body<'tcx> {
212 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
213 source_scopes: IndexVec<SourceScope, SourceScopeData>,
214 local_decls: LocalDecls<'tcx>,
215 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
217 var_debug_info: Vec<VarDebugInfo<'tcx>>,
219 generator_kind: Option<GeneratorKind>,
221 // We need `arg_count` locals, and one for the return place.
223 local_decls.len() > arg_count,
224 "expected at least {} locals, got {}",
229 let mut body = Body {
230 phase: MirPhase::Build,
234 generator_drop: None,
235 generator_layout: None,
238 user_type_annotations,
243 required_consts: Vec::new(),
244 ignore_interior_mut_in_const_validation: false,
245 is_polymorphic: false,
246 predecessor_cache: PredecessorCache::new(),
248 body.is_polymorphic = body.has_param_types_or_consts();
252 /// Returns a partially initialized MIR body containing only a list of basic blocks.
254 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
255 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
257 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
258 let mut body = Body {
259 phase: MirPhase::Build,
261 source_scopes: IndexVec::new(),
263 generator_drop: None,
264 generator_layout: None,
265 local_decls: IndexVec::new(),
266 user_type_annotations: IndexVec::new(),
270 required_consts: Vec::new(),
271 generator_kind: None,
272 var_debug_info: Vec::new(),
273 ignore_interior_mut_in_const_validation: false,
274 is_polymorphic: false,
275 predecessor_cache: PredecessorCache::new(),
277 body.is_polymorphic = body.has_param_types_or_consts();
282 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
287 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
288 // Because the user could mutate basic block terminators via this reference, we need to
289 // invalidate the predecessor cache.
291 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
292 // invalidate the predecessor cache.
293 self.predecessor_cache.invalidate();
294 &mut self.basic_blocks
298 pub fn basic_blocks_and_local_decls_mut(
300 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
301 self.predecessor_cache.invalidate();
302 (&mut self.basic_blocks, &mut self.local_decls)
306 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
309 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
310 &mut LocalDecls<'tcx>,
311 &mut Vec<VarDebugInfo<'tcx>>,
313 self.predecessor_cache.invalidate();
314 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
317 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
319 pub fn is_cfg_cyclic(&self) -> bool {
320 graph::is_cyclic(self)
324 pub fn local_kind(&self, local: Local) -> LocalKind {
325 let index = local.as_usize();
328 self.local_decls[local].mutability == Mutability::Mut,
329 "return place should be mutable"
332 LocalKind::ReturnPointer
333 } else if index < self.arg_count + 1 {
335 } else if self.local_decls[local].is_user_variable() {
342 /// Returns an iterator over all temporaries.
344 pub fn temps_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 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
351 /// Returns an iterator over all user-declared locals.
353 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
354 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
355 let local = Local::new(index);
356 self.local_decls[local].is_user_variable().then_some(local)
360 /// Returns an iterator over all user-declared mutable locals.
362 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
363 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
364 let local = Local::new(index);
365 let decl = &self.local_decls[local];
366 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
374 /// Returns an iterator over all user-declared mutable arguments and locals.
376 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
377 (1..self.local_decls.len()).filter_map(move |index| {
378 let local = Local::new(index);
379 let decl = &self.local_decls[local];
380 if (decl.is_user_variable() || index < self.arg_count + 1)
381 && decl.mutability == Mutability::Mut
390 /// Returns an iterator over all function arguments.
392 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
393 let arg_count = self.arg_count;
394 (1..arg_count + 1).map(Local::new)
397 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
398 /// locals that are neither arguments nor the return place).
400 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
401 let arg_count = self.arg_count;
402 let local_count = self.local_decls.len();
403 (arg_count + 1..local_count).map(Local::new)
406 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
407 /// invalidating statement indices in `Location`s.
408 pub fn make_statement_nop(&mut self, location: Location) {
409 let block = &mut self.basic_blocks[location.block];
410 debug_assert!(location.statement_index < block.statements.len());
411 block.statements[location.statement_index].make_nop()
414 /// Returns the source info associated with `location`.
415 pub fn source_info(&self, location: Location) -> &SourceInfo {
416 let block = &self[location.block];
417 let stmts = &block.statements;
418 let idx = location.statement_index;
419 if idx < stmts.len() {
420 &stmts[idx].source_info
422 assert_eq!(idx, stmts.len());
423 &block.terminator().source_info
427 /// Checks if `sub` is a sub scope of `sup`
428 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
430 match self.source_scopes[sub].parent_scope {
431 None => return false,
438 /// Returns the return type; it always return first element from `local_decls` array.
440 pub fn return_ty(&self) -> Ty<'tcx> {
441 self.local_decls[RETURN_PLACE].ty
444 /// Gets the location of the terminator for the given block.
446 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
447 Location { block: bb, statement_index: self[bb].statements.len() }
451 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
452 self.predecessor_cache.compute(&self.basic_blocks)
456 pub fn dominators(&self) -> Dominators<BasicBlock> {
461 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
464 /// Unsafe because of a PushUnsafeBlock
466 /// Unsafe because of an unsafe fn
468 /// Unsafe because of an `unsafe` block
469 ExplicitUnsafe(hir::HirId),
472 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
473 type Output = BasicBlockData<'tcx>;
476 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
477 &self.basic_blocks()[index]
481 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
483 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
484 &mut self.basic_blocks_mut()[index]
488 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
489 pub enum ClearCrossCrate<T> {
494 impl<T> ClearCrossCrate<T> {
495 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
497 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
498 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
502 pub fn assert_crate_local(self) -> T {
504 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
505 ClearCrossCrate::Set(v) => v,
510 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
511 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
513 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
515 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
516 if E::CLEAR_CROSS_CRATE {
521 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
522 ClearCrossCrate::Set(ref val) => {
523 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
529 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
531 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
532 if D::CLEAR_CROSS_CRATE {
533 return Ok(ClearCrossCrate::Clear);
536 let discr = u8::decode(d)?;
539 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
540 TAG_CLEAR_CROSS_CRATE_SET => {
541 let val = T::decode(d)?;
542 Ok(ClearCrossCrate::Set(val))
544 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
549 /// Grouped information about the source code origin of a MIR entity.
550 /// Intended to be inspected by diagnostics and debuginfo.
551 /// Most passes can work with it as a whole, within a single function.
552 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
553 // `Hash`. Please ping @bjorn3 if removing them.
554 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
555 pub struct SourceInfo {
556 /// The source span for the AST pertaining to this MIR entity.
559 /// The source scope, keeping track of which bindings can be
560 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
561 pub scope: SourceScope,
566 pub fn outermost(span: Span) -> Self {
567 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
571 ///////////////////////////////////////////////////////////////////////////
574 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
575 #[derive(HashStable)]
576 pub enum BorrowKind {
577 /// Data must be immutable and is aliasable.
580 /// The immediately borrowed place must be immutable, but projections from
581 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
582 /// conflict with a mutable borrow of `a.b.c`.
584 /// This is used when lowering matches: when matching on a place we want to
585 /// ensure that place have the same value from the start of the match until
586 /// an arm is selected. This prevents this code from compiling:
588 /// let mut x = &Some(0);
591 /// Some(_) if { x = &None; false } => (),
595 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
596 /// should not prevent `if let None = x { ... }`, for example, because the
597 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
598 /// We can also report errors with this kind of borrow differently.
601 /// Data must be immutable but not aliasable. This kind of borrow
602 /// cannot currently be expressed by the user and is used only in
603 /// implicit closure bindings. It is needed when the closure is
604 /// borrowing or mutating a mutable referent, e.g.:
606 /// let x: &mut isize = ...;
607 /// let y = || *x += 5;
609 /// If we were to try to translate this closure into a more explicit
610 /// form, we'd encounter an error with the code as written:
612 /// struct Env { x: & &mut isize }
613 /// let x: &mut isize = ...;
614 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
615 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
617 /// This is then illegal because you cannot mutate an `&mut` found
618 /// in an aliasable location. To solve, you'd have to translate with
619 /// an `&mut` borrow:
621 /// struct Env { x: & &mut isize }
622 /// let x: &mut isize = ...;
623 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
624 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
626 /// Now the assignment to `**env.x` is legal, but creating a
627 /// mutable pointer to `x` is not because `x` is not mutable. We
628 /// could fix this by declaring `x` as `let mut x`. This is ok in
629 /// user code, if awkward, but extra weird for closures, since the
630 /// borrow is hidden.
632 /// So we introduce a "unique imm" borrow -- the referent is
633 /// immutable, but not aliasable. This solves the problem. For
634 /// simplicity, we don't give users the way to express this
635 /// borrow, it's just used when translating closures.
638 /// Data is mutable and not aliasable.
640 /// `true` if this borrow arose from method-call auto-ref
641 /// (i.e., `adjustment::Adjust::Borrow`).
642 allow_two_phase_borrow: bool,
647 pub fn allows_two_phase_borrow(&self) -> bool {
649 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
650 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
655 ///////////////////////////////////////////////////////////////////////////
656 // Variables and temps
658 rustc_index::newtype_index! {
661 DEBUG_FORMAT = "_{}",
662 const RETURN_PLACE = 0,
666 impl Atom for Local {
667 fn index(self) -> usize {
672 /// Classifies locals into categories. See `Body::local_kind`.
673 #[derive(PartialEq, Eq, Debug, HashStable)]
675 /// User-declared variable binding.
677 /// Compiler-introduced temporary.
679 /// Function argument.
681 /// Location of function's return value.
685 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
686 pub struct VarBindingForm<'tcx> {
687 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
688 pub binding_mode: ty::BindingMode,
689 /// If an explicit type was provided for this variable binding,
690 /// this holds the source Span of that type.
692 /// NOTE: if you want to change this to a `HirId`, be wary that
693 /// doing so breaks incremental compilation (as of this writing),
694 /// while a `Span` does not cause our tests to fail.
695 pub opt_ty_info: Option<Span>,
696 /// Place of the RHS of the =, or the subject of the `match` where this
697 /// variable is initialized. None in the case of `let PATTERN;`.
698 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
699 /// (a) the right-hand side isn't evaluated as a place expression.
700 /// (b) it gives a way to separate this case from the remaining cases
702 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
703 /// The span of the pattern in which this variable was bound.
707 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
708 pub enum BindingForm<'tcx> {
709 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
710 Var(VarBindingForm<'tcx>),
711 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
712 ImplicitSelf(ImplicitSelfKind),
713 /// Reference used in a guard expression to ensure immutability.
717 /// Represents what type of implicit self a function has, if any.
718 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
719 pub enum ImplicitSelfKind {
720 /// Represents a `fn x(self);`.
722 /// Represents a `fn x(mut self);`.
724 /// Represents a `fn x(&self);`.
726 /// Represents a `fn x(&mut self);`.
728 /// Represents when a function does not have a self argument or
729 /// when a function has a `self: X` argument.
733 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
735 mod binding_form_impl {
736 use crate::ich::StableHashingContext;
737 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
739 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
740 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
741 use super::BindingForm::*;
742 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
745 Var(binding) => binding.hash_stable(hcx, hasher),
746 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
753 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
754 /// created during evaluation of expressions in a block tail
755 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
757 /// It is used to improve diagnostics when such temporaries are
758 /// involved in borrow_check errors, e.g., explanations of where the
759 /// temporaries come from, when their destructors are run, and/or how
760 /// one might revise the code to satisfy the borrow checker's rules.
761 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
762 pub struct BlockTailInfo {
763 /// If `true`, then the value resulting from evaluating this tail
764 /// expression is ignored by the block's expression context.
766 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
767 /// but not e.g., `let _x = { ...; tail };`
768 pub tail_result_is_ignored: bool,
770 /// `Span` of the tail expression.
776 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
777 /// argument, or the return place.
778 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
779 pub struct LocalDecl<'tcx> {
780 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
782 /// Temporaries and the return place are always mutable.
783 pub mutability: Mutability,
785 // FIXME(matthewjasper) Don't store in this in `Body`
786 pub local_info: Option<Box<LocalInfo<'tcx>>>,
788 /// `true` if this is an internal local.
790 /// These locals are not based on types in the source code and are only used
791 /// for a few desugarings at the moment.
793 /// The generator transformation will sanity check the locals which are live
794 /// across a suspension point against the type components of the generator
795 /// which type checking knows are live across a suspension point. We need to
796 /// flag drop flags to avoid triggering this check as they are introduced
799 /// Unsafety checking will also ignore dereferences of these locals,
800 /// so they can be used for raw pointers only used in a desugaring.
802 /// This should be sound because the drop flags are fully algebraic, and
803 /// therefore don't affect the OIBIT or outlives properties of the
807 /// If this local is a temporary and `is_block_tail` is `Some`,
808 /// then it is a temporary created for evaluation of some
809 /// subexpression of some block's tail expression (with no
810 /// intervening statement context).
811 // FIXME(matthewjasper) Don't store in this in `Body`
812 pub is_block_tail: Option<BlockTailInfo>,
814 /// The type of this local.
817 /// If the user manually ascribed a type to this variable,
818 /// e.g., via `let x: T`, then we carry that type here. The MIR
819 /// borrow checker needs this information since it can affect
820 /// region inference.
821 // FIXME(matthewjasper) Don't store in this in `Body`
822 pub user_ty: Option<Box<UserTypeProjections>>,
824 /// The *syntactic* (i.e., not visibility) source scope the local is defined
825 /// in. If the local was defined in a let-statement, this
826 /// is *within* the let-statement, rather than outside
829 /// This is needed because the visibility source scope of locals within
830 /// a let-statement is weird.
832 /// The reason is that we want the local to be *within* the let-statement
833 /// for lint purposes, but we want the local to be *after* the let-statement
834 /// for names-in-scope purposes.
836 /// That's it, if we have a let-statement like the one in this
840 /// fn foo(x: &str) {
841 /// #[allow(unused_mut)]
842 /// let mut x: u32 = { // <- one unused mut
843 /// let mut y: u32 = x.parse().unwrap();
850 /// Then, from a lint point of view, the declaration of `x: u32`
851 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
852 /// lint scopes are the same as the AST/HIR nesting.
854 /// However, from a name lookup point of view, the scopes look more like
855 /// as if the let-statements were `match` expressions:
858 /// fn foo(x: &str) {
860 /// match x.parse().unwrap() {
869 /// We care about the name-lookup scopes for debuginfo - if the
870 /// debuginfo instruction pointer is at the call to `x.parse()`, we
871 /// want `x` to refer to `x: &str`, but if it is at the call to
872 /// `drop(x)`, we want it to refer to `x: u32`.
874 /// To allow both uses to work, we need to have more than a single scope
875 /// for a local. We have the `source_info.scope` represent the "syntactic"
876 /// lint scope (with a variable being under its let block) while the
877 /// `var_debug_info.source_info.scope` represents the "local variable"
878 /// scope (where the "rest" of a block is under all prior let-statements).
880 /// The end result looks like this:
884 /// │{ argument x: &str }
886 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
887 /// │ │ // in practice because I'm lazy.
889 /// │ │← x.source_info.scope
890 /// │ │← `x.parse().unwrap()`
892 /// │ │ │← y.source_info.scope
894 /// │ │ │{ let y: u32 }
896 /// │ │ │← y.var_debug_info.source_info.scope
899 /// │ │{ let x: u32 }
900 /// │ │← x.var_debug_info.source_info.scope
901 /// │ │← `drop(x)` // This accesses `x: u32`.
903 pub source_info: SourceInfo,
906 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
907 #[cfg(target_arch = "x86_64")]
908 static_assert_size!(LocalDecl<'_>, 56);
910 /// Extra information about a some locals that's used for diagnostics and for
911 /// classifying variables into local variables, statics, etc, which is needed e.g.
912 /// for unsafety checking.
914 /// Not used for non-StaticRef temporaries, the return place, or anonymous
915 /// function parameters.
916 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
917 pub enum LocalInfo<'tcx> {
918 /// A user-defined local variable or function parameter
920 /// The `BindingForm` is solely used for local diagnostics when generating
921 /// warnings/errors when compiling the current crate, and therefore it need
922 /// not be visible across crates.
923 User(ClearCrossCrate<BindingForm<'tcx>>),
924 /// A temporary created that references the static with the given `DefId`.
925 StaticRef { def_id: DefId, is_thread_local: bool },
926 /// A temporary created that references the const with the given `DefId`
927 ConstRef { def_id: DefId },
930 impl<'tcx> LocalDecl<'tcx> {
931 /// Returns `true` only if local is a binding that can itself be
932 /// made mutable via the addition of the `mut` keyword, namely
933 /// something like the occurrences of `x` in:
934 /// - `fn foo(x: Type) { ... }`,
936 /// - or `match ... { C(x) => ... }`
937 pub fn can_be_made_mutable(&self) -> bool {
938 match self.local_info {
939 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
940 binding_mode: ty::BindingMode::BindByValue(_),
946 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
947 ImplicitSelfKind::Imm,
954 /// Returns `true` if local is definitely not a `ref ident` or
955 /// `ref mut ident` binding. (Such bindings cannot be made into
956 /// mutable bindings, but the inverse does not necessarily hold).
957 pub fn is_nonref_binding(&self) -> bool {
958 match self.local_info {
959 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
960 binding_mode: ty::BindingMode::BindByValue(_),
966 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
972 /// Returns `true` if this variable is a named variable or function
973 /// parameter declared by the user.
975 pub fn is_user_variable(&self) -> bool {
976 match self.local_info {
977 Some(box LocalInfo::User(_)) => true,
982 /// Returns `true` if this is a reference to a variable bound in a `match`
983 /// expression that is used to access said variable for the guard of the
985 pub fn is_ref_for_guard(&self) -> bool {
986 match self.local_info {
987 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
992 /// Returns `Some` if this is a reference to a static item that is used to
993 /// access that static
994 pub fn is_ref_to_static(&self) -> bool {
995 match self.local_info {
996 Some(box LocalInfo::StaticRef { .. }) => true,
1001 /// Returns `Some` if this is a reference to a static item that is used to
1002 /// access that static
1003 pub fn is_ref_to_thread_local(&self) -> bool {
1004 match self.local_info {
1005 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1010 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1011 /// `__next` from a `for` loop.
1013 pub fn from_compiler_desugaring(&self) -> bool {
1014 self.source_info.span.desugaring_kind().is_some()
1017 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1019 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1020 Self::with_source_info(ty, SourceInfo::outermost(span))
1023 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1025 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1027 mutability: Mutability::Mut,
1030 is_block_tail: None,
1037 /// Converts `self` into same `LocalDecl` except tagged as internal.
1039 pub fn internal(mut self) -> Self {
1040 self.internal = true;
1044 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1046 pub fn immutable(mut self) -> Self {
1047 self.mutability = Mutability::Not;
1051 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1053 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1054 assert!(self.is_block_tail.is_none());
1055 self.is_block_tail = Some(info);
1060 /// Debug information pertaining to a user variable.
1061 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1062 pub struct VarDebugInfo<'tcx> {
1065 /// Source info of the user variable, including the scope
1066 /// within which the variable is visible (to debuginfo)
1067 /// (see `LocalDecl`'s `source_info` field for more details).
1068 pub source_info: SourceInfo,
1070 /// Where the data for this user variable is to be found.
1071 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1072 /// based on a `Local`, not a `Static`, and contains no indexing.
1073 pub place: Place<'tcx>,
1076 ///////////////////////////////////////////////////////////////////////////
1079 rustc_index::newtype_index! {
1080 /// A node in the MIR [control-flow graph][CFG].
1082 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1083 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1084 /// as an edge in a graph between basic blocks.
1086 /// Basic blocks consist of a series of [statements][Statement], ending with a
1087 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1088 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1089 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1090 /// needed because some analyses require that there are no critical edges in the CFG.
1092 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1094 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1095 /// [data-flow analyses]:
1096 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1097 /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1098 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1099 pub struct BasicBlock {
1101 DEBUG_FORMAT = "bb{}",
1102 const START_BLOCK = 0,
1107 pub fn start_location(self) -> Location {
1108 Location { block: self, statement_index: 0 }
1112 ///////////////////////////////////////////////////////////////////////////
1113 // BasicBlockData and Terminator
1115 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1116 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1117 pub struct BasicBlockData<'tcx> {
1118 /// List of statements in this block.
1119 pub statements: Vec<Statement<'tcx>>,
1121 /// Terminator for this block.
1123 /// N.B., this should generally ONLY be `None` during construction.
1124 /// Therefore, you should generally access it via the
1125 /// `terminator()` or `terminator_mut()` methods. The only
1126 /// exception is that certain passes, such as `simplify_cfg`, swap
1127 /// out the terminator temporarily with `None` while they continue
1128 /// to recurse over the set of basic blocks.
1129 pub terminator: Option<Terminator<'tcx>>,
1131 /// If true, this block lies on an unwind path. This is used
1132 /// during codegen where distinct kinds of basic blocks may be
1133 /// generated (particularly for MSVC cleanup). Unwind blocks must
1134 /// only branch to other unwind blocks.
1135 pub is_cleanup: bool,
1138 /// Information about an assertion failure.
1139 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1140 pub enum AssertKind<O> {
1141 BoundsCheck { len: O, index: O },
1142 Overflow(BinOp, O, O),
1146 ResumedAfterReturn(GeneratorKind),
1147 ResumedAfterPanic(GeneratorKind),
1150 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1151 pub enum InlineAsmOperand<'tcx> {
1153 reg: InlineAsmRegOrRegClass,
1154 value: Operand<'tcx>,
1157 reg: InlineAsmRegOrRegClass,
1159 place: Option<Place<'tcx>>,
1162 reg: InlineAsmRegOrRegClass,
1164 in_value: Operand<'tcx>,
1165 out_place: Option<Place<'tcx>>,
1168 value: Operand<'tcx>,
1171 value: Box<Constant<'tcx>>,
1178 /// Type for MIR `Assert` terminator error messages.
1179 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1181 pub type Successors<'a> =
1182 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1183 pub type SuccessorsMut<'a> =
1184 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1186 impl<'tcx> BasicBlockData<'tcx> {
1187 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1188 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1191 /// Accessor for terminator.
1193 /// Terminator may not be None after construction of the basic block is complete. This accessor
1194 /// provides a convenience way to reach the terminator.
1195 pub fn terminator(&self) -> &Terminator<'tcx> {
1196 self.terminator.as_ref().expect("invalid terminator state")
1199 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1200 self.terminator.as_mut().expect("invalid terminator state")
1203 pub fn retain_statements<F>(&mut self, mut f: F)
1205 F: FnMut(&mut Statement<'_>) -> bool,
1207 for s in &mut self.statements {
1214 pub fn expand_statements<F, I>(&mut self, mut f: F)
1216 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1217 I: iter::TrustedLen<Item = Statement<'tcx>>,
1219 // Gather all the iterators we'll need to splice in, and their positions.
1220 let mut splices: Vec<(usize, I)> = vec![];
1221 let mut extra_stmts = 0;
1222 for (i, s) in self.statements.iter_mut().enumerate() {
1223 if let Some(mut new_stmts) = f(s) {
1224 if let Some(first) = new_stmts.next() {
1225 // We can already store the first new statement.
1228 // Save the other statements for optimized splicing.
1229 let remaining = new_stmts.size_hint().0;
1231 splices.push((i + 1 + extra_stmts, new_stmts));
1232 extra_stmts += remaining;
1240 // Splice in the new statements, from the end of the block.
1241 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1242 // where a range of elements ("gap") is left uninitialized, with
1243 // splicing adding new elements to the end of that gap and moving
1244 // existing elements from before the gap to the end of the gap.
1245 // For now, this is safe code, emulating a gap but initializing it.
1246 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1247 self.statements.resize(
1249 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1251 for (splice_start, new_stmts) in splices.into_iter().rev() {
1252 let splice_end = splice_start + new_stmts.size_hint().0;
1253 while gap.end > splice_end {
1256 self.statements.swap(gap.start, gap.end);
1258 self.statements.splice(splice_start..splice_end, new_stmts);
1259 gap.end = splice_start;
1263 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1264 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1268 impl<O> AssertKind<O> {
1269 /// Getting a description does not require `O` to be printable, and does not
1270 /// require allocation.
1271 /// The caller is expected to handle `BoundsCheck` separately.
1272 pub fn description(&self) -> &'static str {
1275 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1276 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1277 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1278 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1279 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1280 OverflowNeg(_) => "attempt to negate with overflow",
1281 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1282 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1283 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1284 DivisionByZero(_) => "attempt to divide by zero",
1285 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1286 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1287 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1288 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1289 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1290 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1294 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1295 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1301 BoundsCheck { ref len, ref index } => write!(
1303 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1307 OverflowNeg(op) => {
1308 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1310 DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1311 RemainderByZero(op) => write!(
1313 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1316 Overflow(BinOp::Add, l, r) => write!(
1318 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1321 Overflow(BinOp::Sub, l, r) => write!(
1323 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1326 Overflow(BinOp::Mul, l, r) => write!(
1328 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1331 Overflow(BinOp::Div, l, r) => write!(
1333 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1336 Overflow(BinOp::Rem, l, r) => write!(
1338 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1341 Overflow(BinOp::Shr, _, r) => {
1342 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1344 Overflow(BinOp::Shl, _, r) => {
1345 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1347 _ => write!(f, "\"{}\"", self.description()),
1352 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1356 BoundsCheck { ref len, ref index } => {
1357 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1359 OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1360 DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1361 RemainderByZero(op) => {
1362 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1364 Overflow(BinOp::Add, l, r) => {
1365 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1367 Overflow(BinOp::Sub, l, r) => {
1368 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1370 Overflow(BinOp::Mul, l, r) => {
1371 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1373 Overflow(BinOp::Div, l, r) => {
1374 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1376 Overflow(BinOp::Rem, l, r) => write!(
1378 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1381 Overflow(BinOp::Shr, _, r) => {
1382 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1384 Overflow(BinOp::Shl, _, r) => {
1385 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1387 _ => write!(f, "{}", self.description()),
1392 ///////////////////////////////////////////////////////////////////////////
1395 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1396 pub struct Statement<'tcx> {
1397 pub source_info: SourceInfo,
1398 pub kind: StatementKind<'tcx>,
1401 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1402 #[cfg(target_arch = "x86_64")]
1403 static_assert_size!(Statement<'_>, 32);
1405 impl Statement<'_> {
1406 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1407 /// invalidating statement indices in `Location`s.
1408 pub fn make_nop(&mut self) {
1409 self.kind = StatementKind::Nop
1412 /// Changes a statement to a nop and returns the original statement.
1413 pub fn replace_nop(&mut self) -> Self {
1415 source_info: self.source_info,
1416 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1421 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1422 pub enum StatementKind<'tcx> {
1423 /// Write the RHS Rvalue to the LHS Place.
1424 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1426 /// This represents all the reading that a pattern match may do
1427 /// (e.g., inspecting constants and discriminant values), and the
1428 /// kind of pattern it comes from. This is in order to adapt potential
1429 /// error messages to these specific patterns.
1431 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1432 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1433 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1435 /// Write the discriminant for a variant to the enum Place.
1436 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1438 /// Start a live range for the storage of the local.
1441 /// End the current live range for the storage of the local.
1444 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1445 /// of `StatementKind` low.
1446 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1448 /// Retag references in the given place, ensuring they got fresh tags. This is
1449 /// part of the Stacked Borrows model. These statements are currently only interpreted
1450 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1451 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1452 /// for more details.
1453 Retag(RetagKind, Box<Place<'tcx>>),
1455 /// Encodes a user's type ascription. These need to be preserved
1456 /// intact so that NLL can respect them. For example:
1460 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1461 /// to the user-given type `T`. The effect depends on the specified variance:
1463 /// - `Covariant` -- requires that `T_y <: T`
1464 /// - `Contravariant` -- requires that `T_y :> T`
1465 /// - `Invariant` -- requires that `T_y == T`
1466 /// - `Bivariant` -- no effect
1467 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1469 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1470 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1471 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1472 /// counter varible at runtime, each time the code region is executed.
1473 Coverage(Box<Coverage>),
1475 /// No-op. Useful for deleting instructions without affecting statement indices.
1479 impl<'tcx> StatementKind<'tcx> {
1480 pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1482 StatementKind::Assign(x) => Some(x),
1488 /// Describes what kind of retag is to be performed.
1489 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1490 pub enum RetagKind {
1491 /// The initial retag when entering a function.
1493 /// Retag preparing for a two-phase borrow.
1495 /// Retagging raw pointers.
1497 /// A "normal" retag.
1501 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1502 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1503 pub enum FakeReadCause {
1504 /// Inject a fake read of the borrowed input at the end of each guards
1507 /// This should ensure that you cannot change the variant for an enum while
1508 /// you are in the midst of matching on it.
1511 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1512 /// generate a read of x to check that it is initialized and safe.
1515 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1516 /// in a match guard to ensure that it's value hasn't change by the time
1517 /// we create the OutsideGuard version.
1520 /// Officially, the semantics of
1522 /// `let pattern = <expr>;`
1524 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1525 /// into the pattern.
1527 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1528 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1529 /// but in some cases it can affect the borrow checker, as in #53695.
1530 /// Therefore, we insert a "fake read" here to ensure that we get
1531 /// appropriate errors.
1534 /// If we have an index expression like
1536 /// (*x)[1][{ x = y; 4}]
1538 /// then the first bounds check is invalidated when we evaluate the second
1539 /// index expression. Thus we create a fake borrow of `x` across the second
1540 /// indexer, which will cause a borrow check error.
1544 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1545 pub struct LlvmInlineAsm<'tcx> {
1546 pub asm: hir::LlvmInlineAsmInner,
1547 pub outputs: Box<[Place<'tcx>]>,
1548 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1551 impl Debug for Statement<'_> {
1552 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1553 use self::StatementKind::*;
1555 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1556 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1557 Retag(ref kind, ref place) => write!(
1561 RetagKind::FnEntry => "[fn entry] ",
1562 RetagKind::TwoPhase => "[2phase] ",
1563 RetagKind::Raw => "[raw] ",
1564 RetagKind::Default => "",
1568 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1569 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1570 SetDiscriminant { ref place, variant_index } => {
1571 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1573 LlvmInlineAsm(ref asm) => {
1574 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1576 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1577 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1579 Coverage(box ref coverage) => {
1580 let rgn = &coverage.code_region;
1581 match coverage.kind {
1582 CoverageKind::Counter { id, .. } => {
1583 write!(fmt, "Coverage::Counter({:?}) for {:?}", id.index(), rgn)
1585 CoverageKind::Expression { id, lhs, op, rhs } => write!(
1587 "Coverage::Expression({:?}) = {} {} {} for {:?}",
1590 if op == coverage::Op::Add { "+" } else { "-" },
1594 CoverageKind::Unreachable => write!(fmt, "Coverage::Unreachable for {:?}", rgn),
1597 Nop => write!(fmt, "nop"),
1602 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1603 pub struct Coverage {
1604 pub kind: CoverageKind,
1605 pub code_region: CodeRegion,
1608 ///////////////////////////////////////////////////////////////////////////
1611 /// A path to a value; something that can be evaluated without
1612 /// changing or disturbing program state.
1613 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1614 pub struct Place<'tcx> {
1617 /// projection out of a place (access a field, deref a pointer, etc)
1618 pub projection: &'tcx List<PlaceElem<'tcx>>,
1621 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1622 #[derive(TyEncodable, TyDecodable, HashStable)]
1623 pub enum ProjectionElem<V, T> {
1628 /// These indices are generated by slice patterns. Easiest to explain
1632 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1633 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1634 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1635 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1638 /// index or -index (in Python terms), depending on from_end
1640 /// The thing being indexed must be at least this long. For arrays this
1641 /// is always the exact length.
1643 /// Counting backwards from end? This is always false when indexing an
1648 /// These indices are generated by slice patterns.
1650 /// If `from_end` is true `slice[from..slice.len() - to]`.
1651 /// Otherwise `array[from..to]`.
1655 /// Whether `to` counts from the start or end of the array/slice.
1656 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1657 /// For `ProjectionKind`, this can also be `true` for arrays.
1661 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1662 /// this for ADTs with more than one variant. It may be better to
1663 /// just introduce it always, or always for enums.
1665 /// The included Symbol is the name of the variant, used for printing MIR.
1666 Downcast(Option<Symbol>, VariantIdx),
1669 impl<V, T> ProjectionElem<V, T> {
1670 /// Returns `true` if the target of this projection may refer to a different region of memory
1672 fn is_indirect(&self) -> bool {
1674 Self::Deref => true,
1678 | Self::ConstantIndex { .. }
1679 | Self::Subslice { .. }
1680 | Self::Downcast(_, _) => false,
1685 /// Alias for projections as they appear in places, where the base is a place
1686 /// and the index is a local.
1687 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1689 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1690 #[cfg(target_arch = "x86_64")]
1691 static_assert_size!(PlaceElem<'_>, 24);
1693 /// Alias for projections as they appear in `UserTypeProjection`, where we
1694 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1695 pub type ProjectionKind = ProjectionElem<(), ()>;
1697 rustc_index::newtype_index! {
1700 DEBUG_FORMAT = "field[{}]"
1704 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1705 pub struct PlaceRef<'tcx> {
1707 pub projection: &'tcx [PlaceElem<'tcx>],
1710 impl<'tcx> Place<'tcx> {
1711 // FIXME change this to a const fn by also making List::empty a const fn.
1712 pub fn return_place() -> Place<'tcx> {
1713 Place { local: RETURN_PLACE, projection: List::empty() }
1716 /// Returns `true` if this `Place` contains a `Deref` projection.
1718 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1719 /// same region of memory as its base.
1720 pub fn is_indirect(&self) -> bool {
1721 self.projection.iter().any(|elem| elem.is_indirect())
1724 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1725 /// a single deref of a local.
1727 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1728 pub fn local_or_deref_local(&self) -> Option<Local> {
1729 match self.as_ref() {
1730 PlaceRef { local, projection: [] }
1731 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1736 /// If this place represents a local variable like `_X` with no
1737 /// projections, return `Some(_X)`.
1738 pub fn as_local(&self) -> Option<Local> {
1739 self.as_ref().as_local()
1742 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1743 PlaceRef { local: self.local, projection: &self.projection }
1747 impl From<Local> for Place<'_> {
1748 fn from(local: Local) -> Self {
1749 Place { local, projection: List::empty() }
1753 impl<'tcx> PlaceRef<'tcx> {
1754 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1755 /// a single deref of a local.
1757 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1758 pub fn local_or_deref_local(&self) -> Option<Local> {
1760 PlaceRef { local, projection: [] }
1761 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1766 /// If this place represents a local variable like `_X` with no
1767 /// projections, return `Some(_X)`.
1768 pub fn as_local(&self) -> Option<Local> {
1770 PlaceRef { local, projection: [] } => Some(local),
1776 impl Debug for Place<'_> {
1777 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1778 for elem in self.projection.iter().rev() {
1780 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1781 write!(fmt, "(").unwrap();
1783 ProjectionElem::Deref => {
1784 write!(fmt, "(*").unwrap();
1786 ProjectionElem::Index(_)
1787 | ProjectionElem::ConstantIndex { .. }
1788 | ProjectionElem::Subslice { .. } => {}
1792 write!(fmt, "{:?}", self.local)?;
1794 for elem in self.projection.iter() {
1796 ProjectionElem::Downcast(Some(name), _index) => {
1797 write!(fmt, " as {})", name)?;
1799 ProjectionElem::Downcast(None, index) => {
1800 write!(fmt, " as variant#{:?})", index)?;
1802 ProjectionElem::Deref => {
1805 ProjectionElem::Field(field, ty) => {
1806 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1808 ProjectionElem::Index(ref index) => {
1809 write!(fmt, "[{:?}]", index)?;
1811 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1812 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1814 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1815 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1817 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1818 write!(fmt, "[{:?}:]", from)?;
1820 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1821 write!(fmt, "[:-{:?}]", to)?;
1823 ProjectionElem::Subslice { from, to, from_end: true } => {
1824 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1826 ProjectionElem::Subslice { from, to, from_end: false } => {
1827 write!(fmt, "[{:?}..{:?}]", from, to)?;
1836 ///////////////////////////////////////////////////////////////////////////
1839 rustc_index::newtype_index! {
1840 pub struct SourceScope {
1842 DEBUG_FORMAT = "scope[{}]",
1843 const OUTERMOST_SOURCE_SCOPE = 0,
1847 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1848 pub struct SourceScopeData {
1850 pub parent_scope: Option<SourceScope>,
1852 /// Crate-local information for this source scope, that can't (and
1853 /// needn't) be tracked across crates.
1854 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1857 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1858 pub struct SourceScopeLocalData {
1859 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1860 pub lint_root: hir::HirId,
1861 /// The unsafe block that contains this node.
1865 ///////////////////////////////////////////////////////////////////////////
1868 /// These are values that can appear inside an rvalue. They are intentionally
1869 /// limited to prevent rvalues from being nested in one another.
1870 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1871 pub enum Operand<'tcx> {
1872 /// Copy: The value must be available for use afterwards.
1874 /// This implies that the type of the place must be `Copy`; this is true
1875 /// by construction during build, but also checked by the MIR type checker.
1878 /// Move: The value (including old borrows of it) will not be used again.
1880 /// Safe for values of all types (modulo future developments towards `?Move`).
1881 /// Correct usage patterns are enforced by the borrow checker for safe code.
1882 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1885 /// Synthesizes a constant value.
1886 Constant(Box<Constant<'tcx>>),
1889 impl<'tcx> Debug for Operand<'tcx> {
1890 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1891 use self::Operand::*;
1893 Constant(ref a) => write!(fmt, "{:?}", a),
1894 Copy(ref place) => write!(fmt, "{:?}", place),
1895 Move(ref place) => write!(fmt, "move {:?}", place),
1900 impl<'tcx> Operand<'tcx> {
1901 /// Convenience helper to make a constant that refers to the fn
1902 /// with given `DefId` and substs. Since this is used to synthesize
1903 /// MIR, assumes `user_ty` is None.
1904 pub fn function_handle(
1907 substs: SubstsRef<'tcx>,
1910 let ty = tcx.type_of(def_id).subst(tcx, substs);
1911 Operand::Constant(box Constant {
1914 literal: ty::Const::zero_sized(tcx, ty),
1918 pub fn is_move(&self) -> bool {
1919 matches!(self, Operand::Move(..))
1922 /// Convenience helper to make a literal-like constant from a given scalar value.
1923 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1924 pub fn const_from_scalar(
1929 ) -> Operand<'tcx> {
1931 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1933 .layout_of(param_env_and_ty)
1934 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1936 let scalar_size = abi::Size::from_bytes(match val {
1937 Scalar::Raw { size, .. } => size,
1938 _ => panic!("Invalid scalar type {:?}", val),
1940 scalar_size == type_size
1942 Operand::Constant(box Constant {
1945 literal: ty::Const::from_scalar(tcx, val, ty),
1949 /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1950 /// wraps a constant literal value. Panics if this is not the case.
1951 pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1953 Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1954 Some(scalar) => scalar,
1955 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1957 _ => panic!("{:?}: Constant expected", operand),
1961 /// Convenience helper to make a literal-like constant from a given `&str` slice.
1962 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1963 pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1965 let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1966 let allocation = tcx.intern_const_alloc(allocation);
1967 let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1968 let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1969 Operand::Constant(box Constant {
1972 literal: ty::Const::from_value(tcx, const_val, ty),
1976 /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1977 /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1978 pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1980 Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1981 Some(const_value) => const_value,
1982 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1984 _ => panic!("{:?}: Constant expected", operand),
1988 pub fn to_copy(&self) -> Self {
1990 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1991 Operand::Move(place) => Operand::Copy(place),
1995 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1997 pub fn place(&self) -> Option<Place<'tcx>> {
1999 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2000 Operand::Constant(_) => None,
2004 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2006 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2008 Operand::Constant(x) => Some(&**x),
2009 Operand::Copy(_) | Operand::Move(_) => None,
2014 ///////////////////////////////////////////////////////////////////////////
2017 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
2018 pub enum Rvalue<'tcx> {
2019 /// x (either a move or copy, depending on type of x)
2023 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2026 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2028 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2029 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2031 ThreadLocalRef(DefId),
2033 /// Create a raw pointer to the given place
2034 /// Can be generated by raw address of expressions (`&raw const x`),
2035 /// or when casting a reference to a raw pointer.
2036 AddressOf(Mutability, Place<'tcx>),
2038 /// length of a `[X]` or `[X;n]` value
2041 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2043 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2044 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2046 NullaryOp(NullOp, Ty<'tcx>),
2047 UnaryOp(UnOp, Operand<'tcx>),
2049 /// Read the discriminant of an ADT.
2051 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2052 /// be defined to return, say, a 0) if ADT is not an enum.
2053 Discriminant(Place<'tcx>),
2055 /// Creates an aggregate value, like a tuple or struct. This is
2056 /// only needed because we want to distinguish `dest = Foo { x:
2057 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2058 /// that `Foo` has a destructor. These rvalues can be optimized
2059 /// away after type-checking and before lowering.
2060 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2063 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2066 Pointer(PointerCast),
2069 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2070 pub enum AggregateKind<'tcx> {
2071 /// The type is of the element
2075 /// The second field is the variant index. It's equal to 0 for struct
2076 /// and union expressions. The fourth field is
2077 /// active field number and is present only for union expressions
2078 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2079 /// active field index would identity the field `c`
2080 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2082 Closure(DefId, SubstsRef<'tcx>),
2083 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2086 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2088 /// The `+` operator (addition)
2090 /// The `-` operator (subtraction)
2092 /// The `*` operator (multiplication)
2094 /// The `/` operator (division)
2096 /// The `%` operator (modulus)
2098 /// The `^` operator (bitwise xor)
2100 /// The `&` operator (bitwise and)
2102 /// The `|` operator (bitwise or)
2104 /// The `<<` operator (shift left)
2106 /// The `>>` operator (shift right)
2108 /// The `==` operator (equality)
2110 /// The `<` operator (less than)
2112 /// The `<=` operator (less than or equal to)
2114 /// The `!=` operator (not equal to)
2116 /// The `>=` operator (greater than or equal to)
2118 /// The `>` operator (greater than)
2120 /// The `ptr.offset` operator
2125 pub fn is_checkable(self) -> bool {
2128 Add | Sub | Mul | Shl | Shr => true,
2134 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2136 /// Returns the size of a value of that type
2138 /// Creates a new uninitialized box for a value of that type
2142 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2144 /// The `!` operator for logical inversion
2146 /// The `-` operator for negation
2150 impl<'tcx> Debug for Rvalue<'tcx> {
2151 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2152 use self::Rvalue::*;
2155 Use(ref place) => write!(fmt, "{:?}", place),
2156 Repeat(ref a, ref b) => {
2157 write!(fmt, "[{:?}; ", a)?;
2158 pretty_print_const(b, fmt, false)?;
2161 Len(ref a) => write!(fmt, "Len({:?})", a),
2162 Cast(ref kind, ref place, ref ty) => {
2163 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2165 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2166 CheckedBinaryOp(ref op, ref a, ref b) => {
2167 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2169 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2170 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2171 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2172 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2173 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2174 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2176 Ref(region, borrow_kind, ref place) => {
2177 let kind_str = match borrow_kind {
2178 BorrowKind::Shared => "",
2179 BorrowKind::Shallow => "shallow ",
2180 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2183 // When printing regions, add trailing space if necessary.
2184 let print_region = ty::tls::with(|tcx| {
2185 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2187 let region = if print_region {
2188 let mut region = region.to_string();
2189 if !region.is_empty() {
2194 // Do not even print 'static
2197 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2200 AddressOf(mutability, ref place) => {
2201 let kind_str = match mutability {
2202 Mutability::Mut => "mut",
2203 Mutability::Not => "const",
2206 write!(fmt, "&raw {} {:?}", kind_str, place)
2209 Aggregate(ref kind, ref places) => {
2210 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2211 let mut tuple_fmt = fmt.debug_tuple(name);
2212 for place in places {
2213 tuple_fmt.field(place);
2219 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2221 AggregateKind::Tuple => {
2222 if places.is_empty() {
2229 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2230 let variant_def = &adt_def.variants[variant];
2232 let name = ty::tls::with(|tcx| {
2233 let mut name = String::new();
2234 let substs = tcx.lift(&substs).expect("could not lift for printing");
2235 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2236 .print_def_path(variant_def.def_id, substs)?;
2240 match variant_def.ctor_kind {
2241 CtorKind::Const => fmt.write_str(&name),
2242 CtorKind::Fn => fmt_tuple(fmt, &name),
2243 CtorKind::Fictive => {
2244 let mut struct_fmt = fmt.debug_struct(&name);
2245 for (field, place) in variant_def.fields.iter().zip(places) {
2246 struct_fmt.field(&field.ident.as_str(), place);
2253 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2254 if let Some(def_id) = def_id.as_local() {
2255 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2256 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2257 let substs = tcx.lift(&substs).unwrap();
2260 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2263 let span = tcx.hir().span(hir_id);
2264 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2266 let mut struct_fmt = fmt.debug_struct(&name);
2268 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2269 for (&var_id, place) in upvars.keys().zip(places) {
2270 let var_name = tcx.hir().name(var_id);
2271 struct_fmt.field(&var_name.as_str(), place);
2277 write!(fmt, "[closure]")
2281 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2282 if let Some(def_id) = def_id.as_local() {
2283 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2284 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2285 let mut struct_fmt = fmt.debug_struct(&name);
2287 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2288 for (&var_id, place) in upvars.keys().zip(places) {
2289 let var_name = tcx.hir().name(var_id);
2290 struct_fmt.field(&var_name.as_str(), place);
2296 write!(fmt, "[generator]")
2305 ///////////////////////////////////////////////////////////////////////////
2308 /// Two constants are equal if they are the same constant. Note that
2309 /// this does not necessarily mean that they are `==` in Rust. In
2310 /// particular, one must be wary of `NaN`!
2312 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2313 pub struct Constant<'tcx> {
2316 /// Optional user-given type: for something like
2317 /// `collect::<Vec<_>>`, this would be present and would
2318 /// indicate that `Vec<_>` was explicitly specified.
2320 /// Needed for NLL to impose user-given type constraints.
2321 pub user_ty: Option<UserTypeAnnotationIndex>,
2323 pub literal: &'tcx ty::Const<'tcx>,
2326 impl Constant<'tcx> {
2327 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2328 match self.literal.val.try_to_scalar() {
2329 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2330 GlobalAlloc::Static(def_id) => {
2331 assert!(!tcx.is_thread_local_static(def_id));
2341 /// A collection of projections into user types.
2343 /// They are projections because a binding can occur a part of a
2344 /// parent pattern that has been ascribed a type.
2346 /// Its a collection because there can be multiple type ascriptions on
2347 /// the path from the root of the pattern down to the binding itself.
2352 /// struct S<'a>((i32, &'a str), String);
2353 /// let S((_, w): (i32, &'static str), _): S = ...;
2354 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2355 /// // --------------------------------- ^ (2)
2358 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2359 /// ascribed the type `(i32, &'static str)`.
2361 /// The highlights labelled `(2)` show the whole pattern being
2362 /// ascribed the type `S`.
2364 /// In this example, when we descend to `w`, we will have built up the
2365 /// following two projected types:
2367 /// * base: `S`, projection: `(base.0).1`
2368 /// * base: `(i32, &'static str)`, projection: `base.1`
2370 /// The first will lead to the constraint `w: &'1 str` (for some
2371 /// inferred region `'1`). The second will lead to the constraint `w:
2373 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2374 pub struct UserTypeProjections {
2375 pub contents: Vec<(UserTypeProjection, Span)>,
2378 impl<'tcx> UserTypeProjections {
2379 pub fn none() -> Self {
2380 UserTypeProjections { contents: vec![] }
2383 pub fn is_empty(&self) -> bool {
2384 self.contents.is_empty()
2387 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2388 UserTypeProjections { contents: projs.collect() }
2391 pub fn projections_and_spans(
2393 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2394 self.contents.iter()
2397 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2398 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2401 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2402 self.contents.push((user_ty.clone(), span));
2408 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2410 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2414 pub fn index(self) -> Self {
2415 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2418 pub fn subslice(self, from: u64, to: u64) -> Self {
2419 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2422 pub fn deref(self) -> Self {
2423 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2426 pub fn leaf(self, field: Field) -> Self {
2427 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2430 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2431 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2435 /// Encodes the effect of a user-supplied type annotation on the
2436 /// subcomponents of a pattern. The effect is determined by applying the
2437 /// given list of proejctions to some underlying base type. Often,
2438 /// the projection element list `projs` is empty, in which case this
2439 /// directly encodes a type in `base`. But in the case of complex patterns with
2440 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2441 /// in which case the `projs` vector is used.
2445 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2447 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2448 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2449 /// determined by finding the type of the `.0` field from `T`.
2450 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2451 pub struct UserTypeProjection {
2452 pub base: UserTypeAnnotationIndex,
2453 pub projs: Vec<ProjectionKind>,
2456 impl Copy for ProjectionKind {}
2458 impl UserTypeProjection {
2459 pub(crate) fn index(mut self) -> Self {
2460 self.projs.push(ProjectionElem::Index(()));
2464 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2465 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2469 pub(crate) fn deref(mut self) -> Self {
2470 self.projs.push(ProjectionElem::Deref);
2474 pub(crate) fn leaf(mut self, field: Field) -> Self {
2475 self.projs.push(ProjectionElem::Field(field, ()));
2479 pub(crate) fn variant(
2482 variant_index: VariantIdx,
2485 self.projs.push(ProjectionElem::Downcast(
2486 Some(adt_def.variants[variant_index].ident.name),
2489 self.projs.push(ProjectionElem::Field(field, ()));
2494 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2496 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2497 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2498 use crate::mir::ProjectionElem::*;
2500 let base = self.base.fold_with(folder);
2501 let projs: Vec<_> = self
2504 .map(|&elem| match elem {
2506 Field(f, ()) => Field(f, ()),
2507 Index(()) => Index(()),
2508 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2509 ConstantIndex { offset, min_length, from_end } => {
2510 ConstantIndex { offset, min_length, from_end }
2512 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2516 UserTypeProjection { base, projs }
2519 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2520 self.base.visit_with(visitor)
2521 // Note: there's nothing in `self.proj` to visit.
2525 rustc_index::newtype_index! {
2526 pub struct Promoted {
2528 DEBUG_FORMAT = "promoted[{}]"
2532 impl<'tcx> Debug for Constant<'tcx> {
2533 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2534 write!(fmt, "{}", self)
2538 impl<'tcx> Display for Constant<'tcx> {
2539 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2540 match self.literal.ty.kind() {
2542 _ => write!(fmt, "const ")?,
2544 pretty_print_const(self.literal, fmt, true)
2548 fn pretty_print_const(
2549 c: &ty::Const<'tcx>,
2550 fmt: &mut Formatter<'_>,
2553 use crate::ty::print::PrettyPrinter;
2554 ty::tls::with(|tcx| {
2555 let literal = tcx.lift(&c).unwrap();
2556 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2557 cx.print_alloc_ids = true;
2558 cx.pretty_print_const(literal, print_types)?;
2563 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2564 type Node = BasicBlock;
2567 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2569 fn num_nodes(&self) -> usize {
2570 self.basic_blocks.len()
2574 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2576 fn start_node(&self) -> Self::Node {
2581 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2583 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2584 self.basic_blocks[node].terminator().successors().cloned()
2588 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2589 type Item = BasicBlock;
2590 type Iter = iter::Cloned<Successors<'b>>;
2593 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2594 type Item = BasicBlock;
2595 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2598 impl graph::WithPredecessors for Body<'tcx> {
2600 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2601 self.predecessors()[node].clone().into_iter()
2605 /// `Location` represents the position of the start of the statement; or, if
2606 /// `statement_index` equals the number of statements, then the start of the
2608 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2609 pub struct Location {
2610 /// The block that the location is within.
2611 pub block: BasicBlock,
2613 pub statement_index: usize,
2616 impl fmt::Debug for Location {
2617 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2618 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2623 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2625 /// Returns the location immediately after this one within the enclosing block.
2627 /// Note that if this location represents a terminator, then the
2628 /// resulting location would be out of bounds and invalid.
2629 pub fn successor_within_block(&self) -> Location {
2630 Location { block: self.block, statement_index: self.statement_index + 1 }
2633 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2634 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2635 // If we are in the same block as the other location and are an earlier statement
2636 // then we are a predecessor of `other`.
2637 if self.block == other.block && self.statement_index < other.statement_index {
2641 let predecessors = body.predecessors();
2643 // If we're in another block, then we want to check that block is a predecessor of `other`.
2644 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2645 let mut visited = FxHashSet::default();
2647 while let Some(block) = queue.pop() {
2648 // If we haven't visited this block before, then make sure we visit it's predecessors.
2649 if visited.insert(block) {
2650 queue.extend(predecessors[block].iter().cloned());
2655 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2656 // we found that block by looking at the predecessors of `other`).
2657 if self.block == block {
2665 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2666 if self.block == other.block {
2667 self.statement_index <= other.statement_index
2669 dominators.is_dominated_by(other.block, self.block)