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::{
6 AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, LitToConstInput, Scalar,
8 use crate::mir::visit::MirVisitable;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::visit::{TypeVisitable, TypeVisitor};
13 use crate::ty::{self, DefIdTree, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex};
15 use crate::ty::{GenericArg, InternalSubsts, SubstsRef};
17 use rustc_data_structures::captures::Captures;
18 use rustc_errors::ErrorGuaranteed;
19 use rustc_hir::def::{CtorKind, Namespace};
20 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
21 use rustc_hir::{self, GeneratorKind, ImplicitSelfKind};
22 use rustc_hir::{self as hir, HirId};
23 use rustc_session::Session;
24 use rustc_target::abi::{Size, VariantIdx};
26 use polonius_engine::Atom;
27 pub use rustc_ast::Mutability;
28 use rustc_data_structures::fx::FxHashSet;
29 use rustc_data_structures::graph::dominators::Dominators;
30 use rustc_index::bit_set::BitMatrix;
31 use rustc_index::vec::{Idx, IndexVec};
32 use rustc_serialize::{Decodable, Encodable};
33 use rustc_span::symbol::Symbol;
34 use rustc_span::{Span, DUMMY_SP};
39 use std::convert::TryInto;
40 use std::fmt::{self, Debug, Display, Formatter, Write};
41 use std::ops::{ControlFlow, Index, IndexMut};
44 pub use self::query::*;
45 pub use basic_blocks::BasicBlocks;
50 pub mod generic_graphviz;
51 mod graph_cyclic_cache;
65 pub use terminator::*;
72 pub use self::generic_graph::graphviz_safe_def_name;
73 pub use self::graphviz::write_mir_graphviz;
74 pub use self::pretty::{
75 create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere,
79 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
81 pub trait HasLocalDecls<'tcx> {
82 fn local_decls(&self) -> &LocalDecls<'tcx>;
85 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
87 fn local_decls(&self) -> &LocalDecls<'tcx> {
92 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
94 fn local_decls(&self) -> &LocalDecls<'tcx> {
99 /// A streamlined trait that you can implement to create a pass; the
100 /// pass will be named after the type, and it will consist of a main
101 /// loop that goes over each available MIR and applies `run_pass`.
102 pub trait MirPass<'tcx> {
103 fn name(&self) -> Cow<'_, str> {
104 let name = std::any::type_name::<Self>();
105 if let Some(tail) = name.rfind(':') {
106 Cow::from(&name[tail + 1..])
112 /// Returns `true` if this pass is enabled with the current combination of compiler flags.
113 fn is_enabled(&self, _sess: &Session) -> bool {
117 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
119 fn is_mir_dump_enabled(&self) -> bool {
125 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
127 /// FIXME(JakobDegen): Return a `(usize, usize)` instead.
128 pub fn phase_index(&self) -> usize {
129 const BUILT_PHASE_COUNT: usize = 1;
130 const ANALYSIS_PHASE_COUNT: usize = 2;
132 MirPhase::Built => 1,
133 MirPhase::Analysis(analysis_phase) => {
134 1 + BUILT_PHASE_COUNT + (*analysis_phase as usize)
136 MirPhase::Runtime(runtime_phase) => {
137 1 + BUILT_PHASE_COUNT + ANALYSIS_PHASE_COUNT + (*runtime_phase as usize)
142 /// Parses an `MirPhase` from a pair of strings. Panics if this isn't possible for any reason.
143 pub fn parse(dialect: String, phase: Option<String>) -> Self {
144 match &*dialect.to_ascii_lowercase() {
146 assert!(phase.is_none(), "Cannot specify a phase for `Built` MIR");
149 "analysis" => Self::Analysis(AnalysisPhase::parse(phase)),
150 "runtime" => Self::Runtime(RuntimePhase::parse(phase)),
151 _ => panic!("Unknown MIR dialect {}", dialect),
157 pub fn parse(phase: Option<String>) -> Self {
158 let Some(phase) = phase else {
159 return Self::Initial;
162 match &*phase.to_ascii_lowercase() {
163 "initial" => Self::Initial,
164 "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
165 _ => panic!("Unknown analysis phase {}", phase),
171 pub fn parse(phase: Option<String>) -> Self {
172 let Some(phase) = phase else {
173 return Self::Initial;
176 match &*phase.to_ascii_lowercase() {
177 "initial" => Self::Initial,
178 "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
179 "optimized" => Self::Optimized,
180 _ => panic!("Unknown runtime phase {}", phase),
185 impl Display for MirPhase {
186 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
188 MirPhase::Built => write!(f, "built"),
189 MirPhase::Analysis(p) => write!(f, "analysis-{}", p),
190 MirPhase::Runtime(p) => write!(f, "runtime-{}", p),
195 impl Display for AnalysisPhase {
196 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
198 AnalysisPhase::Initial => write!(f, "initial"),
199 AnalysisPhase::PostCleanup => write!(f, "post_cleanup"),
204 impl Display for RuntimePhase {
205 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
207 RuntimePhase::Initial => write!(f, "initial"),
208 RuntimePhase::PostCleanup => write!(f, "post_cleanup"),
209 RuntimePhase::Optimized => write!(f, "optimized"),
214 /// Where a specific `mir::Body` comes from.
215 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
216 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
217 pub struct MirSource<'tcx> {
218 pub instance: InstanceDef<'tcx>,
220 /// If `Some`, this is a promoted rvalue within the parent function.
221 pub promoted: Option<Promoted>,
224 impl<'tcx> MirSource<'tcx> {
225 pub fn item(def_id: DefId) -> Self {
227 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
232 pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
233 MirSource { instance, promoted: None }
236 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
237 self.instance.with_opt_param()
241 pub fn def_id(&self) -> DefId {
242 self.instance.def_id()
246 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
247 pub struct GeneratorInfo<'tcx> {
248 /// The yield type of the function, if it is a generator.
249 pub yield_ty: Option<Ty<'tcx>>,
251 /// Generator drop glue.
252 pub generator_drop: Option<Body<'tcx>>,
254 /// The layout of a generator. Produced by the state transformation.
255 pub generator_layout: Option<GeneratorLayout<'tcx>>,
257 /// If this is a generator then record the type of source expression that caused this generator
259 pub generator_kind: GeneratorKind,
262 /// The lowered representation of a single function.
263 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
264 pub struct Body<'tcx> {
265 /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
266 /// that indexes into this vector.
267 pub basic_blocks: BasicBlocks<'tcx>,
269 /// Records how far through the "desugaring and optimization" process this particular
270 /// MIR has traversed. This is particularly useful when inlining, since in that context
271 /// we instantiate the promoted constants and add them to our promoted vector -- but those
272 /// promoted items have already been optimized, whereas ours have not. This field allows
273 /// us to see the difference and forego optimization on the inlined promoted items.
276 /// How many passses we have executed since starting the current phase. Used for debug output.
277 pub pass_count: usize,
279 pub source: MirSource<'tcx>,
281 /// A list of source scopes; these are referenced by statements
282 /// and used for debuginfo. Indexed by a `SourceScope`.
283 pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
285 pub generator: Option<Box<GeneratorInfo<'tcx>>>,
287 /// Declarations of locals.
289 /// The first local is the return value pointer, followed by `arg_count`
290 /// locals for the function arguments, followed by any user-declared
291 /// variables and temporaries.
292 pub local_decls: LocalDecls<'tcx>,
294 /// User type annotations.
295 pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
297 /// The number of arguments this function takes.
299 /// Starting at local 1, `arg_count` locals will be provided by the caller
300 /// and can be assumed to be initialized.
302 /// If this MIR was built for a constant, this will be 0.
303 pub arg_count: usize,
305 /// Mark an argument local (which must be a tuple) as getting passed as
306 /// its individual components at the LLVM level.
308 /// This is used for the "rust-call" ABI.
309 pub spread_arg: Option<Local>,
311 /// Debug information pertaining to user variables, including captures.
312 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
314 /// A span representing this MIR, for error reporting.
317 /// Constants that are required to evaluate successfully for this MIR to be well-formed.
318 /// We hold in this field all the constants we are not able to evaluate yet.
319 pub required_consts: Vec<Constant<'tcx>>,
321 /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
323 /// Note that this does not actually mean that this body is not computable right now.
324 /// The repeat count in the following example is polymorphic, but can still be evaluated
325 /// without knowing anything about the type parameter `T`.
329 /// let _ = [0; std::mem::size_of::<*mut T>()];
333 /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
334 /// removed the last mention of all generic params. We do not want to rely on optimizations and
335 /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
336 pub is_polymorphic: bool,
338 /// The phase at which this MIR should be "injected" into the compilation process.
340 /// Everything that comes before this `MirPhase` should be skipped.
342 /// This is only `Some` if the function that this body comes from was annotated with `rustc_custom_mir`.
343 pub injection_phase: Option<MirPhase>,
345 pub tainted_by_errors: Option<ErrorGuaranteed>,
348 impl<'tcx> Body<'tcx> {
350 source: MirSource<'tcx>,
351 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
352 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
353 local_decls: LocalDecls<'tcx>,
354 user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
356 var_debug_info: Vec<VarDebugInfo<'tcx>>,
358 generator_kind: Option<GeneratorKind>,
359 tainted_by_errors: Option<ErrorGuaranteed>,
361 // We need `arg_count` locals, and one for the return place.
363 local_decls.len() > arg_count,
364 "expected at least {} locals, got {}",
369 let mut body = Body {
370 phase: MirPhase::Built,
373 basic_blocks: BasicBlocks::new(basic_blocks),
375 generator: generator_kind.map(|generator_kind| {
376 Box::new(GeneratorInfo {
378 generator_drop: None,
379 generator_layout: None,
384 user_type_annotations,
389 required_consts: Vec::new(),
390 is_polymorphic: false,
391 injection_phase: None,
394 body.is_polymorphic = body.has_non_region_param();
398 /// Returns a partially initialized MIR body containing only a list of basic blocks.
400 /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
401 /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
403 pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
404 let mut body = Body {
405 phase: MirPhase::Built,
407 source: MirSource::item(CRATE_DEF_ID.to_def_id()),
408 basic_blocks: BasicBlocks::new(basic_blocks),
409 source_scopes: IndexVec::new(),
411 local_decls: IndexVec::new(),
412 user_type_annotations: IndexVec::new(),
416 required_consts: Vec::new(),
417 var_debug_info: Vec::new(),
418 is_polymorphic: false,
419 injection_phase: None,
420 tainted_by_errors: None,
422 body.is_polymorphic = body.has_non_region_param();
427 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
428 self.basic_blocks.as_mut()
432 pub fn local_kind(&self, local: Local) -> LocalKind {
433 let index = local.as_usize();
436 self.local_decls[local].mutability == Mutability::Mut,
437 "return place should be mutable"
440 LocalKind::ReturnPointer
441 } else if index < self.arg_count + 1 {
443 } else if self.local_decls[local].is_user_variable() {
450 /// Returns an iterator over all user-declared mutable locals.
452 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
453 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
454 let local = Local::new(index);
455 let decl = &self.local_decls[local];
456 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
464 /// Returns an iterator over all user-declared mutable arguments and locals.
466 pub fn mut_vars_and_args_iter<'a>(
468 ) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
469 (1..self.local_decls.len()).filter_map(move |index| {
470 let local = Local::new(index);
471 let decl = &self.local_decls[local];
472 if (decl.is_user_variable() || index < self.arg_count + 1)
473 && decl.mutability == Mutability::Mut
482 /// Returns an iterator over all function arguments.
484 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
485 (1..self.arg_count + 1).map(Local::new)
488 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
489 /// locals that are neither arguments nor the return place).
491 pub fn vars_and_temps_iter(
493 ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
494 (self.arg_count + 1..self.local_decls.len()).map(Local::new)
498 pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator<Item = LocalDecl<'tcx>> + 'a {
499 self.local_decls.drain(self.arg_count + 1..)
502 /// Returns the source info associated with `location`.
503 pub fn source_info(&self, location: Location) -> &SourceInfo {
504 let block = &self[location.block];
505 let stmts = &block.statements;
506 let idx = location.statement_index;
507 if idx < stmts.len() {
508 &stmts[idx].source_info
510 assert_eq!(idx, stmts.len());
511 &block.terminator().source_info
515 /// Returns the return type; it always return first element from `local_decls` array.
517 pub fn return_ty(&self) -> Ty<'tcx> {
518 self.local_decls[RETURN_PLACE].ty
521 /// Returns the return type; it always return first element from `local_decls` array.
523 pub fn bound_return_ty(&self) -> ty::EarlyBinder<Ty<'tcx>> {
524 ty::EarlyBinder(self.local_decls[RETURN_PLACE].ty)
527 /// Gets the location of the terminator for the given block.
529 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
530 Location { block: bb, statement_index: self[bb].statements.len() }
533 pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
534 let Location { block, statement_index } = location;
535 let block_data = &self.basic_blocks[block];
538 .get(statement_index)
540 .unwrap_or_else(|| Either::Right(block_data.terminator()))
544 pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
545 self.generator.as_ref().and_then(|generator| generator.yield_ty)
549 pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
550 self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
554 pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
555 self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
559 pub fn generator_kind(&self) -> Option<GeneratorKind> {
560 self.generator.as_ref().map(|generator| generator.generator_kind)
564 pub fn should_skip(&self) -> bool {
565 let Some(injection_phase) = self.injection_phase else {
568 injection_phase > self.phase
572 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
575 /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
577 /// Unsafe because of an unsafe fn
579 /// Unsafe because of an `unsafe` block
580 ExplicitUnsafe(hir::HirId),
583 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
584 type Output = BasicBlockData<'tcx>;
587 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
588 &self.basic_blocks[index]
592 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
594 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
595 &mut self.basic_blocks.as_mut()[index]
599 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)]
600 pub enum ClearCrossCrate<T> {
605 impl<T> ClearCrossCrate<T> {
606 pub fn as_ref(&self) -> ClearCrossCrate<&T> {
608 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
609 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
613 pub fn assert_crate_local(self) -> T {
615 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
616 ClearCrossCrate::Set(v) => v,
621 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
622 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
624 impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
626 fn encode(&self, e: &mut E) {
627 if E::CLEAR_CROSS_CRATE {
632 ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
633 ClearCrossCrate::Set(ref val) => {
634 TAG_CLEAR_CROSS_CRATE_SET.encode(e);
640 impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
642 fn decode(d: &mut D) -> ClearCrossCrate<T> {
643 if D::CLEAR_CROSS_CRATE {
644 return ClearCrossCrate::Clear;
647 let discr = u8::decode(d);
650 TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
651 TAG_CLEAR_CROSS_CRATE_SET => {
652 let val = T::decode(d);
653 ClearCrossCrate::Set(val)
655 tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
660 /// Grouped information about the source code origin of a MIR entity.
661 /// Intended to be inspected by diagnostics and debuginfo.
662 /// Most passes can work with it as a whole, within a single function.
663 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
664 // `Hash`. Please ping @bjorn3 if removing them.
665 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
666 pub struct SourceInfo {
667 /// The source span for the AST pertaining to this MIR entity.
670 /// The source scope, keeping track of which bindings can be
671 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
672 pub scope: SourceScope,
677 pub fn outermost(span: Span) -> Self {
678 SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
682 ///////////////////////////////////////////////////////////////////////////
683 // Variables and temps
685 rustc_index::newtype_index! {
688 DEBUG_FORMAT = "_{}",
689 const RETURN_PLACE = 0,
693 impl Atom for Local {
694 fn index(self) -> usize {
699 /// Classifies locals into categories. See `Body::local_kind`.
700 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
702 /// User-declared variable binding.
704 /// Compiler-introduced temporary.
706 /// Function argument.
708 /// Location of function's return value.
712 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
713 pub struct VarBindingForm<'tcx> {
714 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
715 pub binding_mode: ty::BindingMode,
716 /// If an explicit type was provided for this variable binding,
717 /// this holds the source Span of that type.
719 /// NOTE: if you want to change this to a `HirId`, be wary that
720 /// doing so breaks incremental compilation (as of this writing),
721 /// while a `Span` does not cause our tests to fail.
722 pub opt_ty_info: Option<Span>,
723 /// Place of the RHS of the =, or the subject of the `match` where this
724 /// variable is initialized. None in the case of `let PATTERN;`.
725 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
726 /// (a) the right-hand side isn't evaluated as a place expression.
727 /// (b) it gives a way to separate this case from the remaining cases
729 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
730 /// The span of the pattern in which this variable was bound.
734 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
735 pub enum BindingForm<'tcx> {
736 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
737 Var(VarBindingForm<'tcx>),
738 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
739 ImplicitSelf(ImplicitSelfKind),
740 /// Reference used in a guard expression to ensure immutability.
744 TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx>, }
746 mod binding_form_impl {
747 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
748 use rustc_query_system::ich::StableHashingContext;
750 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
751 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
752 use super::BindingForm::*;
753 std::mem::discriminant(self).hash_stable(hcx, hasher);
756 Var(binding) => binding.hash_stable(hcx, hasher),
757 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
764 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
765 /// created during evaluation of expressions in a block tail
766 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
768 /// It is used to improve diagnostics when such temporaries are
769 /// involved in borrow_check errors, e.g., explanations of where the
770 /// temporaries come from, when their destructors are run, and/or how
771 /// one might revise the code to satisfy the borrow checker's rules.
772 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
773 pub struct BlockTailInfo {
774 /// If `true`, then the value resulting from evaluating this tail
775 /// expression is ignored by the block's expression context.
777 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
778 /// but not e.g., `let _x = { ...; tail };`
779 pub tail_result_is_ignored: bool,
781 /// `Span` of the tail expression.
787 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
788 /// argument, or the return place.
789 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
790 pub struct LocalDecl<'tcx> {
791 /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
793 /// Temporaries and the return place are always mutable.
794 pub mutability: Mutability,
796 // FIXME(matthewjasper) Don't store in this in `Body`
797 pub local_info: Option<Box<LocalInfo<'tcx>>>,
799 /// `true` if this is an internal local.
801 /// These locals are not based on types in the source code and are only used
802 /// for a few desugarings at the moment.
804 /// The generator transformation will sanity check the locals which are live
805 /// across a suspension point against the type components of the generator
806 /// which type checking knows are live across a suspension point. We need to
807 /// flag drop flags to avoid triggering this check as they are introduced
808 /// outside of type inference.
810 /// This should be sound because the drop flags are fully algebraic, and
811 /// therefore don't affect the auto-trait or outlives properties of the
815 /// If this local is a temporary and `is_block_tail` is `Some`,
816 /// then it is a temporary created for evaluation of some
817 /// subexpression of some block's tail expression (with no
818 /// intervening statement context).
819 // FIXME(matthewjasper) Don't store in this in `Body`
820 pub is_block_tail: Option<BlockTailInfo>,
822 /// The type of this local.
825 /// If the user manually ascribed a type to this variable,
826 /// e.g., via `let x: T`, then we carry that type here. The MIR
827 /// borrow checker needs this information since it can affect
828 /// region inference.
829 // FIXME(matthewjasper) Don't store in this in `Body`
830 pub user_ty: Option<Box<UserTypeProjections>>,
832 /// The *syntactic* (i.e., not visibility) source scope the local is defined
833 /// in. If the local was defined in a let-statement, this
834 /// is *within* the let-statement, rather than outside
837 /// This is needed because the visibility source scope of locals within
838 /// a let-statement is weird.
840 /// The reason is that we want the local to be *within* the let-statement
841 /// for lint purposes, but we want the local to be *after* the let-statement
842 /// for names-in-scope purposes.
844 /// That's it, if we have a let-statement like the one in this
848 /// fn foo(x: &str) {
849 /// #[allow(unused_mut)]
850 /// let mut x: u32 = { // <- one unused mut
851 /// let mut y: u32 = x.parse().unwrap();
858 /// Then, from a lint point of view, the declaration of `x: u32`
859 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
860 /// lint scopes are the same as the AST/HIR nesting.
862 /// However, from a name lookup point of view, the scopes look more like
863 /// as if the let-statements were `match` expressions:
866 /// fn foo(x: &str) {
868 /// match x.parse::<u32>().unwrap() {
877 /// We care about the name-lookup scopes for debuginfo - if the
878 /// debuginfo instruction pointer is at the call to `x.parse()`, we
879 /// want `x` to refer to `x: &str`, but if it is at the call to
880 /// `drop(x)`, we want it to refer to `x: u32`.
882 /// To allow both uses to work, we need to have more than a single scope
883 /// for a local. We have the `source_info.scope` represent the "syntactic"
884 /// lint scope (with a variable being under its let block) while the
885 /// `var_debug_info.source_info.scope` represents the "local variable"
886 /// scope (where the "rest" of a block is under all prior let-statements).
888 /// The end result looks like this:
892 /// │{ argument x: &str }
894 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
895 /// │ │ // in practice because I'm lazy.
897 /// │ │← x.source_info.scope
898 /// │ │← `x.parse().unwrap()`
900 /// │ │ │← y.source_info.scope
902 /// │ │ │{ let y: u32 }
904 /// │ │ │← y.var_debug_info.source_info.scope
907 /// │ │{ let x: u32 }
908 /// │ │← x.var_debug_info.source_info.scope
909 /// │ │← `drop(x)` // This accesses `x: u32`.
911 pub source_info: SourceInfo,
914 /// Extra information about a some locals that's used for diagnostics and for
915 /// classifying variables into local variables, statics, etc, which is needed e.g.
916 /// for unsafety checking.
918 /// Not used for non-StaticRef temporaries, the return place, or anonymous
919 /// function parameters.
920 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
921 pub enum LocalInfo<'tcx> {
922 /// A user-defined local variable or function parameter
924 /// The `BindingForm` is solely used for local diagnostics when generating
925 /// warnings/errors when compiling the current crate, and therefore it need
926 /// not be visible across crates.
927 User(ClearCrossCrate<BindingForm<'tcx>>),
928 /// A temporary created that references the static with the given `DefId`.
929 StaticRef { def_id: DefId, is_thread_local: bool },
930 /// A temporary created that references the const with the given `DefId`
931 ConstRef { def_id: DefId },
932 /// A temporary created during the creation of an aggregate
933 /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
935 /// A temporary created during the pass `Derefer` to avoid it's retagging
939 impl<'tcx> LocalDecl<'tcx> {
940 /// Returns `true` only if local is a binding that can itself be
941 /// made mutable via the addition of the `mut` keyword, namely
942 /// something like the occurrences of `x` in:
943 /// - `fn foo(x: Type) { ... }`,
945 /// - or `match ... { C(x) => ... }`
946 pub fn can_be_made_mutable(&self) -> bool {
949 Some(box LocalInfo::User(ClearCrossCrate::Set(
950 BindingForm::Var(VarBindingForm {
951 binding_mode: ty::BindingMode::BindByValue(_),
955 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
960 /// Returns `true` if local is definitely not a `ref ident` or
961 /// `ref mut ident` binding. (Such bindings cannot be made into
962 /// mutable bindings, but the inverse does not necessarily hold).
963 pub fn is_nonref_binding(&self) -> bool {
966 Some(box LocalInfo::User(ClearCrossCrate::Set(
967 BindingForm::Var(VarBindingForm {
968 binding_mode: ty::BindingMode::BindByValue(_),
972 }) | BindingForm::ImplicitSelf(_),
977 /// Returns `true` if this variable is a named variable or function
978 /// parameter declared by the user.
980 pub fn is_user_variable(&self) -> bool {
981 matches!(self.local_info, Some(box LocalInfo::User(_)))
984 /// Returns `true` if this is a reference to a variable bound in a `match`
985 /// expression that is used to access said variable for the guard of the
987 pub fn is_ref_for_guard(&self) -> bool {
990 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
994 /// Returns `Some` if this is a reference to a static item that is used to
995 /// access that static.
996 pub fn is_ref_to_static(&self) -> bool {
997 matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1000 /// Returns `Some` if this is a reference to a thread-local static item that is used to
1001 /// access that static.
1002 pub fn is_ref_to_thread_local(&self) -> bool {
1003 match self.local_info {
1004 Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1009 /// Returns `true` if this is a DerefTemp
1010 pub fn is_deref_temp(&self) -> bool {
1011 match self.local_info {
1012 Some(box LocalInfo::DerefTemp) => return true,
1018 /// Returns `true` is the local is from a compiler desugaring, e.g.,
1019 /// `__next` from a `for` loop.
1021 pub fn from_compiler_desugaring(&self) -> bool {
1022 self.source_info.span.desugaring_kind().is_some()
1025 /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1027 pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1028 Self::with_source_info(ty, SourceInfo::outermost(span))
1031 /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1033 pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1035 mutability: Mutability::Mut,
1038 is_block_tail: None,
1045 /// Converts `self` into same `LocalDecl` except tagged as internal.
1047 pub fn internal(mut self) -> Self {
1048 self.internal = true;
1052 /// Converts `self` into same `LocalDecl` except tagged as immutable.
1054 pub fn immutable(mut self) -> Self {
1055 self.mutability = Mutability::Not;
1059 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1061 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1062 assert!(self.is_block_tail.is_none());
1063 self.is_block_tail = Some(info);
1068 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1069 pub enum VarDebugInfoContents<'tcx> {
1070 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1071 /// based on a `Local`, not a `Static`, and contains no indexing.
1073 Const(Constant<'tcx>),
1074 /// The user variable's data is split across several fragments,
1075 /// each described by a `VarDebugInfoFragment`.
1076 /// See DWARF 5's "2.6.1.2 Composite Location Descriptions"
1077 /// and LLVM's `DW_OP_LLVM_fragment` for more details on
1078 /// the underlying debuginfo feature this relies on.
1080 /// Type of the original user variable.
1082 /// All the parts of the original user variable, which ended
1083 /// up in disjoint places, due to optimizations.
1084 fragments: Vec<VarDebugInfoFragment<'tcx>>,
1088 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1089 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1091 VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1092 VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1093 VarDebugInfoContents::Composite { ty, fragments } => {
1094 write!(fmt, "{:?}{{ ", ty)?;
1095 for f in fragments.iter() {
1096 write!(fmt, "{:?}, ", f)?;
1104 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1105 pub struct VarDebugInfoFragment<'tcx> {
1106 /// Where in the composite user variable this fragment is,
1107 /// represented as a "projection" into the composite variable.
1108 /// At lower levels, this corresponds to a byte/bit range.
1109 // NOTE(eddyb) there's an unenforced invariant that this contains
1110 // only `Field`s, and not into `enum` variants or `union`s.
1111 // FIXME(eddyb) support this for `enum`s by either using DWARF's
1112 // more advanced control-flow features (unsupported by LLVM?)
1113 // to match on the discriminant, or by using custom type debuginfo
1114 // with non-overlapping variants for the composite variable.
1115 pub projection: Vec<PlaceElem<'tcx>>,
1117 /// Where the data for this fragment can be found.
1118 // NOTE(eddyb) There's an unenforced invariant that this `Place` is
1119 // contains no indexing (with a non-constant index).
1120 pub contents: Place<'tcx>,
1123 impl Debug for VarDebugInfoFragment<'_> {
1124 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1125 for elem in self.projection.iter() {
1127 ProjectionElem::Field(field, _) => {
1128 write!(fmt, ".{:?}", field.index())?;
1130 _ => bug!("unsupported fragment projection `{:?}`", elem),
1134 write!(fmt, " => {:?}", self.contents)
1138 /// Debug information pertaining to a user variable.
1139 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1140 pub struct VarDebugInfo<'tcx> {
1143 /// Source info of the user variable, including the scope
1144 /// within which the variable is visible (to debuginfo)
1145 /// (see `LocalDecl`'s `source_info` field for more details).
1146 pub source_info: SourceInfo,
1148 /// Where the data for this user variable is to be found.
1149 pub value: VarDebugInfoContents<'tcx>,
1152 ///////////////////////////////////////////////////////////////////////////
1155 rustc_index::newtype_index! {
1156 /// A node in the MIR [control-flow graph][CFG].
1158 /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1159 /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1160 /// as an edge in a graph between basic blocks.
1162 /// Basic blocks consist of a series of [statements][Statement], ending with a
1163 /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1164 /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1165 /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1166 /// needed because some analyses require that there are no critical edges in the CFG.
1168 /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1169 /// the actual data that a basic block holds is in [`BasicBlockData`].
1171 /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1173 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1174 /// [data-flow analyses]:
1175 /// https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1176 /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1177 /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1178 pub struct BasicBlock {
1180 DEBUG_FORMAT = "bb{}",
1181 const START_BLOCK = 0,
1186 pub fn start_location(self) -> Location {
1187 Location { block: self, statement_index: 0 }
1191 ///////////////////////////////////////////////////////////////////////////
1194 /// Data for a basic block, including a list of its statements.
1196 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1197 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1198 pub struct BasicBlockData<'tcx> {
1199 /// List of statements in this block.
1200 pub statements: Vec<Statement<'tcx>>,
1202 /// Terminator for this block.
1204 /// N.B., this should generally ONLY be `None` during construction.
1205 /// Therefore, you should generally access it via the
1206 /// `terminator()` or `terminator_mut()` methods. The only
1207 /// exception is that certain passes, such as `simplify_cfg`, swap
1208 /// out the terminator temporarily with `None` while they continue
1209 /// to recurse over the set of basic blocks.
1210 pub terminator: Option<Terminator<'tcx>>,
1212 /// If true, this block lies on an unwind path. This is used
1213 /// during codegen where distinct kinds of basic blocks may be
1214 /// generated (particularly for MSVC cleanup). Unwind blocks must
1215 /// only branch to other unwind blocks.
1216 pub is_cleanup: bool,
1219 impl<'tcx> BasicBlockData<'tcx> {
1220 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1221 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1224 /// Accessor for terminator.
1226 /// Terminator may not be None after construction of the basic block is complete. This accessor
1227 /// provides a convenient way to reach the terminator.
1229 pub fn terminator(&self) -> &Terminator<'tcx> {
1230 self.terminator.as_ref().expect("invalid terminator state")
1234 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1235 self.terminator.as_mut().expect("invalid terminator state")
1238 pub fn retain_statements<F>(&mut self, mut f: F)
1240 F: FnMut(&mut Statement<'_>) -> bool,
1242 for s in &mut self.statements {
1249 pub fn expand_statements<F, I>(&mut self, mut f: F)
1251 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1252 I: iter::TrustedLen<Item = Statement<'tcx>>,
1254 // Gather all the iterators we'll need to splice in, and their positions.
1255 let mut splices: Vec<(usize, I)> = vec![];
1256 let mut extra_stmts = 0;
1257 for (i, s) in self.statements.iter_mut().enumerate() {
1258 if let Some(mut new_stmts) = f(s) {
1259 if let Some(first) = new_stmts.next() {
1260 // We can already store the first new statement.
1263 // Save the other statements for optimized splicing.
1264 let remaining = new_stmts.size_hint().0;
1266 splices.push((i + 1 + extra_stmts, new_stmts));
1267 extra_stmts += remaining;
1275 // Splice in the new statements, from the end of the block.
1276 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1277 // where a range of elements ("gap") is left uninitialized, with
1278 // splicing adding new elements to the end of that gap and moving
1279 // existing elements from before the gap to the end of the gap.
1280 // For now, this is safe code, emulating a gap but initializing it.
1281 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1282 self.statements.resize(
1284 Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1286 for (splice_start, new_stmts) in splices.into_iter().rev() {
1287 let splice_end = splice_start + new_stmts.size_hint().0;
1288 while gap.end > splice_end {
1291 self.statements.swap(gap.start, gap.end);
1293 self.statements.splice(splice_start..splice_end, new_stmts);
1294 gap.end = splice_start;
1298 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1299 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1302 /// Does the block have no statements and an unreachable terminator?
1303 pub fn is_empty_unreachable(&self) -> bool {
1304 self.statements.is_empty() && matches!(self.terminator().kind, TerminatorKind::Unreachable)
1308 impl<O> AssertKind<O> {
1309 /// Getting a description does not require `O` to be printable, and does not
1310 /// require allocation.
1311 /// The caller is expected to handle `BoundsCheck` separately.
1312 pub fn description(&self) -> &'static str {
1315 Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1316 Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1317 Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1318 Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1319 Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1320 OverflowNeg(_) => "attempt to negate with overflow",
1321 Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1322 Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1323 Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1324 DivisionByZero(_) => "attempt to divide by zero",
1325 RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1326 ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1327 ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1328 ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1329 ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1330 BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1334 /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1335 pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1341 BoundsCheck { ref len, ref index } => write!(
1343 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1347 OverflowNeg(op) => {
1348 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1350 DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1351 RemainderByZero(op) => write!(
1353 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1356 Overflow(BinOp::Add, l, r) => write!(
1358 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1361 Overflow(BinOp::Sub, l, r) => write!(
1363 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1366 Overflow(BinOp::Mul, l, r) => write!(
1368 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1371 Overflow(BinOp::Div, l, r) => write!(
1373 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1376 Overflow(BinOp::Rem, l, r) => write!(
1378 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1381 Overflow(BinOp::Shr, _, r) => {
1382 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1384 Overflow(BinOp::Shl, _, r) => {
1385 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1387 _ => write!(f, "\"{}\"", self.description()),
1392 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1396 BoundsCheck { ref len, ref index } => write!(
1398 "index out of bounds: the length is {:?} but the index is {:?}",
1401 OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1402 DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1403 RemainderByZero(op) => write!(
1405 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1408 Overflow(BinOp::Add, l, r) => {
1409 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1411 Overflow(BinOp::Sub, l, r) => {
1412 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1414 Overflow(BinOp::Mul, l, r) => {
1415 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1417 Overflow(BinOp::Div, l, r) => {
1418 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1420 Overflow(BinOp::Rem, l, r) => write!(
1422 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1425 Overflow(BinOp::Shr, _, r) => {
1426 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1428 Overflow(BinOp::Shl, _, r) => {
1429 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1431 _ => write!(f, "{}", self.description()),
1436 ///////////////////////////////////////////////////////////////////////////
1439 /// A statement in a basic block, including information about its source code.
1440 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1441 pub struct Statement<'tcx> {
1442 pub source_info: SourceInfo,
1443 pub kind: StatementKind<'tcx>,
1446 impl Statement<'_> {
1447 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1448 /// invalidating statement indices in `Location`s.
1449 pub fn make_nop(&mut self) {
1450 self.kind = StatementKind::Nop
1453 /// Changes a statement to a nop and returns the original statement.
1454 #[must_use = "If you don't need the statement, use `make_nop` instead"]
1455 pub fn replace_nop(&mut self) -> Self {
1457 source_info: self.source_info,
1458 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1463 impl Debug for Statement<'_> {
1464 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1465 use self::StatementKind::*;
1467 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1468 FakeRead(box (ref cause, ref place)) => {
1469 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1471 Retag(ref kind, ref place) => write!(
1475 RetagKind::FnEntry => "[fn entry] ",
1476 RetagKind::TwoPhase => "[2phase] ",
1477 RetagKind::Raw => "[raw] ",
1478 RetagKind::Default => "",
1482 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1483 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1484 SetDiscriminant { ref place, variant_index } => {
1485 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1487 Deinit(ref place) => write!(fmt, "Deinit({:?})", place),
1488 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1489 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1491 Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1492 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1494 Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1495 Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
1496 Nop => write!(fmt, "nop"),
1501 impl<'tcx> StatementKind<'tcx> {
1502 pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1504 StatementKind::Assign(x) => Some(x),
1509 pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1511 StatementKind::Assign(x) => Some(x),
1517 ///////////////////////////////////////////////////////////////////////////
1520 impl<V, T> ProjectionElem<V, T> {
1521 /// Returns `true` if the target of this projection may refer to a different region of memory
1523 fn is_indirect(&self) -> bool {
1525 Self::Deref => true,
1529 | Self::OpaqueCast(_)
1530 | Self::ConstantIndex { .. }
1531 | Self::Subslice { .. }
1532 | Self::Downcast(_, _) => false,
1536 /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
1537 pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
1538 matches!(*self, Self::Downcast(_, x) if x == v)
1541 /// Returns `true` if this is a `Field` projection with the given index.
1542 pub fn is_field_to(&self, f: Field) -> bool {
1543 matches!(*self, Self::Field(x, _) if x == f)
1547 /// Alias for projections as they appear in `UserTypeProjection`, where we
1548 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1549 pub type ProjectionKind = ProjectionElem<(), ()>;
1551 rustc_index::newtype_index! {
1552 /// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
1554 /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
1555 /// rustc can identify that a field projection refers to either two different regions of memory
1556 /// or the same one between the base and the 'projection element'.
1557 /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
1559 /// [wrapper]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html#newtype
1560 /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1561 /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
1564 DEBUG_FORMAT = "field[{}]"
1568 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1569 pub struct PlaceRef<'tcx> {
1571 pub projection: &'tcx [PlaceElem<'tcx>],
1574 // Once we stop implementing `Ord` for `DefId`,
1575 // this impl will be unnecessary. Until then, we'll
1576 // leave this impl in place to prevent re-adding a
1577 // dependency on the `Ord` impl for `DefId`
1578 impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
1580 impl<'tcx> Place<'tcx> {
1581 // FIXME change this to a const fn by also making List::empty a const fn.
1582 pub fn return_place() -> Place<'tcx> {
1583 Place { local: RETURN_PLACE, projection: List::empty() }
1586 /// Returns `true` if this `Place` contains a `Deref` projection.
1588 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1589 /// same region of memory as its base.
1590 pub fn is_indirect(&self) -> bool {
1591 self.projection.iter().any(|elem| elem.is_indirect())
1594 /// If MirPhase >= Derefered and if projection contains Deref,
1595 /// It's guaranteed to be in the first place
1596 pub fn has_deref(&self) -> bool {
1597 // To make sure this is not accidentally used in wrong mir phase
1599 self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
1601 self.projection.first() == Some(&PlaceElem::Deref)
1604 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1605 /// a single deref of a local.
1607 pub fn local_or_deref_local(&self) -> Option<Local> {
1608 self.as_ref().local_or_deref_local()
1611 /// If this place represents a local variable like `_X` with no
1612 /// projections, return `Some(_X)`.
1614 pub fn as_local(&self) -> Option<Local> {
1615 self.as_ref().as_local()
1619 pub fn as_ref(&self) -> PlaceRef<'tcx> {
1620 PlaceRef { local: self.local, projection: &self.projection }
1623 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1624 /// its projection and then subsequently more projections are added.
1625 /// As a concrete example, given the place a.b.c, this would yield:
1629 /// Given a place without projections, the iterator is empty.
1631 pub fn iter_projections(
1633 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1634 self.as_ref().iter_projections()
1637 /// Generates a new place by appending `more_projections` to the existing ones
1638 /// and interning the result.
1639 pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
1640 if more_projections.is_empty() {
1644 let mut v: Vec<PlaceElem<'tcx>>;
1646 let new_projections = if self.projection.is_empty() {
1649 v = Vec::with_capacity(self.projection.len() + more_projections.len());
1650 v.extend(self.projection);
1651 v.extend(more_projections);
1655 Place { local: self.local, projection: tcx.intern_place_elems(new_projections) }
1659 impl From<Local> for Place<'_> {
1661 fn from(local: Local) -> Self {
1662 Place { local, projection: List::empty() }
1666 impl<'tcx> PlaceRef<'tcx> {
1667 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1668 /// a single deref of a local.
1669 pub fn local_or_deref_local(&self) -> Option<Local> {
1671 PlaceRef { local, projection: [] }
1672 | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1677 /// If MirPhase >= Derefered and if projection contains Deref,
1678 /// It's guaranteed to be in the first place
1679 pub fn has_deref(&self) -> bool {
1680 self.projection.first() == Some(&PlaceElem::Deref)
1683 /// If this place represents a local variable like `_X` with no
1684 /// projections, return `Some(_X)`.
1686 pub fn as_local(&self) -> Option<Local> {
1688 PlaceRef { local, projection: [] } => Some(local),
1694 pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1695 if let &[ref proj_base @ .., elem] = self.projection {
1696 Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1702 /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1703 /// its projection and then subsequently more projections are added.
1704 /// As a concrete example, given the place a.b.c, this would yield:
1708 /// Given a place without projections, the iterator is empty.
1710 pub fn iter_projections(
1712 ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1713 self.projection.iter().enumerate().map(move |(i, proj)| {
1714 let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1720 impl Debug for Place<'_> {
1721 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1722 for elem in self.projection.iter().rev() {
1724 ProjectionElem::OpaqueCast(_)
1725 | ProjectionElem::Downcast(_, _)
1726 | ProjectionElem::Field(_, _) => {
1727 write!(fmt, "(").unwrap();
1729 ProjectionElem::Deref => {
1730 write!(fmt, "(*").unwrap();
1732 ProjectionElem::Index(_)
1733 | ProjectionElem::ConstantIndex { .. }
1734 | ProjectionElem::Subslice { .. } => {}
1738 write!(fmt, "{:?}", self.local)?;
1740 for elem in self.projection.iter() {
1742 ProjectionElem::OpaqueCast(ty) => {
1743 write!(fmt, " as {})", ty)?;
1745 ProjectionElem::Downcast(Some(name), _index) => {
1746 write!(fmt, " as {})", name)?;
1748 ProjectionElem::Downcast(None, index) => {
1749 write!(fmt, " as variant#{:?})", index)?;
1751 ProjectionElem::Deref => {
1754 ProjectionElem::Field(field, ty) => {
1755 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1757 ProjectionElem::Index(ref index) => {
1758 write!(fmt, "[{:?}]", index)?;
1760 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1761 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1763 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1764 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1766 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1767 write!(fmt, "[{:?}:]", from)?;
1769 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1770 write!(fmt, "[:-{:?}]", to)?;
1772 ProjectionElem::Subslice { from, to, from_end: true } => {
1773 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1775 ProjectionElem::Subslice { from, to, from_end: false } => {
1776 write!(fmt, "[{:?}..{:?}]", from, to)?;
1785 ///////////////////////////////////////////////////////////////////////////
1788 rustc_index::newtype_index! {
1789 pub struct SourceScope {
1791 DEBUG_FORMAT = "scope[{}]",
1792 const OUTERMOST_SOURCE_SCOPE = 0,
1797 /// Finds the original HirId this MIR item came from.
1798 /// This is necessary after MIR optimizations, as otherwise we get a HirId
1799 /// from the function that was inlined instead of the function call site.
1800 pub fn lint_root<'tcx>(
1802 source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1803 ) -> Option<HirId> {
1804 let mut data = &source_scopes[self];
1805 // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
1806 // does not work as I thought it would. Needs more investigation and documentation.
1807 while data.inlined.is_some() {
1809 data = &source_scopes[data.parent_scope.unwrap()];
1812 match &data.local_data {
1813 ClearCrossCrate::Set(data) => Some(data.lint_root),
1814 ClearCrossCrate::Clear => None,
1818 /// The instance this source scope was inlined from, if any.
1820 pub fn inlined_instance<'tcx>(
1822 source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1823 ) -> Option<ty::Instance<'tcx>> {
1824 let scope_data = &source_scopes[self];
1825 if let Some((inlined_instance, _)) = scope_data.inlined {
1826 Some(inlined_instance)
1827 } else if let Some(inlined_scope) = scope_data.inlined_parent_scope {
1828 Some(source_scopes[inlined_scope].inlined.unwrap().0)
1835 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1836 pub struct SourceScopeData<'tcx> {
1838 pub parent_scope: Option<SourceScope>,
1840 /// Whether this scope is the root of a scope tree of another body,
1841 /// inlined into this body by the MIR inliner.
1842 /// `ty::Instance` is the callee, and the `Span` is the call site.
1843 pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1845 /// Nearest (transitive) parent scope (if any) which is inlined.
1846 /// This is an optimization over walking up `parent_scope`
1847 /// until a scope with `inlined: Some(...)` is found.
1848 pub inlined_parent_scope: Option<SourceScope>,
1850 /// Crate-local information for this source scope, that can't (and
1851 /// needn't) be tracked across crates.
1852 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1855 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1856 pub struct SourceScopeLocalData {
1857 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1858 pub lint_root: hir::HirId,
1859 /// The unsafe block that contains this node.
1863 ///////////////////////////////////////////////////////////////////////////
1866 impl<'tcx> Debug for Operand<'tcx> {
1867 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1868 use self::Operand::*;
1870 Constant(ref a) => write!(fmt, "{:?}", a),
1871 Copy(ref place) => write!(fmt, "{:?}", place),
1872 Move(ref place) => write!(fmt, "move {:?}", place),
1877 impl<'tcx> Operand<'tcx> {
1878 /// Convenience helper to make a constant that refers to the fn
1879 /// with given `DefId` and substs. Since this is used to synthesize
1880 /// MIR, assumes `user_ty` is None.
1881 pub fn function_handle(
1884 substs: SubstsRef<'tcx>,
1887 let ty = tcx.mk_fn_def(def_id, substs);
1888 Operand::Constant(Box::new(Constant {
1891 literal: ConstantKind::Val(ConstValue::ZeroSized, ty),
1895 pub fn is_move(&self) -> bool {
1896 matches!(self, Operand::Move(..))
1899 /// Convenience helper to make a literal-like constant from a given scalar value.
1900 /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1901 pub fn const_from_scalar(
1906 ) -> Operand<'tcx> {
1908 let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1910 .layout_of(param_env_and_ty)
1911 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1913 let scalar_size = match val {
1914 Scalar::Int(int) => int.size(),
1915 _ => panic!("Invalid scalar type {:?}", val),
1917 scalar_size == type_size
1919 Operand::Constant(Box::new(Constant {
1922 literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
1926 pub fn to_copy(&self) -> Self {
1928 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1929 Operand::Move(place) => Operand::Copy(place),
1933 /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1935 pub fn place(&self) -> Option<Place<'tcx>> {
1937 Operand::Copy(place) | Operand::Move(place) => Some(*place),
1938 Operand::Constant(_) => None,
1942 /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
1944 pub fn constant(&self) -> Option<&Constant<'tcx>> {
1946 Operand::Constant(x) => Some(&**x),
1947 Operand::Copy(_) | Operand::Move(_) => None,
1951 /// Gets the `ty::FnDef` from an operand if it's a constant function item.
1953 /// While this is unlikely in general, it's the normal case of what you'll
1954 /// find as the `func` in a [`TerminatorKind::Call`].
1955 pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> {
1956 let const_ty = self.constant()?.literal.ty();
1957 if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None }
1961 ///////////////////////////////////////////////////////////////////////////
1964 impl<'tcx> Rvalue<'tcx> {
1965 /// Returns true if rvalue can be safely removed when the result is unused.
1967 pub fn is_safe_to_remove(&self) -> bool {
1969 // Pointer to int casts may be side-effects due to exposing the provenance.
1970 // While the model is undecided, we should be conservative. See
1971 // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
1972 Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => false,
1975 | Rvalue::CopyForDeref(_)
1976 | Rvalue::Repeat(_, _)
1977 | Rvalue::Ref(_, _, _)
1978 | Rvalue::ThreadLocalRef(_)
1979 | Rvalue::AddressOf(_, _)
1983 | CastKind::FloatToInt
1984 | CastKind::FloatToFloat
1985 | CastKind::IntToFloat
1986 | CastKind::FnPtrToPtr
1987 | CastKind::PtrToPtr
1988 | CastKind::Pointer(_)
1989 | CastKind::PointerFromExposedAddress
1990 | CastKind::DynStar,
1994 | Rvalue::BinaryOp(_, _)
1995 | Rvalue::CheckedBinaryOp(_, _)
1996 | Rvalue::NullaryOp(_, _)
1997 | Rvalue::UnaryOp(_, _)
1998 | Rvalue::Discriminant(_)
1999 | Rvalue::Aggregate(_, _)
2000 | Rvalue::ShallowInitBox(_, _) => true,
2006 pub fn allows_two_phase_borrow(&self) -> bool {
2008 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
2009 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
2013 // FIXME: won't be used after diagnostic migration
2014 pub fn describe_mutability(&self) -> &str {
2016 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => "immutable",
2017 BorrowKind::Mut { .. } => "mutable",
2023 pub fn is_checkable(self) -> bool {
2025 matches!(self, Add | Sub | Mul | Shl | Shr)
2029 impl<'tcx> Debug for Rvalue<'tcx> {
2030 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2031 use self::Rvalue::*;
2034 Use(ref place) => write!(fmt, "{:?}", place),
2035 Repeat(ref a, b) => {
2036 write!(fmt, "[{:?}; ", a)?;
2037 pretty_print_const(b, fmt, false)?;
2040 Len(ref a) => write!(fmt, "Len({:?})", a),
2041 Cast(ref kind, ref place, ref ty) => {
2042 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2044 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2045 CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2046 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2048 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2049 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2050 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2051 ThreadLocalRef(did) => ty::tls::with(|tcx| {
2052 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2053 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2055 Ref(region, borrow_kind, ref place) => {
2056 let kind_str = match borrow_kind {
2057 BorrowKind::Shared => "",
2058 BorrowKind::Shallow => "shallow ",
2059 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2062 // When printing regions, add trailing space if necessary.
2063 let print_region = ty::tls::with(|tcx| {
2064 tcx.sess.verbose() || tcx.sess.opts.unstable_opts.identify_regions
2066 let region = if print_region {
2067 let mut region = region.to_string();
2068 if !region.is_empty() {
2073 // Do not even print 'static
2076 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2079 CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place),
2081 AddressOf(mutability, ref place) => {
2082 let kind_str = match mutability {
2083 Mutability::Mut => "mut",
2084 Mutability::Not => "const",
2087 write!(fmt, "&raw {} {:?}", kind_str, place)
2090 Aggregate(ref kind, ref places) => {
2091 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2092 let mut tuple_fmt = fmt.debug_tuple(name);
2093 for place in places {
2094 tuple_fmt.field(place);
2100 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2102 AggregateKind::Tuple => {
2103 if places.is_empty() {
2110 AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => {
2111 ty::tls::with(|tcx| {
2112 let variant_def = &tcx.adt_def(adt_did).variant(variant);
2113 let substs = tcx.lift(substs).expect("could not lift for printing");
2114 let name = FmtPrinter::new(tcx, Namespace::ValueNS)
2115 .print_def_path(variant_def.def_id, substs)?
2118 match variant_def.ctor_kind() {
2119 Some(CtorKind::Const) => fmt.write_str(&name),
2120 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
2122 let mut struct_fmt = fmt.debug_struct(&name);
2123 for (field, place) in iter::zip(&variant_def.fields, places) {
2124 struct_fmt.field(field.name.as_str(), place);
2132 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2133 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
2134 let substs = tcx.lift(substs).unwrap();
2137 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2140 let span = tcx.def_span(def_id);
2143 tcx.sess.source_map().span_to_diagnostic_string(span)
2146 let mut struct_fmt = fmt.debug_struct(&name);
2148 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2149 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2150 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2151 let var_name = tcx.hir().name(var_id);
2152 struct_fmt.field(var_name.as_str(), place);
2159 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2160 let name = format!("[generator@{:?}]", tcx.def_span(def_id));
2161 let mut struct_fmt = fmt.debug_struct(&name);
2163 // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2164 if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2165 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2166 let var_name = tcx.hir().name(var_id);
2167 struct_fmt.field(var_name.as_str(), place);
2176 ShallowInitBox(ref place, ref ty) => {
2177 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2183 ///////////////////////////////////////////////////////////////////////////
2186 /// Two constants are equal if they are the same constant. Note that
2187 /// this does not necessarily mean that they are `==` in Rust. In
2188 /// particular, one must be wary of `NaN`!
2190 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2191 #[derive(TypeFoldable, TypeVisitable)]
2192 pub struct Constant<'tcx> {
2195 /// Optional user-given type: for something like
2196 /// `collect::<Vec<_>>`, this would be present and would
2197 /// indicate that `Vec<_>` was explicitly specified.
2199 /// Needed for NLL to impose user-given type constraints.
2200 pub user_ty: Option<UserTypeAnnotationIndex>,
2202 pub literal: ConstantKind<'tcx>,
2205 #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2206 #[derive(Lift, TypeFoldable, TypeVisitable)]
2207 pub enum ConstantKind<'tcx> {
2208 /// This constant came from the type system
2209 Ty(ty::Const<'tcx>),
2211 /// An unevaluated mir constant which is not part of the type system.
2212 Unevaluated(UnevaluatedConst<'tcx>, Ty<'tcx>),
2214 /// This constant cannot go back into the type system, as it represents
2215 /// something the type system cannot handle (e.g. pointers).
2216 Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2219 impl<'tcx> Constant<'tcx> {
2220 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2221 match self.literal.try_to_scalar() {
2222 Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2223 GlobalAlloc::Static(def_id) => {
2224 assert!(!tcx.is_thread_local_static(def_id));
2233 pub fn ty(&self) -> Ty<'tcx> {
2238 impl<'tcx> ConstantKind<'tcx> {
2240 pub fn ty(&self) -> Ty<'tcx> {
2242 ConstantKind::Ty(c) => c.ty(),
2243 ConstantKind::Val(_, ty) | ConstantKind::Unevaluated(_, ty) => *ty,
2248 pub fn try_to_value(self, tcx: TyCtxt<'tcx>) -> Option<interpret::ConstValue<'tcx>> {
2250 ConstantKind::Ty(c) => match c.kind() {
2251 ty::ConstKind::Value(valtree) => Some(tcx.valtree_to_const_val((c.ty(), valtree))),
2254 ConstantKind::Val(val, _) => Some(val),
2255 ConstantKind::Unevaluated(..) => None,
2260 pub fn try_to_scalar(self) -> Option<Scalar> {
2262 ConstantKind::Ty(c) => match c.kind() {
2263 ty::ConstKind::Value(valtree) => match valtree {
2264 ty::ValTree::Leaf(scalar_int) => Some(Scalar::Int(scalar_int)),
2265 ty::ValTree::Branch(_) => None,
2269 ConstantKind::Val(val, _) => val.try_to_scalar(),
2270 ConstantKind::Unevaluated(..) => None,
2275 pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2276 Some(self.try_to_scalar()?.assert_int())
2280 pub fn try_to_bits(self, size: Size) -> Option<u128> {
2281 self.try_to_scalar_int()?.to_bits(size).ok()
2285 pub fn try_to_bool(self) -> Option<bool> {
2286 self.try_to_scalar_int()?.try_into().ok()
2290 pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
2293 if let Some(val) = c.kind().try_eval_for_mir(tcx, param_env) {
2295 Ok(val) => Self::Val(val, c.ty()),
2296 Err(_) => Self::Ty(tcx.const_error(self.ty())),
2302 Self::Val(_, _) => self,
2303 Self::Unevaluated(uneval, ty) => {
2304 // FIXME: We might want to have a `try_eval`-like function on `Unevaluated`
2305 match tcx.const_eval_resolve(param_env, uneval, None) {
2306 Ok(val) => Self::Val(val, ty),
2307 Err(ErrorHandled::TooGeneric) => self,
2308 Err(ErrorHandled::Reported(guar)) => {
2309 Self::Ty(tcx.const_error_with_guaranteed(ty, guar))
2316 /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
2318 pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2319 self.try_eval_bits(tcx, param_env, ty)
2320 .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
2324 pub fn try_eval_bits(
2327 param_env: ty::ParamEnv<'tcx>,
2331 Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2332 Self::Val(val, t) => {
2335 tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2336 val.try_to_bits(size)
2338 Self::Unevaluated(uneval, ty) => {
2339 match tcx.const_eval_resolve(param_env, *uneval, None) {
2342 .layout_of(param_env.with_reveal_all_normalized(tcx).and(*ty))
2345 val.try_to_bits(size)
2354 pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2356 Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
2357 Self::Val(val, _) => val.try_to_bool(),
2358 Self::Unevaluated(uneval, _) => {
2359 match tcx.const_eval_resolve(param_env, *uneval, None) {
2360 Ok(val) => val.try_to_bool(),
2368 pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2370 Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
2371 Self::Val(val, _) => val.try_to_machine_usize(tcx),
2372 Self::Unevaluated(uneval, _) => {
2373 match tcx.const_eval_resolve(param_env, *uneval, None) {
2374 Ok(val) => val.try_to_machine_usize(tcx),
2382 pub fn from_value(val: ConstValue<'tcx>, ty: Ty<'tcx>) -> Self {
2389 param_env_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
2392 .layout_of(param_env_ty)
2393 .unwrap_or_else(|e| {
2394 bug!("could not compute layout for {:?}: {:?}", param_env_ty.value, e)
2397 let cv = ConstValue::Scalar(Scalar::from_uint(bits, size));
2399 Self::Val(cv, param_env_ty.value)
2403 pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
2404 let cv = ConstValue::from_bool(v);
2405 Self::Val(cv, tcx.types.bool)
2409 pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2410 let cv = ConstValue::ZeroSized;
2414 pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
2415 let ty = tcx.types.usize;
2416 Self::from_bits(tcx, n as u128, ty::ParamEnv::empty().and(ty))
2420 pub fn from_scalar(_tcx: TyCtxt<'tcx>, s: Scalar, ty: Ty<'tcx>) -> Self {
2421 let val = ConstValue::Scalar(s);
2425 /// Literals are converted to `ConstantKindVal`, const generic parameters are eagerly
2426 /// converted to a constant, everything else becomes `Unevaluated`.
2427 pub fn from_anon_const(
2430 param_env: ty::ParamEnv<'tcx>,
2432 Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id), param_env)
2435 #[instrument(skip(tcx), level = "debug", ret)]
2436 pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2437 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2438 let body_id = match tcx.hir().get(hir_id) {
2439 hir::Node::AnonConst(ac) => ac.body,
2441 tcx.def_span(def_id.to_def_id()),
2442 "from_inline_const can only process anonymous constants"
2445 let expr = &tcx.hir().body(body_id).value;
2446 let ty = tcx.typeck(def_id).node_type(hir_id);
2448 let lit_input = match expr.kind {
2449 hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2450 hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
2451 hir::ExprKind::Lit(ref lit) => {
2452 Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2458 if let Some(lit_input) = lit_input {
2459 // If an error occurred, ignore that it's a literal and leave reporting the error up to
2461 match tcx.at(expr.span).lit_to_mir_constant(lit_input) {
2467 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
2469 tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
2471 ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty })
2474 let uneval = UnevaluatedConst {
2475 def: ty::WithOptConstParam::unknown(def_id).to_global(),
2479 debug_assert!(!uneval.has_free_regions());
2481 Self::Unevaluated(uneval, ty)
2484 #[instrument(skip(tcx), level = "debug", ret)]
2485 fn from_opt_const_arg_anon_const(
2487 def: ty::WithOptConstParam<LocalDefId>,
2488 param_env: ty::ParamEnv<'tcx>,
2490 let body_id = match tcx.hir().get_by_def_id(def.did) {
2491 hir::Node::AnonConst(ac) => ac.body,
2493 tcx.def_span(def.did.to_def_id()),
2494 "from_anon_const can only process anonymous constants"
2498 let expr = &tcx.hir().body(body_id).value;
2501 // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2502 // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2503 let expr = match &expr.kind {
2504 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2505 block.expr.as_ref().unwrap()
2509 debug!("expr.kind: {:?}", expr.kind);
2511 let ty = tcx.type_of(def.def_id_for_type_of());
2514 // FIXME(const_generics): We currently have to special case parameters because `min_const_generics`
2515 // does not provide the parents generics to anonymous constants. We still allow generic const
2516 // parameters by themselves however, e.g. `N`. These constants would cause an ICE if we were to
2517 // ever try to substitute the generic parameters in their bodies.
2519 // While this doesn't happen as these constants are always used as `ty::ConstKind::Param`, it does
2520 // cause issues if we were to remove that special-case and try to evaluate the constant instead.
2521 use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
2523 ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
2524 // Find the name and index of the const parameter by indexing the generics of
2525 // the parent item and construct a `ParamConst`.
2526 let item_def_id = tcx.parent(def_id);
2527 let generics = tcx.generics_of(item_def_id);
2528 let index = generics.param_def_id_to_index[&def_id];
2529 let name = tcx.item_name(def_id);
2531 tcx.mk_const(ty::ConstKind::Param(ty::ParamConst::new(index, name)), ty);
2534 return Self::Ty(ty_const);
2539 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2540 let parent_substs = if let Some(parent_hir_id) = tcx.hir().find_parent_node(hir_id) {
2541 if let Some(parent_did) = tcx.hir().opt_local_def_id(parent_hir_id) {
2542 InternalSubsts::identity_for_item(tcx, parent_did.to_def_id())
2544 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2547 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2549 debug!(?parent_substs);
2551 let did = def.did.to_def_id();
2552 let child_substs = InternalSubsts::identity_for_item(tcx, did);
2553 let substs = tcx.mk_substs(parent_substs.into_iter().chain(child_substs.into_iter()));
2556 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2557 let span = tcx.hir().span(hir_id);
2558 let uneval = UnevaluatedConst::new(def.to_global(), substs);
2559 debug!(?span, ?param_env);
2561 match tcx.const_eval_resolve(param_env, uneval, Some(span)) {
2563 debug!("evaluated const value");
2567 debug!("error encountered during evaluation");
2568 // Error was handled in `const_eval_resolve`. Here we just create a
2569 // new unevaluated const and error hard later in codegen
2572 def: def.to_global(),
2573 substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
2582 pub fn from_const(c: ty::Const<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
2584 ty::ConstKind::Value(valtree) => {
2585 let const_val = tcx.valtree_to_const_val((c.ty(), valtree));
2586 Self::Val(const_val, c.ty())
2588 ty::ConstKind::Unevaluated(uv) => Self::Unevaluated(uv.expand(), c.ty()),
2594 /// An unevaluated (potentially generic) constant used in MIR.
2595 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
2596 #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
2597 pub struct UnevaluatedConst<'tcx> {
2598 pub def: ty::WithOptConstParam<DefId>,
2599 pub substs: SubstsRef<'tcx>,
2600 pub promoted: Option<Promoted>,
2603 impl<'tcx> UnevaluatedConst<'tcx> {
2604 // FIXME: probably should get rid of this method. It's also wrong to
2605 // shrink and then later expand a promoted.
2607 pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> {
2608 ty::UnevaluatedConst { def: self.def, substs: self.substs }
2612 impl<'tcx> UnevaluatedConst<'tcx> {
2615 def: ty::WithOptConstParam<DefId>,
2616 substs: SubstsRef<'tcx>,
2617 ) -> UnevaluatedConst<'tcx> {
2618 UnevaluatedConst { def, substs, promoted: Default::default() }
2622 /// A collection of projections into user types.
2624 /// They are projections because a binding can occur a part of a
2625 /// parent pattern that has been ascribed a type.
2627 /// Its a collection because there can be multiple type ascriptions on
2628 /// the path from the root of the pattern down to the binding itself.
2632 /// ```ignore (illustrative)
2633 /// struct S<'a>((i32, &'a str), String);
2634 /// let S((_, w): (i32, &'static str), _): S = ...;
2635 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2636 /// // --------------------------------- ^ (2)
2639 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2640 /// ascribed the type `(i32, &'static str)`.
2642 /// The highlights labelled `(2)` show the whole pattern being
2643 /// ascribed the type `S`.
2645 /// In this example, when we descend to `w`, we will have built up the
2646 /// following two projected types:
2648 /// * base: `S`, projection: `(base.0).1`
2649 /// * base: `(i32, &'static str)`, projection: `base.1`
2651 /// The first will lead to the constraint `w: &'1 str` (for some
2652 /// inferred region `'1`). The second will lead to the constraint `w:
2654 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
2655 pub struct UserTypeProjections {
2656 pub contents: Vec<(UserTypeProjection, Span)>,
2659 impl<'tcx> UserTypeProjections {
2660 pub fn none() -> Self {
2661 UserTypeProjections { contents: vec![] }
2664 pub fn is_empty(&self) -> bool {
2665 self.contents.is_empty()
2668 pub fn projections_and_spans(
2670 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2671 self.contents.iter()
2674 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2675 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2678 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2679 self.contents.push((user_ty.clone(), span));
2685 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2687 self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
2691 pub fn index(self) -> Self {
2692 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2695 pub fn subslice(self, from: u64, to: u64) -> Self {
2696 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2699 pub fn deref(self) -> Self {
2700 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2703 pub fn leaf(self, field: Field) -> Self {
2704 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2707 pub fn variant(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx, field: Field) -> Self {
2708 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2712 /// Encodes the effect of a user-supplied type annotation on the
2713 /// subcomponents of a pattern. The effect is determined by applying the
2714 /// given list of projections to some underlying base type. Often,
2715 /// the projection element list `projs` is empty, in which case this
2716 /// directly encodes a type in `base`. But in the case of complex patterns with
2717 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2718 /// in which case the `projs` vector is used.
2722 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2724 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2725 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2726 /// determined by finding the type of the `.0` field from `T`.
2727 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2728 pub struct UserTypeProjection {
2729 pub base: UserTypeAnnotationIndex,
2730 pub projs: Vec<ProjectionKind>,
2733 impl Copy for ProjectionKind {}
2735 impl UserTypeProjection {
2736 pub(crate) fn index(mut self) -> Self {
2737 self.projs.push(ProjectionElem::Index(()));
2741 pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2742 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2746 pub(crate) fn deref(mut self) -> Self {
2747 self.projs.push(ProjectionElem::Deref);
2751 pub(crate) fn leaf(mut self, field: Field) -> Self {
2752 self.projs.push(ProjectionElem::Field(field, ()));
2756 pub(crate) fn variant(
2758 adt_def: AdtDef<'_>,
2759 variant_index: VariantIdx,
2762 self.projs.push(ProjectionElem::Downcast(
2763 Some(adt_def.variant(variant_index).name),
2766 self.projs.push(ProjectionElem::Field(field, ()));
2771 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2772 fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
2773 Ok(UserTypeProjection {
2774 base: self.base.try_fold_with(folder)?,
2775 projs: self.projs.try_fold_with(folder)?,
2780 impl<'tcx> TypeVisitable<'tcx> for UserTypeProjection {
2781 fn visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> ControlFlow<Vs::BreakTy> {
2782 self.base.visit_with(visitor)
2783 // Note: there's nothing in `self.proj` to visit.
2787 rustc_index::newtype_index! {
2788 pub struct Promoted {
2790 DEBUG_FORMAT = "promoted[{}]"
2794 impl<'tcx> Debug for Constant<'tcx> {
2795 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2796 write!(fmt, "{}", self)
2800 impl<'tcx> Display for Constant<'tcx> {
2801 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2802 match self.ty().kind() {
2804 _ => write!(fmt, "const ")?,
2806 Display::fmt(&self.literal, fmt)
2810 impl<'tcx> Display for ConstantKind<'tcx> {
2811 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2813 ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
2814 ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2815 // FIXME(valtrees): Correctly print mir constants.
2816 ConstantKind::Unevaluated(..) => {
2817 fmt.write_str("_")?;
2824 fn pretty_print_const<'tcx>(
2826 fmt: &mut Formatter<'_>,
2829 use crate::ty::print::PrettyPrinter;
2830 ty::tls::with(|tcx| {
2831 let literal = tcx.lift(c).unwrap();
2832 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2833 cx.print_alloc_ids = true;
2834 let cx = cx.pretty_print_const(literal, print_types)?;
2835 fmt.write_str(&cx.into_buffer())?;
2840 fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
2841 write!(fmt, "b\"{}\"", byte_str.escape_ascii())
2844 fn comma_sep<'tcx>(fmt: &mut Formatter<'_>, elems: Vec<ConstantKind<'tcx>>) -> fmt::Result {
2845 let mut first = true;
2848 fmt.write_str(", ")?;
2850 fmt.write_str(&format!("{}", elem))?;
2856 // FIXME: Move that into `mir/pretty.rs`.
2857 fn pretty_print_const_value<'tcx>(
2858 ct: ConstValue<'tcx>,
2860 fmt: &mut Formatter<'_>,
2863 use crate::ty::print::PrettyPrinter;
2865 ty::tls::with(|tcx| {
2866 let ct = tcx.lift(ct).unwrap();
2867 let ty = tcx.lift(ty).unwrap();
2869 if tcx.sess.verbose() {
2870 fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?;
2874 let u8_type = tcx.types.u8;
2875 match (ct, ty.kind()) {
2876 // Byte/string slices, printed as (byte) string literals.
2877 (ConstValue::Slice { data, start, end }, ty::Ref(_, inner, _)) => {
2878 match inner.kind() {
2881 // The `inspect` here is okay since we checked the bounds, and `u8` carries
2882 // no provenance (we have an active slice reference here). We don't use
2883 // this result to affect interpreter execution.
2886 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2887 pretty_print_byte_str(fmt, byte_str)?;
2892 // The `inspect` here is okay since we checked the bounds, and `str` carries
2893 // no provenance (we have an active `str` reference here). We don't use this
2894 // result to affect interpreter execution.
2897 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2898 fmt.write_str(&format!("{:?}", String::from_utf8_lossy(slice)))?;
2904 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
2905 let n = n.kind().try_to_bits(tcx.data_layout.pointer_size).unwrap();
2906 // cast is ok because we already checked for pointer size (32 or 64 bit) above
2907 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
2908 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
2909 fmt.write_str("*")?;
2910 pretty_print_byte_str(fmt, byte_str)?;
2913 // Aggregates, printed as array/tuple/struct/variant construction syntax.
2915 // NB: the `has_non_region_param` check ensures that we can use
2916 // the `destructure_const` query with an empty `ty::ParamEnv` without
2917 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
2918 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
2919 // to be able to destructure the tuple into `(0u8, *mut T)
2921 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
2922 // correct `ty::ParamEnv` to allow printing *all* constant values.
2923 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
2924 let ct = tcx.lift(ct).unwrap();
2925 let ty = tcx.lift(ty).unwrap();
2926 if let Some(contents) = tcx.try_destructure_mir_constant(
2927 ty::ParamEnv::reveal_all().and(ConstantKind::Val(ct, ty)),
2929 let fields = contents.fields.iter().copied().collect::<Vec<_>>();
2932 fmt.write_str("[")?;
2933 comma_sep(fmt, fields)?;
2934 fmt.write_str("]")?;
2937 fmt.write_str("(")?;
2938 comma_sep(fmt, fields)?;
2939 if contents.fields.len() == 1 {
2940 fmt.write_str(",")?;
2942 fmt.write_str(")")?;
2944 ty::Adt(def, _) if def.variants().is_empty() => {
2945 fmt.write_str(&format!("{{unreachable(): {}}}", ty))?;
2947 ty::Adt(def, substs) => {
2948 let variant_idx = contents
2950 .expect("destructed mir constant of adt without variant idx");
2951 let variant_def = &def.variant(variant_idx);
2952 let substs = tcx.lift(substs).unwrap();
2953 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2954 cx.print_alloc_ids = true;
2955 let cx = cx.print_value_path(variant_def.def_id, substs)?;
2956 fmt.write_str(&cx.into_buffer())?;
2958 match variant_def.ctor_kind() {
2959 Some(CtorKind::Const) => {}
2960 Some(CtorKind::Fn) => {
2961 fmt.write_str("(")?;
2962 comma_sep(fmt, fields)?;
2963 fmt.write_str(")")?;
2966 fmt.write_str(" {{ ")?;
2967 let mut first = true;
2968 for (field_def, field) in iter::zip(&variant_def.fields, fields)
2971 fmt.write_str(", ")?;
2973 fmt.write_str(&format!("{}: {}", field_def.name, field))?;
2976 fmt.write_str(" }}")?;
2980 _ => unreachable!(),
2984 // Fall back to debug pretty printing for invalid constants.
2985 fmt.write_str(&format!("{:?}", ct))?;
2987 fmt.write_str(&format!(": {}", ty))?;
2992 (ConstValue::Scalar(scalar), _) => {
2993 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2994 cx.print_alloc_ids = true;
2995 let ty = tcx.lift(ty).unwrap();
2996 cx = cx.pretty_print_const_scalar(scalar, ty, print_ty)?;
2997 fmt.write_str(&cx.into_buffer())?;
3000 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
3001 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
3002 cx.print_alloc_ids = true;
3003 let cx = cx.print_value_path(*d, s)?;
3004 fmt.write_str(&cx.into_buffer())?;
3007 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
3008 // their fields instead of just dumping the memory.
3012 fmt.write_str(&format!("{:?}", ct))?;
3014 fmt.write_str(&format!(": {}", ty))?;
3020 /// `Location` represents the position of the start of the statement; or, if
3021 /// `statement_index` equals the number of statements, then the start of the
3023 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
3024 pub struct Location {
3025 /// The block that the location is within.
3026 pub block: BasicBlock,
3028 pub statement_index: usize,
3031 impl fmt::Debug for Location {
3032 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3033 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
3038 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
3040 /// Returns the location immediately after this one within the enclosing block.
3042 /// Note that if this location represents a terminator, then the
3043 /// resulting location would be out of bounds and invalid.
3044 pub fn successor_within_block(&self) -> Location {
3045 Location { block: self.block, statement_index: self.statement_index + 1 }
3048 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
3049 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
3050 // If we are in the same block as the other location and are an earlier statement
3051 // then we are a predecessor of `other`.
3052 if self.block == other.block && self.statement_index < other.statement_index {
3056 let predecessors = body.basic_blocks.predecessors();
3058 // If we're in another block, then we want to check that block is a predecessor of `other`.
3059 let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
3060 let mut visited = FxHashSet::default();
3062 while let Some(block) = queue.pop() {
3063 // If we haven't visited this block before, then make sure we visit its predecessors.
3064 if visited.insert(block) {
3065 queue.extend(predecessors[block].iter().cloned());
3070 // If we found the block that `self` is in, then we are a predecessor of `other` (since
3071 // we found that block by looking at the predecessors of `other`).
3072 if self.block == block {
3080 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3081 if self.block == other.block {
3082 self.statement_index <= other.statement_index
3084 dominators.is_dominated_by(other.block, self.block)
3089 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3090 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3093 use rustc_data_structures::static_assert_size;
3094 // tidy-alphabetical-start
3095 static_assert_size!(BasicBlockData<'_>, 144);
3096 static_assert_size!(LocalDecl<'_>, 56);
3097 static_assert_size!(Statement<'_>, 32);
3098 static_assert_size!(StatementKind<'_>, 16);
3099 static_assert_size!(Terminator<'_>, 112);
3100 static_assert_size!(TerminatorKind<'_>, 96);
3101 // tidy-alphabetical-end