1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
5 use crate::mir
::coverage
::{CodeRegion, CoverageKind}
;
6 use crate::mir
::interpret
::{Allocation, ConstValue, GlobalAlloc, Scalar}
;
7 use crate::mir
::visit
::MirVisitable
;
8 use crate::ty
::adjustment
::PointerCast
;
9 use crate::ty
::codec
::{TyDecoder, TyEncoder}
;
10 use crate::ty
::fold
::{TypeFoldable, TypeFolder, TypeVisitor}
;
11 use crate::ty
::print
::{FmtPrinter, Printer}
;
12 use crate::ty
::subst
::{Subst, SubstsRef}
;
14 self, AdtDef
, CanonicalUserTypeAnnotations
, List
, Region
, Ty
, TyCtxt
, UserTypeAnnotationIndex
,
17 use rustc_hir
::def
::{CtorKind, Namespace}
;
18 use rustc_hir
::def_id
::DefId
;
19 use rustc_hir
::{self, GeneratorKind}
;
20 use rustc_target
::abi
::VariantIdx
;
22 use polonius_engine
::Atom
;
23 pub use rustc_ast
::Mutability
;
24 use rustc_data_structures
::fx
::FxHashSet
;
25 use rustc_data_structures
::graph
::dominators
::{dominators, Dominators}
;
26 use rustc_data_structures
::graph
::{self, GraphSuccessors}
;
27 use rustc_index
::bit_set
::BitMatrix
;
28 use rustc_index
::vec
::{Idx, IndexVec}
;
29 use rustc_serialize
::{Decodable, Encodable}
;
30 use rustc_span
::symbol
::Symbol
;
31 use rustc_span
::{Span, DUMMY_SP}
;
32 use rustc_target
::abi
;
33 use rustc_target
::asm
::InlineAsmRegOrRegClass
;
35 use std
::fmt
::{self, Debug, Display, Formatter, Write}
;
36 use std
::ops
::{Index, IndexMut}
;
38 use std
::{iter, mem, option}
;
40 use self::predecessors
::{PredecessorCache, Predecessors}
;
41 pub use self::query
::*;
50 pub use terminator
::*;
56 type LocalDecls
<'tcx
> = IndexVec
<Local
, LocalDecl
<'tcx
>>;
58 pub trait HasLocalDecls
<'tcx
> {
59 fn local_decls(&self) -> &LocalDecls
<'tcx
>;
62 impl<'tcx
> HasLocalDecls
<'tcx
> for LocalDecls
<'tcx
> {
63 fn local_decls(&self) -> &LocalDecls
<'tcx
> {
68 impl<'tcx
> HasLocalDecls
<'tcx
> for Body
<'tcx
> {
69 fn local_decls(&self) -> &LocalDecls
<'tcx
> {
74 /// The various "big phases" that MIR goes through.
76 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
77 /// dialects forbid certain variants or values in certain phases.
79 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
80 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
82 /// Warning: ordering of variants is significant.
83 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
87 // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
88 // We used to have this for pre-miri MIR based const eval.
90 /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
91 /// by creating a new MIR body per promoted element. After this phase (and thus the termination
92 /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
96 /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
97 /// * `DropAndReplace` is gone for good
98 /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
99 /// means that the auto-generated drop glue will be invoked.
101 /// After this phase, generators are explicit state machines (no more `Yield`).
102 /// `AggregateKind::Generator` is gone for good.
103 GeneratorLowering
= 4,
108 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
109 pub fn phase_index(&self) -> usize {
114 /// The lowered representation of a single function.
115 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
116 pub struct Body
<'tcx
> {
117 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
118 /// that indexes into this vector.
119 basic_blocks
: IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>,
121 /// Records how far through the "desugaring and optimization" process this particular
122 /// MIR has traversed. This is particularly useful when inlining, since in that context
123 /// we instantiate the promoted constants and add them to our promoted vector -- but those
124 /// promoted items have already been optimized, whereas ours have not. This field allows
125 /// us to see the difference and forego optimization on the inlined promoted items.
128 /// A list of source scopes; these are referenced by statements
129 /// and used for debuginfo. Indexed by a `SourceScope`.
130 pub source_scopes
: IndexVec
<SourceScope
, SourceScopeData
>,
132 /// The yield type of the function, if it is a generator.
133 pub yield_ty
: Option
<Ty
<'tcx
>>,
135 /// Generator drop glue.
136 pub generator_drop
: Option
<Box
<Body
<'tcx
>>>,
138 /// The layout of a generator. Produced by the state transformation.
139 pub generator_layout
: Option
<GeneratorLayout
<'tcx
>>,
141 /// If this is a generator then record the type of source expression that caused this generator
143 pub generator_kind
: Option
<GeneratorKind
>,
145 /// Declarations of locals.
147 /// The first local is the return value pointer, followed by `arg_count`
148 /// locals for the function arguments, followed by any user-declared
149 /// variables and temporaries.
150 pub local_decls
: LocalDecls
<'tcx
>,
152 /// User type annotations.
153 pub user_type_annotations
: CanonicalUserTypeAnnotations
<'tcx
>,
155 /// The number of arguments this function takes.
157 /// Starting at local 1, `arg_count` locals will be provided by the caller
158 /// and can be assumed to be initialized.
160 /// If this MIR was built for a constant, this will be 0.
161 pub arg_count
: usize,
163 /// Mark an argument local (which must be a tuple) as getting passed as
164 /// its individual components at the LLVM level.
166 /// This is used for the "rust-call" ABI.
167 pub spread_arg
: Option
<Local
>,
169 /// Debug information pertaining to user variables, including captures.
170 pub var_debug_info
: Vec
<VarDebugInfo
<'tcx
>>,
172 /// A span representing this MIR, for error reporting.
175 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
176 /// We hold in this field all the constants we are not able to evaluate yet.
177 pub required_consts
: Vec
<Constant
<'tcx
>>,
179 /// The user may be writing e.g. `&[(SOME_CELL, 42)][i].1` and this would get promoted, because
180 /// we'd statically know that no thing with interior mutability will ever be available to the
181 /// user without some serious unsafe code. Now this means that our promoted is actually
182 /// `&[(SOME_CELL, 42)]` and the MIR using it will do the `&promoted[i].1` projection because
183 /// the index may be a runtime value. Such a promoted value is illegal because it has reachable
184 /// interior mutability. This flag just makes this situation very obvious where the previous
185 /// implementation without the flag hid this situation silently.
186 /// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
187 pub ignore_interior_mut_in_const_validation
: bool
,
189 predecessor_cache
: PredecessorCache
,
192 impl<'tcx
> Body
<'tcx
> {
194 basic_blocks
: IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>,
195 source_scopes
: IndexVec
<SourceScope
, SourceScopeData
>,
196 local_decls
: LocalDecls
<'tcx
>,
197 user_type_annotations
: CanonicalUserTypeAnnotations
<'tcx
>,
199 var_debug_info
: Vec
<VarDebugInfo
<'tcx
>>,
201 generator_kind
: Option
<GeneratorKind
>,
203 // We need `arg_count` locals, and one for the return place.
205 local_decls
.len() > arg_count
,
206 "expected at least {} locals, got {}",
212 phase
: MirPhase
::Build
,
216 generator_drop
: None
,
217 generator_layout
: None
,
220 user_type_annotations
,
225 required_consts
: Vec
::new(),
226 ignore_interior_mut_in_const_validation
: false,
227 predecessor_cache
: PredecessorCache
::new(),
231 /// Returns a partially initialized MIR body containing only a list of basic blocks.
233 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
234 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
236 pub fn new_cfg_only(basic_blocks
: IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>) -> Self {
238 phase
: MirPhase
::Build
,
240 source_scopes
: IndexVec
::new(),
242 generator_drop
: None
,
243 generator_layout
: None
,
244 local_decls
: IndexVec
::new(),
245 user_type_annotations
: IndexVec
::new(),
249 required_consts
: Vec
::new(),
250 generator_kind
: None
,
251 var_debug_info
: Vec
::new(),
252 ignore_interior_mut_in_const_validation
: false,
253 predecessor_cache
: PredecessorCache
::new(),
258 pub fn basic_blocks(&self) -> &IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>> {
263 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>> {
264 // Because the user could mutate basic block terminators via this reference, we need to
265 // invalidate the predecessor cache.
267 // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
268 // invalidate the predecessor cache.
269 self.predecessor_cache
.invalidate();
270 &mut self.basic_blocks
274 pub fn basic_blocks_and_local_decls_mut(
276 ) -> (&mut IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>, &mut LocalDecls
<'tcx
>) {
277 self.predecessor_cache
.invalidate();
278 (&mut self.basic_blocks
, &mut self.local_decls
)
282 pub fn basic_blocks_local_decls_mut_and_var_debug_info(
285 &mut IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>,
286 &mut LocalDecls
<'tcx
>,
287 &mut Vec
<VarDebugInfo
<'tcx
>>,
289 self.predecessor_cache
.invalidate();
290 (&mut self.basic_blocks
, &mut self.local_decls
, &mut self.var_debug_info
)
293 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
295 pub fn is_cfg_cyclic(&self) -> bool
{
296 graph
::is_cyclic(self)
300 pub fn local_kind(&self, local
: Local
) -> LocalKind
{
301 let index
= local
.as_usize();
304 self.local_decls
[local
].mutability
== Mutability
::Mut
,
305 "return place should be mutable"
308 LocalKind
::ReturnPointer
309 } else if index
< self.arg_count
+ 1 {
311 } else if self.local_decls
[local
].is_user_variable() {
318 /// Returns an iterator over all temporaries.
320 pub fn temps_iter
<'a
>(&'a
self) -> impl Iterator
<Item
= Local
> + 'a
{
321 (self.arg_count
+ 1..self.local_decls
.len()).filter_map(move |index
| {
322 let local
= Local
::new(index
);
323 if self.local_decls
[local
].is_user_variable() { None }
else { Some(local) }
327 /// Returns an iterator over all user-declared locals.
329 pub fn vars_iter
<'a
>(&'a
self) -> impl Iterator
<Item
= Local
> + 'a
{
330 (self.arg_count
+ 1..self.local_decls
.len()).filter_map(move |index
| {
331 let local
= Local
::new(index
);
332 self.local_decls
[local
].is_user_variable().then_some(local
)
336 /// Returns an iterator over all user-declared mutable locals.
338 pub fn mut_vars_iter
<'a
>(&'a
self) -> impl Iterator
<Item
= Local
> + 'a
{
339 (self.arg_count
+ 1..self.local_decls
.len()).filter_map(move |index
| {
340 let local
= Local
::new(index
);
341 let decl
= &self.local_decls
[local
];
342 if decl
.is_user_variable() && decl
.mutability
== Mutability
::Mut
{
350 /// Returns an iterator over all user-declared mutable arguments and locals.
352 pub fn mut_vars_and_args_iter
<'a
>(&'a
self) -> impl Iterator
<Item
= Local
> + 'a
{
353 (1..self.local_decls
.len()).filter_map(move |index
| {
354 let local
= Local
::new(index
);
355 let decl
= &self.local_decls
[local
];
356 if (decl
.is_user_variable() || index
< self.arg_count
+ 1)
357 && decl
.mutability
== Mutability
::Mut
366 /// Returns an iterator over all function arguments.
368 pub fn args_iter(&self) -> impl Iterator
<Item
= Local
> + ExactSizeIterator
{
369 let arg_count
= self.arg_count
;
370 (1..arg_count
+ 1).map(Local
::new
)
373 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
374 /// locals that are neither arguments nor the return place).
376 pub fn vars_and_temps_iter(&self) -> impl Iterator
<Item
= Local
> + ExactSizeIterator
{
377 let arg_count
= self.arg_count
;
378 let local_count
= self.local_decls
.len();
379 (arg_count
+ 1..local_count
).map(Local
::new
)
382 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
383 /// invalidating statement indices in `Location`s.
384 pub fn make_statement_nop(&mut self, location
: Location
) {
385 let block
= &mut self.basic_blocks
[location
.block
];
386 debug_assert
!(location
.statement_index
< block
.statements
.len());
387 block
.statements
[location
.statement_index
].make_nop()
390 /// Returns the source info associated with `location`.
391 pub fn source_info(&self, location
: Location
) -> &SourceInfo
{
392 let block
= &self[location
.block
];
393 let stmts
= &block
.statements
;
394 let idx
= location
.statement_index
;
395 if idx
< stmts
.len() {
396 &stmts
[idx
].source_info
398 assert_eq
!(idx
, stmts
.len());
399 &block
.terminator().source_info
403 /// Checks if `sub` is a sub scope of `sup`
404 pub fn is_sub_scope(&self, mut sub
: SourceScope
, sup
: SourceScope
) -> bool
{
406 match self.source_scopes
[sub
].parent_scope
{
407 None
=> return false,
414 /// Returns the return type; it always return first element from `local_decls` array.
416 pub fn return_ty(&self) -> Ty
<'tcx
> {
417 self.local_decls
[RETURN_PLACE
].ty
420 /// Gets the location of the terminator for the given block.
422 pub fn terminator_loc(&self, bb
: BasicBlock
) -> Location
{
423 Location { block: bb, statement_index: self[bb].statements.len() }
427 pub fn predecessors(&self) -> impl std
::ops
::Deref
<Target
= Predecessors
> + '_
{
428 self.predecessor_cache
.compute(&self.basic_blocks
)
432 pub fn dominators(&self) -> Dominators
<BasicBlock
> {
437 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
440 /// Unsafe because of a PushUnsafeBlock
442 /// Unsafe because of an unsafe fn
444 /// Unsafe because of an `unsafe` block
445 ExplicitUnsafe(hir
::HirId
),
448 impl<'tcx
> Index
<BasicBlock
> for Body
<'tcx
> {
449 type Output
= BasicBlockData
<'tcx
>;
452 fn index(&self, index
: BasicBlock
) -> &BasicBlockData
<'tcx
> {
453 &self.basic_blocks()[index
]
457 impl<'tcx
> IndexMut
<BasicBlock
> for Body
<'tcx
> {
459 fn index_mut(&mut self, index
: BasicBlock
) -> &mut BasicBlockData
<'tcx
> {
460 &mut self.basic_blocks_mut()[index
]
464 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
465 pub enum ClearCrossCrate
<T
> {
470 impl<T
> ClearCrossCrate
<T
> {
471 pub fn as_ref(&self) -> ClearCrossCrate
<&T
> {
473 ClearCrossCrate
::Clear
=> ClearCrossCrate
::Clear
,
474 ClearCrossCrate
::Set(v
) => ClearCrossCrate
::Set(v
),
478 pub fn assert_crate_local(self) -> T
{
480 ClearCrossCrate
::Clear
=> bug
!("unwrapping cross-crate data"),
481 ClearCrossCrate
::Set(v
) => v
,
486 const TAG_CLEAR_CROSS_CRATE_CLEAR
: u8 = 0;
487 const TAG_CLEAR_CROSS_CRATE_SET
: u8 = 1;
489 impl<'tcx
, E
: TyEncoder
<'tcx
>, T
: Encodable
<E
>> Encodable
<E
> for ClearCrossCrate
<T
> {
491 fn encode(&self, e
: &mut E
) -> Result
<(), E
::Error
> {
492 if E
::CLEAR_CROSS_CRATE
{
497 ClearCrossCrate
::Clear
=> TAG_CLEAR_CROSS_CRATE_CLEAR
.encode(e
),
498 ClearCrossCrate
::Set(ref val
) => {
499 TAG_CLEAR_CROSS_CRATE_SET
.encode(e
)?
;
505 impl<'tcx
, D
: TyDecoder
<'tcx
>, T
: Decodable
<D
>> Decodable
<D
> for ClearCrossCrate
<T
> {
507 fn decode(d
: &mut D
) -> Result
<ClearCrossCrate
<T
>, D
::Error
> {
508 if D
::CLEAR_CROSS_CRATE
{
509 return Ok(ClearCrossCrate
::Clear
);
512 let discr
= u8::decode(d
)?
;
515 TAG_CLEAR_CROSS_CRATE_CLEAR
=> Ok(ClearCrossCrate
::Clear
),
516 TAG_CLEAR_CROSS_CRATE_SET
=> {
517 let val
= T
::decode(d
)?
;
518 Ok(ClearCrossCrate
::Set(val
))
520 tag
=> Err(d
.error(&format
!("Invalid tag for ClearCrossCrate: {:?}", tag
))),
525 /// Grouped information about the source code origin of a MIR entity.
526 /// Intended to be inspected by diagnostics and debuginfo.
527 /// Most passes can work with it as a whole, within a single function.
528 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
529 // `Hash`. Please ping @bjorn3 if removing them.
530 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
531 pub struct SourceInfo
{
532 /// The source span for the AST pertaining to this MIR entity.
535 /// The source scope, keeping track of which bindings can be
536 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
537 pub scope
: SourceScope
,
542 pub fn outermost(span
: Span
) -> Self {
543 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
547 ///////////////////////////////////////////////////////////////////////////
550 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
551 #[derive(HashStable)]
552 pub enum BorrowKind
{
553 /// Data must be immutable and is aliasable.
556 /// The immediately borrowed place must be immutable, but projections from
557 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
558 /// conflict with a mutable borrow of `a.b.c`.
560 /// This is used when lowering matches: when matching on a place we want to
561 /// ensure that place have the same value from the start of the match until
562 /// an arm is selected. This prevents this code from compiling:
564 /// let mut x = &Some(0);
567 /// Some(_) if { x = &None; false } => (),
571 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
572 /// should not prevent `if let None = x { ... }`, for example, because the
573 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
574 /// We can also report errors with this kind of borrow differently.
577 /// Data must be immutable but not aliasable. This kind of borrow
578 /// cannot currently be expressed by the user and is used only in
579 /// implicit closure bindings. It is needed when the closure is
580 /// borrowing or mutating a mutable referent, e.g.:
582 /// let x: &mut isize = ...;
583 /// let y = || *x += 5;
585 /// If we were to try to translate this closure into a more explicit
586 /// form, we'd encounter an error with the code as written:
588 /// struct Env { x: & &mut isize }
589 /// let x: &mut isize = ...;
590 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
591 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
593 /// This is then illegal because you cannot mutate an `&mut` found
594 /// in an aliasable location. To solve, you'd have to translate with
595 /// an `&mut` borrow:
597 /// struct Env { x: & &mut isize }
598 /// let x: &mut isize = ...;
599 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
600 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
602 /// Now the assignment to `**env.x` is legal, but creating a
603 /// mutable pointer to `x` is not because `x` is not mutable. We
604 /// could fix this by declaring `x` as `let mut x`. This is ok in
605 /// user code, if awkward, but extra weird for closures, since the
606 /// borrow is hidden.
608 /// So we introduce a "unique imm" borrow -- the referent is
609 /// immutable, but not aliasable. This solves the problem. For
610 /// simplicity, we don't give users the way to express this
611 /// borrow, it's just used when translating closures.
614 /// Data is mutable and not aliasable.
616 /// `true` if this borrow arose from method-call auto-ref
617 /// (i.e., `adjustment::Adjust::Borrow`).
618 allow_two_phase_borrow
: bool
,
623 pub fn allows_two_phase_borrow(&self) -> bool
{
625 BorrowKind
::Shared
| BorrowKind
::Shallow
| BorrowKind
::Unique
=> false,
626 BorrowKind
::Mut { allow_two_phase_borrow }
=> allow_two_phase_borrow
,
631 ///////////////////////////////////////////////////////////////////////////
632 // Variables and temps
634 rustc_index
::newtype_index
! {
637 DEBUG_FORMAT
= "_{}",
638 const RETURN_PLACE
= 0,
642 impl Atom
for Local
{
643 fn index(self) -> usize {
648 /// Classifies locals into categories. See `Body::local_kind`.
649 #[derive(PartialEq, Eq, Debug, HashStable)]
651 /// User-declared variable binding.
653 /// Compiler-introduced temporary.
655 /// Function argument.
657 /// Location of function's return value.
661 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
662 pub struct VarBindingForm
<'tcx
> {
663 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
664 pub binding_mode
: ty
::BindingMode
,
665 /// If an explicit type was provided for this variable binding,
666 /// this holds the source Span of that type.
668 /// NOTE: if you want to change this to a `HirId`, be wary that
669 /// doing so breaks incremental compilation (as of this writing),
670 /// while a `Span` does not cause our tests to fail.
671 pub opt_ty_info
: Option
<Span
>,
672 /// Place of the RHS of the =, or the subject of the `match` where this
673 /// variable is initialized. None in the case of `let PATTERN;`.
674 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
675 /// (a) the right-hand side isn't evaluated as a place expression.
676 /// (b) it gives a way to separate this case from the remaining cases
678 pub opt_match_place
: Option
<(Option
<Place
<'tcx
>>, Span
)>,
679 /// The span of the pattern in which this variable was bound.
683 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
684 pub enum BindingForm
<'tcx
> {
685 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
686 Var(VarBindingForm
<'tcx
>),
687 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
688 ImplicitSelf(ImplicitSelfKind
),
689 /// Reference used in a guard expression to ensure immutability.
693 /// Represents what type of implicit self a function has, if any.
694 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
695 pub enum ImplicitSelfKind
{
696 /// Represents a `fn x(self);`.
698 /// Represents a `fn x(mut self);`.
700 /// Represents a `fn x(&self);`.
702 /// Represents a `fn x(&mut self);`.
704 /// Represents when a function does not have a self argument or
705 /// when a function has a `self: X` argument.
709 CloneTypeFoldableAndLiftImpls
! { BindingForm<'tcx>, }
711 mod binding_form_impl
{
712 use crate::ich
::StableHashingContext
;
713 use rustc_data_structures
::stable_hasher
::{HashStable, StableHasher}
;
715 impl<'a
, 'tcx
> HashStable
<StableHashingContext
<'a
>> for super::BindingForm
<'tcx
> {
716 fn hash_stable(&self, hcx
: &mut StableHashingContext
<'a
>, hasher
: &mut StableHasher
) {
717 use super::BindingForm
::*;
718 ::std
::mem
::discriminant(self).hash_stable(hcx
, hasher
);
721 Var(binding
) => binding
.hash_stable(hcx
, hasher
),
722 ImplicitSelf(kind
) => kind
.hash_stable(hcx
, hasher
),
729 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
730 /// created during evaluation of expressions in a block tail
731 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
733 /// It is used to improve diagnostics when such temporaries are
734 /// involved in borrow_check errors, e.g., explanations of where the
735 /// temporaries come from, when their destructors are run, and/or how
736 /// one might revise the code to satisfy the borrow checker's rules.
737 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
738 pub struct BlockTailInfo
{
739 /// If `true`, then the value resulting from evaluating this tail
740 /// expression is ignored by the block's expression context.
742 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
743 /// but not e.g., `let _x = { ...; tail };`
744 pub tail_result_is_ignored
: bool
,
746 /// `Span` of the tail expression.
752 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
753 /// argument, or the return place.
754 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
755 pub struct LocalDecl
<'tcx
> {
756 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
758 /// Temporaries and the return place are always mutable.
759 pub mutability
: Mutability
,
761 // FIXME(matthewjasper) Don't store in this in `Body`
762 pub local_info
: Option
<Box
<LocalInfo
<'tcx
>>>,
764 /// `true` if this is an internal local.
766 /// These locals are not based on types in the source code and are only used
767 /// for a few desugarings at the moment.
769 /// The generator transformation will sanity check the locals which are live
770 /// across a suspension point against the type components of the generator
771 /// which type checking knows are live across a suspension point. We need to
772 /// flag drop flags to avoid triggering this check as they are introduced
775 /// Unsafety checking will also ignore dereferences of these locals,
776 /// so they can be used for raw pointers only used in a desugaring.
778 /// This should be sound because the drop flags are fully algebraic, and
779 /// therefore don't affect the OIBIT or outlives properties of the
783 /// If this local is a temporary and `is_block_tail` is `Some`,
784 /// then it is a temporary created for evaluation of some
785 /// subexpression of some block's tail expression (with no
786 /// intervening statement context).
787 // FIXME(matthewjasper) Don't store in this in `Body`
788 pub is_block_tail
: Option
<BlockTailInfo
>,
790 /// The type of this local.
793 /// If the user manually ascribed a type to this variable,
794 /// e.g., via `let x: T`, then we carry that type here. The MIR
795 /// borrow checker needs this information since it can affect
796 /// region inference.
797 // FIXME(matthewjasper) Don't store in this in `Body`
798 pub user_ty
: Option
<Box
<UserTypeProjections
>>,
800 /// The *syntactic* (i.e., not visibility) source scope the local is defined
801 /// in. If the local was defined in a let-statement, this
802 /// is *within* the let-statement, rather than outside
805 /// This is needed because the visibility source scope of locals within
806 /// a let-statement is weird.
808 /// The reason is that we want the local to be *within* the let-statement
809 /// for lint purposes, but we want the local to be *after* the let-statement
810 /// for names-in-scope purposes.
812 /// That's it, if we have a let-statement like the one in this
816 /// fn foo(x: &str) {
817 /// #[allow(unused_mut)]
818 /// let mut x: u32 = { // <- one unused mut
819 /// let mut y: u32 = x.parse().unwrap();
826 /// Then, from a lint point of view, the declaration of `x: u32`
827 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
828 /// lint scopes are the same as the AST/HIR nesting.
830 /// However, from a name lookup point of view, the scopes look more like
831 /// as if the let-statements were `match` expressions:
834 /// fn foo(x: &str) {
836 /// match x.parse().unwrap() {
845 /// We care about the name-lookup scopes for debuginfo - if the
846 /// debuginfo instruction pointer is at the call to `x.parse()`, we
847 /// want `x` to refer to `x: &str`, but if it is at the call to
848 /// `drop(x)`, we want it to refer to `x: u32`.
850 /// To allow both uses to work, we need to have more than a single scope
851 /// for a local. We have the `source_info.scope` represent the "syntactic"
852 /// lint scope (with a variable being under its let block) while the
853 /// `var_debug_info.source_info.scope` represents the "local variable"
854 /// scope (where the "rest" of a block is under all prior let-statements).
856 /// The end result looks like this:
860 /// │{ argument x: &str }
862 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
863 /// │ │ // in practice because I'm lazy.
865 /// │ │← x.source_info.scope
866 /// │ │← `x.parse().unwrap()`
868 /// │ │ │← y.source_info.scope
870 /// │ │ │{ let y: u32 }
872 /// │ │ │← y.var_debug_info.source_info.scope
875 /// │ │{ let x: u32 }
876 /// │ │← x.var_debug_info.source_info.scope
877 /// │ │← `drop(x)` // This accesses `x: u32`.
879 pub source_info
: SourceInfo
,
882 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
883 #[cfg(target_arch = "x86_64")]
884 static_assert_size
!(LocalDecl
<'_
>, 56);
886 /// Extra information about a some locals that's used for diagnostics and for
887 /// classifying variables into local variables, statics, etc, which is needed e.g.
888 /// for unsafety checking.
890 /// Not used for non-StaticRef temporaries, the return place, or anonymous
891 /// function parameters.
892 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
893 pub enum LocalInfo
<'tcx
> {
894 /// A user-defined local variable or function parameter
896 /// The `BindingForm` is solely used for local diagnostics when generating
897 /// warnings/errors when compiling the current crate, and therefore it need
898 /// not be visible across crates.
899 User(ClearCrossCrate
<BindingForm
<'tcx
>>),
900 /// A temporary created that references the static with the given `DefId`.
901 StaticRef { def_id: DefId, is_thread_local: bool }
,
904 impl<'tcx
> LocalDecl
<'tcx
> {
905 /// Returns `true` only if local is a binding that can itself be
906 /// made mutable via the addition of the `mut` keyword, namely
907 /// something like the occurrences of `x` in:
908 /// - `fn foo(x: Type) { ... }`,
910 /// - or `match ... { C(x) => ... }`
911 pub fn can_be_made_mutable(&self) -> bool
{
912 match self.local_info
{
913 Some(box LocalInfo
::User(ClearCrossCrate
::Set(BindingForm
::Var(VarBindingForm
{
914 binding_mode
: ty
::BindingMode
::BindByValue(_
),
920 Some(box LocalInfo
::User(ClearCrossCrate
::Set(BindingForm
::ImplicitSelf(
921 ImplicitSelfKind
::Imm
,
928 /// Returns `true` if local is definitely not a `ref ident` or
929 /// `ref mut ident` binding. (Such bindings cannot be made into
930 /// mutable bindings, but the inverse does not necessarily hold).
931 pub fn is_nonref_binding(&self) -> bool
{
932 match self.local_info
{
933 Some(box LocalInfo
::User(ClearCrossCrate
::Set(BindingForm
::Var(VarBindingForm
{
934 binding_mode
: ty
::BindingMode
::BindByValue(_
),
940 Some(box LocalInfo
::User(ClearCrossCrate
::Set(BindingForm
::ImplicitSelf(_
)))) => true,
946 /// Returns `true` if this variable is a named variable or function
947 /// parameter declared by the user.
949 pub fn is_user_variable(&self) -> bool
{
950 match self.local_info
{
951 Some(box LocalInfo
::User(_
)) => true,
956 /// Returns `true` if this is a reference to a variable bound in a `match`
957 /// expression that is used to access said variable for the guard of the
959 pub fn is_ref_for_guard(&self) -> bool
{
960 match self.local_info
{
961 Some(box LocalInfo
::User(ClearCrossCrate
::Set(BindingForm
::RefForGuard
))) => true,
966 /// Returns `Some` if this is a reference to a static item that is used to
967 /// access that static
968 pub fn is_ref_to_static(&self) -> bool
{
969 match self.local_info
{
970 Some(box LocalInfo
::StaticRef { .. }
) => true,
975 /// Returns `Some` if this is a reference to a static item that is used to
976 /// access that static
977 pub fn is_ref_to_thread_local(&self) -> bool
{
978 match self.local_info
{
979 Some(box LocalInfo
::StaticRef { is_thread_local, .. }
) => is_thread_local
,
984 /// Returns `true` is the local is from a compiler desugaring, e.g.,
985 /// `__next` from a `for` loop.
987 pub fn from_compiler_desugaring(&self) -> bool
{
988 self.source_info
.span
.desugaring_kind().is_some()
991 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
993 pub fn new(ty
: Ty
<'tcx
>, span
: Span
) -> Self {
994 Self::with_source_info(ty
, SourceInfo
::outermost(span
))
997 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
999 pub fn with_source_info(ty
: Ty
<'tcx
>, source_info
: SourceInfo
) -> Self {
1001 mutability
: Mutability
::Mut
,
1004 is_block_tail
: None
,
1011 /// Converts `self` into same `LocalDecl` except tagged as internal.
1013 pub fn internal(mut self) -> Self {
1014 self.internal
= true;
1018 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1020 pub fn immutable(mut self) -> Self {
1021 self.mutability
= Mutability
::Not
;
1025 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1027 pub fn block_tail(mut self, info
: BlockTailInfo
) -> Self {
1028 assert
!(self.is_block_tail
.is_none());
1029 self.is_block_tail
= Some(info
);
1034 /// Debug information pertaining to a user variable.
1035 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1036 pub struct VarDebugInfo
<'tcx
> {
1039 /// Source info of the user variable, including the scope
1040 /// within which the variable is visible (to debuginfo)
1041 /// (see `LocalDecl`'s `source_info` field for more details).
1042 pub source_info
: SourceInfo
,
1044 /// Where the data for this user variable is to be found.
1045 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1046 /// based on a `Local`, not a `Static`, and contains no indexing.
1047 pub place
: Place
<'tcx
>,
1050 ///////////////////////////////////////////////////////////////////////////
1053 rustc_index
::newtype_index
! {
1054 pub struct BasicBlock
{
1056 DEBUG_FORMAT
= "bb{}",
1057 const START_BLOCK
= 0,
1062 pub fn start_location(self) -> Location
{
1063 Location { block: self, statement_index: 0 }
1067 ///////////////////////////////////////////////////////////////////////////
1068 // BasicBlockData and Terminator
1070 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1071 pub struct BasicBlockData
<'tcx
> {
1072 /// List of statements in this block.
1073 pub statements
: Vec
<Statement
<'tcx
>>,
1075 /// Terminator for this block.
1077 /// N.B., this should generally ONLY be `None` during construction.
1078 /// Therefore, you should generally access it via the
1079 /// `terminator()` or `terminator_mut()` methods. The only
1080 /// exception is that certain passes, such as `simplify_cfg`, swap
1081 /// out the terminator temporarily with `None` while they continue
1082 /// to recurse over the set of basic blocks.
1083 pub terminator
: Option
<Terminator
<'tcx
>>,
1085 /// If true, this block lies on an unwind path. This is used
1086 /// during codegen where distinct kinds of basic blocks may be
1087 /// generated (particularly for MSVC cleanup). Unwind blocks must
1088 /// only branch to other unwind blocks.
1089 pub is_cleanup
: bool
,
1092 /// Information about an assertion failure.
1093 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1094 pub enum AssertKind
<O
> {
1095 BoundsCheck { len: O, index: O }
,
1096 Overflow(BinOp
, O
, O
),
1100 ResumedAfterReturn(GeneratorKind
),
1101 ResumedAfterPanic(GeneratorKind
),
1104 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1105 pub enum InlineAsmOperand
<'tcx
> {
1107 reg
: InlineAsmRegOrRegClass
,
1108 value
: Operand
<'tcx
>,
1111 reg
: InlineAsmRegOrRegClass
,
1113 place
: Option
<Place
<'tcx
>>,
1116 reg
: InlineAsmRegOrRegClass
,
1118 in_value
: Operand
<'tcx
>,
1119 out_place
: Option
<Place
<'tcx
>>,
1122 value
: Operand
<'tcx
>,
1125 value
: Box
<Constant
<'tcx
>>,
1132 /// Type for MIR `Assert` terminator error messages.
1133 pub type AssertMessage
<'tcx
> = AssertKind
<Operand
<'tcx
>>;
1135 pub type Successors
<'a
> =
1136 iter
::Chain
<option
::IntoIter
<&'a BasicBlock
>, slice
::Iter
<'a
, BasicBlock
>>;
1137 pub type SuccessorsMut
<'a
> =
1138 iter
::Chain
<option
::IntoIter
<&'a
mut BasicBlock
>, slice
::IterMut
<'a
, BasicBlock
>>;
1140 impl<'tcx
> BasicBlockData
<'tcx
> {
1141 pub fn new(terminator
: Option
<Terminator
<'tcx
>>) -> BasicBlockData
<'tcx
> {
1142 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1145 /// Accessor for terminator.
1147 /// Terminator may not be None after construction of the basic block is complete. This accessor
1148 /// provides a convenience way to reach the terminator.
1149 pub fn terminator(&self) -> &Terminator
<'tcx
> {
1150 self.terminator
.as_ref().expect("invalid terminator state")
1153 pub fn terminator_mut(&mut self) -> &mut Terminator
<'tcx
> {
1154 self.terminator
.as_mut().expect("invalid terminator state")
1157 pub fn retain_statements
<F
>(&mut self, mut f
: F
)
1159 F
: FnMut(&mut Statement
<'_
>) -> bool
,
1161 for s
in &mut self.statements
{
1168 pub fn expand_statements
<F
, I
>(&mut self, mut f
: F
)
1170 F
: FnMut(&mut Statement
<'tcx
>) -> Option
<I
>,
1171 I
: iter
::TrustedLen
<Item
= Statement
<'tcx
>>,
1173 // Gather all the iterators we'll need to splice in, and their positions.
1174 let mut splices
: Vec
<(usize, I
)> = vec
![];
1175 let mut extra_stmts
= 0;
1176 for (i
, s
) in self.statements
.iter_mut().enumerate() {
1177 if let Some(mut new_stmts
) = f(s
) {
1178 if let Some(first
) = new_stmts
.next() {
1179 // We can already store the first new statement.
1182 // Save the other statements for optimized splicing.
1183 let remaining
= new_stmts
.size_hint().0;
1185 splices
.push((i
+ 1 + extra_stmts
, new_stmts
));
1186 extra_stmts
+= remaining
;
1194 // Splice in the new statements, from the end of the block.
1195 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1196 // where a range of elements ("gap") is left uninitialized, with
1197 // splicing adding new elements to the end of that gap and moving
1198 // existing elements from before the gap to the end of the gap.
1199 // For now, this is safe code, emulating a gap but initializing it.
1200 let mut gap
= self.statements
.len()..self.statements
.len() + extra_stmts
;
1201 self.statements
.resize(
1203 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }
,
1205 for (splice_start
, new_stmts
) in splices
.into_iter().rev() {
1206 let splice_end
= splice_start
+ new_stmts
.size_hint().0;
1207 while gap
.end
> splice_end
{
1210 self.statements
.swap(gap
.start
, gap
.end
);
1212 self.statements
.splice(splice_start
..splice_end
, new_stmts
);
1213 gap
.end
= splice_start
;
1217 pub fn visitable(&self, index
: usize) -> &dyn MirVisitable
<'tcx
> {
1218 if index
< self.statements
.len() { &self.statements[index] }
else { &self.terminator }
1222 impl<O
> AssertKind
<O
> {
1223 /// Getting a description does not require `O` to be printable, and does not
1224 /// require allocation.
1225 /// The caller is expected to handle `BoundsCheck` separately.
1226 pub fn description(&self) -> &'
static str {
1229 Overflow(BinOp
::Add
, _
, _
) => "attempt to add with overflow",
1230 Overflow(BinOp
::Sub
, _
, _
) => "attempt to subtract with overflow",
1231 Overflow(BinOp
::Mul
, _
, _
) => "attempt to multiply with overflow",
1232 Overflow(BinOp
::Div
, _
, _
) => "attempt to divide with overflow",
1233 Overflow(BinOp
::Rem
, _
, _
) => "attempt to calculate the remainder with overflow",
1234 OverflowNeg(_
) => "attempt to negate with overflow",
1235 Overflow(BinOp
::Shr
, _
, _
) => "attempt to shift right with overflow",
1236 Overflow(BinOp
::Shl
, _
, _
) => "attempt to shift left with overflow",
1237 Overflow(op
, _
, _
) => bug
!("{:?} cannot overflow", op
),
1238 DivisionByZero(_
) => "attempt to divide by zero",
1239 RemainderByZero(_
) => "attempt to calculate the remainder with a divisor of zero",
1240 ResumedAfterReturn(GeneratorKind
::Gen
) => "generator resumed after completion",
1241 ResumedAfterReturn(GeneratorKind
::Async(_
)) => "`async fn` resumed after completion",
1242 ResumedAfterPanic(GeneratorKind
::Gen
) => "generator resumed after panicking",
1243 ResumedAfterPanic(GeneratorKind
::Async(_
)) => "`async fn` resumed after panicking",
1244 BoundsCheck { .. }
=> bug
!("Unexpected AssertKind"),
1248 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1249 fn fmt_assert_args
<W
: Write
>(&self, f
: &mut W
) -> fmt
::Result
1255 BoundsCheck { ref len, ref index }
=> write
!(
1257 "\"index out of bounds: the len is {{}} but the index is {{}}\", {:?}, {:?}",
1261 OverflowNeg(op
) => {
1262 write
!(f
, "\"attempt to negate {{}} which would overflow\", {:?}", op
)
1264 DivisionByZero(op
) => write
!(f
, "\"attempt to divide {{}} by zero\", {:?}", op
),
1265 RemainderByZero(op
) => write
!(
1267 "\"attempt to calculate the remainder of {{}} with a divisor of zero\", {:?}",
1270 Overflow(BinOp
::Add
, l
, r
) => write
!(
1272 "\"attempt to compute `{{}} + {{}}` which would overflow\", {:?}, {:?}",
1275 Overflow(BinOp
::Sub
, l
, r
) => write
!(
1277 "\"attempt to compute `{{}} - {{}}` which would overflow\", {:?}, {:?}",
1280 Overflow(BinOp
::Mul
, l
, r
) => write
!(
1282 "\"attempt to compute `{{}} * {{}}` which would overflow\", {:?}, {:?}",
1285 Overflow(BinOp
::Div
, l
, r
) => write
!(
1287 "\"attempt to compute `{{}} / {{}}` which would overflow\", {:?}, {:?}",
1290 Overflow(BinOp
::Rem
, l
, r
) => write
!(
1292 "\"attempt to compute the remainder of `{{}} % {{}}` which would overflow\", {:?}, {:?}",
1295 Overflow(BinOp
::Shr
, _
, r
) => {
1296 write
!(f
, "\"attempt to shift right by {{}} which would overflow\", {:?}", r
)
1298 Overflow(BinOp
::Shl
, _
, r
) => {
1299 write
!(f
, "\"attempt to shift left by {{}} which would overflow\", {:?}", r
)
1301 _
=> write
!(f
, "\"{}\"", self.description()),
1306 impl<O
: fmt
::Debug
> fmt
::Debug
for AssertKind
<O
> {
1307 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1310 BoundsCheck { ref len, ref index }
=> {
1311 write
!(f
, "index out of bounds: the len is {:?} but the index is {:?}", len
, index
)
1313 OverflowNeg(op
) => write
!(f
, "attempt to negate {:#?} which would overflow", op
),
1314 DivisionByZero(op
) => write
!(f
, "attempt to divide {:#?} by zero", op
),
1315 RemainderByZero(op
) => {
1316 write
!(f
, "attempt to calculate the remainder of {:#?} with a divisor of zero", op
)
1318 Overflow(BinOp
::Add
, l
, r
) => {
1319 write
!(f
, "attempt to compute `{:#?} + {:#?}` which would overflow", l
, r
)
1321 Overflow(BinOp
::Sub
, l
, r
) => {
1322 write
!(f
, "attempt to compute `{:#?} - {:#?}` which would overflow", l
, r
)
1324 Overflow(BinOp
::Mul
, l
, r
) => {
1325 write
!(f
, "attempt to compute `{:#?} * {:#?}` which would overflow", l
, r
)
1327 Overflow(BinOp
::Div
, l
, r
) => {
1328 write
!(f
, "attempt to compute `{:#?} / {:#?}` which would overflow", l
, r
)
1330 Overflow(BinOp
::Rem
, l
, r
) => write
!(
1332 "attempt to compute the remainder of `{:#?} % {:#?}` which would overflow",
1335 Overflow(BinOp
::Shr
, _
, r
) => {
1336 write
!(f
, "attempt to shift right by {:#?} which would overflow", r
)
1338 Overflow(BinOp
::Shl
, _
, r
) => {
1339 write
!(f
, "attempt to shift left by {:#?} which would overflow", r
)
1341 _
=> write
!(f
, "{}", self.description()),
1346 ///////////////////////////////////////////////////////////////////////////
1349 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1350 pub struct Statement
<'tcx
> {
1351 pub source_info
: SourceInfo
,
1352 pub kind
: StatementKind
<'tcx
>,
1355 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1356 #[cfg(target_arch = "x86_64")]
1357 static_assert_size
!(Statement
<'_
>, 32);
1359 impl Statement
<'_
> {
1360 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1361 /// invalidating statement indices in `Location`s.
1362 pub fn make_nop(&mut self) {
1363 self.kind
= StatementKind
::Nop
1366 /// Changes a statement to a nop and returns the original statement.
1367 pub fn replace_nop(&mut self) -> Self {
1369 source_info
: self.source_info
,
1370 kind
: mem
::replace(&mut self.kind
, StatementKind
::Nop
),
1375 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1376 pub enum StatementKind
<'tcx
> {
1377 /// Write the RHS Rvalue to the LHS Place.
1378 Assign(Box
<(Place
<'tcx
>, Rvalue
<'tcx
>)>),
1380 /// This represents all the reading that a pattern match may do
1381 /// (e.g., inspecting constants and discriminant values), and the
1382 /// kind of pattern it comes from. This is in order to adapt potential
1383 /// error messages to these specific patterns.
1385 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1386 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1387 FakeRead(FakeReadCause
, Box
<Place
<'tcx
>>),
1389 /// Write the discriminant for a variant to the enum Place.
1390 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx }
,
1392 /// Start a live range for the storage of the local.
1395 /// End the current live range for the storage of the local.
1398 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1399 /// of `StatementKind` low.
1400 LlvmInlineAsm(Box
<LlvmInlineAsm
<'tcx
>>),
1402 /// Retag references in the given place, ensuring they got fresh tags. This is
1403 /// part of the Stacked Borrows model. These statements are currently only interpreted
1404 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1405 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1406 /// for more details.
1407 Retag(RetagKind
, Box
<Place
<'tcx
>>),
1409 /// Encodes a user's type ascription. These need to be preserved
1410 /// intact so that NLL can respect them. For example:
1414 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1415 /// to the user-given type `T`. The effect depends on the specified variance:
1417 /// - `Covariant` -- requires that `T_y <: T`
1418 /// - `Contravariant` -- requires that `T_y :> T`
1419 /// - `Invariant` -- requires that `T_y == T`
1420 /// - `Bivariant` -- no effect
1421 AscribeUserType(Box
<(Place
<'tcx
>, UserTypeProjection
)>, ty
::Variance
),
1423 /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1424 /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1425 /// map into the binary. The `Counter` kind also generates executable code, to increment a
1426 /// counter varible at runtime, each time the code region is executed.
1427 Coverage(Box
<Coverage
>),
1429 /// No-op. Useful for deleting instructions without affecting statement indices.
1433 /// Describes what kind of retag is to be performed.
1434 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1435 pub enum RetagKind
{
1436 /// The initial retag when entering a function.
1438 /// Retag preparing for a two-phase borrow.
1440 /// Retagging raw pointers.
1442 /// A "normal" retag.
1446 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1447 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1448 pub enum FakeReadCause
{
1449 /// Inject a fake read of the borrowed input at the end of each guards
1452 /// This should ensure that you cannot change the variant for an enum while
1453 /// you are in the midst of matching on it.
1456 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1457 /// generate a read of x to check that it is initialized and safe.
1460 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1461 /// in a match guard to ensure that it's value hasn't change by the time
1462 /// we create the OutsideGuard version.
1465 /// Officially, the semantics of
1467 /// `let pattern = <expr>;`
1469 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1470 /// into the pattern.
1472 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1473 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1474 /// but in some cases it can affect the borrow checker, as in #53695.
1475 /// Therefore, we insert a "fake read" here to ensure that we get
1476 /// appropriate errors.
1479 /// If we have an index expression like
1481 /// (*x)[1][{ x = y; 4}]
1483 /// then the first bounds check is invalidated when we evaluate the second
1484 /// index expression. Thus we create a fake borrow of `x` across the second
1485 /// indexer, which will cause a borrow check error.
1489 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1490 pub struct LlvmInlineAsm
<'tcx
> {
1491 pub asm
: hir
::LlvmInlineAsmInner
,
1492 pub outputs
: Box
<[Place
<'tcx
>]>,
1493 pub inputs
: Box
<[(Span
, Operand
<'tcx
>)]>,
1496 impl Debug
for Statement
<'_
> {
1497 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
1498 use self::StatementKind
::*;
1500 Assign(box (ref place
, ref rv
)) => write
!(fmt
, "{:?} = {:?}", place
, rv
),
1501 FakeRead(ref cause
, ref place
) => write
!(fmt
, "FakeRead({:?}, {:?})", cause
, place
),
1502 Retag(ref kind
, ref place
) => write
!(
1506 RetagKind
::FnEntry
=> "[fn entry] ",
1507 RetagKind
::TwoPhase
=> "[2phase] ",
1508 RetagKind
::Raw
=> "[raw] ",
1509 RetagKind
::Default
=> "",
1513 StorageLive(ref place
) => write
!(fmt
, "StorageLive({:?})", place
),
1514 StorageDead(ref place
) => write
!(fmt
, "StorageDead({:?})", place
),
1515 SetDiscriminant { ref place, variant_index }
=> {
1516 write
!(fmt
, "discriminant({:?}) = {:?}", place
, variant_index
)
1518 LlvmInlineAsm(ref asm
) => {
1519 write
!(fmt
, "llvm_asm!({:?} : {:?} : {:?})", asm
.asm
, asm
.outputs
, asm
.inputs
)
1521 AscribeUserType(box (ref place
, ref c_ty
), ref variance
) => {
1522 write
!(fmt
, "AscribeUserType({:?}, {:?}, {:?})", place
, variance
, c_ty
)
1524 Coverage(box ref coverage
) => write
!(fmt
, "{:?}", coverage
),
1525 Nop
=> write
!(fmt
, "nop"),
1530 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1531 pub struct Coverage
{
1532 pub kind
: CoverageKind
,
1533 pub code_region
: CodeRegion
,
1536 ///////////////////////////////////////////////////////////////////////////
1539 /// A path to a value; something that can be evaluated without
1540 /// changing or disturbing program state.
1541 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1542 pub struct Place
<'tcx
> {
1545 /// projection out of a place (access a field, deref a pointer, etc)
1546 pub projection
: &'tcx List
<PlaceElem
<'tcx
>>,
1549 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1550 #[derive(TyEncodable, TyDecodable, HashStable)]
1551 pub enum ProjectionElem
<V
, T
> {
1556 /// These indices are generated by slice patterns. Easiest to explain
1560 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1561 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1562 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1563 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1566 /// index or -index (in Python terms), depending on from_end
1568 /// The thing being indexed must be at least this long. For arrays this
1569 /// is always the exact length.
1571 /// Counting backwards from end? This is always false when indexing an
1576 /// These indices are generated by slice patterns.
1578 /// If `from_end` is true `slice[from..slice.len() - to]`.
1579 /// Otherwise `array[from..to]`.
1583 /// Whether `to` counts from the start or end of the array/slice.
1584 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1585 /// For `ProjectionKind`, this can also be `true` for arrays.
1589 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1590 /// this for ADTs with more than one variant. It may be better to
1591 /// just introduce it always, or always for enums.
1593 /// The included Symbol is the name of the variant, used for printing MIR.
1594 Downcast(Option
<Symbol
>, VariantIdx
),
1597 impl<V
, T
> ProjectionElem
<V
, T
> {
1598 /// Returns `true` if the target of this projection may refer to a different region of memory
1600 fn is_indirect(&self) -> bool
{
1602 Self::Deref
=> true,
1606 | Self::ConstantIndex { .. }
1607 | Self::Subslice { .. }
1608 | Self::Downcast(_
, _
) => false,
1613 /// Alias for projections as they appear in places, where the base is a place
1614 /// and the index is a local.
1615 pub type PlaceElem
<'tcx
> = ProjectionElem
<Local
, Ty
<'tcx
>>;
1617 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1618 #[cfg(target_arch = "x86_64")]
1619 static_assert_size
!(PlaceElem
<'_
>, 16);
1621 /// Alias for projections as they appear in `UserTypeProjection`, where we
1622 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1623 pub type ProjectionKind
= ProjectionElem
<(), ()>;
1625 rustc_index
::newtype_index
! {
1628 DEBUG_FORMAT
= "field[{}]"
1632 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1633 pub struct PlaceRef
<'tcx
> {
1635 pub projection
: &'tcx
[PlaceElem
<'tcx
>],
1638 impl<'tcx
> Place
<'tcx
> {
1639 // FIXME change this to a const fn by also making List::empty a const fn.
1640 pub fn return_place() -> Place
<'tcx
> {
1641 Place { local: RETURN_PLACE, projection: List::empty() }
1644 /// Returns `true` if this `Place` contains a `Deref` projection.
1646 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1647 /// same region of memory as its base.
1648 pub fn is_indirect(&self) -> bool
{
1649 self.projection
.iter().any(|elem
| elem
.is_indirect())
1652 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1653 /// a single deref of a local.
1655 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1656 pub fn local_or_deref_local(&self) -> Option
<Local
> {
1657 match self.as_ref() {
1658 PlaceRef { local, projection: [] }
1659 | PlaceRef { local, projection: [ProjectionElem::Deref] }
=> Some(local
),
1664 /// If this place represents a local variable like `_X` with no
1665 /// projections, return `Some(_X)`.
1666 pub fn as_local(&self) -> Option
<Local
> {
1667 self.as_ref().as_local()
1670 pub fn as_ref(&self) -> PlaceRef
<'tcx
> {
1671 PlaceRef { local: self.local, projection: &self.projection }
1675 impl From
<Local
> for Place
<'_
> {
1676 fn from(local
: Local
) -> Self {
1677 Place { local, projection: List::empty() }
1681 impl<'tcx
> PlaceRef
<'tcx
> {
1682 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1683 /// a single deref of a local.
1685 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1686 pub fn local_or_deref_local(&self) -> Option
<Local
> {
1688 PlaceRef { local, projection: [] }
1689 | PlaceRef { local, projection: [ProjectionElem::Deref] }
=> Some(local
),
1694 /// If this place represents a local variable like `_X` with no
1695 /// projections, return `Some(_X)`.
1696 pub fn as_local(&self) -> Option
<Local
> {
1698 PlaceRef { local, projection: [] }
=> Some(local
),
1704 impl Debug
for Place
<'_
> {
1705 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
1706 for elem
in self.projection
.iter().rev() {
1708 ProjectionElem
::Downcast(_
, _
) | ProjectionElem
::Field(_
, _
) => {
1709 write
!(fmt
, "(").unwrap();
1711 ProjectionElem
::Deref
=> {
1712 write
!(fmt
, "(*").unwrap();
1714 ProjectionElem
::Index(_
)
1715 | ProjectionElem
::ConstantIndex { .. }
1716 | ProjectionElem
::Subslice { .. }
=> {}
1720 write
!(fmt
, "{:?}", self.local
)?
;
1722 for elem
in self.projection
.iter() {
1724 ProjectionElem
::Downcast(Some(name
), _index
) => {
1725 write
!(fmt
, " as {})", name
)?
;
1727 ProjectionElem
::Downcast(None
, index
) => {
1728 write
!(fmt
, " as variant#{:?})", index
)?
;
1730 ProjectionElem
::Deref
=> {
1733 ProjectionElem
::Field(field
, ty
) => {
1734 write
!(fmt
, ".{:?}: {:?})", field
.index(), ty
)?
;
1736 ProjectionElem
::Index(ref index
) => {
1737 write
!(fmt
, "[{:?}]", index
)?
;
1739 ProjectionElem
::ConstantIndex { offset, min_length, from_end: false }
=> {
1740 write
!(fmt
, "[{:?} of {:?}]", offset
, min_length
)?
;
1742 ProjectionElem
::ConstantIndex { offset, min_length, from_end: true }
=> {
1743 write
!(fmt
, "[-{:?} of {:?}]", offset
, min_length
)?
;
1745 ProjectionElem
::Subslice { from, to, from_end: true }
if to
== 0 => {
1746 write
!(fmt
, "[{:?}:]", from
)?
;
1748 ProjectionElem
::Subslice { from, to, from_end: true }
if from
== 0 => {
1749 write
!(fmt
, "[:-{:?}]", to
)?
;
1751 ProjectionElem
::Subslice { from, to, from_end: true }
=> {
1752 write
!(fmt
, "[{:?}:-{:?}]", from
, to
)?
;
1754 ProjectionElem
::Subslice { from, to, from_end: false }
=> {
1755 write
!(fmt
, "[{:?}..{:?}]", from
, to
)?
;
1764 ///////////////////////////////////////////////////////////////////////////
1767 rustc_index
::newtype_index
! {
1768 pub struct SourceScope
{
1770 DEBUG_FORMAT
= "scope[{}]",
1771 const OUTERMOST_SOURCE_SCOPE
= 0,
1775 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1776 pub struct SourceScopeData
{
1778 pub parent_scope
: Option
<SourceScope
>,
1780 /// Crate-local information for this source scope, that can't (and
1781 /// needn't) be tracked across crates.
1782 pub local_data
: ClearCrossCrate
<SourceScopeLocalData
>,
1785 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1786 pub struct SourceScopeLocalData
{
1787 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1788 pub lint_root
: hir
::HirId
,
1789 /// The unsafe block that contains this node.
1793 ///////////////////////////////////////////////////////////////////////////
1796 /// These are values that can appear inside an rvalue. They are intentionally
1797 /// limited to prevent rvalues from being nested in one another.
1798 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1799 pub enum Operand
<'tcx
> {
1800 /// Copy: The value must be available for use afterwards.
1802 /// This implies that the type of the place must be `Copy`; this is true
1803 /// by construction during build, but also checked by the MIR type checker.
1806 /// Move: The value (including old borrows of it) will not be used again.
1808 /// Safe for values of all types (modulo future developments towards `?Move`).
1809 /// Correct usage patterns are enforced by the borrow checker for safe code.
1810 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1813 /// Synthesizes a constant value.
1814 Constant(Box
<Constant
<'tcx
>>),
1817 impl<'tcx
> Debug
for Operand
<'tcx
> {
1818 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
1819 use self::Operand
::*;
1821 Constant(ref a
) => write
!(fmt
, "{:?}", a
),
1822 Copy(ref place
) => write
!(fmt
, "{:?}", place
),
1823 Move(ref place
) => write
!(fmt
, "move {:?}", place
),
1828 impl<'tcx
> Operand
<'tcx
> {
1829 /// Convenience helper to make a constant that refers to the fn
1830 /// with given `DefId` and substs. Since this is used to synthesize
1831 /// MIR, assumes `user_ty` is None.
1832 pub fn function_handle(
1835 substs
: SubstsRef
<'tcx
>,
1838 let ty
= tcx
.type_of(def_id
).subst(tcx
, substs
);
1839 Operand
::Constant(box Constant
{
1842 literal
: ty
::Const
::zero_sized(tcx
, ty
),
1846 /// Convenience helper to make a literal-like constant from a given scalar value.
1847 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1848 pub fn const_from_scalar(
1853 ) -> Operand
<'tcx
> {
1855 let param_env_and_ty
= ty
::ParamEnv
::empty().and(ty
);
1857 .layout_of(param_env_and_ty
)
1858 .unwrap_or_else(|e
| panic
!("could not compute layout for {:?}: {:?}", ty
, e
))
1860 let scalar_size
= abi
::Size
::from_bytes(match val
{
1861 Scalar
::Raw { size, .. }
=> size
,
1862 _
=> panic
!("Invalid scalar type {:?}", val
),
1864 scalar_size
== type_size
1866 Operand
::Constant(box Constant
{
1869 literal
: ty
::Const
::from_scalar(tcx
, val
, ty
),
1873 /// Convenience helper to make a `Scalar` from the given `Operand`, assuming that `Operand`
1874 /// wraps a constant literal value. Panics if this is not the case.
1875 pub fn scalar_from_const(operand
: &Operand
<'tcx
>) -> Scalar
{
1877 Operand
::Constant(constant
) => match constant
.literal
.val
.try_to_scalar() {
1878 Some(scalar
) => scalar
,
1879 _
=> panic
!("{:?}: Scalar value expected", constant
.literal
.val
),
1881 _
=> panic
!("{:?}: Constant expected", operand
),
1885 /// Convenience helper to make a literal-like constant from a given `&str` slice.
1886 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1887 pub fn const_from_str(tcx
: TyCtxt
<'tcx
>, val
: &str, span
: Span
) -> Operand
<'tcx
> {
1889 let allocation
= Allocation
::from_byte_aligned_bytes(val
.as_bytes());
1890 let allocation
= tcx
.intern_const_alloc(allocation
);
1891 let const_val
= ConstValue
::Slice { data: allocation, start: 0, end: val.len() }
;
1892 let ty
= tcx
.mk_imm_ref(tcx
.lifetimes
.re_erased
, tcx
.types
.str_
);
1893 Operand
::Constant(box Constant
{
1896 literal
: ty
::Const
::from_value(tcx
, const_val
, ty
),
1900 /// Convenience helper to make a `ConstValue` from the given `Operand`, assuming that `Operand`
1901 /// wraps a constant value (such as a `&str` slice). Panics if this is not the case.
1902 pub fn value_from_const(operand
: &Operand
<'tcx
>) -> ConstValue
<'tcx
> {
1904 Operand
::Constant(constant
) => match constant
.literal
.val
.try_to_value() {
1905 Some(const_value
) => const_value
,
1906 _
=> panic
!("{:?}: ConstValue expected", constant
.literal
.val
),
1908 _
=> panic
!("{:?}: Constant expected", operand
),
1912 pub fn to_copy(&self) -> Self {
1914 Operand
::Copy(_
) | Operand
::Constant(_
) => self.clone(),
1915 Operand
::Move(place
) => Operand
::Copy(place
),
1919 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1921 pub fn place(&self) -> Option
<Place
<'tcx
>> {
1923 Operand
::Copy(place
) | Operand
::Move(place
) => Some(*place
),
1924 Operand
::Constant(_
) => None
,
1929 ///////////////////////////////////////////////////////////////////////////
1932 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1933 pub enum Rvalue
<'tcx
> {
1934 /// x (either a move or copy, depending on type of x)
1938 Repeat(Operand
<'tcx
>, &'tcx ty
::Const
<'tcx
>),
1941 Ref(Region
<'tcx
>, BorrowKind
, Place
<'tcx
>),
1943 /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
1944 /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
1946 ThreadLocalRef(DefId
),
1948 /// Create a raw pointer to the given place
1949 /// Can be generated by raw address of expressions (`&raw const x`),
1950 /// or when casting a reference to a raw pointer.
1951 AddressOf(Mutability
, Place
<'tcx
>),
1953 /// length of a `[X]` or `[X;n]` value
1956 Cast(CastKind
, Operand
<'tcx
>, Ty
<'tcx
>),
1958 BinaryOp(BinOp
, Operand
<'tcx
>, Operand
<'tcx
>),
1959 CheckedBinaryOp(BinOp
, Operand
<'tcx
>, Operand
<'tcx
>),
1961 NullaryOp(NullOp
, Ty
<'tcx
>),
1962 UnaryOp(UnOp
, Operand
<'tcx
>),
1964 /// Read the discriminant of an ADT.
1966 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
1967 /// be defined to return, say, a 0) if ADT is not an enum.
1968 Discriminant(Place
<'tcx
>),
1970 /// Creates an aggregate value, like a tuple or struct. This is
1971 /// only needed because we want to distinguish `dest = Foo { x:
1972 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1973 /// that `Foo` has a destructor. These rvalues can be optimized
1974 /// away after type-checking and before lowering.
1975 Aggregate(Box
<AggregateKind
<'tcx
>>, Vec
<Operand
<'tcx
>>),
1978 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1981 Pointer(PointerCast
),
1984 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1985 pub enum AggregateKind
<'tcx
> {
1986 /// The type is of the element
1990 /// The second field is the variant index. It's equal to 0 for struct
1991 /// and union expressions. The fourth field is
1992 /// active field number and is present only for union expressions
1993 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1994 /// active field index would identity the field `c`
1995 Adt(&'tcx AdtDef
, VariantIdx
, SubstsRef
<'tcx
>, Option
<UserTypeAnnotationIndex
>, Option
<usize>),
1997 Closure(DefId
, SubstsRef
<'tcx
>),
1998 Generator(DefId
, SubstsRef
<'tcx
>, hir
::Movability
),
2001 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2003 /// The `+` operator (addition)
2005 /// The `-` operator (subtraction)
2007 /// The `*` operator (multiplication)
2009 /// The `/` operator (division)
2011 /// The `%` operator (modulus)
2013 /// The `^` operator (bitwise xor)
2015 /// The `&` operator (bitwise and)
2017 /// The `|` operator (bitwise or)
2019 /// The `<<` operator (shift left)
2021 /// The `>>` operator (shift right)
2023 /// The `==` operator (equality)
2025 /// The `<` operator (less than)
2027 /// The `<=` operator (less than or equal to)
2029 /// The `!=` operator (not equal to)
2031 /// The `>=` operator (greater than or equal to)
2033 /// The `>` operator (greater than)
2035 /// The `ptr.offset` operator
2040 pub fn is_checkable(self) -> bool
{
2043 Add
| Sub
| Mul
| Shl
| Shr
=> true,
2049 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2051 /// Returns the size of a value of that type
2053 /// Creates a new uninitialized box for a value of that type
2057 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2059 /// The `!` operator for logical inversion
2061 /// The `-` operator for negation
2065 impl<'tcx
> Debug
for Rvalue
<'tcx
> {
2066 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
2067 use self::Rvalue
::*;
2070 Use(ref place
) => write
!(fmt
, "{:?}", place
),
2071 Repeat(ref a
, ref b
) => {
2072 write
!(fmt
, "[{:?}; ", a
)?
;
2073 pretty_print_const(b
, fmt
, false)?
;
2076 Len(ref a
) => write
!(fmt
, "Len({:?})", a
),
2077 Cast(ref kind
, ref place
, ref ty
) => {
2078 write
!(fmt
, "{:?} as {:?} ({:?})", place
, ty
, kind
)
2080 BinaryOp(ref op
, ref a
, ref b
) => write
!(fmt
, "{:?}({:?}, {:?})", op
, a
, b
),
2081 CheckedBinaryOp(ref op
, ref a
, ref b
) => {
2082 write
!(fmt
, "Checked{:?}({:?}, {:?})", op
, a
, b
)
2084 UnaryOp(ref op
, ref a
) => write
!(fmt
, "{:?}({:?})", op
, a
),
2085 Discriminant(ref place
) => write
!(fmt
, "discriminant({:?})", place
),
2086 NullaryOp(ref op
, ref t
) => write
!(fmt
, "{:?}({:?})", op
, t
),
2087 ThreadLocalRef(did
) => ty
::tls
::with(|tcx
| {
2088 let muta
= tcx
.static_mutability(did
).unwrap().prefix_str();
2089 write
!(fmt
, "&/*tls*/ {}{}", muta
, tcx
.def_path_str(did
))
2091 Ref(region
, borrow_kind
, ref place
) => {
2092 let kind_str
= match borrow_kind
{
2093 BorrowKind
::Shared
=> "",
2094 BorrowKind
::Shallow
=> "shallow ",
2095 BorrowKind
::Mut { .. }
| BorrowKind
::Unique
=> "mut ",
2098 // When printing regions, add trailing space if necessary.
2099 let print_region
= ty
::tls
::with(|tcx
| {
2100 tcx
.sess
.verbose() || tcx
.sess
.opts
.debugging_opts
.identify_regions
2102 let region
= if print_region
{
2103 let mut region
= region
.to_string();
2104 if !region
.is_empty() {
2109 // Do not even print 'static
2112 write
!(fmt
, "&{}{}{:?}", region
, kind_str
, place
)
2115 AddressOf(mutability
, ref place
) => {
2116 let kind_str
= match mutability
{
2117 Mutability
::Mut
=> "mut",
2118 Mutability
::Not
=> "const",
2121 write
!(fmt
, "&raw {} {:?}", kind_str
, place
)
2124 Aggregate(ref kind
, ref places
) => {
2125 let fmt_tuple
= |fmt
: &mut Formatter
<'_
>, name
: &str| {
2126 let mut tuple_fmt
= fmt
.debug_tuple(name
);
2127 for place
in places
{
2128 tuple_fmt
.field(place
);
2134 AggregateKind
::Array(_
) => write
!(fmt
, "{:?}", places
),
2136 AggregateKind
::Tuple
=> {
2137 if places
.is_empty() {
2144 AggregateKind
::Adt(adt_def
, variant
, substs
, _user_ty
, _
) => {
2145 let variant_def
= &adt_def
.variants
[variant
];
2147 let name
= ty
::tls
::with(|tcx
| {
2148 let mut name
= String
::new();
2149 let substs
= tcx
.lift(&substs
).expect("could not lift for printing");
2150 FmtPrinter
::new(tcx
, &mut name
, Namespace
::ValueNS
)
2151 .print_def_path(variant_def
.def_id
, substs
)?
;
2155 match variant_def
.ctor_kind
{
2156 CtorKind
::Const
=> fmt
.write_str(&name
),
2157 CtorKind
::Fn
=> fmt_tuple(fmt
, &name
),
2158 CtorKind
::Fictive
=> {
2159 let mut struct_fmt
= fmt
.debug_struct(&name
);
2160 for (field
, place
) in variant_def
.fields
.iter().zip(places
) {
2161 struct_fmt
.field(&field
.ident
.as_str(), place
);
2168 AggregateKind
::Closure(def_id
, substs
) => ty
::tls
::with(|tcx
| {
2169 if let Some(def_id
) = def_id
.as_local() {
2170 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
);
2171 let name
= if tcx
.sess
.opts
.debugging_opts
.span_free_formats
{
2172 let substs
= tcx
.lift(&substs
).unwrap();
2175 tcx
.def_path_str_with_substs(def_id
.to_def_id(), substs
),
2178 let span
= tcx
.hir().span(hir_id
);
2179 format
!("[closure@{}]", tcx
.sess
.source_map().span_to_string(span
))
2181 let mut struct_fmt
= fmt
.debug_struct(&name
);
2183 if let Some(upvars
) = tcx
.upvars_mentioned(def_id
) {
2184 for (&var_id
, place
) in upvars
.keys().zip(places
) {
2185 let var_name
= tcx
.hir().name(var_id
);
2186 struct_fmt
.field(&var_name
.as_str(), place
);
2192 write
!(fmt
, "[closure]")
2196 AggregateKind
::Generator(def_id
, _
, _
) => ty
::tls
::with(|tcx
| {
2197 if let Some(def_id
) = def_id
.as_local() {
2198 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
);
2199 let name
= format
!("[generator@{:?}]", tcx
.hir().span(hir_id
));
2200 let mut struct_fmt
= fmt
.debug_struct(&name
);
2202 if let Some(upvars
) = tcx
.upvars_mentioned(def_id
) {
2203 for (&var_id
, place
) in upvars
.keys().zip(places
) {
2204 let var_name
= tcx
.hir().name(var_id
);
2205 struct_fmt
.field(&var_name
.as_str(), place
);
2211 write
!(fmt
, "[generator]")
2220 ///////////////////////////////////////////////////////////////////////////
2223 /// Two constants are equal if they are the same constant. Note that
2224 /// this does not necessarily mean that they are "==" in Rust -- in
2225 /// particular one must be wary of `NaN`!
2227 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, HashStable)]
2228 pub struct Constant
<'tcx
> {
2231 /// Optional user-given type: for something like
2232 /// `collect::<Vec<_>>`, this would be present and would
2233 /// indicate that `Vec<_>` was explicitly specified.
2235 /// Needed for NLL to impose user-given type constraints.
2236 pub user_ty
: Option
<UserTypeAnnotationIndex
>,
2238 pub literal
: &'tcx ty
::Const
<'tcx
>,
2241 impl Constant
<'tcx
> {
2242 pub fn check_static_ptr(&self, tcx
: TyCtxt
<'_
>) -> Option
<DefId
> {
2243 match self.literal
.val
.try_to_scalar() {
2244 Some(Scalar
::Ptr(ptr
)) => match tcx
.global_alloc(ptr
.alloc_id
) {
2245 GlobalAlloc
::Static(def_id
) => {
2246 assert
!(!tcx
.is_thread_local_static(def_id
));
2256 /// A collection of projections into user types.
2258 /// They are projections because a binding can occur a part of a
2259 /// parent pattern that has been ascribed a type.
2261 /// Its a collection because there can be multiple type ascriptions on
2262 /// the path from the root of the pattern down to the binding itself.
2267 /// struct S<'a>((i32, &'a str), String);
2268 /// let S((_, w): (i32, &'static str), _): S = ...;
2269 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2270 /// // --------------------------------- ^ (2)
2273 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2274 /// ascribed the type `(i32, &'static str)`.
2276 /// The highlights labelled `(2)` show the whole pattern being
2277 /// ascribed the type `S`.
2279 /// In this example, when we descend to `w`, we will have built up the
2280 /// following two projected types:
2282 /// * base: `S`, projection: `(base.0).1`
2283 /// * base: `(i32, &'static str)`, projection: `base.1`
2285 /// The first will lead to the constraint `w: &'1 str` (for some
2286 /// inferred region `'1`). The second will lead to the constraint `w:
2288 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2289 pub struct UserTypeProjections
{
2290 pub contents
: Vec
<(UserTypeProjection
, Span
)>,
2293 impl<'tcx
> UserTypeProjections
{
2294 pub fn none() -> Self {
2295 UserTypeProjections { contents: vec![] }
2298 pub fn is_empty(&self) -> bool
{
2299 self.contents
.is_empty()
2302 pub fn from_projections(projs
: impl Iterator
<Item
= (UserTypeProjection
, Span
)>) -> Self {
2303 UserTypeProjections { contents: projs.collect() }
2306 pub fn projections_and_spans(
2308 ) -> impl Iterator
<Item
= &(UserTypeProjection
, Span
)> + ExactSizeIterator
{
2309 self.contents
.iter()
2312 pub fn projections(&self) -> impl Iterator
<Item
= &UserTypeProjection
> + ExactSizeIterator
{
2313 self.contents
.iter().map(|&(ref user_type
, _span
)| user_type
)
2316 pub fn push_projection(mut self, user_ty
: &UserTypeProjection
, span
: Span
) -> Self {
2317 self.contents
.push((user_ty
.clone(), span
));
2323 mut f
: impl FnMut(UserTypeProjection
) -> UserTypeProjection
,
2325 self.contents
= self.contents
.drain(..).map(|(proj
, span
)| (f(proj
), span
)).collect();
2329 pub fn index(self) -> Self {
2330 self.map_projections(|pat_ty_proj
| pat_ty_proj
.index())
2333 pub fn subslice(self, from
: u32, to
: u32) -> Self {
2334 self.map_projections(|pat_ty_proj
| pat_ty_proj
.subslice(from
, to
))
2337 pub fn deref(self) -> Self {
2338 self.map_projections(|pat_ty_proj
| pat_ty_proj
.deref())
2341 pub fn leaf(self, field
: Field
) -> Self {
2342 self.map_projections(|pat_ty_proj
| pat_ty_proj
.leaf(field
))
2345 pub fn variant(self, adt_def
: &'tcx AdtDef
, variant_index
: VariantIdx
, field
: Field
) -> Self {
2346 self.map_projections(|pat_ty_proj
| pat_ty_proj
.variant(adt_def
, variant_index
, field
))
2350 /// Encodes the effect of a user-supplied type annotation on the
2351 /// subcomponents of a pattern. The effect is determined by applying the
2352 /// given list of proejctions to some underlying base type. Often,
2353 /// the projection element list `projs` is empty, in which case this
2354 /// directly encodes a type in `base`. But in the case of complex patterns with
2355 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2356 /// in which case the `projs` vector is used.
2360 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2362 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2363 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2364 /// determined by finding the type of the `.0` field from `T`.
2365 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2366 pub struct UserTypeProjection
{
2367 pub base
: UserTypeAnnotationIndex
,
2368 pub projs
: Vec
<ProjectionKind
>,
2371 impl Copy
for ProjectionKind {}
2373 impl UserTypeProjection
{
2374 pub(crate) fn index(mut self) -> Self {
2375 self.projs
.push(ProjectionElem
::Index(()));
2379 pub(crate) fn subslice(mut self, from
: u32, to
: u32) -> Self {
2380 self.projs
.push(ProjectionElem
::Subslice { from, to, from_end: true }
);
2384 pub(crate) fn deref(mut self) -> Self {
2385 self.projs
.push(ProjectionElem
::Deref
);
2389 pub(crate) fn leaf(mut self, field
: Field
) -> Self {
2390 self.projs
.push(ProjectionElem
::Field(field
, ()));
2394 pub(crate) fn variant(
2397 variant_index
: VariantIdx
,
2400 self.projs
.push(ProjectionElem
::Downcast(
2401 Some(adt_def
.variants
[variant_index
].ident
.name
),
2404 self.projs
.push(ProjectionElem
::Field(field
, ()));
2409 CloneTypeFoldableAndLiftImpls
! { ProjectionKind, }
2411 impl<'tcx
> TypeFoldable
<'tcx
> for UserTypeProjection
{
2412 fn super_fold_with
<F
: TypeFolder
<'tcx
>>(&self, folder
: &mut F
) -> Self {
2413 use crate::mir
::ProjectionElem
::*;
2415 let base
= self.base
.fold_with(folder
);
2416 let projs
: Vec
<_
> = self
2419 .map(|&elem
| match elem
{
2421 Field(f
, ()) => Field(f
, ()),
2422 Index(()) => Index(()),
2423 Downcast(symbol
, variantidx
) => Downcast(symbol
, variantidx
),
2424 ConstantIndex { offset, min_length, from_end }
=> {
2425 ConstantIndex { offset, min_length, from_end }
2427 Subslice { from, to, from_end }
=> Subslice { from, to, from_end }
,
2431 UserTypeProjection { base, projs }
2434 fn super_visit_with
<Vs
: TypeVisitor
<'tcx
>>(&self, visitor
: &mut Vs
) -> bool
{
2435 self.base
.visit_with(visitor
)
2436 // Note: there's nothing in `self.proj` to visit.
2440 rustc_index
::newtype_index
! {
2441 pub struct Promoted
{
2443 DEBUG_FORMAT
= "promoted[{}]"
2447 impl<'tcx
> Debug
for Constant
<'tcx
> {
2448 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
2449 write
!(fmt
, "{}", self)
2453 impl<'tcx
> Display
for Constant
<'tcx
> {
2454 fn fmt(&self, fmt
: &mut Formatter
<'_
>) -> fmt
::Result
{
2455 match self.literal
.ty
.kind
{
2457 _
=> write
!(fmt
, "const ")?
,
2459 pretty_print_const(self.literal
, fmt
, true)
2463 fn pretty_print_const(
2464 c
: &ty
::Const
<'tcx
>,
2465 fmt
: &mut Formatter
<'_
>,
2468 use crate::ty
::print
::PrettyPrinter
;
2469 ty
::tls
::with(|tcx
| {
2470 let literal
= tcx
.lift(&c
).unwrap();
2471 let mut cx
= FmtPrinter
::new(tcx
, fmt
, Namespace
::ValueNS
);
2472 cx
.print_alloc_ids
= true;
2473 cx
.pretty_print_const(literal
, print_types
)?
;
2478 impl<'tcx
> graph
::DirectedGraph
for Body
<'tcx
> {
2479 type Node
= BasicBlock
;
2482 impl<'tcx
> graph
::WithNumNodes
for Body
<'tcx
> {
2484 fn num_nodes(&self) -> usize {
2485 self.basic_blocks
.len()
2489 impl<'tcx
> graph
::WithStartNode
for Body
<'tcx
> {
2491 fn start_node(&self) -> Self::Node
{
2496 impl<'tcx
> graph
::WithSuccessors
for Body
<'tcx
> {
2498 fn successors(&self, node
: Self::Node
) -> <Self as GraphSuccessors
<'_
>>::Iter
{
2499 self.basic_blocks
[node
].terminator().successors().cloned()
2503 impl<'a
, 'b
> graph
::GraphSuccessors
<'b
> for Body
<'a
> {
2504 type Item
= BasicBlock
;
2505 type Iter
= iter
::Cloned
<Successors
<'b
>>;
2508 impl graph
::GraphPredecessors
<'graph
> for Body
<'tcx
> {
2509 type Item
= BasicBlock
;
2510 type Iter
= smallvec
::IntoIter
<[BasicBlock
; 4]>;
2513 impl graph
::WithPredecessors
for Body
<'tcx
> {
2515 fn predecessors(&self, node
: Self::Node
) -> <Self as graph
::GraphPredecessors
<'_
>>::Iter
{
2516 self.predecessors()[node
].clone().into_iter()
2520 /// `Location` represents the position of the start of the statement; or, if
2521 /// `statement_index` equals the number of statements, then the start of the
2523 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2524 pub struct Location
{
2525 /// The block that the location is within.
2526 pub block
: BasicBlock
,
2528 pub statement_index
: usize,
2531 impl fmt
::Debug
for Location
{
2532 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2533 write
!(fmt
, "{:?}[{}]", self.block
, self.statement_index
)
2538 pub const START
: Location
= Location { block: START_BLOCK, statement_index: 0 }
;
2540 /// Returns the location immediately after this one within the enclosing block.
2542 /// Note that if this location represents a terminator, then the
2543 /// resulting location would be out of bounds and invalid.
2544 pub fn successor_within_block(&self) -> Location
{
2545 Location { block: self.block, statement_index: self.statement_index + 1 }
2548 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2549 pub fn is_predecessor_of
<'tcx
>(&self, other
: Location
, body
: &Body
<'tcx
>) -> bool
{
2550 // If we are in the same block as the other location and are an earlier statement
2551 // then we are a predecessor of `other`.
2552 if self.block
== other
.block
&& self.statement_index
< other
.statement_index
{
2556 let predecessors
= body
.predecessors();
2558 // If we're in another block, then we want to check that block is a predecessor of `other`.
2559 let mut queue
: Vec
<BasicBlock
> = predecessors
[other
.block
].to_vec();
2560 let mut visited
= FxHashSet
::default();
2562 while let Some(block
) = queue
.pop() {
2563 // If we haven't visited this block before, then make sure we visit it's predecessors.
2564 if visited
.insert(block
) {
2565 queue
.extend(predecessors
[block
].iter().cloned());
2570 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2571 // we found that block by looking at the predecessors of `other`).
2572 if self.block
== block
{
2580 pub fn dominates(&self, other
: Location
, dominators
: &Dominators
<BasicBlock
>) -> bool
{
2581 if self.block
== other
.block
{
2582 self.statement_index
<= other
.statement_index
2584 dominators
.is_dominated_by(other
.block
, self.block
)