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::interpret::{Allocation, ConstValue, GlobalAlloc, Scalar};
6 use crate::mir::visit::MirVisitable;
7 use crate::ty::adjustment::PointerCast;
8 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
9 use crate::ty::print::{FmtPrinter, Printer};
10 use crate::ty::subst::{Subst, SubstsRef};
12 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
15 use rustc_hir::def::{CtorKind, Namespace};
16 use rustc_hir::def_id::DefId;
17 use rustc_hir::{self, GeneratorKind};
18 use rustc_target::abi::VariantIdx;
20 use polonius_engine::Atom;
21 pub use rustc_ast::ast::Mutability;
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphSuccessors};
25 use rustc_index::bit_set::BitMatrix;
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_macros::HashStable;
28 use rustc_serialize::{Decodable, Encodable};
29 use rustc_span::symbol::Symbol;
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::abi;
32 use rustc_target::asm::InlineAsmRegOrRegClass;
34 use std::fmt::{self, Debug, Display, Formatter, Write};
35 use std::ops::{Index, IndexMut};
37 use std::{iter, mem, option};
39 use self::predecessors::{PredecessorCache, Predecessors};
40 pub use self::query::*;
49 pub use terminator::*;
55 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
57 pub trait HasLocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx>;
61 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
62 fn local_decls(&self) -> &LocalDecls<'tcx> {
67 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
68 fn local_decls(&self) -> &LocalDecls<'tcx> {
73 /// The various "big phases" that MIR goes through.
75 /// Warning: ordering of variants is significant.
76 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
87 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
88 pub fn phase_index(&self) -> usize {
93 /// The lowered representation of a single function.
94 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
95 pub struct Body<'tcx> {
96 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
97 /// that indexes into this vector.
98 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
100 /// Records how far through the "desugaring and optimization" process this particular
101 /// MIR has traversed. This is particularly useful when inlining, since in that context
102 /// we instantiate the promoted constants and add them to our promoted vector -- but those
103 /// promoted items have already been optimized, whereas ours have not. This field allows
104 /// us to see the difference and forego optimization on the inlined promoted items.
107 /// A list of source scopes; these are referenced by statements
108 /// and used for debuginfo. Indexed by a `SourceScope`.
109 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
111 /// The yield type of the function, if it is a generator.
112 pub yield_ty: Option<Ty<'tcx>>,
114 /// Generator drop glue.
115 pub generator_drop: Option<Box<Body<'tcx>>>,
117 /// The layout of a generator. Produced by the state transformation.
118 pub generator_layout: Option<GeneratorLayout<'tcx>>,
120 /// If this is a generator then record the type of source expression that caused this generator
122 pub generator_kind: Option<GeneratorKind>,
124 /// Declarations of locals.
126 /// The first local is the return value pointer, followed by `arg_count`
127 /// locals for the function arguments, followed by any user-declared
128 /// variables and temporaries.
129 pub local_decls: LocalDecls<'tcx>,
131 /// User type annotations.
132 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
134 /// The number of arguments this function takes.
136 /// Starting at local 1, `arg_count` locals will be provided by the caller
137 /// and can be assumed to be initialized.
139 /// If this MIR was built for a constant, this will be 0.
140 pub arg_count: usize,
142 /// Mark an argument local (which must be a tuple) as getting passed as
143 /// its individual components at the LLVM level.
145 /// This is used for the "rust-call" ABI.
146 pub spread_arg: Option<Local>,
148 /// Debug information pertaining to user variables, including captures.
149 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
151 /// A span representing this MIR, for error reporting.
154 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
155 /// We hold in this field all the constants we are not able to evaluate yet.
156 pub required_consts: Vec<Constant<'tcx>>,
158 /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
159 /// we'd statically know that no thing with interior mutability will ever be available to the
160 /// user without some serious unsafe code. Now this means that our promoted is actually
161 /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
162 /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
163 /// interior mutability. This flag just makes this situation very obvious where the previous
164 /// implementation without the flag hid this situation silently.
165 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
166 pub ignore_interior_mut_in_const_validation: bool,
168 predecessor_cache: PredecessorCache,
171 impl<'tcx> Body<'tcx> {
173 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
174 source_scopes: IndexVec<SourceScope, SourceScopeData>,
175 local_decls: LocalDecls<'tcx>,
176 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
178 var_debug_info: Vec<VarDebugInfo<'tcx>>,
180 generator_kind: Option<GeneratorKind>,
182 // We need `arg_count` locals, and one for the return place.
184 local_decls.len() > arg_count,
185 "expected at least {} locals, got {}",
191 phase: MirPhase::Build,
195 generator_drop: None,
196 generator_layout: None,
199 user_type_annotations,
204 required_consts: Vec::new(),
205 ignore_interior_mut_in_const_validation: false,
206 predecessor_cache: PredecessorCache::new(),
210 /// Returns a partially initialized MIR body containing only a list of basic blocks.
212 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
213 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
215 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
217 phase: MirPhase::Build,
219 source_scopes: IndexVec::new(),
221 generator_drop: None,
222 generator_layout: None,
223 local_decls: IndexVec::new(),
224 user_type_annotations: IndexVec::new(),
228 required_consts: Vec::new(),
229 generator_kind: None,
230 var_debug_info: Vec::new(),
231 ignore_interior_mut_in_const_validation: false,
232 predecessor_cache: PredecessorCache::new(),
237 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
242 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
243 // Because the user could mutate basic block terminators via this reference, we need to
244 // invalidate the predecessor cache.
246 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
247 // invalidate the predecessor cache.
248 self.predecessor_cache.invalidate();
249 &mut self.basic_blocks
253 pub fn basic_blocks_and_local_decls_mut(
255 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
256 self.predecessor_cache.invalidate();
257 (&mut self.basic_blocks, &mut self.local_decls)
261 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
264 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
265 &mut LocalDecls<'tcx>,
266 &mut Vec<VarDebugInfo<'tcx>>,
268 self.predecessor_cache.invalidate();
269 (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
272 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
274 pub fn is_cfg_cyclic(&self) -> bool {
275 graph::is_cyclic(self)
279 pub fn local_kind(&self, local: Local) -> LocalKind {
280 let index = local.as_usize();
283 self.local_decls[local].mutability == Mutability::Mut,
284 "return place should be mutable"
287 LocalKind::ReturnPointer
288 } else if index < self.arg_count + 1 {
290 } else if self.local_decls[local].is_user_variable() {
297 /// Returns an iterator over all temporaries.
299 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
300 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
301 let local = Local::new(index);
302 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
306 /// Returns an iterator over all user-declared locals.
308 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
309 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
310 let local = Local::new(index);
311 self.local_decls[local].is_user_variable().then_some(local)
315 /// Returns an iterator over all user-declared mutable locals.
317 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
318 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
319 let local = Local::new(index);
320 let decl = &self.local_decls[local];
321 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
329 /// Returns an iterator over all user-declared mutable arguments and locals.
331 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
332 (1..self.local_decls.len()).filter_map(move |index| {
333 let local = Local::new(index);
334 let decl = &self.local_decls[local];
335 if (decl.is_user_variable() || index < self.arg_count + 1)
336 && decl.mutability == Mutability::Mut
345 /// Returns an iterator over all function arguments.
347 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
348 let arg_count = self.arg_count;
349 (1..arg_count + 1).map(Local::new)
352 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
353 /// locals that are neither arguments nor the return place).
355 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
356 let arg_count = self.arg_count;
357 let local_count = self.local_decls.len();
358 (arg_count + 1..local_count).map(Local::new)
361 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
362 /// invalidating statement indices in `Location`s.
363 pub fn make_statement_nop(&mut self, location: Location) {
364 let block = &mut self.basic_blocks[location.block];
365 debug_assert!(location.statement_index < block.statements.len());
366 block.statements[location.statement_index].make_nop()
369 /// Returns the source info associated with `location`.
370 pub fn source_info(&self, location: Location) -> &SourceInfo {
371 let block = &self[location.block];
372 let stmts = &block.statements;
373 let idx = location.statement_index;
374 if idx < stmts.len() {
375 &stmts[idx].source_info
377 assert_eq!(idx, stmts.len());
378 &block.terminator().source_info
382 /// Checks if `sub` is a sub scope of `sup`
383 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
385 match self.source_scopes[sub].parent_scope {
386 None => return false,
393 /// Returns the return type; it always return first element from `local_decls` array.
395 pub fn return_ty(&self) -> Ty<'tcx> {
396 self.local_decls[RETURN_PLACE].ty
399 /// Gets the location of the terminator for the given block.
401 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
402 Location { block: bb, statement_index: self[bb].statements.len() }
406 pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
407 self.predecessor_cache.compute(&self.basic_blocks)
411 pub fn dominators(&self) -> Dominators<BasicBlock> {
416 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
419 /// Unsafe because of a PushUnsafeBlock
421 /// Unsafe because of an unsafe fn
423 /// Unsafe because of an `unsafe` block
424 ExplicitUnsafe(hir::HirId),
427 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
428 type Output = BasicBlockData<'tcx>;
431 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
432 &self.basic_blocks()[index]
436 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
438 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
439 &mut self.basic_blocks_mut()[index]
443 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
444 pub enum ClearCrossCrate<T> {
449 impl<T> ClearCrossCrate<T> {
450 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
452 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
453 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
457 pub fn assert_crate_local(self) -> T {
459 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
460 ClearCrossCrate::Set(v) => v,
465 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
466 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
468 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {
470 fn default_encode<E: rustc_serialize::Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
472 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
473 ClearCrossCrate::Set(ref val) => {
474 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
480 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {
482 fn default_decode<D>(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error>
484 D: rustc_serialize::Decoder,
486 let discr = u8::decode(d)?;
489 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
490 TAG_CLEAR_CROSS_CRATE_SET => {
491 let val = T::decode(d)?;
492 Ok(ClearCrossCrate::Set(val))
499 /// Grouped information about the source code origin of a MIR entity.
500 /// Intended to be inspected by diagnostics and debuginfo.
501 /// Most passes can work with it as a whole, within a single function.
502 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
503 // `Hash`. Please ping @bjorn3 if removing them.
504 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
505 pub struct SourceInfo {
506 /// The source span for the AST pertaining to this MIR entity.
509 /// The source scope, keeping track of which bindings can be
510 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
511 pub scope: SourceScope,
516 pub fn outermost(span: Span) -> Self {
517 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
521 ///////////////////////////////////////////////////////////////////////////
524 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
525 #[derive(HashStable)]
526 pub enum BorrowKind {
527 /// Data must be immutable and is aliasable.
530 /// The immediately borrowed place must be immutable, but projections from
531 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
532 /// conflict with a mutable borrow of `a.b.c`.
534 /// This is used when lowering matches: when matching on a place we want to
535 /// ensure that place have the same value from the start of the match until
536 /// an arm is selected. This prevents this code from compiling:
538 /// let mut x = &Some(0);
541 /// Some(_) if { x = &None; false } => (),
545 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
546 /// should not prevent `if let None = x { ... }`, for example, because the
547 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
548 /// We can also report errors with this kind of borrow differently.
551 /// Data must be immutable but not aliasable. This kind of borrow
552 /// cannot currently be expressed by the user and is used only in
553 /// implicit closure bindings. It is needed when the closure is
554 /// borrowing or mutating a mutable referent, e.g.:
556 /// let x: &mut isize = ...;
557 /// let y = || *x += 5;
559 /// If we were to try to translate this closure into a more explicit
560 /// form, we'd encounter an error with the code as written:
562 /// struct Env { x: & &mut isize }
563 /// let x: &mut isize = ...;
564 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
565 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
567 /// This is then illegal because you cannot mutate an `&mut` found
568 /// in an aliasable location. To solve, you'd have to translate with
569 /// an `&mut` borrow:
571 /// struct Env { x: & &mut isize }
572 /// let x: &mut isize = ...;
573 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
574 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
576 /// Now the assignment to `**env.x` is legal, but creating a
577 /// mutable pointer to `x` is not because `x` is not mutable. We
578 /// could fix this by declaring `x` as `let mut x`. This is ok in
579 /// user code, if awkward, but extra weird for closures, since the
580 /// borrow is hidden.
582 /// So we introduce a "unique imm" borrow -- the referent is
583 /// immutable, but not aliasable. This solves the problem. For
584 /// simplicity, we don't give users the way to express this
585 /// borrow, it's just used when translating closures.
588 /// Data is mutable and not aliasable.
590 /// `true` if this borrow arose from method-call auto-ref
591 /// (i.e., `adjustment::Adjust::Borrow`).
592 allow_two_phase_borrow: bool,
597 pub fn allows_two_phase_borrow(&self) -> bool {
599 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
600 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
605 ///////////////////////////////////////////////////////////////////////////
606 // Variables and temps
608 rustc_index::newtype_index! {
611 DEBUG_FORMAT = "_{}",
612 const RETURN_PLACE = 0,
616 impl Atom for Local {
617 fn index(self) -> usize {
622 /// Classifies locals into categories. See `Body::local_kind`.
623 #[derive(PartialEq, Eq, Debug, HashStable)]
625 /// User-declared variable binding.
627 /// Compiler-introduced temporary.
629 /// Function argument.
631 /// Location of function's return value.
635 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
636 pub struct VarBindingForm<'tcx> {
637 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
638 pub binding_mode: ty::BindingMode,
639 /// If an explicit type was provided for this variable binding,
640 /// this holds the source Span of that type.
642 /// NOTE: if you want to change this to a `HirId`, be wary that
643 /// doing so breaks incremental compilation (as of this writing),
644 /// while a `Span` does not cause our tests to fail.
645 pub opt_ty_info: Option<Span>,
646 /// Place of the RHS of the =, or the subject of the `match` where this
647 /// variable is initialized. None in the case of `let PATTERN;`.
648 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
649 /// (a) the right-hand side isn't evaluated as a place expression.
650 /// (b) it gives a way to separate this case from the remaining cases
652 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
653 /// The span of the pattern in which this variable was bound.
657 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
658 pub enum BindingForm<'tcx> {
659 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
660 Var(VarBindingForm<'tcx>),
661 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
662 ImplicitSelf(ImplicitSelfKind),
663 /// Reference used in a guard expression to ensure immutability.
667 /// Represents what type of implicit self a function has, if any.
668 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
669 pub enum ImplicitSelfKind {
670 /// Represents a `fn x(self);`.
672 /// Represents a `fn x(mut self);`.
674 /// Represents a `fn x(&self);`.
676 /// Represents a `fn x(&mut self);`.
678 /// Represents when a function does not have a self argument or
679 /// when a function has a `self: X` argument.
683 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
685 mod binding_form_impl {
686 use crate::ich::StableHashingContext;
687 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
689 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
690 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
691 use super::BindingForm::*;
692 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
695 Var(binding) => binding.hash_stable(hcx, hasher),
696 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
703 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
704 /// created during evaluation of expressions in a block tail
705 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
707 /// It is used to improve diagnostics when such temporaries are
708 /// involved in borrow_check errors, e.g., explanations of where the
709 /// temporaries come from, when their destructors are run, and/or how
710 /// one might revise the code to satisfy the borrow checker's rules.
711 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
712 pub struct BlockTailInfo {
713 /// If `true`, then the value resulting from evaluating this tail
714 /// expression is ignored by the block's expression context.
716 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
717 /// but not e.g., `let _x = { ...; tail };`
718 pub tail_result_is_ignored: bool,
720 /// `Span` of the tail expression.
726 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
727 /// argument, or the return place.
728 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
729 pub struct LocalDecl<'tcx> {
730 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
732 /// Temporaries and the return place are always mutable.
733 pub mutability: Mutability,
735 // FIXME(matthewjasper) Don't store in this in `Body`
736 pub local_info: Option<Box<LocalInfo<'tcx>>>,
738 /// `true` if this is an internal local.
740 /// These locals are not based on types in the source code and are only used
741 /// for a few desugarings at the moment.
743 /// The generator transformation will sanity check the locals which are live
744 /// across a suspension point against the type components of the generator
745 /// which type checking knows are live across a suspension point. We need to
746 /// flag drop flags to avoid triggering this check as they are introduced
749 /// Unsafety checking will also ignore dereferences of these locals,
750 /// so they can be used for raw pointers only used in a desugaring.
752 /// This should be sound because the drop flags are fully algebraic, and
753 /// therefore don't affect the OIBIT or outlives properties of the
757 /// If this local is a temporary and `is_block_tail` is `Some`,
758 /// then it is a temporary created for evaluation of some
759 /// subexpression of some block's tail expression (with no
760 /// intervening statement context).
761 // FIXME(matthewjasper) Don't store in this in `Body`
762 pub is_block_tail: Option<BlockTailInfo>,
764 /// The type of this local.
767 /// If the user manually ascribed a type to this variable,
768 /// e.g., via `let x: T`, then we carry that type here. The MIR
769 /// borrow checker needs this information since it can affect
770 /// region inference.
771 // FIXME(matthewjasper) Don't store in this in `Body`
772 pub user_ty: Option<Box<UserTypeProjections>>,
774 /// The *syntactic* (i.e., not visibility) source scope the local is defined
775 /// in. If the local was defined in a let-statement, this
776 /// is *within* the let-statement, rather than outside
779 /// This is needed because the visibility source scope of locals within
780 /// a let-statement is weird.
782 /// The reason is that we want the local to be *within* the let-statement
783 /// for lint purposes, but we want the local to be *after* the let-statement
784 /// for names-in-scope purposes.
786 /// That's it, if we have a let-statement like the one in this
790 /// fn foo(x: &str) {
791 /// #[allow(unused_mut)]
792 /// let mut x: u32 = { // <- one unused mut
793 /// let mut y: u32 = x.parse().unwrap();
800 /// Then, from a lint point of view, the declaration of `x: u32`
801 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
802 /// lint scopes are the same as the AST/HIR nesting.
804 /// However, from a name lookup point of view, the scopes look more like
805 /// as if the let-statements were `match` expressions:
808 /// fn foo(x: &str) {
810 /// match x.parse().unwrap() {
819 /// We care about the name-lookup scopes for debuginfo - if the
820 /// debuginfo instruction pointer is at the call to `x.parse()`, we
821 /// want `x` to refer to `x: &str`, but if it is at the call to
822 /// `drop(x)`, we want it to refer to `x: u32`.
824 /// To allow both uses to work, we need to have more than a single scope
825 /// for a local. We have the `source_info.scope` represent the "syntactic"
826 /// lint scope (with a variable being under its let block) while the
827 /// `var_debug_info.source_info.scope` represents the "local variable"
828 /// scope (where the "rest" of a block is under all prior let-statements).
830 /// The end result looks like this:
834 /// │{ argument x: &str }
836 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
837 /// │ │ // in practice because I'm lazy.
839 /// │ │← x.source_info.scope
840 /// │ │← `x.parse().unwrap()`
842 /// │ │ │← y.source_info.scope
844 /// │ │ │{ let y: u32 }
846 /// │ │ │← y.var_debug_info.source_info.scope
849 /// │ │{ let x: u32 }
850 /// │ │← x.var_debug_info.source_info.scope
851 /// │ │← `drop(x)` // This accesses `x: u32`.
853 pub source_info: SourceInfo,
856 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
857 #[cfg(target_arch = "x86_64")]
858 static_assert_size!(LocalDecl<'_>, 56);
860 /// Extra information about a some locals that's used for diagnostics. (Not
861 /// used for non-StaticRef temporaries, the return place, or anonymous function
863 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
864 pub enum LocalInfo<'tcx> {
865 /// A user-defined local variable or function parameter
867 /// The `BindingForm` is solely used for local diagnostics when generating
868 /// warnings/errors when compiling the current crate, and therefore it need
869 /// not be visible across crates.
870 User(ClearCrossCrate<BindingForm<'tcx>>),
871 /// A temporary created that references the static with the given `DefId`.
872 StaticRef { def_id: DefId, is_thread_local: bool },
875 impl<'tcx> LocalDecl<'tcx> {
876 /// Returns `true` only if local is a binding that can itself be
877 /// made mutable via the addition of the `mut` keyword, namely
878 /// something like the occurrences of `x` in:
879 /// - `fn foo(x: Type) { ... }`,
881 /// - or `match ... { C(x) => ... }`
882 pub fn can_be_made_mutable(&self) -> bool {
883 match self.local_info {
884 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
885 binding_mode: ty::BindingMode::BindByValue(_),
891 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
892 ImplicitSelfKind::Imm,
899 /// Returns `true` if local is definitely not a `ref ident` or
900 /// `ref mut ident` binding. (Such bindings cannot be made into
901 /// mutable bindings, but the inverse does not necessarily hold).
902 pub fn is_nonref_binding(&self) -> bool {
903 match self.local_info {
904 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
905 binding_mode: ty::BindingMode::BindByValue(_),
911 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_)))) => true,
917 /// Returns `true` if this variable is a named variable or function
918 /// parameter declared by the user.
920 pub fn is_user_variable(&self) -> bool {
921 match self.local_info {
922 Some(box LocalInfo::User(_)) => true,
927 /// Returns `true` if this is a reference to a variable bound in a `match`
928 /// expression that is used to access said variable for the guard of the
930 pub fn is_ref_for_guard(&self) -> bool {
931 match self.local_info {
932 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) => true,
937 /// Returns `Some` if this is a reference to a static item that is used to
938 /// access that static
939 pub fn is_ref_to_static(&self) -> bool {
940 match self.local_info {
941 Some(box LocalInfo::StaticRef { .. }) => true,
946 /// Returns `Some` if this is a reference to a static item that is used to
947 /// access that static
948 pub fn is_ref_to_thread_local(&self) -> bool {
949 match self.local_info {
950 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
955 /// Returns `true` is the local is from a compiler desugaring, e.g.,
956 /// `__next` from a `for` loop.
958 pub fn from_compiler_desugaring(&self) -> bool {
959 self.source_info.span.desugaring_kind().is_some()
962 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
964 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
965 Self::with_source_info(ty, SourceInfo::outermost(span))
968 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
970 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
972 mutability: Mutability::Mut,
982 /// Converts `self` into same `LocalDecl` except tagged as internal.
984 pub fn internal(mut self) -> Self {
985 self.internal = true;
989 /// Converts `self` into same `LocalDecl` except tagged as immutable.
991 pub fn immutable(mut self) -> Self {
992 self.mutability = Mutability::Not;
996 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
998 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
999 assert!(self.is_block_tail.is_none());
1000 self.is_block_tail = Some(info);
1005 /// Debug information pertaining to a user variable.
1006 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1007 pub struct VarDebugInfo<'tcx> {
1010 /// Source info of the user variable, including the scope
1011 /// within which the variable is visible (to debuginfo)
1012 /// (see `LocalDecl`'s `source_info` field for more details).
1013 pub source_info: SourceInfo,
1015 /// Where the data for this user variable is to be found.
1016 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1017 /// based on a `Local`, not a `Static`, and contains no indexing.
1018 pub place: Place<'tcx>,
1021 ///////////////////////////////////////////////////////////////////////////
1024 rustc_index::newtype_index! {
1025 pub struct BasicBlock {
1027 DEBUG_FORMAT = "bb{}",
1028 const START_BLOCK = 0,
1033 pub fn start_location(self) -> Location {
1034 Location { block: self, statement_index: 0 }
1038 ///////////////////////////////////////////////////////////////////////////
1039 // BasicBlockData and Terminator
1041 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1042 pub struct BasicBlockData<'tcx> {
1043 /// List of statements in this block.
1044 pub statements: Vec<Statement<'tcx>>,
1046 /// Terminator for this block.
1048 /// N.B., this should generally ONLY be `None` during construction.
1049 /// Therefore, you should generally access it via the
1050 /// `terminator()` or `terminator_mut()` methods. The only
1051 /// exception is that certain passes, such as `simplify_cfg`, swap
1052 /// out the terminator temporarily with `None` while they continue
1053 /// to recurse over the set of basic blocks.
1054 pub terminator: Option<Terminator<'tcx>>,
1056 /// If true, this block lies on an unwind path. This is used
1057 /// during codegen where distinct kinds of basic blocks may be
1058 /// generated (particularly for MSVC cleanup). Unwind blocks must
1059 /// only branch to other unwind blocks.
1060 pub is_cleanup: bool,
1063 /// Information about an assertion failure.
1064 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1065 pub enum AssertKind<O> {
1066 BoundsCheck { len: O, index: O },
1067 Overflow(BinOp, O, O),
1071 ResumedAfterReturn(GeneratorKind),
1072 ResumedAfterPanic(GeneratorKind),
1075 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1076 pub enum InlineAsmOperand<'tcx> {
1078 reg: InlineAsmRegOrRegClass,
1079 value: Operand<'tcx>,
1082 reg: InlineAsmRegOrRegClass,
1084 place: Option<Place<'tcx>>,
1087 reg: InlineAsmRegOrRegClass,
1089 in_value: Operand<'tcx>,
1090 out_place: Option<Place<'tcx>>,
1093 value: Operand<'tcx>,
1096 value: Box<Constant<'tcx>>,
1103 /// Type for MIR `Assert` terminator error messages.
1104 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1106 pub type Successors<'a> =
1107 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1108 pub type SuccessorsMut<'a> =
1109 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1111 impl<'tcx> BasicBlockData<'tcx> {
1112 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1113 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1116 /// Accessor for terminator.
1118 /// Terminator may not be None after construction of the basic block is complete. This accessor
1119 /// provides a convenience way to reach the terminator.
1120 pub fn terminator(&self) -> &Terminator<'tcx> {
1121 self.terminator.as_ref().expect("invalid terminator state")
1124 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1125 self.terminator.as_mut().expect("invalid terminator state")
1128 pub fn retain_statements<F>(&mut self, mut f: F)
1130 F: FnMut(&mut Statement<'_>) -> bool,
1132 for s in &mut self.statements {
1139 pub fn expand_statements<F, I>(&mut self, mut f: F)
1141 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1142 I: iter::TrustedLen<Item = Statement<'tcx>>,
1144 // Gather all the iterators we'll need to splice in, and their positions.
1145 let mut splices: Vec<(usize, I)> = vec![];
1146 let mut extra_stmts = 0;
1147 for (i, s) in self.statements.iter_mut().enumerate() {
1148 if let Some(mut new_stmts) = f(s) {
1149 if let Some(first) = new_stmts.next() {
1150 // We can already store the first new statement.
1153 // Save the other statements for optimized splicing.
1154 let remaining = new_stmts.size_hint().0;
1156 splices.push((i + 1 + extra_stmts, new_stmts));
1157 extra_stmts += remaining;
1165 // Splice in the new statements, from the end of the block.
1166 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1167 // where a range of elements ("gap") is left uninitialized, with
1168 // splicing adding new elements to the end of that gap and moving
1169 // existing elements from before the gap to the end of the gap.
1170 // For now, this is safe code, emulating a gap but initializing it.
1171 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1172 self.statements.resize(
1174 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1176 for (splice_start, new_stmts) in splices.into_iter().rev() {
1177 let splice_end = splice_start + new_stmts.size_hint().0;
1178 while gap.end > splice_end {
1181 self.statements.swap(gap.start, gap.end);
1183 self.statements.splice(splice_start..splice_end, new_stmts);
1184 gap.end = splice_start;
1188 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1189 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1193 impl<O> AssertKind<O> {
1194 /// Getting a description does not require `O` to be printable, and does not
1195 /// require allocation.
1196 /// The caller is expected to handle `BoundsCheck` separately.
1197 pub fn description(&self) -> &'static str {
1200 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1201 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1202 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1203 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1204 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1205 OverflowNeg(_) => "attempt to negate with overflow",
1206 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1207 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1208 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1209 DivisionByZero(_) => "attempt to divide by zero",
1210 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1211 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1212 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1213 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1214 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1215 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1219 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1220 fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1226 BoundsCheck { ref len, ref index } => write!(
1228 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1232 OverflowNeg(op) => {
1233 write!(f, "\"attempt to negate {{}} which would overflow\", {:?}", op)
1235 DivisionByZero(op) => write!(f, "\"attempt to divide {{}} by zero\", {:?}", op),
1236 RemainderByZero(op) => write!(
1238 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1241 Overflow(BinOp::Add, l, r) => write!(
1243 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1246 Overflow(BinOp::Sub, l, r) => write!(
1248 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1251 Overflow(BinOp::Mul, l, r) => write!(
1253 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1256 Overflow(BinOp::Div, l, r) => write!(
1258 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1261 Overflow(BinOp::Rem, l, r) => write!(
1263 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1266 Overflow(BinOp::Shr, _, r) => {
1267 write!(f, "\"attempt to shift right by {{}} which would overflow\", {:?}", r)
1269 Overflow(BinOp::Shl, _, r) => {
1270 write!(f, "\"attempt to shift left by {{}} which would overflow\", {:?}", r)
1272 _ => write!(f, "\"{}\"", self.description()),
1277 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281 BoundsCheck { ref len, ref index } => {
1282 write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index)
1284 OverflowNeg(op) => write!(f, "attempt to negate {:#?} which would overflow", op),
1285 DivisionByZero(op) => write!(f, "attempt to divide {:#?} by zero", op),
1286 RemainderByZero(op) => {
1287 write!(f, "attempt to calculate the remainder of {:#?} with a divisor of zero", op)
1289 Overflow(BinOp::Add, l, r) => {
1290 write!(f, "attempt to compute `{:#?} + {:#?}` which would overflow", l, r)
1292 Overflow(BinOp::Sub, l, r) => {
1293 write!(f, "attempt to compute `{:#?} - {:#?}` which would overflow", l, r)
1295 Overflow(BinOp::Mul, l, r) => {
1296 write!(f, "attempt to compute `{:#?} * {:#?}` which would overflow", l, r)
1298 Overflow(BinOp::Div, l, r) => {
1299 write!(f, "attempt to compute `{:#?} / {:#?}` which would overflow", l, r)
1301 Overflow(BinOp::Rem, l, r) => write!(
1303 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1306 Overflow(BinOp::Shr, _, r) => {
1307 write!(f, "attempt to shift right by {:#?} which would overflow", r)
1309 Overflow(BinOp::Shl, _, r) => {
1310 write!(f, "attempt to shift left by {:#?} which would overflow", r)
1312 _ => write!(f, "{}", self.description()),
1317 ///////////////////////////////////////////////////////////////////////////
1320 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1321 pub struct Statement<'tcx> {
1322 pub source_info: SourceInfo,
1323 pub kind: StatementKind<'tcx>,
1326 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1327 #[cfg(target_arch = "x86_64")]
1328 static_assert_size!(Statement<'_>, 32);
1330 impl Statement<'_> {
1331 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1332 /// invalidating statement indices in `Location`s.
1333 pub fn make_nop(&mut self) {
1334 self.kind = StatementKind::Nop
1337 /// Changes a statement to a nop and returns the original statement.
1338 pub fn replace_nop(&mut self) -> Self {
1340 source_info: self.source_info,
1341 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1346 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1347 pub enum StatementKind<'tcx> {
1348 /// Write the RHS Rvalue to the LHS Place.
1349 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1351 /// This represents all the reading that a pattern match may do
1352 /// (e.g., inspecting constants and discriminant values), and the
1353 /// kind of pattern it comes from. This is in order to adapt potential
1354 /// error messages to these specific patterns.
1356 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1357 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1358 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1360 /// Write the discriminant for a variant to the enum Place.
1361 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1363 /// Start a live range for the storage of the local.
1366 /// End the current live range for the storage of the local.
1369 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1370 /// of `StatementKind` low.
1371 LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1373 /// Retag references in the given place, ensuring they got fresh tags. This is
1374 /// part of the Stacked Borrows model. These statements are currently only interpreted
1375 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1376 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1377 /// for more details.
1378 Retag(RetagKind, Box<Place<'tcx>>),
1380 /// Encodes a user's type ascription. These need to be preserved
1381 /// intact so that NLL can respect them. For example:
1385 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1386 /// to the user-given type `T`. The effect depends on the specified variance:
1388 /// - `Covariant` -- requires that `T_y <: T`
1389 /// - `Contravariant` -- requires that `T_y :> T`
1390 /// - `Invariant` -- requires that `T_y == T`
1391 /// - `Bivariant` -- no effect
1392 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1394 /// No-op. Useful for deleting instructions without affecting statement indices.
1398 /// Describes what kind of retag is to be performed.
1399 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1400 pub enum RetagKind {
1401 /// The initial retag when entering a function.
1403 /// Retag preparing for a two-phase borrow.
1405 /// Retagging raw pointers.
1407 /// A "normal" retag.
1411 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1412 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1413 pub enum FakeReadCause {
1414 /// Inject a fake read of the borrowed input at the end of each guards
1417 /// This should ensure that you cannot change the variant for an enum while
1418 /// you are in the midst of matching on it.
1421 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1422 /// generate a read of x to check that it is initialized and safe.
1425 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1426 /// in a match guard to ensure that it's value hasn't change by the time
1427 /// we create the OutsideGuard version.
1430 /// Officially, the semantics of
1432 /// `let pattern = <expr>;`
1434 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1435 /// into the pattern.
1437 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1438 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1439 /// but in some cases it can affect the borrow checker, as in #53695.
1440 /// Therefore, we insert a "fake read" here to ensure that we get
1441 /// appropriate errors.
1444 /// If we have an index expression like
1446 /// (*x)[1][{ x = y; 4}]
1448 /// then the first bounds check is invalidated when we evaluate the second
1449 /// index expression. Thus we create a fake borrow of `x` across the second
1450 /// indexer, which will cause a borrow check error.
1454 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1455 pub struct LlvmInlineAsm<'tcx> {
1456 pub asm: hir::LlvmInlineAsmInner,
1457 pub outputs: Box<[Place<'tcx>]>,
1458 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1461 impl Debug for Statement<'_> {
1462 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1463 use self::StatementKind::*;
1465 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1466 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1467 Retag(ref kind, ref place) => write!(
1471 RetagKind::FnEntry => "[fn entry] ",
1472 RetagKind::TwoPhase => "[2phase] ",
1473 RetagKind::Raw => "[raw] ",
1474 RetagKind::Default => "",
1478 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1479 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1480 SetDiscriminant { ref place, variant_index } => {
1481 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1483 LlvmInlineAsm(ref asm) => {
1484 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1486 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1487 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1489 Nop => write!(fmt, "nop"),
1494 ///////////////////////////////////////////////////////////////////////////
1497 /// A path to a value; something that can be evaluated without
1498 /// changing or disturbing program state.
1499 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1500 pub struct Place<'tcx> {
1503 /// projection out of a place (access a field, deref a pointer, etc)
1504 pub projection: &'tcx List<PlaceElem<'tcx>>,
1507 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1509 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1510 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1511 pub enum ProjectionElem<V, T> {
1516 /// These indices are generated by slice patterns. Easiest to explain
1520 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1521 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1522 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1523 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1526 /// index or -index (in Python terms), depending on from_end
1528 /// The thing being indexed must be at least this long. For arrays this
1529 /// is always the exact length.
1531 /// Counting backwards from end? This is always false when indexing an
1536 /// These indices are generated by slice patterns.
1538 /// If `from_end` is true `slice[from..slice.len() - to]`.
1539 /// Otherwise `array[from..to]`.
1543 /// Whether `to` counts from the start or end of the array/slice.
1544 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1545 /// For `ProjectionKind`, this can also be `true` for arrays.
1549 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1550 /// this for ADTs with more than one variant. It may be better to
1551 /// just introduce it always, or always for enums.
1553 /// The included Symbol is the name of the variant, used for printing MIR.
1554 Downcast(Option<Symbol>, VariantIdx),
1557 impl<V, T> ProjectionElem<V, T> {
1558 /// Returns `true` if the target of this projection may refer to a different region of memory
1560 fn is_indirect(&self) -> bool {
1562 Self::Deref => true,
1566 | Self::ConstantIndex { .. }
1567 | Self::Subslice { .. }
1568 | Self::Downcast(_, _) => false,
1573 /// Alias for projections as they appear in places, where the base is a place
1574 /// and the index is a local.
1575 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1577 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1578 #[cfg(target_arch = "x86_64")]
1579 static_assert_size!(PlaceElem<'_>, 16);
1581 /// Alias for projections as they appear in `UserTypeProjection`, where we
1582 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1583 pub type ProjectionKind = ProjectionElem<(), ()>;
1585 rustc_index::newtype_index! {
1588 DEBUG_FORMAT = "field[{}]"
1592 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1593 pub struct PlaceRef<'tcx> {
1595 pub projection: &'tcx [PlaceElem<'tcx>],
1598 impl<'tcx> Place<'tcx> {
1599 // FIXME change this to a const fn by also making List::empty a const fn.
1600 pub fn return_place() -> Place<'tcx> {
1601 Place { local: RETURN_PLACE, projection: List::empty() }
1604 /// Returns `true` if this `Place` contains a `Deref` projection.
1606 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1607 /// same region of memory as its base.
1608 pub fn is_indirect(&self) -> bool {
1609 self.projection.iter().any(|elem| elem.is_indirect())
1612 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1613 /// a single deref of a local.
1615 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1616 pub fn local_or_deref_local(&self) -> Option<Local> {
1617 match self.as_ref() {
1618 PlaceRef { local, projection: [] }
1619 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1624 /// If this place represents a local variable like `_X` with no
1625 /// projections, return `Some(_X)`.
1626 pub fn as_local(&self) -> Option<Local> {
1627 self.as_ref().as_local()
1630 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1631 PlaceRef { local: self.local, projection: &self.projection }
1635 impl From<Local> for Place<'_> {
1636 fn from(local: Local) -> Self {
1637 Place { local, projection: List::empty() }
1641 impl<'tcx> PlaceRef<'tcx> {
1642 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1643 /// a single deref of a local.
1645 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1646 pub fn local_or_deref_local(&self) -> Option<Local> {
1648 PlaceRef { local, projection: [] }
1649 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1654 /// If this place represents a local variable like `_X` with no
1655 /// projections, return `Some(_X)`.
1656 pub fn as_local(&self) -> Option<Local> {
1658 PlaceRef { local, projection: [] } => Some(local),
1664 impl Debug for Place<'_> {
1665 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1666 for elem in self.projection.iter().rev() {
1668 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1669 write!(fmt, "(").unwrap();
1671 ProjectionElem::Deref => {
1672 write!(fmt, "(*").unwrap();
1674 ProjectionElem::Index(_)
1675 | ProjectionElem::ConstantIndex { .. }
1676 | ProjectionElem::Subslice { .. } => {}
1680 write!(fmt, "{:?}", self.local)?;
1682 for elem in self.projection.iter() {
1684 ProjectionElem::Downcast(Some(name), _index) => {
1685 write!(fmt, " as {})", name)?;
1687 ProjectionElem::Downcast(None, index) => {
1688 write!(fmt, " as variant#{:?})", index)?;
1690 ProjectionElem::Deref => {
1693 ProjectionElem::Field(field, ty) => {
1694 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1696 ProjectionElem::Index(ref index) => {
1697 write!(fmt, "[{:?}]", index)?;
1699 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1700 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1702 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1703 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1705 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1706 write!(fmt, "[{:?}:]", from)?;
1708 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1709 write!(fmt, "[:-{:?}]", to)?;
1711 ProjectionElem::Subslice { from, to, from_end: true } => {
1712 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1714 ProjectionElem::Subslice { from, to, from_end: false } => {
1715 write!(fmt, "[{:?}..{:?}]", from, to)?;
1724 ///////////////////////////////////////////////////////////////////////////
1727 rustc_index::newtype_index! {
1728 pub struct SourceScope {
1730 DEBUG_FORMAT = "scope[{}]",
1731 const OUTERMOST_SOURCE_SCOPE = 0,
1735 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1736 pub struct SourceScopeData {
1738 pub parent_scope: Option<SourceScope>,
1740 /// Crate-local information for this source scope, that can't (and
1741 /// needn't) be tracked across crates.
1742 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1745 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1746 pub struct SourceScopeLocalData {
1747 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1748 pub lint_root: hir::HirId,
1749 /// The unsafe block that contains this node.
1753 ///////////////////////////////////////////////////////////////////////////
1756 /// These are values that can appear inside an rvalue. They are intentionally
1757 /// limited to prevent rvalues from being nested in one another.
1758 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1759 pub enum Operand<'tcx> {
1760 /// Copy: The value must be available for use afterwards.
1762 /// This implies that the type of the place must be `Copy`; this is true
1763 /// by construction during build, but also checked by the MIR type checker.
1766 /// Move: The value (including old borrows of it) will not be used again.
1768 /// Safe for values of all types (modulo future developments towards `?Move`).
1769 /// Correct usage patterns are enforced by the borrow checker for safe code.
1770 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1773 /// Synthesizes a constant value.
1774 Constant(Box<Constant<'tcx>>),
1777 impl<'tcx> Debug for Operand<'tcx> {
1778 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1779 use self::Operand::*;
1781 Constant(ref a) => write!(fmt, "{:?}", a),
1782 Copy(ref place) => write!(fmt, "{:?}", place),
1783 Move(ref place) => write!(fmt, "move {:?}", place),
1788 impl<'tcx> Operand<'tcx> {
1789 /// Convenience helper to make a constant that refers to the fn
1790 /// with given `DefId` and substs. Since this is used to synthesize
1791 /// MIR, assumes `user_ty` is None.
1792 pub fn function_handle(
1795 substs: SubstsRef<'tcx>,
1798 let ty = tcx.type_of(def_id).subst(tcx, substs);
1799 Operand::Constant(box Constant {
1802 literal: ty::Const::zero_sized(tcx, ty),
1806 /// Convenience helper to make a literal-like constant from a given scalar value.
1807 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1808 pub fn const_from_scalar(
1813 ) -> Operand<'tcx> {
1815 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1817 .layout_of(param_env_and_ty)
1818 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1820 let scalar_size = abi::Size::from_bytes(match val {
1821 Scalar::Raw { size, .. } => size,
1822 _ => panic!("Invalid scalar type {:?}", val),
1824 scalar_size == type_size
1826 Operand::Constant(box Constant {
1829 literal: ty::Const::from_scalar(tcx, val, ty),
1833 /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1834 /// wraps a constant literal value. Panics if this is not the case.
1835 pub fn scalar_from_const(operand: &Operand<'tcx>) -> Scalar {
1837 Operand::Constant(constant) => match constant.literal.val.try_to_scalar() {
1838 Some(scalar) => scalar,
1839 _ => panic!("{:?}: Scalar value expected", constant.literal.val),
1841 _ => panic!("{:?}: Constant expected", operand),
1845 /// Convenience helper to make a literal-like constant from a given `&str` slice.
1846 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1847 pub fn const_from_str(tcx: TyCtxt<'tcx>, val: &str, span: Span) -> Operand<'tcx> {
1849 let allocation = Allocation::from_byte_aligned_bytes(val.as_bytes());
1850 let allocation = tcx.intern_const_alloc(allocation);
1851 let const_val = ConstValue::Slice { data: allocation, start: 0, end: val.len() };
1852 let ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, tcx.types.str_);
1853 Operand::Constant(box Constant {
1856 literal: ty::Const::from_value(tcx, const_val, ty),
1860 /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1861 /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1862 pub fn value_from_const(operand: &Operand<'tcx>) -> ConstValue<'tcx> {
1864 Operand::Constant(constant) => match constant.literal.val.try_to_value() {
1865 Some(const_value) => const_value,
1866 _ => panic!("{:?}: ConstValue expected", constant.literal.val),
1868 _ => panic!("{:?}: Constant expected", operand),
1872 pub fn to_copy(&self) -> Self {
1874 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1875 Operand::Move(place) => Operand::Copy(place),
1879 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1881 pub fn place(&self) -> Option<Place<'tcx>> {
1883 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1884 Operand::Constant(_) => None,
1889 ///////////////////////////////////////////////////////////////////////////
1892 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1893 pub enum Rvalue<'tcx> {
1894 /// x (either a move or copy, depending on type of x)
1898 Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
1901 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1903 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
1904 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
1906 ThreadLocalRef(DefId),
1908 /// Create a raw pointer to the given place
1909 /// Can be generated by raw address of expressions (`&raw const x`),
1910 /// or when casting a reference to a raw pointer.
1911 AddressOf(Mutability, Place<'tcx>),
1913 /// length of a `[X]` or `[X;n]` value
1916 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1918 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1919 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1921 NullaryOp(NullOp, Ty<'tcx>),
1922 UnaryOp(UnOp, Operand<'tcx>),
1924 /// Read the discriminant of an ADT.
1926 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
1927 /// be defined to return, say, a 0) if ADT is not an enum.
1928 Discriminant(Place<'tcx>),
1930 /// Creates an aggregate value, like a tuple or struct. This is
1931 /// only needed because we want to distinguish `dest = Foo { x:
1932 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1933 /// that `Foo` has a destructor. These rvalues can be optimized
1934 /// away after type-checking and before lowering.
1935 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1938 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1941 Pointer(PointerCast),
1944 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1945 pub enum AggregateKind<'tcx> {
1946 /// The type is of the element
1950 /// The second field is the variant index. It's equal to 0 for struct
1951 /// and union expressions. The fourth field is
1952 /// active field number and is present only for union expressions
1953 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1954 /// active field index would identity the field `c`
1955 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
1957 Closure(DefId, SubstsRef<'tcx>),
1958 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
1961 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
1963 /// The `+` operator (addition)
1965 /// The `-` operator (subtraction)
1967 /// The `*` operator (multiplication)
1969 /// The `/` operator (division)
1971 /// The `%` operator (modulus)
1973 /// The `^` operator (bitwise xor)
1975 /// The `&` operator (bitwise and)
1977 /// The `|` operator (bitwise or)
1979 /// The `<<` operator (shift left)
1981 /// The `>>` operator (shift right)
1983 /// The `==` operator (equality)
1985 /// The `<` operator (less than)
1987 /// The `<=` operator (less than or equal to)
1989 /// The `!=` operator (not equal to)
1991 /// The `>=` operator (greater than or equal to)
1993 /// The `>` operator (greater than)
1995 /// The `ptr.offset` operator
2000 pub fn is_checkable(self) -> bool {
2003 Add | Sub | Mul | Shl | Shr => true,
2009 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2011 /// Returns the size of a value of that type
2013 /// Creates a new uninitialized box for a value of that type
2017 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2019 /// The `!` operator for logical inversion
2021 /// The `-` operator for negation
2025 impl<'tcx> Debug for Rvalue<'tcx> {
2026 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2027 use self::Rvalue::*;
2030 Use(ref place) => write!(fmt, "{:?}", place),
2031 Repeat(ref a, ref b) => {
2032 write!(fmt, "[{:?}; ", a)?;
2033 pretty_print_const(b, fmt, false)?;
2036 Len(ref a) => write!(fmt, "Len({:?})", a),
2037 Cast(ref kind, ref place, ref ty) => {
2038 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2040 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2041 CheckedBinaryOp(ref op, ref a, ref b) => {
2042 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2044 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2045 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2046 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2047 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2048 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2049 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2051 Ref(region, borrow_kind, ref place) => {
2052 let kind_str = match borrow_kind {
2053 BorrowKind::Shared => "",
2054 BorrowKind::Shallow => "shallow ",
2055 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2058 // When printing regions, add trailing space if necessary.
2059 let print_region = ty::tls::with(|tcx| {
2060 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2062 let region = if print_region {
2063 let mut region = region.to_string();
2064 if !region.is_empty() {
2069 // Do not even print 'static
2072 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2075 AddressOf(mutability, ref place) => {
2076 let kind_str = match mutability {
2077 Mutability::Mut => "mut",
2078 Mutability::Not => "const",
2081 write!(fmt, "&raw {} {:?}", kind_str, place)
2084 Aggregate(ref kind, ref places) => {
2085 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2086 let mut tuple_fmt = fmt.debug_tuple(name);
2087 for place in places {
2088 tuple_fmt.field(place);
2094 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2096 AggregateKind::Tuple => {
2097 if places.is_empty() {
2104 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2105 let variant_def = &adt_def.variants[variant];
2107 let name = ty::tls::with(|tcx| {
2108 let mut name = String::new();
2109 let substs = tcx.lift(&substs).expect("could not lift for printing");
2110 FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2111 .print_def_path(variant_def.def_id, substs)?;
2115 match variant_def.ctor_kind {
2116 CtorKind::Const => fmt.write_str(&name),
2117 CtorKind::Fn => fmt_tuple(fmt, &name),
2118 CtorKind::Fictive => {
2119 let mut struct_fmt = fmt.debug_struct(&name);
2120 for (field, place) in variant_def.fields.iter().zip(places) {
2121 struct_fmt.field(&field.ident.as_str(), place);
2128 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2129 if let Some(def_id) = def_id.as_local() {
2130 let hir_id = tcx.hir().as_local_hir_id(def_id);
2131 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2132 let substs = tcx.lift(&substs).unwrap();
2135 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2138 let span = tcx.hir().span(hir_id);
2139 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2141 let mut struct_fmt = fmt.debug_struct(&name);
2143 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2144 for (&var_id, place) in upvars.keys().zip(places) {
2145 let var_name = tcx.hir().name(var_id);
2146 struct_fmt.field(&var_name.as_str(), place);
2152 write!(fmt, "[closure]")
2156 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2157 if let Some(def_id) = def_id.as_local() {
2158 let hir_id = tcx.hir().as_local_hir_id(def_id);
2159 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2160 let mut struct_fmt = fmt.debug_struct(&name);
2162 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2163 for (&var_id, place) in upvars.keys().zip(places) {
2164 let var_name = tcx.hir().name(var_id);
2165 struct_fmt.field(&var_name.as_str(), place);
2171 write!(fmt, "[generator]")
2180 ///////////////////////////////////////////////////////////////////////////
2183 /// Two constants are equal if they are the same constant. Note that
2184 /// this does not necessarily mean that they are "==" in Rust -- in
2185 /// particular one must be wary of `NaN`!
2187 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2188 pub struct Constant<'tcx> {
2191 /// Optional user-given type: for something like
2192 /// `collect::<Vec<_>>`, this would be present and would
2193 /// indicate that `Vec<_>` was explicitly specified.
2195 /// Needed for NLL to impose user-given type constraints.
2196 pub user_ty: Option<UserTypeAnnotationIndex>,
2198 pub literal: &'tcx ty::Const<'tcx>,
2201 impl Constant<'tcx> {
2202 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2203 match self.literal.val.try_to_scalar() {
2204 Some(Scalar::Ptr(ptr)) => match tcx.global_alloc(ptr.alloc_id) {
2205 GlobalAlloc::Static(def_id) => {
2206 assert!(!tcx.is_thread_local_static(def_id));
2216 /// A collection of projections into user types.
2218 /// They are projections because a binding can occur a part of a
2219 /// parent pattern that has been ascribed a type.
2221 /// Its a collection because there can be multiple type ascriptions on
2222 /// the path from the root of the pattern down to the binding itself.
2227 /// struct S<'a>((i32, &'a str), String);
2228 /// let S((_, w): (i32, &'static str), _): S = ...;
2229 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2230 /// // --------------------------------- ^ (2)
2233 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2234 /// ascribed the type `(i32, &'static str)`.
2236 /// The highlights labelled `(2)` show the whole pattern being
2237 /// ascribed the type `S`.
2239 /// In this example, when we descend to `w`, we will have built up the
2240 /// following two projected types:
2242 /// * base: `S`, projection: `(base.0).1`
2243 /// * base: `(i32, &'static str)`, projection: `base.1`
2245 /// The first will lead to the constraint `w: &'1 str` (for some
2246 /// inferred region `'1`). The second will lead to the constraint `w:
2248 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2249 pub struct UserTypeProjections {
2250 pub contents: Vec<(UserTypeProjection, Span)>,
2253 impl<'tcx> UserTypeProjections {
2254 pub fn none() -> Self {
2255 UserTypeProjections { contents: vec![] }
2258 pub fn is_empty(&self) -> bool {
2259 self.contents.is_empty()
2262 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2263 UserTypeProjections { contents: projs.collect() }
2266 pub fn projections_and_spans(
2268 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2269 self.contents.iter()
2272 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2273 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2276 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2277 self.contents.push((user_ty.clone(), span));
2283 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2285 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2289 pub fn index(self) -> Self {
2290 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2293 pub fn subslice(self, from: u32, to: u32) -> Self {
2294 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2297 pub fn deref(self) -> Self {
2298 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2301 pub fn leaf(self, field: Field) -> Self {
2302 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2305 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2306 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2310 /// Encodes the effect of a user-supplied type annotation on the
2311 /// subcomponents of a pattern. The effect is determined by applying the
2312 /// given list of proejctions to some underlying base type. Often,
2313 /// the projection element list `projs` is empty, in which case this
2314 /// directly encodes a type in `base`. But in the case of complex patterns with
2315 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2316 /// in which case the `projs` vector is used.
2320 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2322 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2323 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2324 /// determined by finding the type of the `.0` field from `T`.
2325 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2326 pub struct UserTypeProjection {
2327 pub base: UserTypeAnnotationIndex,
2328 pub projs: Vec<ProjectionKind>,
2331 impl Copy for ProjectionKind {}
2333 impl UserTypeProjection {
2334 pub(crate) fn index(mut self) -> Self {
2335 self.projs.push(ProjectionElem::Index(()));
2339 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2340 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2344 pub(crate) fn deref(mut self) -> Self {
2345 self.projs.push(ProjectionElem::Deref);
2349 pub(crate) fn leaf(mut self, field: Field) -> Self {
2350 self.projs.push(ProjectionElem::Field(field, ()));
2354 pub(crate) fn variant(
2357 variant_index: VariantIdx,
2360 self.projs.push(ProjectionElem::Downcast(
2361 Some(adt_def.variants[variant_index].ident.name),
2364 self.projs.push(ProjectionElem::Field(field, ()));
2369 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2371 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2372 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2373 use crate::mir::ProjectionElem::*;
2375 let base = self.base.fold_with(folder);
2376 let projs: Vec<_> = self
2379 .map(|&elem| match elem {
2381 Field(f, ()) => Field(f, ()),
2382 Index(()) => Index(()),
2383 Downcast(symbol, variantidx) => Downcast(symbol, variantidx),
2384 ConstantIndex { offset, min_length, from_end } => {
2385 ConstantIndex { offset, min_length, from_end }
2387 Subslice { from, to, from_end } => Subslice { from, to, from_end },
2391 UserTypeProjection { base, projs }
2394 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2395 self.base.visit_with(visitor)
2396 // Note: there's nothing in `self.proj` to visit.
2400 rustc_index::newtype_index! {
2401 pub struct Promoted {
2403 DEBUG_FORMAT = "promoted[{}]"
2407 impl<'tcx> Debug for Constant<'tcx> {
2408 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2409 write!(fmt, "{}", self)
2413 impl<'tcx> Display for Constant<'tcx> {
2414 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2415 write!(fmt, "const ")?;
2416 pretty_print_const(self.literal, fmt, true)
2420 fn pretty_print_const(
2421 c: &ty::Const<'tcx>,
2422 fmt: &mut Formatter<'_>,
2425 use crate::ty::print::PrettyPrinter;
2426 ty::tls::with(|tcx| {
2427 let literal = tcx.lift(&c).unwrap();
2428 let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2429 cx.print_alloc_ids = true;
2430 cx.pretty_print_const(literal, print_types)?;
2435 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2436 type Node = BasicBlock;
2439 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2441 fn num_nodes(&self) -> usize {
2442 self.basic_blocks.len()
2446 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2448 fn start_node(&self) -> Self::Node {
2453 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2455 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2456 self.basic_blocks[node].terminator().successors().cloned()
2460 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2461 type Item = BasicBlock;
2462 type Iter = iter::Cloned<Successors<'b>>;
2465 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2466 type Item = BasicBlock;
2467 type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2470 impl graph::WithPredecessors for Body<'tcx> {
2472 fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2473 self.predecessors()[node].clone().into_iter()
2477 /// `Location` represents the position of the start of the statement; or, if
2478 /// `statement_index` equals the number of statements, then the start of the
2480 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2481 pub struct Location {
2482 /// The block that the location is within.
2483 pub block: BasicBlock,
2485 pub statement_index: usize,
2488 impl fmt::Debug for Location {
2489 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2490 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2495 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2497 /// Returns the location immediately after this one within the enclosing block.
2499 /// Note that if this location represents a terminator, then the
2500 /// resulting location would be out of bounds and invalid.
2501 pub fn successor_within_block(&self) -> Location {
2502 Location { block: self.block, statement_index: self.statement_index + 1 }
2505 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2506 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2507 // If we are in the same block as the other location and are an earlier statement
2508 // then we are a predecessor of `other`.
2509 if self.block == other.block && self.statement_index < other.statement_index {
2513 let predecessors = body.predecessors();
2515 // If we're in another block, then we want to check that block is a predecessor of `other`.
2516 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2517 let mut visited = FxHashSet::default();
2519 while let Some(block) = queue.pop() {
2520 // If we haven't visited this block before, then make sure we visit it's predecessors.
2521 if visited.insert(block) {
2522 queue.extend(predecessors[block].iter().cloned());
2527 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2528 // we found that block by looking at the predecessors of `other`).
2529 if self.block == block {
2537 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2538 if self.block == other.block {
2539 self.statement_index <= other.statement_index
2541 dominators.is_dominated_by(other.block, self.block)