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::graph_cyclic_cache::GraphIsCyclicCache;
39 use self::predecessors::{PredecessorCache, Predecessors};
40 pub use self::query::*;
42 pub mod abstract_const;
44 mod graph_cyclic_cache;
51 pub use terminator::*;
57 pub 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 /// Where a specific `mir::Body` comes from.
116 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
117 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
118 pub struct MirSource<'tcx> {
119 pub instance: InstanceDef<'tcx>,
121 /// If `Some`, this is a promoted rvalue within the parent function.
122 pub promoted: Option<Promoted>,
125 impl<'tcx> MirSource<'tcx> {
126 pub fn item(def_id: DefId) -> Self {
128 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
133 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
134 MirSource { instance, promoted: None }
137 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
138 self.instance.with_opt_param()
142 pub fn def_id(&self) -> DefId {
143 self.instance.def_id()
147 /// The lowered representation of a single function.
148 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
149 pub struct Body<'tcx> {
150 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
151 /// that indexes into this vector.
152 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
154 /// Records how far through the "desugaring and optimization" process this particular
155 /// MIR has traversed. This is particularly useful when inlining, since in that context
156 /// we instantiate the promoted constants and add them to our promoted vector -- but those
157 /// promoted items have already been optimized, whereas ours have not. This field allows
158 /// us to see the difference and forego optimization on the inlined promoted items.
161 pub source: MirSource<'tcx>,
163 /// A list of source scopes; these are referenced by statements
164 /// and used for debuginfo. Indexed by a `SourceScope`.
165 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
167 /// The yield type of the function, if it is a generator.
168 pub yield_ty: Option<Ty<'tcx>>,
170 /// Generator drop glue.
171 pub generator_drop: Option<Box<Body<'tcx>>>,
173 /// The layout of a generator. Produced by the state transformation.
174 pub generator_layout: Option<GeneratorLayout<'tcx>>,
176 /// If this is a generator then record the type of source expression that caused this generator
178 pub generator_kind: Option<GeneratorKind>,
180 /// Declarations of locals.
182 /// The first local is the return value pointer, followed by `arg_count`
183 /// locals for the function arguments, followed by any user-declared
184 /// variables and temporaries.
185 pub local_decls: LocalDecls<'tcx>,
187 /// User type annotations.
188 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
190 /// The number of arguments this function takes.
192 /// Starting at local 1, `arg_count` locals will be provided by the caller
193 /// and can be assumed to be initialized.
195 /// If this MIR was built for a constant, this will be 0.
196 pub arg_count: usize,
198 /// Mark an argument local (which must be a tuple) as getting passed as
199 /// its individual components at the LLVM level.
201 /// This is used for the "rust-call" ABI.
202 pub spread_arg: Option<Local>,
204 /// Debug information pertaining to user variables, including captures.
205 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
207 /// A span representing this MIR, for error reporting.
210 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
211 /// We hold in this field all the constants we are not able to evaluate yet.
212 pub required_consts: Vec<Constant<'tcx>>,
214 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
216 /// Note that this does not actually mean that this body is not computable right now.
217 /// The repeat count in the following example is polymorphic, but can still be evaluated
218 /// without knowing anything about the type parameter `T`.
222 /// let _ = [0; std::mem::size_of::<*mut T>()];
226 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
227 /// removed the last mention of all generic params. We do not want to rely on optimizations and
228 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
229 pub is_polymorphic: bool,
231 predecessor_cache: PredecessorCache,
232 is_cyclic: GraphIsCyclicCache,
235 impl<'tcx> Body<'tcx> {
237 source: MirSource<'tcx>,
238 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
239 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
240 local_decls: LocalDecls<'tcx>,
241 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
243 var_debug_info: Vec<VarDebugInfo<'tcx>>,
245 generator_kind: Option<GeneratorKind>,
247 // We need `arg_count` locals, and one for the return place.
249 local_decls.len() > arg_count,
250 "expected at least {} locals, got {}",
255 let mut body = Body {
256 phase: MirPhase::Build,
261 generator_drop: None,
262 generator_layout: None,
265 user_type_annotations,
270 required_consts: Vec::new(),
271 is_polymorphic: false,
272 predecessor_cache: PredecessorCache::new(),
273 is_cyclic: GraphIsCyclicCache::new(),
275 body.is_polymorphic = body.has_param_types_or_consts();
279 /// Returns a partially initialized MIR body containing only a list of basic blocks.
281 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
282 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
284 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
285 let mut body = Body {
286 phase: MirPhase::Build,
287 source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
289 source_scopes: IndexVec::new(),
291 generator_drop: None,
292 generator_layout: None,
293 local_decls: IndexVec::new(),
294 user_type_annotations: IndexVec::new(),
298 required_consts: Vec::new(),
299 generator_kind: None,
300 var_debug_info: Vec::new(),
301 is_polymorphic: false,
302 predecessor_cache: PredecessorCache::new(),
303 is_cyclic: GraphIsCyclicCache::new(),
305 body.is_polymorphic = body.has_param_types_or_consts();
310 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
315 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
316 // Because the user could mutate basic block terminators via this reference, we need to
317 // invalidate the caches.
319 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
320 // invalidate the caches.
321 self.predecessor_cache.invalidate();
322 self.is_cyclic.invalidate();
323 &mut self.basic_blocks
327 pub fn basic_blocks_and_local_decls_mut(
329 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
330 self.predecessor_cache.invalidate();
331 self.is_cyclic.invalidate();
332 (&mut self.basic_blocks, &mut self.local_decls)
336 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
339 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
340 &mut LocalDecls<'tcx>,
341 &mut Vec<VarDebugInfo<'tcx>>,
343 self.predecessor_cache.invalidate();
344 self.is_cyclic.invalidate();
345 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
348 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
350 pub fn is_cfg_cyclic(&self) -> bool {
351 self.is_cyclic.is_cyclic(self)
355 pub fn local_kind(&self, local: Local) -> LocalKind {
356 let index = local.as_usize();
359 self.local_decls[local].mutability == Mutability::Mut,
360 "return place should be mutable"
363 LocalKind::ReturnPointer
364 } else if index < self.arg_count + 1 {
366 } else if self.local_decls[local].is_user_variable() {
373 /// Returns an iterator over all temporaries.
375 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
376 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
377 let local = Local::new(index);
378 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
382 /// Returns an iterator over all user-declared locals.
384 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
385 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
386 let local = Local::new(index);
387 self.local_decls[local].is_user_variable().then_some(local)
391 /// Returns an iterator over all user-declared mutable locals.
393 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
394 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
395 let local = Local::new(index);
396 let decl = &self.local_decls[local];
397 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
405 /// Returns an iterator over all user-declared mutable arguments and locals.
407 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
408 (1..self.local_decls.len()).filter_map(move |index| {
409 let local = Local::new(index);
410 let decl = &self.local_decls[local];
411 if (decl.is_user_variable() || index < self.arg_count + 1)
412 && decl.mutability == Mutability::Mut
421 /// Returns an iterator over all function arguments.
423 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
424 let arg_count = self.arg_count;
425 (1..arg_count + 1).map(Local::new)
428 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
429 /// locals that are neither arguments nor the return place).
431 pub fn vars_and_temps_iter(
433 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
434 let arg_count = self.arg_count;
435 let local_count = self.local_decls.len();
436 (arg_count + 1..local_count).map(Local::new)
439 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
440 /// invalidating statement indices in `Location`s.
441 pub fn make_statement_nop(&mut self, location: Location) {
442 let block = &mut self.basic_blocks[location.block];
443 debug_assert!(location.statement_index < block.statements.len());
444 block.statements[location.statement_index].make_nop()
447 /// Returns the source info associated with `location`.
448 pub fn source_info(&self, location: Location) -> &SourceInfo {
449 let block = &self[location.block];
450 let stmts = &block.statements;
451 let idx = location.statement_index;
452 if idx < stmts.len() {
453 &stmts[idx].source_info
455 assert_eq!(idx, stmts.len());
456 &block.terminator().source_info
460 /// Returns the return type; it always return first element from `local_decls` array.
462 pub fn return_ty(&self) -> Ty<'tcx> {
463 self.local_decls[RETURN_PLACE].ty
466 /// Gets the location of the terminator for the given block.
468 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
469 Location { block: bb, statement_index: self[bb].statements.len() }
473 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
474 self.predecessor_cache.compute(&self.basic_blocks)
478 pub fn dominators(&self) -> Dominators<BasicBlock> {
483 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
486 /// Unsafe because of a PushUnsafeBlock
488 /// Unsafe because of an unsafe fn
490 /// Unsafe because of an `unsafe` block
491 ExplicitUnsafe(hir::HirId),
494 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
495 type Output = BasicBlockData<'tcx>;
498 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
499 &self.basic_blocks()[index]
503 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
505 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
506 &mut self.basic_blocks_mut()[index]
510 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
511 pub enum ClearCrossCrate<T> {
516 impl<T> ClearCrossCrate<T> {
517 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
519 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
520 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
524 pub fn assert_crate_local(self) -> T {
526 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
527 ClearCrossCrate::Set(v) => v,
532 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
533 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
535 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
537 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
538 if E::CLEAR_CROSS_CRATE {
543 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
544 ClearCrossCrate::Set(ref val) => {
545 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
551 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
553 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
554 if D::CLEAR_CROSS_CRATE {
555 return Ok(ClearCrossCrate::Clear);
558 let discr = u8::decode(d)?;
561 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
562 TAG_CLEAR_CROSS_CRATE_SET => {
563 let val = T::decode(d)?;
564 Ok(ClearCrossCrate::Set(val))
566 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
571 /// Grouped information about the source code origin of a MIR entity.
572 /// Intended to be inspected by diagnostics and debuginfo.
573 /// Most passes can work with it as a whole, within a single function.
574 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
575 // `Hash`. Please ping @bjorn3 if removing them.
576 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
577 pub struct SourceInfo {
578 /// The source span for the AST pertaining to this MIR entity.
581 /// The source scope, keeping track of which bindings can be
582 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
583 pub scope: SourceScope,
588 pub fn outermost(span: Span) -> Self {
589 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
593 ///////////////////////////////////////////////////////////////////////////
596 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
597 #[derive(Hash, HashStable)]
598 pub enum BorrowKind {
599 /// Data must be immutable and is aliasable.
602 /// The immediately borrowed place must be immutable, but projections from
603 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
604 /// conflict with a mutable borrow of `a.b.c`.
606 /// This is used when lowering matches: when matching on a place we want to
607 /// ensure that place have the same value from the start of the match until
608 /// an arm is selected. This prevents this code from compiling:
610 /// let mut x = &Some(0);
613 /// Some(_) if { x = &None; false } => (),
617 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
618 /// should not prevent `if let None = x { ... }`, for example, because the
619 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
620 /// We can also report errors with this kind of borrow differently.
623 /// Data must be immutable but not aliasable. This kind of borrow
624 /// cannot currently be expressed by the user and is used only in
625 /// implicit closure bindings. It is needed when the closure is
626 /// borrowing or mutating a mutable referent, e.g.:
628 /// let x: &mut isize = ...;
629 /// let y = || *x += 5;
631 /// If we were to try to translate this closure into a more explicit
632 /// form, we'd encounter an error with the code as written:
634 /// struct Env { x: & &mut isize }
635 /// let x: &mut isize = ...;
636 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
637 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
639 /// This is then illegal because you cannot mutate an `&mut` found
640 /// in an aliasable location. To solve, you'd have to translate with
641 /// an `&mut` borrow:
643 /// struct Env { x: & &mut isize }
644 /// let x: &mut isize = ...;
645 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
646 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
648 /// Now the assignment to `**env.x` is legal, but creating a
649 /// mutable pointer to `x` is not because `x` is not mutable. We
650 /// could fix this by declaring `x` as `let mut x`. This is ok in
651 /// user code, if awkward, but extra weird for closures, since the
652 /// borrow is hidden.
654 /// So we introduce a "unique imm" borrow -- the referent is
655 /// immutable, but not aliasable. This solves the problem. For
656 /// simplicity, we don't give users the way to express this
657 /// borrow, it's just used when translating closures.
660 /// Data is mutable and not aliasable.
662 /// `true` if this borrow arose from method-call auto-ref
663 /// (i.e., `adjustment::Adjust::Borrow`).
664 allow_two_phase_borrow: bool,
669 pub fn allows_two_phase_borrow(&self) -> bool {
671 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
672 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
677 ///////////////////////////////////////////////////////////////////////////
678 // Variables and temps
680 rustc_index::newtype_index! {
683 DEBUG_FORMAT = "_{}",
684 const RETURN_PLACE = 0,
688 impl Atom for Local {
689 fn index(self) -> usize {
694 /// Classifies locals into categories. See `Body::local_kind`.
695 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
697 /// User-declared variable binding.
699 /// Compiler-introduced temporary.
701 /// Function argument.
703 /// Location of function's return value.
707 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
708 pub struct VarBindingForm<'tcx> {
709 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
710 pub binding_mode: ty::BindingMode,
711 /// If an explicit type was provided for this variable binding,
712 /// this holds the source Span of that type.
714 /// NOTE: if you want to change this to a `HirId`, be wary that
715 /// doing so breaks incremental compilation (as of this writing),
716 /// while a `Span` does not cause our tests to fail.
717 pub opt_ty_info: Option<Span>,
718 /// Place of the RHS of the =, or the subject of the `match` where this
719 /// variable is initialized. None in the case of `let PATTERN;`.
720 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
721 /// (a) the right-hand side isn't evaluated as a place expression.
722 /// (b) it gives a way to separate this case from the remaining cases
724 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
725 /// The span of the pattern in which this variable was bound.
729 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
730 pub enum BindingForm<'tcx> {
731 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
732 Var(VarBindingForm<'tcx>),
733 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
734 ImplicitSelf(ImplicitSelfKind),
735 /// Reference used in a guard expression to ensure immutability.
739 /// Represents what type of implicit self a function has, if any.
740 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
741 pub enum ImplicitSelfKind {
742 /// Represents a `fn x(self);`.
744 /// Represents a `fn x(mut self);`.
746 /// Represents a `fn x(&self);`.
748 /// Represents a `fn x(&mut self);`.
750 /// Represents when a function does not have a self argument or
751 /// when a function has a `self: X` argument.
755 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
757 mod binding_form_impl {
758 use crate::ich::StableHashingContext;
759 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
761 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
762 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
763 use super::BindingForm::*;
764 std::mem::discriminant(self).hash_stable(hcx, hasher);
767 Var(binding) => binding.hash_stable(hcx, hasher),
768 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
775 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
776 /// created during evaluation of expressions in a block tail
777 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
779 /// It is used to improve diagnostics when such temporaries are
780 /// involved in borrow_check errors, e.g., explanations of where the
781 /// temporaries come from, when their destructors are run, and/or how
782 /// one might revise the code to satisfy the borrow checker's rules.
783 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
784 pub struct BlockTailInfo {
785 /// If `true`, then the value resulting from evaluating this tail
786 /// expression is ignored by the block's expression context.
788 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
789 /// but not e.g., `let _x = { ...; tail };`
790 pub tail_result_is_ignored: bool,
792 /// `Span` of the tail expression.
798 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
799 /// argument, or the return place.
800 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
801 pub struct LocalDecl<'tcx> {
802 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
804 /// Temporaries and the return place are always mutable.
805 pub mutability: Mutability,
807 // FIXME(matthewjasper) Don't store in this in `Body`
808 pub local_info: Option<Box<LocalInfo<'tcx>>>,
810 /// `true` if this is an internal local.
812 /// These locals are not based on types in the source code and are only used
813 /// for a few desugarings at the moment.
815 /// The generator transformation will sanity check the locals which are live
816 /// across a suspension point against the type components of the generator
817 /// which type checking knows are live across a suspension point. We need to
818 /// flag drop flags to avoid triggering this check as they are introduced
821 /// This should be sound because the drop flags are fully algebraic, and
822 /// therefore don't affect the auto-trait or outlives properties of the
826 /// If this local is a temporary and `is_block_tail` is `Some`,
827 /// then it is a temporary created for evaluation of some
828 /// subexpression of some block's tail expression (with no
829 /// intervening statement context).
830 // FIXME(matthewjasper) Don't store in this in `Body`
831 pub is_block_tail: Option<BlockTailInfo>,
833 /// The type of this local.
836 /// If the user manually ascribed a type to this variable,
837 /// e.g., via `let x: T`, then we carry that type here. The MIR
838 /// borrow checker needs this information since it can affect
839 /// region inference.
840 // FIXME(matthewjasper) Don't store in this in `Body`
841 pub user_ty: Option<Box<UserTypeProjections>>,
843 /// The *syntactic* (i.e., not visibility) source scope the local is defined
844 /// in. If the local was defined in a let-statement, this
845 /// is *within* the let-statement, rather than outside
848 /// This is needed because the visibility source scope of locals within
849 /// a let-statement is weird.
851 /// The reason is that we want the local to be *within* the let-statement
852 /// for lint purposes, but we want the local to be *after* the let-statement
853 /// for names-in-scope purposes.
855 /// That's it, if we have a let-statement like the one in this
859 /// fn foo(x: &str) {
860 /// #[allow(unused_mut)]
861 /// let mut x: u32 = { // <- one unused mut
862 /// let mut y: u32 = x.parse().unwrap();
869 /// Then, from a lint point of view, the declaration of `x: u32`
870 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
871 /// lint scopes are the same as the AST/HIR nesting.
873 /// However, from a name lookup point of view, the scopes look more like
874 /// as if the let-statements were `match` expressions:
877 /// fn foo(x: &str) {
879 /// match x.parse().unwrap() {
888 /// We care about the name-lookup scopes for debuginfo - if the
889 /// debuginfo instruction pointer is at the call to `x.parse()`, we
890 /// want `x` to refer to `x: &str`, but if it is at the call to
891 /// `drop(x)`, we want it to refer to `x: u32`.
893 /// To allow both uses to work, we need to have more than a single scope
894 /// for a local. We have the `source_info.scope` represent the "syntactic"
895 /// lint scope (with a variable being under its let block) while the
896 /// `var_debug_info.source_info.scope` represents the "local variable"
897 /// scope (where the "rest" of a block is under all prior let-statements).
899 /// The end result looks like this:
903 /// │{ argument x: &str }
905 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
906 /// │ │ // in practice because I'm lazy.
908 /// │ │← x.source_info.scope
909 /// │ │← `x.parse().unwrap()`
911 /// │ │ │← y.source_info.scope
913 /// │ │ │{ let y: u32 }
915 /// │ │ │← y.var_debug_info.source_info.scope
918 /// │ │{ let x: u32 }
919 /// │ │← x.var_debug_info.source_info.scope
920 /// │ │← `drop(x)` // This accesses `x: u32`.
922 pub source_info: SourceInfo,
925 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
926 #[cfg(target_arch = "x86_64")]
927 static_assert_size!(LocalDecl<'_>, 56);
929 /// Extra information about a some locals that's used for diagnostics and for
930 /// classifying variables into local variables, statics, etc, which is needed e.g.
931 /// for unsafety checking.
933 /// Not used for non-StaticRef temporaries, the return place, or anonymous
934 /// function parameters.
935 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
936 pub enum LocalInfo<'tcx> {
937 /// A user-defined local variable or function parameter
939 /// The `BindingForm` is solely used for local diagnostics when generating
940 /// warnings/errors when compiling the current crate, and therefore it need
941 /// not be visible across crates.
942 User(ClearCrossCrate<BindingForm<'tcx>>),
943 /// A temporary created that references the static with the given `DefId`.
944 StaticRef { def_id: DefId, is_thread_local: bool },
945 /// A temporary created that references the const with the given `DefId`
946 ConstRef { def_id: DefId },
949 impl<'tcx> LocalDecl<'tcx> {
950 /// Returns `true` only if local is a binding that can itself be
951 /// made mutable via the addition of the `mut` keyword, namely
952 /// something like the occurrences of `x` in:
953 /// - `fn foo(x: Type) { ... }`,
955 /// - or `match ... { C(x) => ... }`
956 pub fn can_be_made_mutable(&self) -> bool {
959 Some(box LocalInfo::User(ClearCrossCrate::Set(
960 BindingForm::Var(VarBindingForm {
961 binding_mode: ty::BindingMode::BindByValue(_),
965 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
970 /// Returns `true` if local is definitely not a `ref ident` or
971 /// `ref mut ident` binding. (Such bindings cannot be made into
972 /// mutable bindings, but the inverse does not necessarily hold).
973 pub fn is_nonref_binding(&self) -> bool {
976 Some(box LocalInfo::User(ClearCrossCrate::Set(
977 BindingForm::Var(VarBindingForm {
978 binding_mode: ty::BindingMode::BindByValue(_),
982 }) | BindingForm::ImplicitSelf(_),
987 /// Returns `true` if this variable is a named variable or function
988 /// parameter declared by the user.
990 pub fn is_user_variable(&self) -> bool {
991 matches!(self.local_info, Some(box LocalInfo::User(_)))
994 /// Returns `true` if this is a reference to a variable bound in a `match`
995 /// expression that is used to access said variable for the guard of the
997 pub fn is_ref_for_guard(&self) -> bool {
1000 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
1004 /// Returns `Some` if this is a reference to a static item that is used to
1005 /// access that static.
1006 pub fn is_ref_to_static(&self) -> bool {
1007 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1010 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1011 /// access that static.
1012 pub fn is_ref_to_thread_local(&self) -> bool {
1013 match self.local_info {
1014 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1019 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1020 /// `__next` from a `for` loop.
1022 pub fn from_compiler_desugaring(&self) -> bool {
1023 self.source_info.span.desugaring_kind().is_some()
1026 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1028 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1029 Self::with_source_info(ty, SourceInfo::outermost(span))
1032 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1034 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1036 mutability: Mutability::Mut,
1039 is_block_tail: None,
1046 /// Converts `self` into same `LocalDecl` except tagged as internal.
1048 pub fn internal(mut self) -> Self {
1049 self.internal = true;
1053 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1055 pub fn immutable(mut self) -> Self {
1056 self.mutability = Mutability::Not;
1060 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1062 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1063 assert!(self.is_block_tail.is_none());
1064 self.is_block_tail = Some(info);
1069 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1070 pub enum VarDebugInfoContents<'tcx> {
1071 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1072 /// based on a `Local`, not a `Static`, and contains no indexing.
1074 Const(Constant<'tcx>),
1077 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1078 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1080 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1081 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1086 /// Debug information pertaining to a user variable.
1087 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1088 pub struct VarDebugInfo<'tcx> {
1091 /// Source info of the user variable, including the scope
1092 /// within which the variable is visible (to debuginfo)
1093 /// (see `LocalDecl`'s `source_info` field for more details).
1094 pub source_info: SourceInfo,
1096 /// Where the data for this user variable is to be found.
1097 pub value: VarDebugInfoContents<'tcx>,
1100 ///////////////////////////////////////////////////////////////////////////
1103 rustc_index::newtype_index! {
1104 /// A node in the MIR [control-flow graph][CFG].
1106 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1107 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1108 /// as an edge in a graph between basic blocks.
1110 /// Basic blocks consist of a series of [statements][Statement], ending with a
1111 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1112 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1113 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1114 /// needed because some analyses require that there are no critical edges in the CFG.
1116 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1117 /// the actual data that a basic block holds is in [`BasicBlockData`].
1119 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1121 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1122 /// [data-flow analyses]:
1123 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1124 /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1125 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1126 pub struct BasicBlock {
1128 DEBUG_FORMAT = "bb{}",
1129 const START_BLOCK = 0,
1134 pub fn start_location(self) -> Location {
1135 Location { block: self, statement_index: 0 }
1139 ///////////////////////////////////////////////////////////////////////////
1140 // BasicBlockData and Terminator
1142 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1143 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1144 pub struct BasicBlockData<'tcx> {
1145 /// List of statements in this block.
1146 pub statements: Vec<Statement<'tcx>>,
1148 /// Terminator for this block.
1150 /// N.B., this should generally ONLY be `None` during construction.
1151 /// Therefore, you should generally access it via the
1152 /// `terminator()` or `terminator_mut()` methods. The only
1153 /// exception is that certain passes, such as `simplify_cfg`, swap
1154 /// out the terminator temporarily with `None` while they continue
1155 /// to recurse over the set of basic blocks.
1156 pub terminator: Option<Terminator<'tcx>>,
1158 /// If true, this block lies on an unwind path. This is used
1159 /// during codegen where distinct kinds of basic blocks may be
1160 /// generated (particularly for MSVC cleanup). Unwind blocks must
1161 /// only branch to other unwind blocks.
1162 pub is_cleanup: bool,
1165 /// Information about an assertion failure.
1166 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
1167 pub enum AssertKind<O> {
1168 BoundsCheck { len: O, index: O },
1169 Overflow(BinOp, O, O),
1173 ResumedAfterReturn(GeneratorKind),
1174 ResumedAfterPanic(GeneratorKind),
1188 pub enum InlineAsmOperand<'tcx> {
1190 reg: InlineAsmRegOrRegClass,
1191 value: Operand<'tcx>,
1194 reg: InlineAsmRegOrRegClass,
1196 place: Option<Place<'tcx>>,
1199 reg: InlineAsmRegOrRegClass,
1201 in_value: Operand<'tcx>,
1202 out_place: Option<Place<'tcx>>,
1205 value: Operand<'tcx>,
1208 value: Box<Constant<'tcx>>,
1215 /// Type for MIR `Assert` terminator error messages.
1216 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1218 pub type Successors<'a> =
1219 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1220 pub type SuccessorsMut<'a> =
1221 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1223 impl<'tcx> BasicBlockData<'tcx> {
1224 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1225 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1228 /// Accessor for terminator.
1230 /// Terminator may not be None after construction of the basic block is complete. This accessor
1231 /// provides a convenience way to reach the terminator.
1232 pub fn terminator(&self) -> &Terminator<'tcx> {
1233 self.terminator.as_ref().expect("invalid terminator state")
1236 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1237 self.terminator.as_mut().expect("invalid terminator state")
1240 pub fn retain_statements<F>(&mut self, mut f: F)
1242 F: FnMut(&mut Statement<'_>) -> bool,
1244 for s in &mut self.statements {
1251 pub fn expand_statements<F, I>(&mut self, mut f: F)
1253 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1254 I: iter::TrustedLen<Item = Statement<'tcx>>,
1256 // Gather all the iterators we'll need to splice in, and their positions.
1257 let mut splices: Vec<(usize, I)> = vec![];
1258 let mut extra_stmts = 0;
1259 for (i, s) in self.statements.iter_mut().enumerate() {
1260 if let Some(mut new_stmts) = f(s) {
1261 if let Some(first) = new_stmts.next() {
1262 // We can already store the first new statement.
1265 // Save the other statements for optimized splicing.
1266 let remaining = new_stmts.size_hint().0;
1268 splices.push((i + 1 + extra_stmts, new_stmts));
1269 extra_stmts += remaining;
1277 // Splice in the new statements, from the end of the block.
1278 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1279 // where a range of elements ("gap") is left uninitialized, with
1280 // splicing adding new elements to the end of that gap and moving
1281 // existing elements from before the gap to the end of the gap.
1282 // For now, this is safe code, emulating a gap but initializing it.
1283 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1284 self.statements.resize(
1286 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1288 for (splice_start, new_stmts) in splices.into_iter().rev() {
1289 let splice_end = splice_start + new_stmts.size_hint().0;
1290 while gap.end > splice_end {
1293 self.statements.swap(gap.start, gap.end);
1295 self.statements.splice(splice_start..splice_end, new_stmts);
1296 gap.end = splice_start;
1300 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1301 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1305 impl<O> AssertKind<O> {
1306 /// Getting a description does not require `O` to be printable, and does not
1307 /// require allocation.
1308 /// The caller is expected to handle `BoundsCheck` separately.
1309 pub fn description(&self) -> &'static str {
1312 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1313 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1314 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1315 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1316 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1317 OverflowNeg(_) => "attempt to negate with overflow",
1318 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1319 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1320 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1321 DivisionByZero(_) => "attempt to divide by zero",
1322 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1323 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1324 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1325 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1326 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1327 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1331 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1332 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1338 BoundsCheck { ref len, ref index } => write!(
1340 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1344 OverflowNeg(op) => {
1345 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1347 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1348 RemainderByZero(op) => write!(
1350 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1353 Overflow(BinOp::Add, l, r) => write!(
1355 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1358 Overflow(BinOp::Sub, l, r) => write!(
1360 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1363 Overflow(BinOp::Mul, l, r) => write!(
1365 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1368 Overflow(BinOp::Div, l, r) => write!(
1370 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1373 Overflow(BinOp::Rem, l, r) => write!(
1375 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1378 Overflow(BinOp::Shr, _, r) => {
1379 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1381 Overflow(BinOp::Shl, _, r) => {
1382 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1384 _ => write!(f, "\"{}\"", self.description()),
1389 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1393 BoundsCheck { ref len, ref index } => write!(
1395 "index out of bounds: the length is {:?} but the index is {:?}",
1398 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1399 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1400 RemainderByZero(op) => write!(
1402 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1405 Overflow(BinOp::Add, l, r) => {
1406 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1408 Overflow(BinOp::Sub, l, r) => {
1409 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1411 Overflow(BinOp::Mul, l, r) => {
1412 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1414 Overflow(BinOp::Div, l, r) => {
1415 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1417 Overflow(BinOp::Rem, l, r) => write!(
1419 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1422 Overflow(BinOp::Shr, _, r) => {
1423 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1425 Overflow(BinOp::Shl, _, r) => {
1426 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1428 _ => write!(f, "{}", self.description()),
1433 ///////////////////////////////////////////////////////////////////////////
1436 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1437 pub struct Statement<'tcx> {
1438 pub source_info: SourceInfo,
1439 pub kind: StatementKind<'tcx>,
1442 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1443 #[cfg(target_arch = "x86_64")]
1444 static_assert_size!(Statement<'_>, 32);
1446 impl Statement<'_> {
1447 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1448 /// invalidating statement indices in `Location`s.
1449 pub fn make_nop(&mut self) {
1450 self.kind = StatementKind::Nop
1453 /// Changes a statement to a nop and returns the original statement.
1454 pub fn replace_nop(&mut self) -> Self {
1456 source_info: self.source_info,
1457 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1462 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1463 pub enum StatementKind<'tcx> {
1464 /// Write the RHS Rvalue to the LHS Place.
1465 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1467 /// This represents all the reading that a pattern match may do
1468 /// (e.g., inspecting constants and discriminant values), and the
1469 /// kind of pattern it comes from. This is in order to adapt potential
1470 /// error messages to these specific patterns.
1472 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1473 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1474 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1476 /// Write the discriminant for a variant to the enum Place.
1477 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1479 /// Start a live range for the storage of the local.
1482 /// End the current live range for the storage of the local.
1485 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1486 /// of `StatementKind` low.
1487 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1489 /// Retag references in the given place, ensuring they got fresh tags. This is
1490 /// part of the Stacked Borrows model. These statements are currently only interpreted
1491 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1492 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1493 /// for more details.
1494 Retag(RetagKind, Box<Place<'tcx>>),
1496 /// Encodes a user's type ascription. These need to be preserved
1497 /// intact so that NLL can respect them. For example:
1501 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1502 /// to the user-given type `T`. The effect depends on the specified variance:
1504 /// - `Covariant` -- requires that `T_y <: T`
1505 /// - `Contravariant` -- requires that `T_y :> T`
1506 /// - `Invariant` -- requires that `T_y == T`
1507 /// - `Bivariant` -- no effect
1508 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1510 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1511 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1512 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1513 /// counter varible at runtime, each time the code region is executed.
1514 Coverage(Box<Coverage>),
1516 /// No-op. Useful for deleting instructions without affecting statement indices.
1520 impl<'tcx> StatementKind<'tcx> {
1521 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1523 StatementKind::Assign(x) => Some(x),
1528 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1530 StatementKind::Assign(x) => Some(x),
1536 /// Describes what kind of retag is to be performed.
1537 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1538 pub enum RetagKind {
1539 /// The initial retag when entering a function.
1541 /// Retag preparing for a two-phase borrow.
1543 /// Retagging raw pointers.
1545 /// A "normal" retag.
1549 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1550 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1551 pub enum FakeReadCause {
1552 /// Inject a fake read of the borrowed input at the end of each guards
1555 /// This should ensure that you cannot change the variant for an enum while
1556 /// you are in the midst of matching on it.
1559 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1560 /// generate a read of x to check that it is initialized and safe.
1563 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1564 /// in a match guard to ensure that it's value hasn't change by the time
1565 /// we create the OutsideGuard version.
1568 /// Officially, the semantics of
1570 /// `let pattern = <expr>;`
1572 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1573 /// into the pattern.
1575 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1576 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1577 /// but in some cases it can affect the borrow checker, as in #53695.
1578 /// Therefore, we insert a "fake read" here to ensure that we get
1579 /// appropriate errors.
1582 /// If we have an index expression like
1584 /// (*x)[1][{ x = y; 4}]
1586 /// then the first bounds check is invalidated when we evaluate the second
1587 /// index expression. Thus we create a fake borrow of `x` across the second
1588 /// indexer, which will cause a borrow check error.
1592 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1593 pub struct LlvmInlineAsm<'tcx> {
1594 pub asm: hir::LlvmInlineAsmInner,
1595 pub outputs: Box<[Place<'tcx>]>,
1596 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1599 impl Debug for Statement<'_> {
1600 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1601 use self::StatementKind::*;
1603 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1604 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1605 Retag(ref kind, ref place) => write!(
1609 RetagKind::FnEntry => "[fn entry] ",
1610 RetagKind::TwoPhase => "[2phase] ",
1611 RetagKind::Raw => "[raw] ",
1612 RetagKind::Default => "",
1616 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1617 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1618 SetDiscriminant { ref place, variant_index } => {
1619 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1621 LlvmInlineAsm(ref asm) => {
1622 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1624 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1625 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1627 Coverage(box ref coverage) => {
1628 if let Some(rgn) = &coverage.code_region {
1629 write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1631 write!(fmt, "Coverage::{:?}", coverage.kind)
1634 Nop => write!(fmt, "nop"),
1639 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1640 pub struct Coverage {
1641 pub kind: CoverageKind,
1642 pub code_region: Option<CodeRegion>,
1645 ///////////////////////////////////////////////////////////////////////////
1648 /// A path to a value; something that can be evaluated without
1649 /// changing or disturbing program state.
1650 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1651 pub struct Place<'tcx> {
1654 /// projection out of a place (access a field, deref a pointer, etc)
1655 pub projection: &'tcx List<PlaceElem<'tcx>>,
1658 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1659 #[derive(TyEncodable, TyDecodable, HashStable)]
1660 pub enum ProjectionElem<V, T> {
1665 /// These indices are generated by slice patterns. Easiest to explain
1669 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1670 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1671 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1672 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1675 /// index or -index (in Python terms), depending on from_end
1677 /// The thing being indexed must be at least this long. For arrays this
1678 /// is always the exact length.
1680 /// Counting backwards from end? This is always false when indexing an
1685 /// These indices are generated by slice patterns.
1687 /// If `from_end` is true `slice[from..slice.len() - to]`.
1688 /// Otherwise `array[from..to]`.
1692 /// Whether `to` counts from the start or end of the array/slice.
1693 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1694 /// For `ProjectionKind`, this can also be `true` for arrays.
1698 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1699 /// this for ADTs with more than one variant. It may be better to
1700 /// just introduce it always, or always for enums.
1702 /// The included Symbol is the name of the variant, used for printing MIR.
1703 Downcast(Option<Symbol>, VariantIdx),
1706 impl<V, T> ProjectionElem<V, T> {
1707 /// Returns `true` if the target of this projection may refer to a different region of memory
1709 fn is_indirect(&self) -> bool {
1711 Self::Deref => true,
1715 | Self::ConstantIndex { .. }
1716 | Self::Subslice { .. }
1717 | Self::Downcast(_, _) => false,
1722 /// Alias for projections as they appear in places, where the base is a place
1723 /// and the index is a local.
1724 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1726 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1727 #[cfg(target_arch = "x86_64")]
1728 static_assert_size!(PlaceElem<'_>, 24);
1730 /// Alias for projections as they appear in `UserTypeProjection`, where we
1731 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1732 pub type ProjectionKind = ProjectionElem<(), ()>;
1734 rustc_index::newtype_index! {
1737 DEBUG_FORMAT = "field[{}]"
1741 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1742 pub struct PlaceRef<'tcx> {
1744 pub projection: &'tcx [PlaceElem<'tcx>],
1747 impl<'tcx> Place<'tcx> {
1748 // FIXME change this to a const fn by also making List::empty a const fn.
1749 pub fn return_place() -> Place<'tcx> {
1750 Place { local: RETURN_PLACE, projection: List::empty() }
1753 /// Returns `true` if this `Place` contains a `Deref` projection.
1755 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1756 /// same region of memory as its base.
1757 pub fn is_indirect(&self) -> bool {
1758 self.projection.iter().any(|elem| elem.is_indirect())
1761 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1762 /// a single deref of a local.
1764 pub fn local_or_deref_local(&self) -> Option<Local> {
1765 self.as_ref().local_or_deref_local()
1768 /// If this place represents a local variable like `_X` with no
1769 /// projections, return `Some(_X)`.
1771 pub fn as_local(&self) -> Option<Local> {
1772 self.as_ref().as_local()
1775 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1776 PlaceRef { local: self.local, projection: &self.projection }
1779 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1780 /// its projection and then subsequently more projections are added.
1781 /// As a concrete example, given the place a.b.c, this would yield:
1785 /// Given a place without projections, the iterator is empty.
1786 pub fn iter_projections(
1788 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1789 self.projection.iter().enumerate().map(move |(i, proj)| {
1790 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1796 impl From<Local> for Place<'_> {
1797 fn from(local: Local) -> Self {
1798 Place { local, projection: List::empty() }
1802 impl<'tcx> PlaceRef<'tcx> {
1803 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1804 /// a single deref of a local.
1805 pub fn local_or_deref_local(&self) -> Option<Local> {
1807 PlaceRef { local, projection: [] }
1808 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1813 /// If this place represents a local variable like `_X` with no
1814 /// projections, return `Some(_X)`.
1815 pub fn as_local(&self) -> Option<Local> {
1817 PlaceRef { local, projection: [] } => Some(local),
1822 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1823 if let &[ref proj_base @ .., elem] = self.projection {
1824 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1831 impl Debug for Place<'_> {
1832 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1833 for elem in self.projection.iter().rev() {
1835 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1836 write!(fmt, "(").unwrap();
1838 ProjectionElem::Deref => {
1839 write!(fmt, "(*").unwrap();
1841 ProjectionElem::Index(_)
1842 | ProjectionElem::ConstantIndex { .. }
1843 | ProjectionElem::Subslice { .. } => {}
1847 write!(fmt, "{:?}", self.local)?;
1849 for elem in self.projection.iter() {
1851 ProjectionElem::Downcast(Some(name), _index) => {
1852 write!(fmt, " as {})", name)?;
1854 ProjectionElem::Downcast(None, index) => {
1855 write!(fmt, " as variant#{:?})", index)?;
1857 ProjectionElem::Deref => {
1860 ProjectionElem::Field(field, ty) => {
1861 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1863 ProjectionElem::Index(ref index) => {
1864 write!(fmt, "[{:?}]", index)?;
1866 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1867 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1869 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1870 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1872 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1873 write!(fmt, "[{:?}:]", from)?;
1875 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1876 write!(fmt, "[:-{:?}]", to)?;
1878 ProjectionElem::Subslice { from, to, from_end: true } => {
1879 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1881 ProjectionElem::Subslice { from, to, from_end: false } => {
1882 write!(fmt, "[{:?}..{:?}]", from, to)?;
1891 ///////////////////////////////////////////////////////////////////////////
1894 rustc_index::newtype_index! {
1895 pub struct SourceScope {
1897 DEBUG_FORMAT = "scope[{}]",
1898 const OUTERMOST_SOURCE_SCOPE = 0,
1902 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1903 pub struct SourceScopeData<'tcx> {
1905 pub parent_scope: Option<SourceScope>,
1907 /// Whether this scope is the root of a scope tree of another body,
1908 /// inlined into this body by the MIR inliner.
1909 /// `ty::Instance` is the callee, and the `Span` is the call site.
1910 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1912 /// Nearest (transitive) parent scope (if any) which is inlined.
1913 /// This is an optimization over walking up `parent_scope`
1914 /// until a scope with `inlined: Some(...)` is found.
1915 pub inlined_parent_scope: Option<SourceScope>,
1917 /// Crate-local information for this source scope, that can't (and
1918 /// needn't) be tracked across crates.
1919 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1922 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1923 pub struct SourceScopeLocalData {
1924 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1925 pub lint_root: hir::HirId,
1926 /// The unsafe block that contains this node.
1930 ///////////////////////////////////////////////////////////////////////////
1933 /// These are values that can appear inside an rvalue. They are intentionally
1934 /// limited to prevent rvalues from being nested in one another.
1935 #[derive(Clone, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
1936 pub enum Operand<'tcx> {
1937 /// Copy: The value must be available for use afterwards.
1939 /// This implies that the type of the place must be `Copy`; this is true
1940 /// by construction during build, but also checked by the MIR type checker.
1943 /// Move: The value (including old borrows of it) will not be used again.
1945 /// Safe for values of all types (modulo future developments towards `?Move`).
1946 /// Correct usage patterns are enforced by the borrow checker for safe code.
1947 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1950 /// Synthesizes a constant value.
1951 Constant(Box<Constant<'tcx>>),
1954 impl<'tcx> Debug for Operand<'tcx> {
1955 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1956 use self::Operand::*;
1958 Constant(ref a) => write!(fmt, "{:?}", a),
1959 Copy(ref place) => write!(fmt, "{:?}", place),
1960 Move(ref place) => write!(fmt, "move {:?}", place),
1965 impl<'tcx> Operand<'tcx> {
1966 /// Convenience helper to make a constant that refers to the fn
1967 /// with given `DefId` and substs. Since this is used to synthesize
1968 /// MIR, assumes `user_ty` is None.
1969 pub fn function_handle(
1972 substs: SubstsRef<'tcx>,
1975 let ty = tcx.type_of(def_id).subst(tcx, substs);
1976 Operand::Constant(box Constant {
1979 literal: ty::Const::zero_sized(tcx, ty),
1983 pub fn is_move(&self) -> bool {
1984 matches!(self, Operand::Move(..))
1987 /// Convenience helper to make a literal-like constant from a given scalar value.
1988 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1989 pub fn const_from_scalar(
1994 ) -> Operand<'tcx> {
1996 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1998 .layout_of(param_env_and_ty)
1999 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2001 let scalar_size = match val {
2002 Scalar::Int(int) => int.size(),
2003 _ => panic!("Invalid scalar type {:?}", val),
2005 scalar_size == type_size
2007 Operand::Constant(box Constant {
2010 literal: ty::Const::from_scalar(tcx, val, ty),
2014 pub fn to_copy(&self) -> Self {
2016 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2017 Operand::Move(place) => Operand::Copy(place),
2021 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2023 pub fn place(&self) -> Option<Place<'tcx>> {
2025 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2026 Operand::Constant(_) => None,
2030 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2032 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2034 Operand::Constant(x) => Some(&**x),
2035 Operand::Copy(_) | Operand::Move(_) => None,
2040 ///////////////////////////////////////////////////////////////////////////
2043 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2044 pub enum Rvalue<'tcx> {
2045 /// x (either a move or copy, depending on type of x)
2049 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2052 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2054 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2055 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2057 ThreadLocalRef(DefId),
2059 /// Create a raw pointer to the given place
2060 /// Can be generated by raw address of expressions (`&raw const x`),
2061 /// or when casting a reference to a raw pointer.
2062 AddressOf(Mutability, Place<'tcx>),
2064 /// length of a `[X]` or `[X;n]` value
2067 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2069 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2070 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2072 NullaryOp(NullOp, Ty<'tcx>),
2073 UnaryOp(UnOp, Operand<'tcx>),
2075 /// Read the discriminant of an ADT.
2077 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2078 /// be defined to return, say, a 0) if ADT is not an enum.
2079 Discriminant(Place<'tcx>),
2081 /// Creates an aggregate value, like a tuple or struct. This is
2082 /// only needed because we want to distinguish `dest = Foo { x:
2083 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2084 /// that `Foo` has a destructor. These rvalues can be optimized
2085 /// away after type-checking and before lowering.
2086 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2089 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2092 Pointer(PointerCast),
2095 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2096 pub enum AggregateKind<'tcx> {
2097 /// The type is of the element
2101 /// The second field is the variant index. It's equal to 0 for struct
2102 /// and union expressions. The fourth field is
2103 /// active field number and is present only for union expressions
2104 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2105 /// active field index would identity the field `c`
2106 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2108 Closure(DefId, SubstsRef<'tcx>),
2109 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2112 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2114 /// The `+` operator (addition)
2116 /// The `-` operator (subtraction)
2118 /// The `*` operator (multiplication)
2120 /// The `/` operator (division)
2122 /// The `%` operator (modulus)
2124 /// The `^` operator (bitwise xor)
2126 /// The `&` operator (bitwise and)
2128 /// The `|` operator (bitwise or)
2130 /// The `<<` operator (shift left)
2132 /// The `>>` operator (shift right)
2134 /// The `==` operator (equality)
2136 /// The `<` operator (less than)
2138 /// The `<=` operator (less than or equal to)
2140 /// The `!=` operator (not equal to)
2142 /// The `>=` operator (greater than or equal to)
2144 /// The `>` operator (greater than)
2146 /// The `ptr.offset` operator
2151 pub fn is_checkable(self) -> bool {
2153 matches!(self, Add | Sub | Mul | Shl | Shr)
2157 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2159 /// Returns the size of a value of that type
2161 /// Creates a new uninitialized box for a value of that type
2165 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2167 /// The `!` operator for logical inversion
2169 /// The `-` operator for negation
2173 impl<'tcx> Debug for Rvalue<'tcx> {
2174 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2175 use self::Rvalue::*;
2178 Use(ref place) => write!(fmt, "{:?}", place),
2179 Repeat(ref a, ref b) => {
2180 write!(fmt, "[{:?}; ", a)?;
2181 pretty_print_const(b, fmt, false)?;
2184 Len(ref a) => write!(fmt, "Len({:?})", a),
2185 Cast(ref kind, ref place, ref ty) => {
2186 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2188 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2189 CheckedBinaryOp(ref op, ref a, ref b) => {
2190 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2192 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2193 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2194 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2195 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2196 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2197 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2199 Ref(region, borrow_kind, ref place) => {
2200 let kind_str = match borrow_kind {
2201 BorrowKind::Shared => "",
2202 BorrowKind::Shallow => "shallow ",
2203 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2206 // When printing regions, add trailing space if necessary.
2207 let print_region = ty::tls::with(|tcx| {
2208 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2210 let region = if print_region {
2211 let mut region = region.to_string();
2212 if !region.is_empty() {
2217 // Do not even print 'static
2220 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2223 AddressOf(mutability, ref place) => {
2224 let kind_str = match mutability {
2225 Mutability::Mut => "mut",
2226 Mutability::Not => "const",
2229 write!(fmt, "&raw {} {:?}", kind_str, place)
2232 Aggregate(ref kind, ref places) => {
2233 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2234 let mut tuple_fmt = fmt.debug_tuple(name);
2235 for place in places {
2236 tuple_fmt.field(place);
2242 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2244 AggregateKind::Tuple => {
2245 if places.is_empty() {
2252 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2253 let variant_def = &adt_def.variants[variant];
2255 let name = ty::tls::with(|tcx| {
2256 let mut name = String::new();
2257 let substs = tcx.lift(substs).expect("could not lift for printing");
2258 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2259 .print_def_path(variant_def.def_id, substs)?;
2263 match variant_def.ctor_kind {
2264 CtorKind::Const => fmt.write_str(&name),
2265 CtorKind::Fn => fmt_tuple(fmt, &name),
2266 CtorKind::Fictive => {
2267 let mut struct_fmt = fmt.debug_struct(&name);
2268 for (field, place) in variant_def.fields.iter().zip(places) {
2269 struct_fmt.field(&field.ident.as_str(), place);
2276 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2277 if let Some(def_id) = def_id.as_local() {
2278 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2279 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2280 let substs = tcx.lift(substs).unwrap();
2283 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2286 let span = tcx.hir().span(hir_id);
2287 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2289 let mut struct_fmt = fmt.debug_struct(&name);
2291 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2292 for (&var_id, place) in upvars.keys().zip(places) {
2293 let var_name = tcx.hir().name(var_id);
2294 struct_fmt.field(&var_name.as_str(), place);
2300 write!(fmt, "[closure]")
2304 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2305 if let Some(def_id) = def_id.as_local() {
2306 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2307 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2308 let mut struct_fmt = fmt.debug_struct(&name);
2310 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2311 for (&var_id, place) in upvars.keys().zip(places) {
2312 let var_name = tcx.hir().name(var_id);
2313 struct_fmt.field(&var_name.as_str(), place);
2319 write!(fmt, "[generator]")
2328 ///////////////////////////////////////////////////////////////////////////
2331 /// Two constants are equal if they are the same constant. Note that
2332 /// this does not necessarily mean that they are `==` in Rust. In
2333 /// particular, one must be wary of `NaN`!
2335 #[derive(Clone, Copy, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
2336 pub struct Constant<'tcx> {
2339 /// Optional user-given type: for something like
2340 /// `collect::<Vec<_>>`, this would be present and would
2341 /// indicate that `Vec<_>` was explicitly specified.
2343 /// Needed for NLL to impose user-given type constraints.
2344 pub user_ty: Option<UserTypeAnnotationIndex>,
2346 pub literal: &'tcx ty::Const<'tcx>,
2349 impl Constant<'tcx> {
2350 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2351 match self.literal.val.try_to_scalar() {
2352 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2353 GlobalAlloc::Static(def_id) => {
2354 assert!(!tcx.is_thread_local_static(def_id));
2364 /// A collection of projections into user types.
2366 /// They are projections because a binding can occur a part of a
2367 /// parent pattern that has been ascribed a type.
2369 /// Its a collection because there can be multiple type ascriptions on
2370 /// the path from the root of the pattern down to the binding itself.
2375 /// struct S<'a>((i32, &'a str), String);
2376 /// let S((_, w): (i32, &'static str), _): S = ...;
2377 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2378 /// // --------------------------------- ^ (2)
2381 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2382 /// ascribed the type `(i32, &'static str)`.
2384 /// The highlights labelled `(2)` show the whole pattern being
2385 /// ascribed the type `S`.
2387 /// In this example, when we descend to `w`, we will have built up the
2388 /// following two projected types:
2390 /// * base: `S`, projection: `(base.0).1`
2391 /// * base: `(i32, &'static str)`, projection: `base.1`
2393 /// The first will lead to the constraint `w: &'1 str` (for some
2394 /// inferred region `'1`). The second will lead to the constraint `w:
2396 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2397 pub struct UserTypeProjections {
2398 pub contents: Vec<(UserTypeProjection, Span)>,
2401 impl<'tcx> UserTypeProjections {
2402 pub fn none() -> Self {
2403 UserTypeProjections { contents: vec![] }
2406 pub fn is_empty(&self) -> bool {
2407 self.contents.is_empty()
2410 pub fn projections_and_spans(
2412 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2413 self.contents.iter()
2416 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2417 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2420 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2421 self.contents.push((user_ty.clone(), span));
2427 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2429 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2433 pub fn index(self) -> Self {
2434 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2437 pub fn subslice(self, from: u64, to: u64) -> Self {
2438 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2441 pub fn deref(self) -> Self {
2442 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2445 pub fn leaf(self, field: Field) -> Self {
2446 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2449 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2450 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2454 /// Encodes the effect of a user-supplied type annotation on the
2455 /// subcomponents of a pattern. The effect is determined by applying the
2456 /// given list of proejctions to some underlying base type. Often,
2457 /// the projection element list `projs` is empty, in which case this
2458 /// directly encodes a type in `base`. But in the case of complex patterns with
2459 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2460 /// in which case the `projs` vector is used.
2464 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2466 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2467 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2468 /// determined by finding the type of the `.0` field from `T`.
2469 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2470 pub struct UserTypeProjection {
2471 pub base: UserTypeAnnotationIndex,
2472 pub projs: Vec<ProjectionKind>,
2475 impl Copy for ProjectionKind {}
2477 impl UserTypeProjection {
2478 pub(crate) fn index(mut self) -> Self {
2479 self.projs.push(ProjectionElem::Index(()));
2483 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2484 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2488 pub(crate) fn deref(mut self) -> Self {
2489 self.projs.push(ProjectionElem::Deref);
2493 pub(crate) fn leaf(mut self, field: Field) -> Self {
2494 self.projs.push(ProjectionElem::Field(field, ()));
2498 pub(crate) fn variant(
2501 variant_index: VariantIdx,
2504 self.projs.push(ProjectionElem::Downcast(
2505 Some(adt_def.variants[variant_index].ident.name),
2508 self.projs.push(ProjectionElem::Field(field, ()));
2513 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2515 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2516 fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
2517 UserTypeProjection {
2518 base: self.base.fold_with(folder),
2519 projs: self.projs.fold_with(folder),
2523 fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2526 ) -> ControlFlow<Vs::BreakTy> {
2527 self.base.visit_with(visitor)
2528 // Note: there's nothing in `self.proj` to visit.
2532 rustc_index::newtype_index! {
2533 pub struct Promoted {
2535 DEBUG_FORMAT = "promoted[{}]"
2539 impl<'tcx> Debug for Constant<'tcx> {
2540 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2541 write!(fmt, "{}", self)
2545 impl<'tcx> Display for Constant<'tcx> {
2546 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2547 match self.literal.ty.kind() {
2549 _ => write!(fmt, "const ")?,
2551 pretty_print_const(self.literal, fmt, true)
2555 fn pretty_print_const(
2556 c: &ty::Const<'tcx>,
2557 fmt: &mut Formatter<'_>,
2560 use crate::ty::print::PrettyPrinter;
2561 ty::tls::with(|tcx| {
2562 let literal = tcx.lift(c).unwrap();
2563 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2564 cx.print_alloc_ids = true;
2565 cx.pretty_print_const(literal, print_types)?;
2570 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2571 type Node = BasicBlock;
2574 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2576 fn num_nodes(&self) -> usize {
2577 self.basic_blocks.len()
2581 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2583 fn start_node(&self) -> Self::Node {
2588 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2590 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2591 self.basic_blocks[node].terminator().successors().cloned()
2595 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2596 type Item = BasicBlock;
2597 type Iter = iter::Cloned<Successors<'b>>;
2600 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2601 type Item = BasicBlock;
2602 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2605 impl graph::WithPredecessors for Body<'tcx> {
2607 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2608 self.predecessors()[node].clone().into_iter()
2612 /// `Location` represents the position of the start of the statement; or, if
2613 /// `statement_index` equals the number of statements, then the start of the
2615 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2616 pub struct Location {
2617 /// The block that the location is within.
2618 pub block: BasicBlock,
2620 pub statement_index: usize,
2623 impl fmt::Debug for Location {
2624 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2625 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2630 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2632 /// Returns the location immediately after this one within the enclosing block.
2634 /// Note that if this location represents a terminator, then the
2635 /// resulting location would be out of bounds and invalid.
2636 pub fn successor_within_block(&self) -> Location {
2637 Location { block: self.block, statement_index: self.statement_index + 1 }
2640 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2641 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2642 // If we are in the same block as the other location and are an earlier statement
2643 // then we are a predecessor of `other`.
2644 if self.block == other.block && self.statement_index < other.statement_index {
2648 let predecessors = body.predecessors();
2650 // If we're in another block, then we want to check that block is a predecessor of `other`.
2651 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2652 let mut visited = FxHashSet::default();
2654 while let Some(block) = queue.pop() {
2655 // If we haven't visited this block before, then make sure we visit it's predecessors.
2656 if visited.insert(block) {
2657 queue.extend(predecessors[block].iter().cloned());
2662 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2663 // we found that block by looking at the predecessors of `other`).
2664 if self.block == block {
2672 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2673 if self.block == other.block {
2674 self.statement_index <= other.statement_index
2676 dominators.is_dominated_by(other.block, self.block)