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, 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};
13 use crate::ty::{self, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, Region, UserTypeAnnotationIndex};
16 use rustc_hir::def::{CtorKind, Namespace};
17 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
18 use rustc_hir::{self, GeneratorKind};
19 use rustc_target::abi::VariantIdx;
21 use polonius_engine::Atom;
22 pub use rustc_ast::Mutability;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphSuccessors};
26 use rustc_index::bit_set::BitMatrix;
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_serialize::{Decodable, Encodable};
29 use rustc_span::symbol::Symbol;
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::asm::InlineAsmRegOrRegClass;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::ops::{ControlFlow, Index, IndexMut};
36 use std::{iter, mem, option};
38 use self::predecessors::{PredecessorCache, Predecessors};
39 pub use self::query::*;
41 pub mod abstract_const;
49 pub use terminator::*;
55 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
57 pub trait HasLocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx>;
61 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
62 fn local_decls(&self) -> &LocalDecls<'tcx> {
67 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
68 fn local_decls(&self) -> &LocalDecls<'tcx> {
73 /// The various "big phases" that MIR goes through.
75 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
76 /// dialects forbid certain variants or values in certain phases.
78 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
79 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
81 /// Warning: ordering of variants is significant.
82 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
86 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
87 // We used to have this for pre-miri MIR based const eval.
89 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
90 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
91 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
95 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
96 /// * `DropAndReplace` is gone for good
97 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
98 /// means that the auto-generated drop glue will be invoked.
100 /// After this phase, generators are explicit state machines (no more `Yield`).
101 /// `AggregateKind::Generator` is gone for good.
102 GeneratorLowering = 4,
107 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
108 pub fn phase_index(&self) -> usize {
113 /// Where a specific `mir::Body` comes from.
114 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
115 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
116 pub struct MirSource<'tcx> {
117 pub instance: InstanceDef<'tcx>,
119 /// If `Some`, this is a promoted rvalue within the parent function.
120 pub promoted: Option<Promoted>,
123 impl<'tcx> MirSource<'tcx> {
124 pub fn item(def_id: DefId) -> Self {
126 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
131 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
132 MirSource { instance, promoted: None }
135 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
136 self.instance.with_opt_param()
140 pub fn def_id(&self) -> DefId {
141 self.instance.def_id()
145 /// The lowered representation of a single function.
146 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
147 pub struct Body<'tcx> {
148 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
149 /// that indexes into this vector.
150 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
152 /// Records how far through the "desugaring and optimization" process this particular
153 /// MIR has traversed. This is particularly useful when inlining, since in that context
154 /// we instantiate the promoted constants and add them to our promoted vector -- but those
155 /// promoted items have already been optimized, whereas ours have not. This field allows
156 /// us to see the difference and forego optimization on the inlined promoted items.
159 pub source: MirSource<'tcx>,
161 /// A list of source scopes; these are referenced by statements
162 /// and used for debuginfo. Indexed by a `SourceScope`.
163 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
165 /// The yield type of the function, if it is a generator.
166 pub yield_ty: Option<Ty<'tcx>>,
168 /// Generator drop glue.
169 pub generator_drop: Option<Box<Body<'tcx>>>,
171 /// The layout of a generator. Produced by the state transformation.
172 pub generator_layout: Option<GeneratorLayout<'tcx>>,
174 /// If this is a generator then record the type of source expression that caused this generator
176 pub generator_kind: Option<GeneratorKind>,
178 /// Declarations of locals.
180 /// The first local is the return value pointer, followed by `arg_count`
181 /// locals for the function arguments, followed by any user-declared
182 /// variables and temporaries.
183 pub local_decls: LocalDecls<'tcx>,
185 /// User type annotations.
186 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
188 /// The number of arguments this function takes.
190 /// Starting at local 1, `arg_count` locals will be provided by the caller
191 /// and can be assumed to be initialized.
193 /// If this MIR was built for a constant, this will be 0.
194 pub arg_count: usize,
196 /// Mark an argument local (which must be a tuple) as getting passed as
197 /// its individual components at the LLVM level.
199 /// This is used for the "rust-call" ABI.
200 pub spread_arg: Option<Local>,
202 /// Debug information pertaining to user variables, including captures.
203 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
205 /// A span representing this MIR, for error reporting.
208 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
209 /// We hold in this field all the constants we are not able to evaluate yet.
210 pub required_consts: Vec<Constant<'tcx>>,
212 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
214 /// Note that this does not actually mean that this body is not computable right now.
215 /// The repeat count in the following example is polymorphic, but can still be evaluated
216 /// without knowing anything about the type parameter `T`.
220 /// let _ = [0; std::mem::size_of::<*mut T>()];
224 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
225 /// removed the last mention of all generic params. We do not want to rely on optimizations and
226 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
227 pub is_polymorphic: bool,
229 predecessor_cache: PredecessorCache,
232 impl<'tcx> Body<'tcx> {
234 source: MirSource<'tcx>,
235 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
236 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
237 local_decls: LocalDecls<'tcx>,
238 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
240 var_debug_info: Vec<VarDebugInfo<'tcx>>,
242 generator_kind: Option<GeneratorKind>,
244 // We need `arg_count` locals, and one for the return place.
246 local_decls.len() > arg_count,
247 "expected at least {} locals, got {}",
252 let mut body = Body {
253 phase: MirPhase::Build,
258 generator_drop: None,
259 generator_layout: None,
262 user_type_annotations,
267 required_consts: Vec::new(),
268 is_polymorphic: false,
269 predecessor_cache: PredecessorCache::new(),
271 body.is_polymorphic = body.has_param_types_or_consts();
275 /// Returns a partially initialized MIR body containing only a list of basic blocks.
277 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
278 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
280 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
281 let mut body = Body {
282 phase: MirPhase::Build,
283 source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
285 source_scopes: IndexVec::new(),
287 generator_drop: None,
288 generator_layout: None,
289 local_decls: IndexVec::new(),
290 user_type_annotations: IndexVec::new(),
294 required_consts: Vec::new(),
295 generator_kind: None,
296 var_debug_info: Vec::new(),
297 is_polymorphic: false,
298 predecessor_cache: PredecessorCache::new(),
300 body.is_polymorphic = body.has_param_types_or_consts();
305 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
310 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
311 // Because the user could mutate basic block terminators via this reference, we need to
312 // invalidate the predecessor cache.
314 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
315 // invalidate the predecessor cache.
316 self.predecessor_cache.invalidate();
317 &mut self.basic_blocks
321 pub fn basic_blocks_and_local_decls_mut(
323 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
324 self.predecessor_cache.invalidate();
325 (&mut self.basic_blocks, &mut self.local_decls)
329 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
332 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
333 &mut LocalDecls<'tcx>,
334 &mut Vec<VarDebugInfo<'tcx>>,
336 self.predecessor_cache.invalidate();
337 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
340 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
342 pub fn is_cfg_cyclic(&self) -> bool {
343 graph::is_cyclic(self)
347 pub fn local_kind(&self, local: Local) -> LocalKind {
348 let index = local.as_usize();
351 self.local_decls[local].mutability == Mutability::Mut,
352 "return place should be mutable"
355 LocalKind::ReturnPointer
356 } else if index < self.arg_count + 1 {
358 } else if self.local_decls[local].is_user_variable() {
365 /// Returns an iterator over all temporaries.
367 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
368 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
369 let local = Local::new(index);
370 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
374 /// Returns an iterator over all user-declared locals.
376 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
377 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
378 let local = Local::new(index);
379 self.local_decls[local].is_user_variable().then_some(local)
383 /// Returns an iterator over all user-declared mutable locals.
385 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
386 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
387 let local = Local::new(index);
388 let decl = &self.local_decls[local];
389 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
397 /// Returns an iterator over all user-declared mutable arguments and locals.
399 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
400 (1..self.local_decls.len()).filter_map(move |index| {
401 let local = Local::new(index);
402 let decl = &self.local_decls[local];
403 if (decl.is_user_variable() || index < self.arg_count + 1)
404 && decl.mutability == Mutability::Mut
413 /// Returns an iterator over all function arguments.
415 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
416 let arg_count = self.arg_count;
417 (1..arg_count + 1).map(Local::new)
420 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
421 /// locals that are neither arguments nor the return place).
423 pub fn vars_and_temps_iter(
425 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
426 let arg_count = self.arg_count;
427 let local_count = self.local_decls.len();
428 (arg_count + 1..local_count).map(Local::new)
431 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
432 /// invalidating statement indices in `Location`s.
433 pub fn make_statement_nop(&mut self, location: Location) {
434 let block = &mut self.basic_blocks[location.block];
435 debug_assert!(location.statement_index < block.statements.len());
436 block.statements[location.statement_index].make_nop()
439 /// Returns the source info associated with `location`.
440 pub fn source_info(&self, location: Location) -> &SourceInfo {
441 let block = &self[location.block];
442 let stmts = &block.statements;
443 let idx = location.statement_index;
444 if idx < stmts.len() {
445 &stmts[idx].source_info
447 assert_eq!(idx, stmts.len());
448 &block.terminator().source_info
452 /// Returns the return type; it always return first element from `local_decls` array.
454 pub fn return_ty(&self) -> Ty<'tcx> {
455 self.local_decls[RETURN_PLACE].ty
458 /// Gets the location of the terminator for the given block.
460 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
461 Location { block: bb, statement_index: self[bb].statements.len() }
465 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
466 self.predecessor_cache.compute(&self.basic_blocks)
470 pub fn dominators(&self) -> Dominators<BasicBlock> {
475 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
478 /// Unsafe because of a PushUnsafeBlock
480 /// Unsafe because of an unsafe fn
482 /// Unsafe because of an `unsafe` block
483 ExplicitUnsafe(hir::HirId),
486 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
487 type Output = BasicBlockData<'tcx>;
490 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
491 &self.basic_blocks()[index]
495 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
497 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
498 &mut self.basic_blocks_mut()[index]
502 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
503 pub enum ClearCrossCrate<T> {
508 impl<T> ClearCrossCrate<T> {
509 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
511 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
512 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
516 pub fn assert_crate_local(self) -> T {
518 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
519 ClearCrossCrate::Set(v) => v,
524 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
525 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
527 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
529 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
530 if E::CLEAR_CROSS_CRATE {
535 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
536 ClearCrossCrate::Set(ref val) => {
537 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
543 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
545 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
546 if D::CLEAR_CROSS_CRATE {
547 return Ok(ClearCrossCrate::Clear);
550 let discr = u8::decode(d)?;
553 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
554 TAG_CLEAR_CROSS_CRATE_SET => {
555 let val = T::decode(d)?;
556 Ok(ClearCrossCrate::Set(val))
558 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
563 /// Grouped information about the source code origin of a MIR entity.
564 /// Intended to be inspected by diagnostics and debuginfo.
565 /// Most passes can work with it as a whole, within a single function.
566 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
567 // `Hash`. Please ping @bjorn3 if removing them.
568 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
569 pub struct SourceInfo {
570 /// The source span for the AST pertaining to this MIR entity.
573 /// The source scope, keeping track of which bindings can be
574 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
575 pub scope: SourceScope,
580 pub fn outermost(span: Span) -> Self {
581 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
585 ///////////////////////////////////////////////////////////////////////////
588 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
589 #[derive(HashStable)]
590 pub enum BorrowKind {
591 /// Data must be immutable and is aliasable.
594 /// The immediately borrowed place must be immutable, but projections from
595 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
596 /// conflict with a mutable borrow of `a.b.c`.
598 /// This is used when lowering matches: when matching on a place we want to
599 /// ensure that place have the same value from the start of the match until
600 /// an arm is selected. This prevents this code from compiling:
602 /// let mut x = &Some(0);
605 /// Some(_) if { x = &None; false } => (),
609 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
610 /// should not prevent `if let None = x { ... }`, for example, because the
611 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
612 /// We can also report errors with this kind of borrow differently.
615 /// Data must be immutable but not aliasable. This kind of borrow
616 /// cannot currently be expressed by the user and is used only in
617 /// implicit closure bindings. It is needed when the closure is
618 /// borrowing or mutating a mutable referent, e.g.:
620 /// let x: &mut isize = ...;
621 /// let y = || *x += 5;
623 /// If we were to try to translate this closure into a more explicit
624 /// form, we'd encounter an error with the code as written:
626 /// struct Env { x: & &mut isize }
627 /// let x: &mut isize = ...;
628 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
629 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
631 /// This is then illegal because you cannot mutate an `&mut` found
632 /// in an aliasable location. To solve, you'd have to translate with
633 /// an `&mut` borrow:
635 /// struct Env { x: & &mut isize }
636 /// let x: &mut isize = ...;
637 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
638 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
640 /// Now the assignment to `**env.x` is legal, but creating a
641 /// mutable pointer to `x` is not because `x` is not mutable. We
642 /// could fix this by declaring `x` as `let mut x`. This is ok in
643 /// user code, if awkward, but extra weird for closures, since the
644 /// borrow is hidden.
646 /// So we introduce a "unique imm" borrow -- the referent is
647 /// immutable, but not aliasable. This solves the problem. For
648 /// simplicity, we don't give users the way to express this
649 /// borrow, it's just used when translating closures.
652 /// Data is mutable and not aliasable.
654 /// `true` if this borrow arose from method-call auto-ref
655 /// (i.e., `adjustment::Adjust::Borrow`).
656 allow_two_phase_borrow: bool,
661 pub fn allows_two_phase_borrow(&self) -> bool {
663 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
664 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
669 ///////////////////////////////////////////////////////////////////////////
670 // Variables and temps
672 rustc_index::newtype_index! {
675 DEBUG_FORMAT = "_{}",
676 const RETURN_PLACE = 0,
680 impl Atom for Local {
681 fn index(self) -> usize {
686 /// Classifies locals into categories. See `Body::local_kind`.
687 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
689 /// User-declared variable binding.
691 /// Compiler-introduced temporary.
693 /// Function argument.
695 /// Location of function's return value.
699 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
700 pub struct VarBindingForm<'tcx> {
701 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
702 pub binding_mode: ty::BindingMode,
703 /// If an explicit type was provided for this variable binding,
704 /// this holds the source Span of that type.
706 /// NOTE: if you want to change this to a `HirId`, be wary that
707 /// doing so breaks incremental compilation (as of this writing),
708 /// while a `Span` does not cause our tests to fail.
709 pub opt_ty_info: Option<Span>,
710 /// Place of the RHS of the =, or the subject of the `match` where this
711 /// variable is initialized. None in the case of `let PATTERN;`.
712 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
713 /// (a) the right-hand side isn't evaluated as a place expression.
714 /// (b) it gives a way to separate this case from the remaining cases
716 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
717 /// The span of the pattern in which this variable was bound.
721 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
722 pub enum BindingForm<'tcx> {
723 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
724 Var(VarBindingForm<'tcx>),
725 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
726 ImplicitSelf(ImplicitSelfKind),
727 /// Reference used in a guard expression to ensure immutability.
731 /// Represents what type of implicit self a function has, if any.
732 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
733 pub enum ImplicitSelfKind {
734 /// Represents a `fn x(self);`.
736 /// Represents a `fn x(mut self);`.
738 /// Represents a `fn x(&self);`.
740 /// Represents a `fn x(&mut self);`.
742 /// Represents when a function does not have a self argument or
743 /// when a function has a `self: X` argument.
747 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
749 mod binding_form_impl {
750 use crate::ich::StableHashingContext;
751 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
753 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
754 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
755 use super::BindingForm::*;
756 std::mem::discriminant(self).hash_stable(hcx, hasher);
759 Var(binding) => binding.hash_stable(hcx, hasher),
760 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
767 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
768 /// created during evaluation of expressions in a block tail
769 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
771 /// It is used to improve diagnostics when such temporaries are
772 /// involved in borrow_check errors, e.g., explanations of where the
773 /// temporaries come from, when their destructors are run, and/or how
774 /// one might revise the code to satisfy the borrow checker's rules.
775 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
776 pub struct BlockTailInfo {
777 /// If `true`, then the value resulting from evaluating this tail
778 /// expression is ignored by the block's expression context.
780 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
781 /// but not e.g., `let _x = { ...; tail };`
782 pub tail_result_is_ignored: bool,
784 /// `Span` of the tail expression.
790 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
791 /// argument, or the return place.
792 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
793 pub struct LocalDecl<'tcx> {
794 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
796 /// Temporaries and the return place are always mutable.
797 pub mutability: Mutability,
799 // FIXME(matthewjasper) Don't store in this in `Body`
800 pub local_info: Option<Box<LocalInfo<'tcx>>>,
802 /// `true` if this is an internal local.
804 /// These locals are not based on types in the source code and are only used
805 /// for a few desugarings at the moment.
807 /// The generator transformation will sanity check the locals which are live
808 /// across a suspension point against the type components of the generator
809 /// which type checking knows are live across a suspension point. We need to
810 /// flag drop flags to avoid triggering this check as they are introduced
813 /// This should be sound because the drop flags are fully algebraic, and
814 /// therefore don't affect the OIBIT or outlives properties of the
818 /// If this local is a temporary and `is_block_tail` is `Some`,
819 /// then it is a temporary created for evaluation of some
820 /// subexpression of some block's tail expression (with no
821 /// intervening statement context).
822 // FIXME(matthewjasper) Don't store in this in `Body`
823 pub is_block_tail: Option<BlockTailInfo>,
825 /// The type of this local.
828 /// If the user manually ascribed a type to this variable,
829 /// e.g., via `let x: T`, then we carry that type here. The MIR
830 /// borrow checker needs this information since it can affect
831 /// region inference.
832 // FIXME(matthewjasper) Don't store in this in `Body`
833 pub user_ty: Option<Box<UserTypeProjections>>,
835 /// The *syntactic* (i.e., not visibility) source scope the local is defined
836 /// in. If the local was defined in a let-statement, this
837 /// is *within* the let-statement, rather than outside
840 /// This is needed because the visibility source scope of locals within
841 /// a let-statement is weird.
843 /// The reason is that we want the local to be *within* the let-statement
844 /// for lint purposes, but we want the local to be *after* the let-statement
845 /// for names-in-scope purposes.
847 /// That's it, if we have a let-statement like the one in this
851 /// fn foo(x: &str) {
852 /// #[allow(unused_mut)]
853 /// let mut x: u32 = { // <- one unused mut
854 /// let mut y: u32 = x.parse().unwrap();
861 /// Then, from a lint point of view, the declaration of `x: u32`
862 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
863 /// lint scopes are the same as the AST/HIR nesting.
865 /// However, from a name lookup point of view, the scopes look more like
866 /// as if the let-statements were `match` expressions:
869 /// fn foo(x: &str) {
871 /// match x.parse().unwrap() {
880 /// We care about the name-lookup scopes for debuginfo - if the
881 /// debuginfo instruction pointer is at the call to `x.parse()`, we
882 /// want `x` to refer to `x: &str`, but if it is at the call to
883 /// `drop(x)`, we want it to refer to `x: u32`.
885 /// To allow both uses to work, we need to have more than a single scope
886 /// for a local. We have the `source_info.scope` represent the "syntactic"
887 /// lint scope (with a variable being under its let block) while the
888 /// `var_debug_info.source_info.scope` represents the "local variable"
889 /// scope (where the "rest" of a block is under all prior let-statements).
891 /// The end result looks like this:
895 /// │{ argument x: &str }
897 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
898 /// │ │ // in practice because I'm lazy.
900 /// │ │← x.source_info.scope
901 /// │ │← `x.parse().unwrap()`
903 /// │ │ │← y.source_info.scope
905 /// │ │ │{ let y: u32 }
907 /// │ │ │← y.var_debug_info.source_info.scope
910 /// │ │{ let x: u32 }
911 /// │ │← x.var_debug_info.source_info.scope
912 /// │ │← `drop(x)` // This accesses `x: u32`.
914 pub source_info: SourceInfo,
917 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
918 #[cfg(target_arch = "x86_64")]
919 static_assert_size!(LocalDecl<'_>, 56);
921 /// Extra information about a some locals that's used for diagnostics and for
922 /// classifying variables into local variables, statics, etc, which is needed e.g.
923 /// for unsafety checking.
925 /// Not used for non-StaticRef temporaries, the return place, or anonymous
926 /// function parameters.
927 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
928 pub enum LocalInfo<'tcx> {
929 /// A user-defined local variable or function parameter
931 /// The `BindingForm` is solely used for local diagnostics when generating
932 /// warnings/errors when compiling the current crate, and therefore it need
933 /// not be visible across crates.
934 User(ClearCrossCrate<BindingForm<'tcx>>),
935 /// A temporary created that references the static with the given `DefId`.
936 StaticRef { def_id: DefId, is_thread_local: bool },
937 /// A temporary created that references the const with the given `DefId`
938 ConstRef { def_id: DefId },
941 impl<'tcx> LocalDecl<'tcx> {
942 /// Returns `true` only if local is a binding that can itself be
943 /// made mutable via the addition of the `mut` keyword, namely
944 /// something like the occurrences of `x` in:
945 /// - `fn foo(x: Type) { ... }`,
947 /// - or `match ... { C(x) => ... }`
948 pub fn can_be_made_mutable(&self) -> bool {
951 Some(box LocalInfo::User(ClearCrossCrate::Set(
952 BindingForm::Var(VarBindingForm {
953 binding_mode: ty::BindingMode::BindByValue(_),
958 | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
963 /// Returns `true` if local is definitely not a `ref ident` or
964 /// `ref mut ident` binding. (Such bindings cannot be made into
965 /// mutable bindings, but the inverse does not necessarily hold).
966 pub fn is_nonref_binding(&self) -> bool {
969 Some(box LocalInfo::User(ClearCrossCrate::Set(
970 BindingForm::Var(VarBindingForm {
971 binding_mode: ty::BindingMode::BindByValue(_),
976 | BindingForm::ImplicitSelf(_),
981 /// Returns `true` if this variable is a named variable or function
982 /// parameter declared by the user.
984 pub fn is_user_variable(&self) -> bool {
985 matches!(self.local_info, Some(box LocalInfo::User(_)))
988 /// Returns `true` if this is a reference to a variable bound in a `match`
989 /// expression that is used to access said variable for the guard of the
991 pub fn is_ref_for_guard(&self) -> bool {
994 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
998 /// Returns `Some` if this is a reference to a static item that is used to
999 /// access that static.
1000 pub fn is_ref_to_static(&self) -> bool {
1001 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1004 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1005 /// access that static.
1006 pub fn is_ref_to_thread_local(&self) -> bool {
1007 match self.local_info {
1008 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1013 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1014 /// `__next` from a `for` loop.
1016 pub fn from_compiler_desugaring(&self) -> bool {
1017 self.source_info.span.desugaring_kind().is_some()
1020 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1022 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1023 Self::with_source_info(ty, SourceInfo::outermost(span))
1026 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1028 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1030 mutability: Mutability::Mut,
1033 is_block_tail: None,
1040 /// Converts `self` into same `LocalDecl` except tagged as internal.
1042 pub fn internal(mut self) -> Self {
1043 self.internal = true;
1047 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1049 pub fn immutable(mut self) -> Self {
1050 self.mutability = Mutability::Not;
1054 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1056 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1057 assert!(self.is_block_tail.is_none());
1058 self.is_block_tail = Some(info);
1063 /// Debug information pertaining to a user variable.
1064 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1065 pub struct VarDebugInfo<'tcx> {
1068 /// Source info of the user variable, including the scope
1069 /// within which the variable is visible (to debuginfo)
1070 /// (see `LocalDecl`'s `source_info` field for more details).
1071 pub source_info: SourceInfo,
1073 /// Where the data for this user variable is to be found.
1074 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1075 /// based on a `Local`, not a `Static`, and contains no indexing.
1076 pub place: Place<'tcx>,
1079 ///////////////////////////////////////////////////////////////////////////
1082 rustc_index::newtype_index! {
1083 /// A node in the MIR [control-flow graph][CFG].
1085 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1086 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1087 /// as an edge in a graph between basic blocks.
1089 /// Basic blocks consist of a series of [statements][Statement], ending with a
1090 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1091 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1092 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1093 /// needed because some analyses require that there are no critical edges in the CFG.
1095 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1096 /// the actual data that a basic block holds is in [`BasicBlockData`].
1098 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1100 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1101 /// [data-flow analyses]:
1102 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1103 /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1104 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1105 pub struct BasicBlock {
1107 DEBUG_FORMAT = "bb{}",
1108 const START_BLOCK = 0,
1113 pub fn start_location(self) -> Location {
1114 Location { block: self, statement_index: 0 }
1118 ///////////////////////////////////////////////////////////////////////////
1119 // BasicBlockData and Terminator
1121 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1122 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1123 pub struct BasicBlockData<'tcx> {
1124 /// List of statements in this block.
1125 pub statements: Vec<Statement<'tcx>>,
1127 /// Terminator for this block.
1129 /// N.B., this should generally ONLY be `None` during construction.
1130 /// Therefore, you should generally access it via the
1131 /// `terminator()` or `terminator_mut()` methods. The only
1132 /// exception is that certain passes, such as `simplify_cfg`, swap
1133 /// out the terminator temporarily with `None` while they continue
1134 /// to recurse over the set of basic blocks.
1135 pub terminator: Option<Terminator<'tcx>>,
1137 /// If true, this block lies on an unwind path. This is used
1138 /// during codegen where distinct kinds of basic blocks may be
1139 /// generated (particularly for MSVC cleanup). Unwind blocks must
1140 /// only branch to other unwind blocks.
1141 pub is_cleanup: bool,
1144 /// Information about an assertion failure.
1145 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1146 pub enum AssertKind<O> {
1147 BoundsCheck { len: O, index: O },
1148 Overflow(BinOp, O, O),
1152 ResumedAfterReturn(GeneratorKind),
1153 ResumedAfterPanic(GeneratorKind),
1156 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1157 pub enum InlineAsmOperand<'tcx> {
1159 reg: InlineAsmRegOrRegClass,
1160 value: Operand<'tcx>,
1163 reg: InlineAsmRegOrRegClass,
1165 place: Option<Place<'tcx>>,
1168 reg: InlineAsmRegOrRegClass,
1170 in_value: Operand<'tcx>,
1171 out_place: Option<Place<'tcx>>,
1174 value: Operand<'tcx>,
1177 value: Box<Constant<'tcx>>,
1184 /// Type for MIR `Assert` terminator error messages.
1185 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1187 pub type Successors<'a> =
1188 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1189 pub type SuccessorsMut<'a> =
1190 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1192 impl<'tcx> BasicBlockData<'tcx> {
1193 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1194 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1197 /// Accessor for terminator.
1199 /// Terminator may not be None after construction of the basic block is complete. This accessor
1200 /// provides a convenience way to reach the terminator.
1201 pub fn terminator(&self) -> &Terminator<'tcx> {
1202 self.terminator.as_ref().expect("invalid terminator state")
1205 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1206 self.terminator.as_mut().expect("invalid terminator state")
1209 pub fn retain_statements<F>(&mut self, mut f: F)
1211 F: FnMut(&mut Statement<'_>) -> bool,
1213 for s in &mut self.statements {
1220 pub fn expand_statements<F, I>(&mut self, mut f: F)
1222 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1223 I: iter::TrustedLen<Item = Statement<'tcx>>,
1225 // Gather all the iterators we'll need to splice in, and their positions.
1226 let mut splices: Vec<(usize, I)> = vec![];
1227 let mut extra_stmts = 0;
1228 for (i, s) in self.statements.iter_mut().enumerate() {
1229 if let Some(mut new_stmts) = f(s) {
1230 if let Some(first) = new_stmts.next() {
1231 // We can already store the first new statement.
1234 // Save the other statements for optimized splicing.
1235 let remaining = new_stmts.size_hint().0;
1237 splices.push((i + 1 + extra_stmts, new_stmts));
1238 extra_stmts += remaining;
1246 // Splice in the new statements, from the end of the block.
1247 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1248 // where a range of elements ("gap") is left uninitialized, with
1249 // splicing adding new elements to the end of that gap and moving
1250 // existing elements from before the gap to the end of the gap.
1251 // For now, this is safe code, emulating a gap but initializing it.
1252 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1253 self.statements.resize(
1255 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1257 for (splice_start, new_stmts) in splices.into_iter().rev() {
1258 let splice_end = splice_start + new_stmts.size_hint().0;
1259 while gap.end > splice_end {
1262 self.statements.swap(gap.start, gap.end);
1264 self.statements.splice(splice_start..splice_end, new_stmts);
1265 gap.end = splice_start;
1269 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1270 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1274 impl<O> AssertKind<O> {
1275 /// Getting a description does not require `O` to be printable, and does not
1276 /// require allocation.
1277 /// The caller is expected to handle `BoundsCheck` separately.
1278 pub fn description(&self) -> &'static str {
1281 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1282 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1283 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1284 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1285 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1286 OverflowNeg(_) => "attempt to negate with overflow",
1287 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1288 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1289 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1290 DivisionByZero(_) => "attempt to divide by zero",
1291 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1292 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1293 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1294 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1295 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1296 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1300 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1301 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1307 BoundsCheck { ref len, ref index } => write!(
1309 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1313 OverflowNeg(op) => {
1314 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1316 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1317 RemainderByZero(op) => write!(
1319 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1322 Overflow(BinOp::Add, l, r) => write!(
1324 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1327 Overflow(BinOp::Sub, l, r) => write!(
1329 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1332 Overflow(BinOp::Mul, l, r) => write!(
1334 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1337 Overflow(BinOp::Div, l, r) => write!(
1339 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1342 Overflow(BinOp::Rem, l, r) => write!(
1344 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1347 Overflow(BinOp::Shr, _, r) => {
1348 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1350 Overflow(BinOp::Shl, _, r) => {
1351 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1353 _ => write!(f, "\"{}\"", self.description()),
1358 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1362 BoundsCheck { ref len, ref index } => write!(
1364 "index out of bounds: the length is {:?} but the index is {:?}",
1367 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1368 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1369 RemainderByZero(op) => write!(
1371 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1374 Overflow(BinOp::Add, l, r) => {
1375 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1377 Overflow(BinOp::Sub, l, r) => {
1378 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1380 Overflow(BinOp::Mul, l, r) => {
1381 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1383 Overflow(BinOp::Div, l, r) => {
1384 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1386 Overflow(BinOp::Rem, l, r) => write!(
1388 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1391 Overflow(BinOp::Shr, _, r) => {
1392 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1394 Overflow(BinOp::Shl, _, r) => {
1395 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1397 _ => write!(f, "{}", self.description()),
1402 ///////////////////////////////////////////////////////////////////////////
1405 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1406 pub struct Statement<'tcx> {
1407 pub source_info: SourceInfo,
1408 pub kind: StatementKind<'tcx>,
1411 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1412 #[cfg(target_arch = "x86_64")]
1413 static_assert_size!(Statement<'_>, 32);
1415 impl Statement<'_> {
1416 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1417 /// invalidating statement indices in `Location`s.
1418 pub fn make_nop(&mut self) {
1419 self.kind = StatementKind::Nop
1422 /// Changes a statement to a nop and returns the original statement.
1423 pub fn replace_nop(&mut self) -> Self {
1425 source_info: self.source_info,
1426 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1431 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1432 pub enum StatementKind<'tcx> {
1433 /// Write the RHS Rvalue to the LHS Place.
1434 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1436 /// This represents all the reading that a pattern match may do
1437 /// (e.g., inspecting constants and discriminant values), and the
1438 /// kind of pattern it comes from. This is in order to adapt potential
1439 /// error messages to these specific patterns.
1441 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1442 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1443 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1445 /// Write the discriminant for a variant to the enum Place.
1446 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1448 /// Start a live range for the storage of the local.
1451 /// End the current live range for the storage of the local.
1454 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1455 /// of `StatementKind` low.
1456 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1458 /// Retag references in the given place, ensuring they got fresh tags. This is
1459 /// part of the Stacked Borrows model. These statements are currently only interpreted
1460 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1461 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1462 /// for more details.
1463 Retag(RetagKind, Box<Place<'tcx>>),
1465 /// Encodes a user's type ascription. These need to be preserved
1466 /// intact so that NLL can respect them. For example:
1470 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1471 /// to the user-given type `T`. The effect depends on the specified variance:
1473 /// - `Covariant` -- requires that `T_y <: T`
1474 /// - `Contravariant` -- requires that `T_y :> T`
1475 /// - `Invariant` -- requires that `T_y == T`
1476 /// - `Bivariant` -- no effect
1477 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1479 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1480 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1481 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1482 /// counter varible at runtime, each time the code region is executed.
1483 Coverage(Box<Coverage>),
1485 /// No-op. Useful for deleting instructions without affecting statement indices.
1489 impl<'tcx> StatementKind<'tcx> {
1490 pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1492 StatementKind::Assign(x) => Some(x),
1498 /// Describes what kind of retag is to be performed.
1499 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1500 pub enum RetagKind {
1501 /// The initial retag when entering a function.
1503 /// Retag preparing for a two-phase borrow.
1505 /// Retagging raw pointers.
1507 /// A "normal" retag.
1511 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1512 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1513 pub enum FakeReadCause {
1514 /// Inject a fake read of the borrowed input at the end of each guards
1517 /// This should ensure that you cannot change the variant for an enum while
1518 /// you are in the midst of matching on it.
1521 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1522 /// generate a read of x to check that it is initialized and safe.
1525 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1526 /// in a match guard to ensure that it's value hasn't change by the time
1527 /// we create the OutsideGuard version.
1530 /// Officially, the semantics of
1532 /// `let pattern = <expr>;`
1534 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1535 /// into the pattern.
1537 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1538 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1539 /// but in some cases it can affect the borrow checker, as in #53695.
1540 /// Therefore, we insert a "fake read" here to ensure that we get
1541 /// appropriate errors.
1544 /// If we have an index expression like
1546 /// (*x)[1][{ x = y; 4}]
1548 /// then the first bounds check is invalidated when we evaluate the second
1549 /// index expression. Thus we create a fake borrow of `x` across the second
1550 /// indexer, which will cause a borrow check error.
1554 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1555 pub struct LlvmInlineAsm<'tcx> {
1556 pub asm: hir::LlvmInlineAsmInner,
1557 pub outputs: Box<[Place<'tcx>]>,
1558 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1561 impl Debug for Statement<'_> {
1562 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1563 use self::StatementKind::*;
1565 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1566 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1567 Retag(ref kind, ref place) => write!(
1571 RetagKind::FnEntry => "[fn entry] ",
1572 RetagKind::TwoPhase => "[2phase] ",
1573 RetagKind::Raw => "[raw] ",
1574 RetagKind::Default => "",
1578 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1579 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1580 SetDiscriminant { ref place, variant_index } => {
1581 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1583 LlvmInlineAsm(ref asm) => {
1584 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1586 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1587 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1589 Coverage(box ref coverage) => {
1590 if let Some(rgn) = &coverage.code_region {
1591 write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1593 write!(fmt, "Coverage::{:?}", coverage.kind)
1596 Nop => write!(fmt, "nop"),
1601 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1602 pub struct Coverage {
1603 pub kind: CoverageKind,
1604 pub code_region: Option<CodeRegion>,
1607 ///////////////////////////////////////////////////////////////////////////
1610 /// A path to a value; something that can be evaluated without
1611 /// changing or disturbing program state.
1612 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1613 pub struct Place<'tcx> {
1616 /// projection out of a place (access a field, deref a pointer, etc)
1617 pub projection: &'tcx List<PlaceElem<'tcx>>,
1620 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1621 #[derive(TyEncodable, TyDecodable, HashStable)]
1622 pub enum ProjectionElem<V, T> {
1627 /// These indices are generated by slice patterns. Easiest to explain
1631 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1632 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1633 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1634 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1637 /// index or -index (in Python terms), depending on from_end
1639 /// The thing being indexed must be at least this long. For arrays this
1640 /// is always the exact length.
1642 /// Counting backwards from end? This is always false when indexing an
1647 /// These indices are generated by slice patterns.
1649 /// If `from_end` is true `slice[from..slice.len() - to]`.
1650 /// Otherwise `array[from..to]`.
1654 /// Whether `to` counts from the start or end of the array/slice.
1655 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1656 /// For `ProjectionKind`, this can also be `true` for arrays.
1660 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1661 /// this for ADTs with more than one variant. It may be better to
1662 /// just introduce it always, or always for enums.
1664 /// The included Symbol is the name of the variant, used for printing MIR.
1665 Downcast(Option<Symbol>, VariantIdx),
1668 impl<V, T> ProjectionElem<V, T> {
1669 /// Returns `true` if the target of this projection may refer to a different region of memory
1671 fn is_indirect(&self) -> bool {
1673 Self::Deref => true,
1677 | Self::ConstantIndex { .. }
1678 | Self::Subslice { .. }
1679 | Self::Downcast(_, _) => false,
1684 /// Alias for projections as they appear in places, where the base is a place
1685 /// and the index is a local.
1686 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1688 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1689 #[cfg(target_arch = "x86_64")]
1690 static_assert_size!(PlaceElem<'_>, 24);
1692 /// Alias for projections as they appear in `UserTypeProjection`, where we
1693 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1694 pub type ProjectionKind = ProjectionElem<(), ()>;
1696 rustc_index::newtype_index! {
1699 DEBUG_FORMAT = "field[{}]"
1703 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1704 pub struct PlaceRef<'tcx> {
1706 pub projection: &'tcx [PlaceElem<'tcx>],
1709 impl<'tcx> Place<'tcx> {
1710 // FIXME change this to a const fn by also making List::empty a const fn.
1711 pub fn return_place() -> Place<'tcx> {
1712 Place { local: RETURN_PLACE, projection: List::empty() }
1715 /// Returns `true` if this `Place` contains a `Deref` projection.
1717 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1718 /// same region of memory as its base.
1719 pub fn is_indirect(&self) -> bool {
1720 self.projection.iter().any(|elem| elem.is_indirect())
1723 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1724 /// a single deref of a local.
1726 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1727 pub fn local_or_deref_local(&self) -> Option<Local> {
1728 match self.as_ref() {
1729 PlaceRef { local, projection: [] }
1730 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1735 /// If this place represents a local variable like `_X` with no
1736 /// projections, return `Some(_X)`.
1737 pub fn as_local(&self) -> Option<Local> {
1738 self.as_ref().as_local()
1741 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1742 PlaceRef { local: self.local, projection: &self.projection }
1746 impl From<Local> for Place<'_> {
1747 fn from(local: Local) -> Self {
1748 Place { local, projection: List::empty() }
1752 impl<'tcx> PlaceRef<'tcx> {
1753 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1754 /// a single deref of a local.
1756 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1757 pub fn local_or_deref_local(&self) -> Option<Local> {
1759 PlaceRef { local, projection: [] }
1760 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1765 /// If this place represents a local variable like `_X` with no
1766 /// projections, return `Some(_X)`.
1767 pub fn as_local(&self) -> Option<Local> {
1769 PlaceRef { local, projection: [] } => Some(local),
1775 impl Debug for Place<'_> {
1776 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1777 for elem in self.projection.iter().rev() {
1779 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1780 write!(fmt, "(").unwrap();
1782 ProjectionElem::Deref => {
1783 write!(fmt, "(*").unwrap();
1785 ProjectionElem::Index(_)
1786 | ProjectionElem::ConstantIndex { .. }
1787 | ProjectionElem::Subslice { .. } => {}
1791 write!(fmt, "{:?}", self.local)?;
1793 for elem in self.projection.iter() {
1795 ProjectionElem::Downcast(Some(name), _index) => {
1796 write!(fmt, " as {})", name)?;
1798 ProjectionElem::Downcast(None, index) => {
1799 write!(fmt, " as variant#{:?})", index)?;
1801 ProjectionElem::Deref => {
1804 ProjectionElem::Field(field, ty) => {
1805 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1807 ProjectionElem::Index(ref index) => {
1808 write!(fmt, "[{:?}]", index)?;
1810 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1811 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1813 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1814 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1816 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1817 write!(fmt, "[{:?}:]", from)?;
1819 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1820 write!(fmt, "[:-{:?}]", to)?;
1822 ProjectionElem::Subslice { from, to, from_end: true } => {
1823 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1825 ProjectionElem::Subslice { from, to, from_end: false } => {
1826 write!(fmt, "[{:?}..{:?}]", from, to)?;
1835 ///////////////////////////////////////////////////////////////////////////
1838 rustc_index::newtype_index! {
1839 pub struct SourceScope {
1841 DEBUG_FORMAT = "scope[{}]",
1842 const OUTERMOST_SOURCE_SCOPE = 0,
1846 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1847 pub struct SourceScopeData<'tcx> {
1849 pub parent_scope: Option<SourceScope>,
1851 /// Whether this scope is the root of a scope tree of another body,
1852 /// inlined into this body by the MIR inliner.
1853 /// `ty::Instance` is the callee, and the `Span` is the call site.
1854 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1856 /// Nearest (transitive) parent scope (if any) which is inlined.
1857 /// This is an optimization over walking up `parent_scope`
1858 /// until a scope with `inlined: Some(...)` is found.
1859 pub inlined_parent_scope: Option<SourceScope>,
1861 /// Crate-local information for this source scope, that can't (and
1862 /// needn't) be tracked across crates.
1863 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1866 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1867 pub struct SourceScopeLocalData {
1868 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1869 pub lint_root: hir::HirId,
1870 /// The unsafe block that contains this node.
1874 ///////////////////////////////////////////////////////////////////////////
1877 /// These are values that can appear inside an rvalue. They are intentionally
1878 /// limited to prevent rvalues from being nested in one another.
1879 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1880 pub enum Operand<'tcx> {
1881 /// Copy: The value must be available for use afterwards.
1883 /// This implies that the type of the place must be `Copy`; this is true
1884 /// by construction during build, but also checked by the MIR type checker.
1887 /// Move: The value (including old borrows of it) will not be used again.
1889 /// Safe for values of all types (modulo future developments towards `?Move`).
1890 /// Correct usage patterns are enforced by the borrow checker for safe code.
1891 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1894 /// Synthesizes a constant value.
1895 Constant(Box<Constant<'tcx>>),
1898 impl<'tcx> Debug for Operand<'tcx> {
1899 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1900 use self::Operand::*;
1902 Constant(ref a) => write!(fmt, "{:?}", a),
1903 Copy(ref place) => write!(fmt, "{:?}", place),
1904 Move(ref place) => write!(fmt, "move {:?}", place),
1909 impl<'tcx> Operand<'tcx> {
1910 /// Convenience helper to make a constant that refers to the fn
1911 /// with given `DefId` and substs. Since this is used to synthesize
1912 /// MIR, assumes `user_ty` is None.
1913 pub fn function_handle(
1916 substs: SubstsRef<'tcx>,
1919 let ty = tcx.type_of(def_id).subst(tcx, substs);
1920 Operand::Constant(box Constant {
1923 literal: ty::Const::zero_sized(tcx, ty),
1927 pub fn is_move(&self) -> bool {
1928 matches!(self, Operand::Move(..))
1931 /// Convenience helper to make a literal-like constant from a given scalar value.
1932 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1933 pub fn const_from_scalar(
1938 ) -> Operand<'tcx> {
1940 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1942 .layout_of(param_env_and_ty)
1943 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1945 let scalar_size = match val {
1946 Scalar::Int(int) => int.size(),
1947 _ => panic!("Invalid scalar type {:?}", val),
1949 scalar_size == type_size
1951 Operand::Constant(box Constant {
1954 literal: ty::Const::from_scalar(tcx, val, ty),
1958 pub fn to_copy(&self) -> Self {
1960 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1961 Operand::Move(place) => Operand::Copy(place),
1965 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1967 pub fn place(&self) -> Option<Place<'tcx>> {
1969 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1970 Operand::Constant(_) => None,
1974 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
1976 pub fn constant(&self) -> Option<&Constant<'tcx>> {
1978 Operand::Constant(x) => Some(&**x),
1979 Operand::Copy(_) | Operand::Move(_) => None,
1984 ///////////////////////////////////////////////////////////////////////////
1987 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1988 pub enum Rvalue<'tcx> {
1989 /// x (either a move or copy, depending on type of x)
1993 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
1996 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1998 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
1999 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2001 ThreadLocalRef(DefId),
2003 /// Create a raw pointer to the given place
2004 /// Can be generated by raw address of expressions (`&raw const x`),
2005 /// or when casting a reference to a raw pointer.
2006 AddressOf(Mutability, Place<'tcx>),
2008 /// length of a `[X]` or `[X;n]` value
2011 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2013 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2014 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2016 NullaryOp(NullOp, Ty<'tcx>),
2017 UnaryOp(UnOp, Operand<'tcx>),
2019 /// Read the discriminant of an ADT.
2021 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2022 /// be defined to return, say, a 0) if ADT is not an enum.
2023 Discriminant(Place<'tcx>),
2025 /// Creates an aggregate value, like a tuple or struct. This is
2026 /// only needed because we want to distinguish `dest = Foo { x:
2027 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2028 /// that `Foo` has a destructor. These rvalues can be optimized
2029 /// away after type-checking and before lowering.
2030 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2033 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2036 Pointer(PointerCast),
2039 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2040 pub enum AggregateKind<'tcx> {
2041 /// The type is of the element
2045 /// The second field is the variant index. It's equal to 0 for struct
2046 /// and union expressions. The fourth field is
2047 /// active field number and is present only for union expressions
2048 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2049 /// active field index would identity the field `c`
2050 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2052 Closure(DefId, SubstsRef<'tcx>),
2053 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2056 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2058 /// The `+` operator (addition)
2060 /// The `-` operator (subtraction)
2062 /// The `*` operator (multiplication)
2064 /// The `/` operator (division)
2066 /// The `%` operator (modulus)
2068 /// The `^` operator (bitwise xor)
2070 /// The `&` operator (bitwise and)
2072 /// The `|` operator (bitwise or)
2074 /// The `<<` operator (shift left)
2076 /// The `>>` operator (shift right)
2078 /// The `==` operator (equality)
2080 /// The `<` operator (less than)
2082 /// The `<=` operator (less than or equal to)
2084 /// The `!=` operator (not equal to)
2086 /// The `>=` operator (greater than or equal to)
2088 /// The `>` operator (greater than)
2090 /// The `ptr.offset` operator
2095 pub fn is_checkable(self) -> bool {
2097 matches!(self, Add | Sub | Mul | Shl | Shr)
2101 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2103 /// Returns the size of a value of that type
2105 /// Creates a new uninitialized box for a value of that type
2109 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2111 /// The `!` operator for logical inversion
2113 /// The `-` operator for negation
2117 impl<'tcx> Debug for Rvalue<'tcx> {
2118 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2119 use self::Rvalue::*;
2122 Use(ref place) => write!(fmt, "{:?}", place),
2123 Repeat(ref a, ref b) => {
2124 write!(fmt, "[{:?}; ", a)?;
2125 pretty_print_const(b, fmt, false)?;
2128 Len(ref a) => write!(fmt, "Len({:?})", a),
2129 Cast(ref kind, ref place, ref ty) => {
2130 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2132 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2133 CheckedBinaryOp(ref op, ref a, ref b) => {
2134 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2136 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2137 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2138 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2139 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2140 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2141 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2143 Ref(region, borrow_kind, ref place) => {
2144 let kind_str = match borrow_kind {
2145 BorrowKind::Shared => "",
2146 BorrowKind::Shallow => "shallow ",
2147 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2150 // When printing regions, add trailing space if necessary.
2151 let print_region = ty::tls::with(|tcx| {
2152 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2154 let region = if print_region {
2155 let mut region = region.to_string();
2156 if !region.is_empty() {
2161 // Do not even print 'static
2164 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2167 AddressOf(mutability, ref place) => {
2168 let kind_str = match mutability {
2169 Mutability::Mut => "mut",
2170 Mutability::Not => "const",
2173 write!(fmt, "&raw {} {:?}", kind_str, place)
2176 Aggregate(ref kind, ref places) => {
2177 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2178 let mut tuple_fmt = fmt.debug_tuple(name);
2179 for place in places {
2180 tuple_fmt.field(place);
2186 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2188 AggregateKind::Tuple => {
2189 if places.is_empty() {
2196 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2197 let variant_def = &adt_def.variants[variant];
2199 let name = ty::tls::with(|tcx| {
2200 let mut name = String::new();
2201 let substs = tcx.lift(substs).expect("could not lift for printing");
2202 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2203 .print_def_path(variant_def.def_id, substs)?;
2207 match variant_def.ctor_kind {
2208 CtorKind::Const => fmt.write_str(&name),
2209 CtorKind::Fn => fmt_tuple(fmt, &name),
2210 CtorKind::Fictive => {
2211 let mut struct_fmt = fmt.debug_struct(&name);
2212 for (field, place) in variant_def.fields.iter().zip(places) {
2213 struct_fmt.field(&field.ident.as_str(), place);
2220 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2221 if let Some(def_id) = def_id.as_local() {
2222 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2223 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2224 let substs = tcx.lift(substs).unwrap();
2227 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2230 let span = tcx.hir().span(hir_id);
2231 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2233 let mut struct_fmt = fmt.debug_struct(&name);
2235 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2236 for (&var_id, place) in upvars.keys().zip(places) {
2237 let var_name = tcx.hir().name(var_id);
2238 struct_fmt.field(&var_name.as_str(), place);
2244 write!(fmt, "[closure]")
2248 AggregateKind::Generator(def_id, _, _) => 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 = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2252 let mut struct_fmt = fmt.debug_struct(&name);
2254 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2255 for (&var_id, place) in upvars.keys().zip(places) {
2256 let var_name = tcx.hir().name(var_id);
2257 struct_fmt.field(&var_name.as_str(), place);
2263 write!(fmt, "[generator]")
2272 ///////////////////////////////////////////////////////////////////////////
2275 /// Two constants are equal if they are the same constant. Note that
2276 /// this does not necessarily mean that they are `==` in Rust. In
2277 /// particular, one must be wary of `NaN`!
2279 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2280 pub struct Constant<'tcx> {
2283 /// Optional user-given type: for something like
2284 /// `collect::<Vec<_>>`, this would be present and would
2285 /// indicate that `Vec<_>` was explicitly specified.
2287 /// Needed for NLL to impose user-given type constraints.
2288 pub user_ty: Option<UserTypeAnnotationIndex>,
2290 pub literal: &'tcx ty::Const<'tcx>,
2293 impl Constant<'tcx> {
2294 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2295 match self.literal.val.try_to_scalar() {
2296 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2297 GlobalAlloc::Static(def_id) => {
2298 assert!(!tcx.is_thread_local_static(def_id));
2308 /// A collection of projections into user types.
2310 /// They are projections because a binding can occur a part of a
2311 /// parent pattern that has been ascribed a type.
2313 /// Its a collection because there can be multiple type ascriptions on
2314 /// the path from the root of the pattern down to the binding itself.
2319 /// struct S<'a>((i32, &'a str), String);
2320 /// let S((_, w): (i32, &'static str), _): S = ...;
2321 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2322 /// // --------------------------------- ^ (2)
2325 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2326 /// ascribed the type `(i32, &'static str)`.
2328 /// The highlights labelled `(2)` show the whole pattern being
2329 /// ascribed the type `S`.
2331 /// In this example, when we descend to `w`, we will have built up the
2332 /// following two projected types:
2334 /// * base: `S`, projection: `(base.0).1`
2335 /// * base: `(i32, &'static str)`, projection: `base.1`
2337 /// The first will lead to the constraint `w: &'1 str` (for some
2338 /// inferred region `'1`). The second will lead to the constraint `w:
2340 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2341 pub struct UserTypeProjections {
2342 pub contents: Vec<(UserTypeProjection, Span)>,
2345 impl<'tcx> UserTypeProjections {
2346 pub fn none() -> Self {
2347 UserTypeProjections { contents: vec![] }
2350 pub fn is_empty(&self) -> bool {
2351 self.contents.is_empty()
2354 pub fn projections_and_spans(
2356 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2357 self.contents.iter()
2360 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2361 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2364 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2365 self.contents.push((user_ty.clone(), span));
2371 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2373 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2377 pub fn index(self) -> Self {
2378 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2381 pub fn subslice(self, from: u64, to: u64) -> Self {
2382 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2385 pub fn deref(self) -> Self {
2386 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2389 pub fn leaf(self, field: Field) -> Self {
2390 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2393 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2394 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2398 /// Encodes the effect of a user-supplied type annotation on the
2399 /// subcomponents of a pattern. The effect is determined by applying the
2400 /// given list of proejctions to some underlying base type. Often,
2401 /// the projection element list `projs` is empty, in which case this
2402 /// directly encodes a type in `base`. But in the case of complex patterns with
2403 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2404 /// in which case the `projs` vector is used.
2408 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2410 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2411 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2412 /// determined by finding the type of the `.0` field from `T`.
2413 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2414 pub struct UserTypeProjection {
2415 pub base: UserTypeAnnotationIndex,
2416 pub projs: Vec<ProjectionKind>,
2419 impl Copy for ProjectionKind {}
2421 impl UserTypeProjection {
2422 pub(crate) fn index(mut self) -> Self {
2423 self.projs.push(ProjectionElem::Index(()));
2427 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2428 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2432 pub(crate) fn deref(mut self) -> Self {
2433 self.projs.push(ProjectionElem::Deref);
2437 pub(crate) fn leaf(mut self, field: Field) -> Self {
2438 self.projs.push(ProjectionElem::Field(field, ()));
2442 pub(crate) fn variant(
2445 variant_index: VariantIdx,
2448 self.projs.push(ProjectionElem::Downcast(
2449 Some(adt_def.variants[variant_index].ident.name),
2452 self.projs.push(ProjectionElem::Field(field, ()));
2457 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2459 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2460 fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
2461 UserTypeProjection {
2462 base: self.base.fold_with(folder),
2463 projs: self.projs.fold_with(folder),
2467 fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2470 ) -> ControlFlow<Vs::BreakTy> {
2471 self.base.visit_with(visitor)
2472 // Note: there's nothing in `self.proj` to visit.
2476 rustc_index::newtype_index! {
2477 pub struct Promoted {
2479 DEBUG_FORMAT = "promoted[{}]"
2483 impl<'tcx> Debug for Constant<'tcx> {
2484 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2485 write!(fmt, "{}", self)
2489 impl<'tcx> Display for Constant<'tcx> {
2490 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2491 match self.literal.ty.kind() {
2493 _ => write!(fmt, "const ")?,
2495 pretty_print_const(self.literal, fmt, true)
2499 fn pretty_print_const(
2500 c: &ty::Const<'tcx>,
2501 fmt: &mut Formatter<'_>,
2504 use crate::ty::print::PrettyPrinter;
2505 ty::tls::with(|tcx| {
2506 let literal = tcx.lift(c).unwrap();
2507 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2508 cx.print_alloc_ids = true;
2509 cx.pretty_print_const(literal, print_types)?;
2514 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2515 type Node = BasicBlock;
2518 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2520 fn num_nodes(&self) -> usize {
2521 self.basic_blocks.len()
2525 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2527 fn start_node(&self) -> Self::Node {
2532 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2534 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2535 self.basic_blocks[node].terminator().successors().cloned()
2539 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2540 type Item = BasicBlock;
2541 type Iter = iter::Cloned<Successors<'b>>;
2544 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2545 type Item = BasicBlock;
2546 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2549 impl graph::WithPredecessors for Body<'tcx> {
2551 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2552 self.predecessors()[node].clone().into_iter()
2556 /// `Location` represents the position of the start of the statement; or, if
2557 /// `statement_index` equals the number of statements, then the start of the
2559 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2560 pub struct Location {
2561 /// The block that the location is within.
2562 pub block: BasicBlock,
2564 pub statement_index: usize,
2567 impl fmt::Debug for Location {
2568 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2569 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2574 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2576 /// Returns the location immediately after this one within the enclosing block.
2578 /// Note that if this location represents a terminator, then the
2579 /// resulting location would be out of bounds and invalid.
2580 pub fn successor_within_block(&self) -> Location {
2581 Location { block: self.block, statement_index: self.statement_index + 1 }
2584 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2585 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2586 // If we are in the same block as the other location and are an earlier statement
2587 // then we are a predecessor of `other`.
2588 if self.block == other.block && self.statement_index < other.statement_index {
2592 let predecessors = body.predecessors();
2594 // If we're in another block, then we want to check that block is a predecessor of `other`.
2595 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2596 let mut visited = FxHashSet::default();
2598 while let Some(block) = queue.pop() {
2599 // If we haven't visited this block before, then make sure we visit it's predecessors.
2600 if visited.insert(block) {
2601 queue.extend(predecessors[block].iter().cloned());
2606 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2607 // we found that block by looking at the predecessors of `other`).
2608 if self.block == block {
2616 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2617 if self.block == other.block {
2618 self.statement_index <= other.statement_index
2620 dominators.is_dominated_by(other.block, self.block)