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> {
65 fn local_decls(&self) -> &LocalDecls<'tcx> {
70 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
72 fn local_decls(&self) -> &LocalDecls<'tcx> {
77 /// The various "big phases" that MIR goes through.
79 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
80 /// dialects forbid certain variants or values in certain phases.
82 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
83 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
85 /// Warning: ordering of variants is significant.
86 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
90 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
91 // We used to have this for pre-miri MIR based const eval.
93 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
94 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
95 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
99 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
100 /// * `DropAndReplace` is gone for good
101 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
102 /// means that the auto-generated drop glue will be invoked.
104 /// After this phase, generators are explicit state machines (no more `Yield`).
105 /// `AggregateKind::Generator` is gone for good.
106 GeneratorLowering = 4,
111 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
112 pub fn phase_index(&self) -> usize {
117 /// Where a specific `mir::Body` comes from.
118 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
119 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
120 pub struct MirSource<'tcx> {
121 pub instance: InstanceDef<'tcx>,
123 /// If `Some`, this is a promoted rvalue within the parent function.
124 pub promoted: Option<Promoted>,
127 impl<'tcx> MirSource<'tcx> {
128 pub fn item(def_id: DefId) -> Self {
130 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
135 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
136 MirSource { instance, promoted: None }
139 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
140 self.instance.with_opt_param()
144 pub fn def_id(&self) -> DefId {
145 self.instance.def_id()
149 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
150 pub struct GeneratorInfo<'tcx> {
151 /// The yield type of the function, if it is a generator.
152 pub yield_ty: Option<Ty<'tcx>>,
154 /// Generator drop glue.
155 pub generator_drop: Option<Body<'tcx>>,
157 /// The layout of a generator. Produced by the state transformation.
158 pub generator_layout: Option<GeneratorLayout<'tcx>>,
160 /// If this is a generator then record the type of source expression that caused this generator
162 pub generator_kind: GeneratorKind,
165 /// The lowered representation of a single function.
166 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
167 pub struct Body<'tcx> {
168 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
169 /// that indexes into this vector.
170 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
172 /// Records how far through the "desugaring and optimization" process this particular
173 /// MIR has traversed. This is particularly useful when inlining, since in that context
174 /// we instantiate the promoted constants and add them to our promoted vector -- but those
175 /// promoted items have already been optimized, whereas ours have not. This field allows
176 /// us to see the difference and forego optimization on the inlined promoted items.
179 pub source: MirSource<'tcx>,
181 /// A list of source scopes; these are referenced by statements
182 /// and used for debuginfo. Indexed by a `SourceScope`.
183 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
185 pub generator: Option<Box<GeneratorInfo<'tcx>>>,
187 /// Declarations of locals.
189 /// The first local is the return value pointer, followed by `arg_count`
190 /// locals for the function arguments, followed by any user-declared
191 /// variables and temporaries.
192 pub local_decls: LocalDecls<'tcx>,
194 /// User type annotations.
195 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
197 /// The number of arguments this function takes.
199 /// Starting at local 1, `arg_count` locals will be provided by the caller
200 /// and can be assumed to be initialized.
202 /// If this MIR was built for a constant, this will be 0.
203 pub arg_count: usize,
205 /// Mark an argument local (which must be a tuple) as getting passed as
206 /// its individual components at the LLVM level.
208 /// This is used for the "rust-call" ABI.
209 pub spread_arg: Option<Local>,
211 /// Debug information pertaining to user variables, including captures.
212 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
214 /// A span representing this MIR, for error reporting.
217 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
218 /// We hold in this field all the constants we are not able to evaluate yet.
219 pub required_consts: Vec<Constant<'tcx>>,
221 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
223 /// Note that this does not actually mean that this body is not computable right now.
224 /// The repeat count in the following example is polymorphic, but can still be evaluated
225 /// without knowing anything about the type parameter `T`.
229 /// let _ = [0; std::mem::size_of::<*mut T>()];
233 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
234 /// removed the last mention of all generic params. We do not want to rely on optimizations and
235 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
236 pub is_polymorphic: bool,
238 predecessor_cache: PredecessorCache,
239 is_cyclic: GraphIsCyclicCache,
242 impl<'tcx> Body<'tcx> {
244 source: MirSource<'tcx>,
245 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
246 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
247 local_decls: LocalDecls<'tcx>,
248 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
250 var_debug_info: Vec<VarDebugInfo<'tcx>>,
252 generator_kind: Option<GeneratorKind>,
254 // We need `arg_count` locals, and one for the return place.
256 local_decls.len() > arg_count,
257 "expected at least {} locals, got {}",
262 let mut body = Body {
263 phase: MirPhase::Build,
267 generator: generator_kind.map(|generator_kind| {
268 Box::new(GeneratorInfo {
270 generator_drop: None,
271 generator_layout: None,
276 user_type_annotations,
281 required_consts: Vec::new(),
282 is_polymorphic: false,
283 predecessor_cache: PredecessorCache::new(),
284 is_cyclic: GraphIsCyclicCache::new(),
286 body.is_polymorphic = body.has_param_types_or_consts();
290 /// Returns a partially initialized MIR body containing only a list of basic blocks.
292 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
293 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
295 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
296 let mut body = Body {
297 phase: MirPhase::Build,
298 source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
300 source_scopes: IndexVec::new(),
302 local_decls: IndexVec::new(),
303 user_type_annotations: IndexVec::new(),
307 required_consts: Vec::new(),
308 var_debug_info: Vec::new(),
309 is_polymorphic: false,
310 predecessor_cache: PredecessorCache::new(),
311 is_cyclic: GraphIsCyclicCache::new(),
313 body.is_polymorphic = body.has_param_types_or_consts();
318 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
323 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
324 // Because the user could mutate basic block terminators via this reference, we need to
325 // invalidate the caches.
327 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
328 // invalidate the caches.
329 self.predecessor_cache.invalidate();
330 self.is_cyclic.invalidate();
331 &mut self.basic_blocks
335 pub fn basic_blocks_and_local_decls_mut(
337 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
338 self.predecessor_cache.invalidate();
339 self.is_cyclic.invalidate();
340 (&mut self.basic_blocks, &mut self.local_decls)
344 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
347 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
348 &mut LocalDecls<'tcx>,
349 &mut Vec<VarDebugInfo<'tcx>>,
351 self.predecessor_cache.invalidate();
352 self.is_cyclic.invalidate();
353 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
356 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
358 pub fn is_cfg_cyclic(&self) -> bool {
359 self.is_cyclic.is_cyclic(self)
363 pub fn local_kind(&self, local: Local) -> LocalKind {
364 let index = local.as_usize();
367 self.local_decls[local].mutability == Mutability::Mut,
368 "return place should be mutable"
371 LocalKind::ReturnPointer
372 } else if index < self.arg_count + 1 {
374 } else if self.local_decls[local].is_user_variable() {
381 /// Returns an iterator over all temporaries.
383 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
384 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
385 let local = Local::new(index);
386 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
390 /// Returns an iterator over all user-declared locals.
392 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
393 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
394 let local = Local::new(index);
395 self.local_decls[local].is_user_variable().then_some(local)
399 /// Returns an iterator over all user-declared mutable locals.
401 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
402 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
403 let local = Local::new(index);
404 let decl = &self.local_decls[local];
405 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
413 /// Returns an iterator over all user-declared mutable arguments and locals.
415 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
416 (1..self.local_decls.len()).filter_map(move |index| {
417 let local = Local::new(index);
418 let decl = &self.local_decls[local];
419 if (decl.is_user_variable() || index < self.arg_count + 1)
420 && decl.mutability == Mutability::Mut
429 /// Returns an iterator over all function arguments.
431 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
432 let arg_count = self.arg_count;
433 (1..arg_count + 1).map(Local::new)
436 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
437 /// locals that are neither arguments nor the return place).
439 pub fn vars_and_temps_iter(
441 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
442 let arg_count = self.arg_count;
443 let local_count = self.local_decls.len();
444 (arg_count + 1..local_count).map(Local::new)
447 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
448 /// invalidating statement indices in `Location`s.
449 pub fn make_statement_nop(&mut self, location: Location) {
450 let block = &mut self.basic_blocks[location.block];
451 debug_assert!(location.statement_index < block.statements.len());
452 block.statements[location.statement_index].make_nop()
455 /// Returns the source info associated with `location`.
456 pub fn source_info(&self, location: Location) -> &SourceInfo {
457 let block = &self[location.block];
458 let stmts = &block.statements;
459 let idx = location.statement_index;
460 if idx < stmts.len() {
461 &stmts[idx].source_info
463 assert_eq!(idx, stmts.len());
464 &block.terminator().source_info
468 /// Returns the return type; it always return first element from `local_decls` array.
470 pub fn return_ty(&self) -> Ty<'tcx> {
471 self.local_decls[RETURN_PLACE].ty
474 /// Gets the location of the terminator for the given block.
476 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
477 Location { block: bb, statement_index: self[bb].statements.len() }
481 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
482 self.predecessor_cache.compute(&self.basic_blocks)
486 pub fn dominators(&self) -> Dominators<BasicBlock> {
491 pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
492 self.generator.as_ref().and_then(|generator| generator.yield_ty)
496 pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
497 self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
501 pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
502 self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
506 pub fn generator_kind(&self) -> Option<GeneratorKind> {
507 self.generator.as_ref().map(|generator| generator.generator_kind)
511 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
514 /// Unsafe because of a PushUnsafeBlock
516 /// Unsafe because of an unsafe fn
518 /// Unsafe because of an `unsafe` block
519 ExplicitUnsafe(hir::HirId),
522 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
523 type Output = BasicBlockData<'tcx>;
526 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
527 &self.basic_blocks()[index]
531 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
533 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
534 &mut self.basic_blocks_mut()[index]
538 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
539 pub enum ClearCrossCrate<T> {
544 impl<T> ClearCrossCrate<T> {
545 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
547 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
548 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
552 pub fn assert_crate_local(self) -> T {
554 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
555 ClearCrossCrate::Set(v) => v,
560 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
561 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
563 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
565 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
566 if E::CLEAR_CROSS_CRATE {
571 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
572 ClearCrossCrate::Set(ref val) => {
573 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
579 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
581 fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
582 if D::CLEAR_CROSS_CRATE {
583 return Ok(ClearCrossCrate::Clear);
586 let discr = u8::decode(d)?;
589 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
590 TAG_CLEAR_CROSS_CRATE_SET => {
591 let val = T::decode(d)?;
592 Ok(ClearCrossCrate::Set(val))
594 tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
599 /// Grouped information about the source code origin of a MIR entity.
600 /// Intended to be inspected by diagnostics and debuginfo.
601 /// Most passes can work with it as a whole, within a single function.
602 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
603 // `Hash`. Please ping @bjorn3 if removing them.
604 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
605 pub struct SourceInfo {
606 /// The source span for the AST pertaining to this MIR entity.
609 /// The source scope, keeping track of which bindings can be
610 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
611 pub scope: SourceScope,
616 pub fn outermost(span: Span) -> Self {
617 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
621 ///////////////////////////////////////////////////////////////////////////
624 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
625 #[derive(Hash, HashStable)]
626 pub enum BorrowKind {
627 /// Data must be immutable and is aliasable.
630 /// The immediately borrowed place must be immutable, but projections from
631 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
632 /// conflict with a mutable borrow of `a.b.c`.
634 /// This is used when lowering matches: when matching on a place we want to
635 /// ensure that place have the same value from the start of the match until
636 /// an arm is selected. This prevents this code from compiling:
638 /// let mut x = &Some(0);
641 /// Some(_) if { x = &None; false } => (),
645 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
646 /// should not prevent `if let None = x { ... }`, for example, because the
647 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
648 /// We can also report errors with this kind of borrow differently.
651 /// Data must be immutable but not aliasable. This kind of borrow
652 /// cannot currently be expressed by the user and is used only in
653 /// implicit closure bindings. It is needed when the closure is
654 /// borrowing or mutating a mutable referent, e.g.:
656 /// let x: &mut isize = ...;
657 /// let y = || *x += 5;
659 /// If we were to try to translate this closure into a more explicit
660 /// form, we'd encounter an error with the code as written:
662 /// struct Env { x: & &mut isize }
663 /// let x: &mut isize = ...;
664 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
665 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
667 /// This is then illegal because you cannot mutate an `&mut` found
668 /// in an aliasable location. To solve, you'd have to translate with
669 /// an `&mut` borrow:
671 /// struct Env { x: & &mut isize }
672 /// let x: &mut isize = ...;
673 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
674 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
676 /// Now the assignment to `**env.x` is legal, but creating a
677 /// mutable pointer to `x` is not because `x` is not mutable. We
678 /// could fix this by declaring `x` as `let mut x`. This is ok in
679 /// user code, if awkward, but extra weird for closures, since the
680 /// borrow is hidden.
682 /// So we introduce a "unique imm" borrow -- the referent is
683 /// immutable, but not aliasable. This solves the problem. For
684 /// simplicity, we don't give users the way to express this
685 /// borrow, it's just used when translating closures.
688 /// Data is mutable and not aliasable.
690 /// `true` if this borrow arose from method-call auto-ref
691 /// (i.e., `adjustment::Adjust::Borrow`).
692 allow_two_phase_borrow: bool,
697 pub fn allows_two_phase_borrow(&self) -> bool {
699 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
700 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
705 ///////////////////////////////////////////////////////////////////////////
706 // Variables and temps
708 rustc_index::newtype_index! {
711 DEBUG_FORMAT = "_{}",
712 const RETURN_PLACE = 0,
716 impl Atom for Local {
717 fn index(self) -> usize {
722 /// Classifies locals into categories. See `Body::local_kind`.
723 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
725 /// User-declared variable binding.
727 /// Compiler-introduced temporary.
729 /// Function argument.
731 /// Location of function's return value.
735 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
736 pub struct VarBindingForm<'tcx> {
737 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
738 pub binding_mode: ty::BindingMode,
739 /// If an explicit type was provided for this variable binding,
740 /// this holds the source Span of that type.
742 /// NOTE: if you want to change this to a `HirId`, be wary that
743 /// doing so breaks incremental compilation (as of this writing),
744 /// while a `Span` does not cause our tests to fail.
745 pub opt_ty_info: Option<Span>,
746 /// Place of the RHS of the =, or the subject of the `match` where this
747 /// variable is initialized. None in the case of `let PATTERN;`.
748 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
749 /// (a) the right-hand side isn't evaluated as a place expression.
750 /// (b) it gives a way to separate this case from the remaining cases
752 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
753 /// The span of the pattern in which this variable was bound.
757 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
758 pub enum BindingForm<'tcx> {
759 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
760 Var(VarBindingForm<'tcx>),
761 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
762 ImplicitSelf(ImplicitSelfKind),
763 /// Reference used in a guard expression to ensure immutability.
767 /// Represents what type of implicit self a function has, if any.
768 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
769 pub enum ImplicitSelfKind {
770 /// Represents a `fn x(self);`.
772 /// Represents a `fn x(mut self);`.
774 /// Represents a `fn x(&self);`.
776 /// Represents a `fn x(&mut self);`.
778 /// Represents when a function does not have a self argument or
779 /// when a function has a `self: X` argument.
783 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
785 mod binding_form_impl {
786 use crate::ich::StableHashingContext;
787 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
789 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
790 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
791 use super::BindingForm::*;
792 std::mem::discriminant(self).hash_stable(hcx, hasher);
795 Var(binding) => binding.hash_stable(hcx, hasher),
796 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
803 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
804 /// created during evaluation of expressions in a block tail
805 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
807 /// It is used to improve diagnostics when such temporaries are
808 /// involved in borrow_check errors, e.g., explanations of where the
809 /// temporaries come from, when their destructors are run, and/or how
810 /// one might revise the code to satisfy the borrow checker's rules.
811 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
812 pub struct BlockTailInfo {
813 /// If `true`, then the value resulting from evaluating this tail
814 /// expression is ignored by the block's expression context.
816 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
817 /// but not e.g., `let _x = { ...; tail };`
818 pub tail_result_is_ignored: bool,
820 /// `Span` of the tail expression.
826 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
827 /// argument, or the return place.
828 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
829 pub struct LocalDecl<'tcx> {
830 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
832 /// Temporaries and the return place are always mutable.
833 pub mutability: Mutability,
835 // FIXME(matthewjasper) Don't store in this in `Body`
836 pub local_info: Option<Box<LocalInfo<'tcx>>>,
838 /// `true` if this is an internal local.
840 /// These locals are not based on types in the source code and are only used
841 /// for a few desugarings at the moment.
843 /// The generator transformation will sanity check the locals which are live
844 /// across a suspension point against the type components of the generator
845 /// which type checking knows are live across a suspension point. We need to
846 /// flag drop flags to avoid triggering this check as they are introduced
849 /// This should be sound because the drop flags are fully algebraic, and
850 /// therefore don't affect the auto-trait or outlives properties of the
854 /// If this local is a temporary and `is_block_tail` is `Some`,
855 /// then it is a temporary created for evaluation of some
856 /// subexpression of some block's tail expression (with no
857 /// intervening statement context).
858 // FIXME(matthewjasper) Don't store in this in `Body`
859 pub is_block_tail: Option<BlockTailInfo>,
861 /// The type of this local.
864 /// If the user manually ascribed a type to this variable,
865 /// e.g., via `let x: T`, then we carry that type here. The MIR
866 /// borrow checker needs this information since it can affect
867 /// region inference.
868 // FIXME(matthewjasper) Don't store in this in `Body`
869 pub user_ty: Option<Box<UserTypeProjections>>,
871 /// The *syntactic* (i.e., not visibility) source scope the local is defined
872 /// in. If the local was defined in a let-statement, this
873 /// is *within* the let-statement, rather than outside
876 /// This is needed because the visibility source scope of locals within
877 /// a let-statement is weird.
879 /// The reason is that we want the local to be *within* the let-statement
880 /// for lint purposes, but we want the local to be *after* the let-statement
881 /// for names-in-scope purposes.
883 /// That's it, if we have a let-statement like the one in this
887 /// fn foo(x: &str) {
888 /// #[allow(unused_mut)]
889 /// let mut x: u32 = { // <- one unused mut
890 /// let mut y: u32 = x.parse().unwrap();
897 /// Then, from a lint point of view, the declaration of `x: u32`
898 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
899 /// lint scopes are the same as the AST/HIR nesting.
901 /// However, from a name lookup point of view, the scopes look more like
902 /// as if the let-statements were `match` expressions:
905 /// fn foo(x: &str) {
907 /// match x.parse().unwrap() {
916 /// We care about the name-lookup scopes for debuginfo - if the
917 /// debuginfo instruction pointer is at the call to `x.parse()`, we
918 /// want `x` to refer to `x: &str`, but if it is at the call to
919 /// `drop(x)`, we want it to refer to `x: u32`.
921 /// To allow both uses to work, we need to have more than a single scope
922 /// for a local. We have the `source_info.scope` represent the "syntactic"
923 /// lint scope (with a variable being under its let block) while the
924 /// `var_debug_info.source_info.scope` represents the "local variable"
925 /// scope (where the "rest" of a block is under all prior let-statements).
927 /// The end result looks like this:
931 /// │{ argument x: &str }
933 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
934 /// │ │ // in practice because I'm lazy.
936 /// │ │← x.source_info.scope
937 /// │ │← `x.parse().unwrap()`
939 /// │ │ │← y.source_info.scope
941 /// │ │ │{ let y: u32 }
943 /// │ │ │← y.var_debug_info.source_info.scope
946 /// │ │{ let x: u32 }
947 /// │ │← x.var_debug_info.source_info.scope
948 /// │ │← `drop(x)` // This accesses `x: u32`.
950 pub source_info: SourceInfo,
953 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
954 #[cfg(target_arch = "x86_64")]
955 static_assert_size!(LocalDecl<'_>, 56);
957 /// Extra information about a some locals that's used for diagnostics and for
958 /// classifying variables into local variables, statics, etc, which is needed e.g.
959 /// for unsafety checking.
961 /// Not used for non-StaticRef temporaries, the return place, or anonymous
962 /// function parameters.
963 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
964 pub enum LocalInfo<'tcx> {
965 /// A user-defined local variable or function parameter
967 /// The `BindingForm` is solely used for local diagnostics when generating
968 /// warnings/errors when compiling the current crate, and therefore it need
969 /// not be visible across crates.
970 User(ClearCrossCrate<BindingForm<'tcx>>),
971 /// A temporary created that references the static with the given `DefId`.
972 StaticRef { def_id: DefId, is_thread_local: bool },
973 /// A temporary created that references the const with the given `DefId`
974 ConstRef { def_id: DefId },
977 impl<'tcx> LocalDecl<'tcx> {
978 /// Returns `true` only if local is a binding that can itself be
979 /// made mutable via the addition of the `mut` keyword, namely
980 /// something like the occurrences of `x` in:
981 /// - `fn foo(x: Type) { ... }`,
983 /// - or `match ... { C(x) => ... }`
984 pub fn can_be_made_mutable(&self) -> bool {
987 Some(box LocalInfo::User(ClearCrossCrate::Set(
988 BindingForm::Var(VarBindingForm {
989 binding_mode: ty::BindingMode::BindByValue(_),
993 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
998 /// Returns `true` if local is definitely not a `ref ident` or
999 /// `ref mut ident` binding. (Such bindings cannot be made into
1000 /// mutable bindings, but the inverse does not necessarily hold).
1001 pub fn is_nonref_binding(&self) -> bool {
1004 Some(box LocalInfo::User(ClearCrossCrate::Set(
1005 BindingForm::Var(VarBindingForm {
1006 binding_mode: ty::BindingMode::BindByValue(_),
1010 }) | BindingForm::ImplicitSelf(_),
1015 /// Returns `true` if this variable is a named variable or function
1016 /// parameter declared by the user.
1018 pub fn is_user_variable(&self) -> bool {
1019 matches!(self.local_info, Some(box LocalInfo::User(_)))
1022 /// Returns `true` if this is a reference to a variable bound in a `match`
1023 /// expression that is used to access said variable for the guard of the
1025 pub fn is_ref_for_guard(&self) -> bool {
1028 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
1032 /// Returns `Some` if this is a reference to a static item that is used to
1033 /// access that static.
1034 pub fn is_ref_to_static(&self) -> bool {
1035 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1038 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1039 /// access that static.
1040 pub fn is_ref_to_thread_local(&self) -> bool {
1041 match self.local_info {
1042 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1047 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1048 /// `__next` from a `for` loop.
1050 pub fn from_compiler_desugaring(&self) -> bool {
1051 self.source_info.span.desugaring_kind().is_some()
1054 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1056 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1057 Self::with_source_info(ty, SourceInfo::outermost(span))
1060 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1062 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1064 mutability: Mutability::Mut,
1067 is_block_tail: None,
1074 /// Converts `self` into same `LocalDecl` except tagged as internal.
1076 pub fn internal(mut self) -> Self {
1077 self.internal = true;
1081 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1083 pub fn immutable(mut self) -> Self {
1084 self.mutability = Mutability::Not;
1088 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1090 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1091 assert!(self.is_block_tail.is_none());
1092 self.is_block_tail = Some(info);
1097 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1098 pub enum VarDebugInfoContents<'tcx> {
1099 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1100 /// based on a `Local`, not a `Static`, and contains no indexing.
1102 Const(Constant<'tcx>),
1105 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1106 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1108 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1109 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1114 /// Debug information pertaining to a user variable.
1115 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1116 pub struct VarDebugInfo<'tcx> {
1119 /// Source info of the user variable, including the scope
1120 /// within which the variable is visible (to debuginfo)
1121 /// (see `LocalDecl`'s `source_info` field for more details).
1122 pub source_info: SourceInfo,
1124 /// Where the data for this user variable is to be found.
1125 pub value: VarDebugInfoContents<'tcx>,
1128 ///////////////////////////////////////////////////////////////////////////
1131 rustc_index::newtype_index! {
1132 /// A node in the MIR [control-flow graph][CFG].
1134 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1135 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1136 /// as an edge in a graph between basic blocks.
1138 /// Basic blocks consist of a series of [statements][Statement], ending with a
1139 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1140 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1141 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1142 /// needed because some analyses require that there are no critical edges in the CFG.
1144 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1145 /// the actual data that a basic block holds is in [`BasicBlockData`].
1147 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1149 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1150 /// [data-flow analyses]:
1151 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1152 /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1153 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1154 pub struct BasicBlock {
1156 DEBUG_FORMAT = "bb{}",
1157 const START_BLOCK = 0,
1162 pub fn start_location(self) -> Location {
1163 Location { block: self, statement_index: 0 }
1167 ///////////////////////////////////////////////////////////////////////////
1168 // BasicBlockData and Terminator
1170 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1171 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1172 pub struct BasicBlockData<'tcx> {
1173 /// List of statements in this block.
1174 pub statements: Vec<Statement<'tcx>>,
1176 /// Terminator for this block.
1178 /// N.B., this should generally ONLY be `None` during construction.
1179 /// Therefore, you should generally access it via the
1180 /// `terminator()` or `terminator_mut()` methods. The only
1181 /// exception is that certain passes, such as `simplify_cfg`, swap
1182 /// out the terminator temporarily with `None` while they continue
1183 /// to recurse over the set of basic blocks.
1184 pub terminator: Option<Terminator<'tcx>>,
1186 /// If true, this block lies on an unwind path. This is used
1187 /// during codegen where distinct kinds of basic blocks may be
1188 /// generated (particularly for MSVC cleanup). Unwind blocks must
1189 /// only branch to other unwind blocks.
1190 pub is_cleanup: bool,
1193 /// Information about an assertion failure.
1194 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
1195 pub enum AssertKind<O> {
1196 BoundsCheck { len: O, index: O },
1197 Overflow(BinOp, O, O),
1201 ResumedAfterReturn(GeneratorKind),
1202 ResumedAfterPanic(GeneratorKind),
1216 pub enum InlineAsmOperand<'tcx> {
1218 reg: InlineAsmRegOrRegClass,
1219 value: Operand<'tcx>,
1222 reg: InlineAsmRegOrRegClass,
1224 place: Option<Place<'tcx>>,
1227 reg: InlineAsmRegOrRegClass,
1229 in_value: Operand<'tcx>,
1230 out_place: Option<Place<'tcx>>,
1233 value: Operand<'tcx>,
1236 value: Box<Constant<'tcx>>,
1243 /// Type for MIR `Assert` terminator error messages.
1244 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1246 pub type Successors<'a> =
1247 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1248 pub type SuccessorsMut<'a> =
1249 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1251 impl<'tcx> BasicBlockData<'tcx> {
1252 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1253 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1256 /// Accessor for terminator.
1258 /// Terminator may not be None after construction of the basic block is complete. This accessor
1259 /// provides a convenience way to reach the terminator.
1260 pub fn terminator(&self) -> &Terminator<'tcx> {
1261 self.terminator.as_ref().expect("invalid terminator state")
1264 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1265 self.terminator.as_mut().expect("invalid terminator state")
1268 pub fn retain_statements<F>(&mut self, mut f: F)
1270 F: FnMut(&mut Statement<'_>) -> bool,
1272 for s in &mut self.statements {
1279 pub fn expand_statements<F, I>(&mut self, mut f: F)
1281 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1282 I: iter::TrustedLen<Item = Statement<'tcx>>,
1284 // Gather all the iterators we'll need to splice in, and their positions.
1285 let mut splices: Vec<(usize, I)> = vec![];
1286 let mut extra_stmts = 0;
1287 for (i, s) in self.statements.iter_mut().enumerate() {
1288 if let Some(mut new_stmts) = f(s) {
1289 if let Some(first) = new_stmts.next() {
1290 // We can already store the first new statement.
1293 // Save the other statements for optimized splicing.
1294 let remaining = new_stmts.size_hint().0;
1296 splices.push((i + 1 + extra_stmts, new_stmts));
1297 extra_stmts += remaining;
1305 // Splice in the new statements, from the end of the block.
1306 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1307 // where a range of elements ("gap") is left uninitialized, with
1308 // splicing adding new elements to the end of that gap and moving
1309 // existing elements from before the gap to the end of the gap.
1310 // For now, this is safe code, emulating a gap but initializing it.
1311 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1312 self.statements.resize(
1314 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1316 for (splice_start, new_stmts) in splices.into_iter().rev() {
1317 let splice_end = splice_start + new_stmts.size_hint().0;
1318 while gap.end > splice_end {
1321 self.statements.swap(gap.start, gap.end);
1323 self.statements.splice(splice_start..splice_end, new_stmts);
1324 gap.end = splice_start;
1328 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1329 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1333 impl<O> AssertKind<O> {
1334 /// Getting a description does not require `O` to be printable, and does not
1335 /// require allocation.
1336 /// The caller is expected to handle `BoundsCheck` separately.
1337 pub fn description(&self) -> &'static str {
1340 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1341 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1342 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1343 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1344 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1345 OverflowNeg(_) => "attempt to negate with overflow",
1346 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1347 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1348 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1349 DivisionByZero(_) => "attempt to divide by zero",
1350 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1351 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1352 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1353 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1354 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1355 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1359 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1360 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1366 BoundsCheck { ref len, ref index } => write!(
1368 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1372 OverflowNeg(op) => {
1373 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1375 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1376 RemainderByZero(op) => write!(
1378 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1381 Overflow(BinOp::Add, l, r) => write!(
1383 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1386 Overflow(BinOp::Sub, l, r) => write!(
1388 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1391 Overflow(BinOp::Mul, l, r) => write!(
1393 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1396 Overflow(BinOp::Div, l, r) => write!(
1398 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1401 Overflow(BinOp::Rem, l, r) => write!(
1403 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1406 Overflow(BinOp::Shr, _, r) => {
1407 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1409 Overflow(BinOp::Shl, _, r) => {
1410 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1412 _ => write!(f, "\"{}\"", self.description()),
1417 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421 BoundsCheck { ref len, ref index } => write!(
1423 "index out of bounds: the length is {:?} but the index is {:?}",
1426 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1427 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1428 RemainderByZero(op) => write!(
1430 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1433 Overflow(BinOp::Add, l, r) => {
1434 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1436 Overflow(BinOp::Sub, l, r) => {
1437 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1439 Overflow(BinOp::Mul, l, r) => {
1440 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1442 Overflow(BinOp::Div, l, r) => {
1443 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1445 Overflow(BinOp::Rem, l, r) => write!(
1447 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1450 Overflow(BinOp::Shr, _, r) => {
1451 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1453 Overflow(BinOp::Shl, _, r) => {
1454 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1456 _ => write!(f, "{}", self.description()),
1461 ///////////////////////////////////////////////////////////////////////////
1464 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1465 pub struct Statement<'tcx> {
1466 pub source_info: SourceInfo,
1467 pub kind: StatementKind<'tcx>,
1470 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1471 #[cfg(target_arch = "x86_64")]
1472 static_assert_size!(Statement<'_>, 32);
1474 impl Statement<'_> {
1475 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1476 /// invalidating statement indices in `Location`s.
1477 pub fn make_nop(&mut self) {
1478 self.kind = StatementKind::Nop
1481 /// Changes a statement to a nop and returns the original statement.
1482 pub fn replace_nop(&mut self) -> Self {
1484 source_info: self.source_info,
1485 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1490 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1491 pub enum StatementKind<'tcx> {
1492 /// Write the RHS Rvalue to the LHS Place.
1493 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1495 /// This represents all the reading that a pattern match may do
1496 /// (e.g., inspecting constants and discriminant values), and the
1497 /// kind of pattern it comes from. This is in order to adapt potential
1498 /// error messages to these specific patterns.
1500 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1501 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1502 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1504 /// Write the discriminant for a variant to the enum Place.
1505 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1507 /// Start a live range for the storage of the local.
1510 /// End the current live range for the storage of the local.
1513 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1514 /// of `StatementKind` low.
1515 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1517 /// Retag references in the given place, ensuring they got fresh tags. This is
1518 /// part of the Stacked Borrows model. These statements are currently only interpreted
1519 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1520 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1521 /// for more details.
1522 Retag(RetagKind, Box<Place<'tcx>>),
1524 /// Encodes a user's type ascription. These need to be preserved
1525 /// intact so that NLL can respect them. For example:
1529 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1530 /// to the user-given type `T`. The effect depends on the specified variance:
1532 /// - `Covariant` -- requires that `T_y <: T`
1533 /// - `Contravariant` -- requires that `T_y :> T`
1534 /// - `Invariant` -- requires that `T_y == T`
1535 /// - `Bivariant` -- no effect
1536 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1538 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1539 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1540 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1541 /// counter varible at runtime, each time the code region is executed.
1542 Coverage(Box<Coverage>),
1544 /// No-op. Useful for deleting instructions without affecting statement indices.
1548 impl<'tcx> StatementKind<'tcx> {
1549 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1551 StatementKind::Assign(x) => Some(x),
1556 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1558 StatementKind::Assign(x) => Some(x),
1564 /// Describes what kind of retag is to be performed.
1565 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1566 pub enum RetagKind {
1567 /// The initial retag when entering a function.
1569 /// Retag preparing for a two-phase borrow.
1571 /// Retagging raw pointers.
1573 /// A "normal" retag.
1577 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1578 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1579 pub enum FakeReadCause {
1580 /// Inject a fake read of the borrowed input at the end of each guards
1583 /// This should ensure that you cannot change the variant for an enum while
1584 /// you are in the midst of matching on it.
1587 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1588 /// generate a read of x to check that it is initialized and safe.
1591 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1592 /// in a match guard to ensure that it's value hasn't change by the time
1593 /// we create the OutsideGuard version.
1596 /// Officially, the semantics of
1598 /// `let pattern = <expr>;`
1600 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1601 /// into the pattern.
1603 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1604 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1605 /// but in some cases it can affect the borrow checker, as in #53695.
1606 /// Therefore, we insert a "fake read" here to ensure that we get
1607 /// appropriate errors.
1610 /// If we have an index expression like
1612 /// (*x)[1][{ x = y; 4}]
1614 /// then the first bounds check is invalidated when we evaluate the second
1615 /// index expression. Thus we create a fake borrow of `x` across the second
1616 /// indexer, which will cause a borrow check error.
1620 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1621 pub struct LlvmInlineAsm<'tcx> {
1622 pub asm: hir::LlvmInlineAsmInner,
1623 pub outputs: Box<[Place<'tcx>]>,
1624 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1627 impl Debug for Statement<'_> {
1628 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1629 use self::StatementKind::*;
1631 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1632 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1633 Retag(ref kind, ref place) => write!(
1637 RetagKind::FnEntry => "[fn entry] ",
1638 RetagKind::TwoPhase => "[2phase] ",
1639 RetagKind::Raw => "[raw] ",
1640 RetagKind::Default => "",
1644 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1645 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1646 SetDiscriminant { ref place, variant_index } => {
1647 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1649 LlvmInlineAsm(ref asm) => {
1650 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1652 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1653 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1655 Coverage(box ref coverage) => {
1656 if let Some(rgn) = &coverage.code_region {
1657 write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1659 write!(fmt, "Coverage::{:?}", coverage.kind)
1662 Nop => write!(fmt, "nop"),
1667 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1668 pub struct Coverage {
1669 pub kind: CoverageKind,
1670 pub code_region: Option<CodeRegion>,
1673 ///////////////////////////////////////////////////////////////////////////
1676 /// A path to a value; something that can be evaluated without
1677 /// changing or disturbing program state.
1678 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1679 pub struct Place<'tcx> {
1682 /// projection out of a place (access a field, deref a pointer, etc)
1683 pub projection: &'tcx List<PlaceElem<'tcx>>,
1686 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1687 #[derive(TyEncodable, TyDecodable, HashStable)]
1688 pub enum ProjectionElem<V, T> {
1693 /// These indices are generated by slice patterns. Easiest to explain
1697 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1698 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1699 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1700 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1703 /// index or -index (in Python terms), depending on from_end
1705 /// The thing being indexed must be at least this long. For arrays this
1706 /// is always the exact length.
1708 /// Counting backwards from end? This is always false when indexing an
1713 /// These indices are generated by slice patterns.
1715 /// If `from_end` is true `slice[from..slice.len() - to]`.
1716 /// Otherwise `array[from..to]`.
1720 /// Whether `to` counts from the start or end of the array/slice.
1721 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1722 /// For `ProjectionKind`, this can also be `true` for arrays.
1726 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1727 /// this for ADTs with more than one variant. It may be better to
1728 /// just introduce it always, or always for enums.
1730 /// The included Symbol is the name of the variant, used for printing MIR.
1731 Downcast(Option<Symbol>, VariantIdx),
1734 impl<V, T> ProjectionElem<V, T> {
1735 /// Returns `true` if the target of this projection may refer to a different region of memory
1737 fn is_indirect(&self) -> bool {
1739 Self::Deref => true,
1743 | Self::ConstantIndex { .. }
1744 | Self::Subslice { .. }
1745 | Self::Downcast(_, _) => false,
1750 /// Alias for projections as they appear in places, where the base is a place
1751 /// and the index is a local.
1752 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1754 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1755 #[cfg(target_arch = "x86_64")]
1756 static_assert_size!(PlaceElem<'_>, 24);
1758 /// Alias for projections as they appear in `UserTypeProjection`, where we
1759 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1760 pub type ProjectionKind = ProjectionElem<(), ()>;
1762 rustc_index::newtype_index! {
1765 DEBUG_FORMAT = "field[{}]"
1769 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1770 pub struct PlaceRef<'tcx> {
1772 pub projection: &'tcx [PlaceElem<'tcx>],
1775 impl<'tcx> Place<'tcx> {
1776 // FIXME change this to a const fn by also making List::empty a const fn.
1777 pub fn return_place() -> Place<'tcx> {
1778 Place { local: RETURN_PLACE, projection: List::empty() }
1781 /// Returns `true` if this `Place` contains a `Deref` projection.
1783 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1784 /// same region of memory as its base.
1785 pub fn is_indirect(&self) -> bool {
1786 self.projection.iter().any(|elem| elem.is_indirect())
1789 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1790 /// a single deref of a local.
1792 pub fn local_or_deref_local(&self) -> Option<Local> {
1793 self.as_ref().local_or_deref_local()
1796 /// If this place represents a local variable like `_X` with no
1797 /// projections, return `Some(_X)`.
1799 pub fn as_local(&self) -> Option<Local> {
1800 self.as_ref().as_local()
1804 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1805 PlaceRef { local: self.local, projection: &self.projection }
1808 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1809 /// its projection and then subsequently more projections are added.
1810 /// As a concrete example, given the place a.b.c, this would yield:
1814 /// Given a place without projections, the iterator is empty.
1816 pub fn iter_projections(
1818 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1819 self.projection.iter().enumerate().map(move |(i, proj)| {
1820 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1826 impl From<Local> for Place<'_> {
1827 fn from(local: Local) -> Self {
1828 Place { local, projection: List::empty() }
1832 impl<'tcx> PlaceRef<'tcx> {
1833 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1834 /// a single deref of a local.
1835 pub fn local_or_deref_local(&self) -> Option<Local> {
1837 PlaceRef { local, projection: [] }
1838 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1843 /// If this place represents a local variable like `_X` with no
1844 /// projections, return `Some(_X)`.
1845 pub fn as_local(&self) -> Option<Local> {
1847 PlaceRef { local, projection: [] } => Some(local),
1852 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1853 if let &[ref proj_base @ .., elem] = self.projection {
1854 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1861 impl Debug for Place<'_> {
1862 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1863 for elem in self.projection.iter().rev() {
1865 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1866 write!(fmt, "(").unwrap();
1868 ProjectionElem::Deref => {
1869 write!(fmt, "(*").unwrap();
1871 ProjectionElem::Index(_)
1872 | ProjectionElem::ConstantIndex { .. }
1873 | ProjectionElem::Subslice { .. } => {}
1877 write!(fmt, "{:?}", self.local)?;
1879 for elem in self.projection.iter() {
1881 ProjectionElem::Downcast(Some(name), _index) => {
1882 write!(fmt, " as {})", name)?;
1884 ProjectionElem::Downcast(None, index) => {
1885 write!(fmt, " as variant#{:?})", index)?;
1887 ProjectionElem::Deref => {
1890 ProjectionElem::Field(field, ty) => {
1891 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1893 ProjectionElem::Index(ref index) => {
1894 write!(fmt, "[{:?}]", index)?;
1896 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1897 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1899 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1900 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1902 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1903 write!(fmt, "[{:?}:]", from)?;
1905 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1906 write!(fmt, "[:-{:?}]", to)?;
1908 ProjectionElem::Subslice { from, to, from_end: true } => {
1909 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1911 ProjectionElem::Subslice { from, to, from_end: false } => {
1912 write!(fmt, "[{:?}..{:?}]", from, to)?;
1921 ///////////////////////////////////////////////////////////////////////////
1924 rustc_index::newtype_index! {
1925 pub struct SourceScope {
1927 DEBUG_FORMAT = "scope[{}]",
1928 const OUTERMOST_SOURCE_SCOPE = 0,
1932 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1933 pub struct SourceScopeData<'tcx> {
1935 pub parent_scope: Option<SourceScope>,
1937 /// Whether this scope is the root of a scope tree of another body,
1938 /// inlined into this body by the MIR inliner.
1939 /// `ty::Instance` is the callee, and the `Span` is the call site.
1940 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1942 /// Nearest (transitive) parent scope (if any) which is inlined.
1943 /// This is an optimization over walking up `parent_scope`
1944 /// until a scope with `inlined: Some(...)` is found.
1945 pub inlined_parent_scope: Option<SourceScope>,
1947 /// Crate-local information for this source scope, that can't (and
1948 /// needn't) be tracked across crates.
1949 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1952 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1953 pub struct SourceScopeLocalData {
1954 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1955 pub lint_root: hir::HirId,
1956 /// The unsafe block that contains this node.
1960 ///////////////////////////////////////////////////////////////////////////
1963 /// These are values that can appear inside an rvalue. They are intentionally
1964 /// limited to prevent rvalues from being nested in one another.
1965 #[derive(Clone, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
1966 pub enum Operand<'tcx> {
1967 /// Copy: The value must be available for use afterwards.
1969 /// This implies that the type of the place must be `Copy`; this is true
1970 /// by construction during build, but also checked by the MIR type checker.
1973 /// Move: The value (including old borrows of it) will not be used again.
1975 /// Safe for values of all types (modulo future developments towards `?Move`).
1976 /// Correct usage patterns are enforced by the borrow checker for safe code.
1977 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1980 /// Synthesizes a constant value.
1981 Constant(Box<Constant<'tcx>>),
1984 impl<'tcx> Debug for Operand<'tcx> {
1985 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1986 use self::Operand::*;
1988 Constant(ref a) => write!(fmt, "{:?}", a),
1989 Copy(ref place) => write!(fmt, "{:?}", place),
1990 Move(ref place) => write!(fmt, "move {:?}", place),
1995 impl<'tcx> Operand<'tcx> {
1996 /// Convenience helper to make a constant that refers to the fn
1997 /// with given `DefId` and substs. Since this is used to synthesize
1998 /// MIR, assumes `user_ty` is None.
1999 pub fn function_handle(
2002 substs: SubstsRef<'tcx>,
2005 let ty = tcx.type_of(def_id).subst(tcx, substs);
2006 Operand::Constant(box Constant {
2009 literal: ty::Const::zero_sized(tcx, ty),
2013 pub fn is_move(&self) -> bool {
2014 matches!(self, Operand::Move(..))
2017 /// Convenience helper to make a literal-like constant from a given scalar value.
2018 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
2019 pub fn const_from_scalar(
2024 ) -> Operand<'tcx> {
2026 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
2028 .layout_of(param_env_and_ty)
2029 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2031 let scalar_size = match val {
2032 Scalar::Int(int) => int.size(),
2033 _ => panic!("Invalid scalar type {:?}", val),
2035 scalar_size == type_size
2037 Operand::Constant(box Constant {
2040 literal: ty::Const::from_scalar(tcx, val, ty),
2044 pub fn to_copy(&self) -> Self {
2046 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2047 Operand::Move(place) => Operand::Copy(place),
2051 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2053 pub fn place(&self) -> Option<Place<'tcx>> {
2055 Operand::Copy(place) | Operand::Move(place) => Some(*place),
2056 Operand::Constant(_) => None,
2060 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2062 pub fn constant(&self) -> Option<&Constant<'tcx>> {
2064 Operand::Constant(x) => Some(&**x),
2065 Operand::Copy(_) | Operand::Move(_) => None,
2070 ///////////////////////////////////////////////////////////////////////////
2073 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2074 pub enum Rvalue<'tcx> {
2075 /// x (either a move or copy, depending on type of x)
2079 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2082 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2084 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2085 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2087 ThreadLocalRef(DefId),
2089 /// Create a raw pointer to the given place
2090 /// Can be generated by raw address of expressions (`&raw const x`),
2091 /// or when casting a reference to a raw pointer.
2092 AddressOf(Mutability, Place<'tcx>),
2094 /// length of a `[X]` or `[X;n]` value
2097 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2099 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2100 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2102 NullaryOp(NullOp, Ty<'tcx>),
2103 UnaryOp(UnOp, Operand<'tcx>),
2105 /// Read the discriminant of an ADT.
2107 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2108 /// be defined to return, say, a 0) if ADT is not an enum.
2109 Discriminant(Place<'tcx>),
2111 /// Creates an aggregate value, like a tuple or struct. This is
2112 /// only needed because we want to distinguish `dest = Foo { x:
2113 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2114 /// that `Foo` has a destructor. These rvalues can be optimized
2115 /// away after type-checking and before lowering.
2116 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2119 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2122 Pointer(PointerCast),
2125 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2126 pub enum AggregateKind<'tcx> {
2127 /// The type is of the element
2131 /// The second field is the variant index. It's equal to 0 for struct
2132 /// and union expressions. The fourth field is
2133 /// active field number and is present only for union expressions
2134 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2135 /// active field index would identity the field `c`
2136 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2138 Closure(DefId, SubstsRef<'tcx>),
2139 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2142 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2144 /// The `+` operator (addition)
2146 /// The `-` operator (subtraction)
2148 /// The `*` operator (multiplication)
2150 /// The `/` operator (division)
2152 /// The `%` operator (modulus)
2154 /// The `^` operator (bitwise xor)
2156 /// The `&` operator (bitwise and)
2158 /// The `|` operator (bitwise or)
2160 /// The `<<` operator (shift left)
2162 /// The `>>` operator (shift right)
2164 /// The `==` operator (equality)
2166 /// The `<` operator (less than)
2168 /// The `<=` operator (less than or equal to)
2170 /// The `!=` operator (not equal to)
2172 /// The `>=` operator (greater than or equal to)
2174 /// The `>` operator (greater than)
2176 /// The `ptr.offset` operator
2181 pub fn is_checkable(self) -> bool {
2183 matches!(self, Add | Sub | Mul | Shl | Shr)
2187 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2189 /// Returns the size of a value of that type
2191 /// Creates a new uninitialized box for a value of that type
2195 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2197 /// The `!` operator for logical inversion
2199 /// The `-` operator for negation
2203 impl<'tcx> Debug for Rvalue<'tcx> {
2204 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2205 use self::Rvalue::*;
2208 Use(ref place) => write!(fmt, "{:?}", place),
2209 Repeat(ref a, ref b) => {
2210 write!(fmt, "[{:?}; ", a)?;
2211 pretty_print_const(b, fmt, false)?;
2214 Len(ref a) => write!(fmt, "Len({:?})", a),
2215 Cast(ref kind, ref place, ref ty) => {
2216 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2218 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2219 CheckedBinaryOp(ref op, ref a, ref b) => {
2220 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2222 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2223 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2224 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2225 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2226 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2227 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2229 Ref(region, borrow_kind, ref place) => {
2230 let kind_str = match borrow_kind {
2231 BorrowKind::Shared => "",
2232 BorrowKind::Shallow => "shallow ",
2233 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2236 // When printing regions, add trailing space if necessary.
2237 let print_region = ty::tls::with(|tcx| {
2238 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2240 let region = if print_region {
2241 let mut region = region.to_string();
2242 if !region.is_empty() {
2247 // Do not even print 'static
2250 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2253 AddressOf(mutability, ref place) => {
2254 let kind_str = match mutability {
2255 Mutability::Mut => "mut",
2256 Mutability::Not => "const",
2259 write!(fmt, "&raw {} {:?}", kind_str, place)
2262 Aggregate(ref kind, ref places) => {
2263 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2264 let mut tuple_fmt = fmt.debug_tuple(name);
2265 for place in places {
2266 tuple_fmt.field(place);
2272 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2274 AggregateKind::Tuple => {
2275 if places.is_empty() {
2282 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2283 let variant_def = &adt_def.variants[variant];
2285 let name = ty::tls::with(|tcx| {
2286 let mut name = String::new();
2287 let substs = tcx.lift(substs).expect("could not lift for printing");
2288 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2289 .print_def_path(variant_def.def_id, substs)?;
2293 match variant_def.ctor_kind {
2294 CtorKind::Const => fmt.write_str(&name),
2295 CtorKind::Fn => fmt_tuple(fmt, &name),
2296 CtorKind::Fictive => {
2297 let mut struct_fmt = fmt.debug_struct(&name);
2298 for (field, place) in variant_def.fields.iter().zip(places) {
2299 struct_fmt.field(&field.ident.as_str(), place);
2306 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2307 if let Some(def_id) = def_id.as_local() {
2308 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2309 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2310 let substs = tcx.lift(substs).unwrap();
2313 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2316 let span = tcx.hir().span(hir_id);
2317 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2319 let mut struct_fmt = fmt.debug_struct(&name);
2321 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2322 for (&var_id, place) in upvars.keys().zip(places) {
2323 let var_name = tcx.hir().name(var_id);
2324 struct_fmt.field(&var_name.as_str(), place);
2330 write!(fmt, "[closure]")
2334 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2335 if let Some(def_id) = def_id.as_local() {
2336 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2337 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2338 let mut struct_fmt = fmt.debug_struct(&name);
2340 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2341 for (&var_id, place) in upvars.keys().zip(places) {
2342 let var_name = tcx.hir().name(var_id);
2343 struct_fmt.field(&var_name.as_str(), place);
2349 write!(fmt, "[generator]")
2358 ///////////////////////////////////////////////////////////////////////////
2361 /// Two constants are equal if they are the same constant. Note that
2362 /// this does not necessarily mean that they are `==` in Rust. In
2363 /// particular, one must be wary of `NaN`!
2365 #[derive(Clone, Copy, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
2366 pub struct Constant<'tcx> {
2369 /// Optional user-given type: for something like
2370 /// `collect::<Vec<_>>`, this would be present and would
2371 /// indicate that `Vec<_>` was explicitly specified.
2373 /// Needed for NLL to impose user-given type constraints.
2374 pub user_ty: Option<UserTypeAnnotationIndex>,
2376 pub literal: &'tcx ty::Const<'tcx>,
2379 impl Constant<'tcx> {
2380 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2381 match self.literal.val.try_to_scalar() {
2382 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2383 GlobalAlloc::Static(def_id) => {
2384 assert!(!tcx.is_thread_local_static(def_id));
2394 /// A collection of projections into user types.
2396 /// They are projections because a binding can occur a part of a
2397 /// parent pattern that has been ascribed a type.
2399 /// Its a collection because there can be multiple type ascriptions on
2400 /// the path from the root of the pattern down to the binding itself.
2405 /// struct S<'a>((i32, &'a str), String);
2406 /// let S((_, w): (i32, &'static str), _): S = ...;
2407 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2408 /// // --------------------------------- ^ (2)
2411 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2412 /// ascribed the type `(i32, &'static str)`.
2414 /// The highlights labelled `(2)` show the whole pattern being
2415 /// ascribed the type `S`.
2417 /// In this example, when we descend to `w`, we will have built up the
2418 /// following two projected types:
2420 /// * base: `S`, projection: `(base.0).1`
2421 /// * base: `(i32, &'static str)`, projection: `base.1`
2423 /// The first will lead to the constraint `w: &'1 str` (for some
2424 /// inferred region `'1`). The second will lead to the constraint `w:
2426 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2427 pub struct UserTypeProjections {
2428 pub contents: Vec<(UserTypeProjection, Span)>,
2431 impl<'tcx> UserTypeProjections {
2432 pub fn none() -> Self {
2433 UserTypeProjections { contents: vec![] }
2436 pub fn is_empty(&self) -> bool {
2437 self.contents.is_empty()
2440 pub fn projections_and_spans(
2442 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2443 self.contents.iter()
2446 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2447 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2450 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2451 self.contents.push((user_ty.clone(), span));
2457 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2459 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2463 pub fn index(self) -> Self {
2464 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2467 pub fn subslice(self, from: u64, to: u64) -> Self {
2468 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2471 pub fn deref(self) -> Self {
2472 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2475 pub fn leaf(self, field: Field) -> Self {
2476 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2479 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2480 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2484 /// Encodes the effect of a user-supplied type annotation on the
2485 /// subcomponents of a pattern. The effect is determined by applying the
2486 /// given list of proejctions to some underlying base type. Often,
2487 /// the projection element list `projs` is empty, in which case this
2488 /// directly encodes a type in `base`. But in the case of complex patterns with
2489 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2490 /// in which case the `projs` vector is used.
2494 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2496 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2497 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2498 /// determined by finding the type of the `.0` field from `T`.
2499 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2500 pub struct UserTypeProjection {
2501 pub base: UserTypeAnnotationIndex,
2502 pub projs: Vec<ProjectionKind>,
2505 impl Copy for ProjectionKind {}
2507 impl UserTypeProjection {
2508 pub(crate) fn index(mut self) -> Self {
2509 self.projs.push(ProjectionElem::Index(()));
2513 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2514 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2518 pub(crate) fn deref(mut self) -> Self {
2519 self.projs.push(ProjectionElem::Deref);
2523 pub(crate) fn leaf(mut self, field: Field) -> Self {
2524 self.projs.push(ProjectionElem::Field(field, ()));
2528 pub(crate) fn variant(
2531 variant_index: VariantIdx,
2534 self.projs.push(ProjectionElem::Downcast(
2535 Some(adt_def.variants[variant_index].ident.name),
2538 self.projs.push(ProjectionElem::Field(field, ()));
2543 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2545 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2546 fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
2547 UserTypeProjection {
2548 base: self.base.fold_with(folder),
2549 projs: self.projs.fold_with(folder),
2553 fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2556 ) -> ControlFlow<Vs::BreakTy> {
2557 self.base.visit_with(visitor)
2558 // Note: there's nothing in `self.proj` to visit.
2562 rustc_index::newtype_index! {
2563 pub struct Promoted {
2565 DEBUG_FORMAT = "promoted[{}]"
2569 impl<'tcx> Debug for Constant<'tcx> {
2570 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2571 write!(fmt, "{}", self)
2575 impl<'tcx> Display for Constant<'tcx> {
2576 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2577 match self.literal.ty.kind() {
2579 _ => write!(fmt, "const ")?,
2581 pretty_print_const(self.literal, fmt, true)
2585 fn pretty_print_const(
2586 c: &ty::Const<'tcx>,
2587 fmt: &mut Formatter<'_>,
2590 use crate::ty::print::PrettyPrinter;
2591 ty::tls::with(|tcx| {
2592 let literal = tcx.lift(c).unwrap();
2593 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2594 cx.print_alloc_ids = true;
2595 cx.pretty_print_const(literal, print_types)?;
2600 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2601 type Node = BasicBlock;
2604 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2606 fn num_nodes(&self) -> usize {
2607 self.basic_blocks.len()
2611 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2613 fn start_node(&self) -> Self::Node {
2618 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2620 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2621 self.basic_blocks[node].terminator().successors().cloned()
2625 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2626 type Item = BasicBlock;
2627 type Iter = iter::Cloned<Successors<'b>>;
2630 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2631 type Item = BasicBlock;
2632 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2635 impl graph::WithPredecessors for Body<'tcx> {
2637 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2638 self.predecessors()[node].clone().into_iter()
2642 /// `Location` represents the position of the start of the statement; or, if
2643 /// `statement_index` equals the number of statements, then the start of the
2645 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2646 pub struct Location {
2647 /// The block that the location is within.
2648 pub block: BasicBlock,
2650 pub statement_index: usize,
2653 impl fmt::Debug for Location {
2654 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2655 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2660 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2662 /// Returns the location immediately after this one within the enclosing block.
2664 /// Note that if this location represents a terminator, then the
2665 /// resulting location would be out of bounds and invalid.
2666 pub fn successor_within_block(&self) -> Location {
2667 Location { block: self.block, statement_index: self.statement_index + 1 }
2670 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2671 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2672 // If we are in the same block as the other location and are an earlier statement
2673 // then we are a predecessor of `other`.
2674 if self.block == other.block && self.statement_index < other.statement_index {
2678 let predecessors = body.predecessors();
2680 // If we're in another block, then we want to check that block is a predecessor of `other`.
2681 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2682 let mut visited = FxHashSet::default();
2684 while let Some(block) = queue.pop() {
2685 // If we haven't visited this block before, then make sure we visit it's predecessors.
2686 if visited.insert(block) {
2687 queue.extend(predecessors[block].iter().cloned());
2692 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2693 // we found that block by looking at the predecessors of `other`).
2694 if self.block == block {
2702 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2703 if self.block == other.block {
2704 self.statement_index <= other.statement_index
2706 dominators.is_dominated_by(other.block, self.block)