rustc_middle/mir/
mod.rs

1//! MIR datatypes and passes. See the [rustc dev guide] for more info.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4
5use std::borrow::Cow;
6use std::fmt::{self, Debug, Formatter};
7use std::iter;
8use std::ops::{Index, IndexMut};
9
10pub use basic_blocks::{BasicBlocks, SwitchTargetValue};
11use either::Either;
12use polonius_engine::Atom;
13use rustc_abi::{FieldIdx, VariantIdx};
14pub use rustc_ast::Mutability;
15use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16use rustc_data_structures::graph::dominators::Dominators;
17use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg};
18use rustc_hir::def::{CtorKind, Namespace};
19use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
20use rustc_hir::{
21    self as hir, BindingMode, ByRef, CoroutineDesugaring, CoroutineKind, HirId, ImplicitSelfKind,
22};
23use rustc_index::bit_set::DenseBitSet;
24use rustc_index::{Idx, IndexSlice, IndexVec};
25use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
26use rustc_serialize::{Decodable, Encodable};
27use rustc_span::source_map::Spanned;
28use rustc_span::{DUMMY_SP, Span, Symbol};
29use tracing::{debug, trace};
30
31pub use self::query::*;
32use crate::mir::interpret::{AllocRange, Scalar};
33use crate::ty::codec::{TyDecoder, TyEncoder};
34use crate::ty::print::{FmtPrinter, Printer, pretty_print_const, with_no_trimmed_paths};
35use crate::ty::{
36    self, GenericArg, GenericArgsRef, Instance, InstanceKind, List, Ty, TyCtxt, TypeVisitableExt,
37    TypingEnv, UserTypeAnnotationIndex,
38};
39
40mod basic_blocks;
41mod consts;
42pub mod coverage;
43mod generic_graph;
44pub mod generic_graphviz;
45pub mod graphviz;
46pub mod interpret;
47pub mod mono;
48pub mod pretty;
49mod query;
50mod statement;
51mod syntax;
52mod terminator;
53
54pub mod traversal;
55pub mod visit;
56
57pub use consts::*;
58use pretty::pretty_print_const_value;
59pub use statement::*;
60pub use syntax::*;
61pub use terminator::*;
62
63pub use self::generic_graph::graphviz_safe_def_name;
64pub use self::graphviz::write_mir_graphviz;
65pub use self::pretty::{
66    PassWhere, create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty,
67};
68
69/// Types for locals
70pub type LocalDecls<'tcx> = IndexSlice<Local, LocalDecl<'tcx>>;
71
72pub trait HasLocalDecls<'tcx> {
73    fn local_decls(&self) -> &LocalDecls<'tcx>;
74}
75
76impl<'tcx> HasLocalDecls<'tcx> for IndexVec<Local, LocalDecl<'tcx>> {
77    #[inline]
78    fn local_decls(&self) -> &LocalDecls<'tcx> {
79        self
80    }
81}
82
83impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
84    #[inline]
85    fn local_decls(&self) -> &LocalDecls<'tcx> {
86        self
87    }
88}
89
90impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
91    #[inline]
92    fn local_decls(&self) -> &LocalDecls<'tcx> {
93        &self.local_decls
94    }
95}
96
97impl MirPhase {
98    pub fn name(&self) -> &'static str {
99        match *self {
100            MirPhase::Built => "built",
101            MirPhase::Analysis(AnalysisPhase::Initial) => "analysis",
102            MirPhase::Analysis(AnalysisPhase::PostCleanup) => "analysis-post-cleanup",
103            MirPhase::Runtime(RuntimePhase::Initial) => "runtime",
104            MirPhase::Runtime(RuntimePhase::PostCleanup) => "runtime-post-cleanup",
105            MirPhase::Runtime(RuntimePhase::Optimized) => "runtime-optimized",
106        }
107    }
108
109    /// Gets the (dialect, phase) index of the current `MirPhase`. Both numbers
110    /// are 1-indexed.
111    pub fn index(&self) -> (usize, usize) {
112        match *self {
113            MirPhase::Built => (1, 1),
114            MirPhase::Analysis(analysis_phase) => (2, 1 + analysis_phase as usize),
115            MirPhase::Runtime(runtime_phase) => (3, 1 + runtime_phase as usize),
116        }
117    }
118}
119
120/// Where a specific `mir::Body` comes from.
121#[derive(Copy, Clone, Debug, PartialEq, Eq)]
122#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
123pub struct MirSource<'tcx> {
124    pub instance: InstanceKind<'tcx>,
125
126    /// If `Some`, this is a promoted rvalue within the parent function.
127    pub promoted: Option<Promoted>,
128}
129
130impl<'tcx> MirSource<'tcx> {
131    pub fn item(def_id: DefId) -> Self {
132        MirSource { instance: InstanceKind::Item(def_id), promoted: None }
133    }
134
135    pub fn from_instance(instance: InstanceKind<'tcx>) -> Self {
136        MirSource { instance, promoted: None }
137    }
138
139    #[inline]
140    pub fn def_id(&self) -> DefId {
141        self.instance.def_id()
142    }
143}
144
145/// Additional information carried by a MIR body when it is lowered from a coroutine.
146/// This information is modified as it is lowered during the `StateTransform` MIR pass,
147/// so not all fields will be active at a given time. For example, the `yield_ty` is
148/// taken out of the field after yields are turned into returns, and the `coroutine_drop`
149/// body is only populated after the state transform pass.
150#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
151pub struct CoroutineInfo<'tcx> {
152    /// The yield type of the function. This field is removed after the state transform pass.
153    pub yield_ty: Option<Ty<'tcx>>,
154
155    /// The resume type of the function. This field is removed after the state transform pass.
156    pub resume_ty: Option<Ty<'tcx>>,
157
158    /// Coroutine drop glue. This field is populated after the state transform pass.
159    pub coroutine_drop: Option<Body<'tcx>>,
160
161    /// Coroutine async drop glue.
162    pub coroutine_drop_async: Option<Body<'tcx>>,
163
164    /// When coroutine has sync drop, this is async proxy calling `coroutine_drop` sync impl.
165    pub coroutine_drop_proxy_async: Option<Body<'tcx>>,
166
167    /// The layout of a coroutine. Produced by the state transformation.
168    pub coroutine_layout: Option<CoroutineLayout<'tcx>>,
169
170    /// If this is a coroutine then record the type of source expression that caused this coroutine
171    /// to be created.
172    pub coroutine_kind: CoroutineKind,
173}
174
175impl<'tcx> CoroutineInfo<'tcx> {
176    // Sets up `CoroutineInfo` for a pre-coroutine-transform MIR body.
177    pub fn initial(
178        coroutine_kind: CoroutineKind,
179        yield_ty: Ty<'tcx>,
180        resume_ty: Ty<'tcx>,
181    ) -> CoroutineInfo<'tcx> {
182        CoroutineInfo {
183            coroutine_kind,
184            yield_ty: Some(yield_ty),
185            resume_ty: Some(resume_ty),
186            coroutine_drop: None,
187            coroutine_drop_async: None,
188            coroutine_drop_proxy_async: None,
189            coroutine_layout: None,
190        }
191    }
192}
193
194/// Some item that needs to monomorphize successfully for a MIR body to be considered well-formed.
195#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, HashStable, TyEncodable, TyDecodable)]
196#[derive(TypeFoldable, TypeVisitable)]
197pub enum MentionedItem<'tcx> {
198    /// A function that gets called. We don't necessarily know its precise type yet, since it can be
199    /// hidden behind a generic.
200    Fn(Ty<'tcx>),
201    /// A type that has its drop shim called.
202    Drop(Ty<'tcx>),
203    /// Unsizing casts might require vtables, so we have to record them.
204    UnsizeCast { source_ty: Ty<'tcx>, target_ty: Ty<'tcx> },
205    /// A closure that is coerced to a function pointer.
206    Closure(Ty<'tcx>),
207}
208
209/// The lowered representation of a single function.
210#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
211pub struct Body<'tcx> {
212    /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
213    /// that indexes into this vector.
214    pub basic_blocks: BasicBlocks<'tcx>,
215
216    /// Records how far through the "desugaring and optimization" process this particular
217    /// MIR has traversed. This is particularly useful when inlining, since in that context
218    /// we instantiate the promoted constants and add them to our promoted vector -- but those
219    /// promoted items have already been optimized, whereas ours have not. This field allows
220    /// us to see the difference and forego optimization on the inlined promoted items.
221    pub phase: MirPhase,
222
223    /// How many passes we have executed since starting the current phase. Used for debug output.
224    pub pass_count: usize,
225
226    pub source: MirSource<'tcx>,
227
228    /// A list of source scopes; these are referenced by statements
229    /// and used for debuginfo. Indexed by a `SourceScope`.
230    pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
231
232    /// Additional information carried by a MIR body when it is lowered from a coroutine.
233    ///
234    /// Note that the coroutine drop shim, any promoted consts, and other synthetic MIR
235    /// bodies that come from processing a coroutine body are not typically coroutines
236    /// themselves, and should probably set this to `None` to avoid carrying redundant
237    /// information.
238    pub coroutine: Option<Box<CoroutineInfo<'tcx>>>,
239
240    /// Declarations of locals.
241    ///
242    /// The first local is the return value pointer, followed by `arg_count`
243    /// locals for the function arguments, followed by any user-declared
244    /// variables and temporaries.
245    pub local_decls: IndexVec<Local, LocalDecl<'tcx>>,
246
247    /// User type annotations.
248    pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
249
250    /// The number of arguments this function takes.
251    ///
252    /// Starting at local 1, `arg_count` locals will be provided by the caller
253    /// and can be assumed to be initialized.
254    ///
255    /// If this MIR was built for a constant, this will be 0.
256    pub arg_count: usize,
257
258    /// Mark an argument local (which must be a tuple) as getting passed as
259    /// its individual components at the LLVM level.
260    ///
261    /// This is used for the "rust-call" ABI.
262    pub spread_arg: Option<Local>,
263
264    /// Debug information pertaining to user variables, including captures.
265    pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
266
267    /// A span representing this MIR, for error reporting.
268    pub span: Span,
269
270    /// Constants that are required to evaluate successfully for this MIR to be well-formed.
271    /// We hold in this field all the constants we are not able to evaluate yet.
272    /// `None` indicates that the list has not been computed yet.
273    ///
274    /// This is soundness-critical, we make a guarantee that all consts syntactically mentioned in a
275    /// function have successfully evaluated if the function ever gets executed at runtime.
276    pub required_consts: Option<Vec<ConstOperand<'tcx>>>,
277
278    /// Further items that were mentioned in this function and hence *may* become monomorphized,
279    /// depending on optimizations. We use this to avoid optimization-dependent compile errors: the
280    /// collector recursively traverses all "mentioned" items and evaluates all their
281    /// `required_consts`.
282    /// `None` indicates that the list has not been computed yet.
283    ///
284    /// This is *not* soundness-critical and the contents of this list are *not* a stable guarantee.
285    /// All that's relevant is that this set is optimization-level-independent, and that it includes
286    /// everything that the collector would consider "used". (For example, we currently compute this
287    /// set after drop elaboration, so some drop calls that can never be reached are not considered
288    /// "mentioned".) See the documentation of `CollectionMode` in
289    /// `compiler/rustc_monomorphize/src/collector.rs` for more context.
290    pub mentioned_items: Option<Vec<Spanned<MentionedItem<'tcx>>>>,
291
292    /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
293    ///
294    /// Note that this does not actually mean that this body is not computable right now.
295    /// The repeat count in the following example is polymorphic, but can still be evaluated
296    /// without knowing anything about the type parameter `T`.
297    ///
298    /// ```rust
299    /// fn test<T>() {
300    ///     let _ = [0; size_of::<*mut T>()];
301    /// }
302    /// ```
303    ///
304    /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
305    /// removed the last mention of all generic params. We do not want to rely on optimizations and
306    /// potentially allow things like `[u8; size_of::<T>() * 0]` due to this.
307    pub is_polymorphic: bool,
308
309    /// The phase at which this MIR should be "injected" into the compilation process.
310    ///
311    /// Everything that comes before this `MirPhase` should be skipped.
312    ///
313    /// This is only `Some` if the function that this body comes from was annotated with `rustc_custom_mir`.
314    pub injection_phase: Option<MirPhase>,
315
316    pub tainted_by_errors: Option<ErrorGuaranteed>,
317
318    /// Coverage information collected from THIR/MIR during MIR building,
319    /// to be used by the `InstrumentCoverage` pass.
320    ///
321    /// Only present if coverage is enabled and this function is eligible.
322    /// Boxed to limit space overhead in non-coverage builds.
323    #[type_foldable(identity)]
324    #[type_visitable(ignore)]
325    pub coverage_info_hi: Option<Box<coverage::CoverageInfoHi>>,
326
327    /// Per-function coverage information added by the `InstrumentCoverage`
328    /// pass, to be used in conjunction with the coverage statements injected
329    /// into this body's blocks.
330    ///
331    /// If `-Cinstrument-coverage` is not active, or if an individual function
332    /// is not eligible for coverage, then this should always be `None`.
333    #[type_foldable(identity)]
334    #[type_visitable(ignore)]
335    pub function_coverage_info: Option<Box<coverage::FunctionCoverageInfo>>,
336}
337
338impl<'tcx> Body<'tcx> {
339    pub fn new(
340        source: MirSource<'tcx>,
341        basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
342        source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
343        local_decls: IndexVec<Local, LocalDecl<'tcx>>,
344        user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
345        arg_count: usize,
346        var_debug_info: Vec<VarDebugInfo<'tcx>>,
347        span: Span,
348        coroutine: Option<Box<CoroutineInfo<'tcx>>>,
349        tainted_by_errors: Option<ErrorGuaranteed>,
350    ) -> Self {
351        // We need `arg_count` locals, and one for the return place.
352        assert!(
353            local_decls.len() > arg_count,
354            "expected at least {} locals, got {}",
355            arg_count + 1,
356            local_decls.len()
357        );
358
359        let mut body = Body {
360            phase: MirPhase::Built,
361            pass_count: 0,
362            source,
363            basic_blocks: BasicBlocks::new(basic_blocks),
364            source_scopes,
365            coroutine,
366            local_decls,
367            user_type_annotations,
368            arg_count,
369            spread_arg: None,
370            var_debug_info,
371            span,
372            required_consts: None,
373            mentioned_items: None,
374            is_polymorphic: false,
375            injection_phase: None,
376            tainted_by_errors,
377            coverage_info_hi: None,
378            function_coverage_info: None,
379        };
380        body.is_polymorphic = body.has_non_region_param();
381        body
382    }
383
384    /// Returns a partially initialized MIR body containing only a list of basic blocks.
385    ///
386    /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
387    /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
388    /// crate.
389    pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
390        let mut body = Body {
391            phase: MirPhase::Built,
392            pass_count: 0,
393            source: MirSource::item(CRATE_DEF_ID.to_def_id()),
394            basic_blocks: BasicBlocks::new(basic_blocks),
395            source_scopes: IndexVec::new(),
396            coroutine: None,
397            local_decls: IndexVec::new(),
398            user_type_annotations: IndexVec::new(),
399            arg_count: 0,
400            spread_arg: None,
401            span: DUMMY_SP,
402            required_consts: None,
403            mentioned_items: None,
404            var_debug_info: Vec::new(),
405            is_polymorphic: false,
406            injection_phase: None,
407            tainted_by_errors: None,
408            coverage_info_hi: None,
409            function_coverage_info: None,
410        };
411        body.is_polymorphic = body.has_non_region_param();
412        body
413    }
414
415    #[inline]
416    pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
417        self.basic_blocks.as_mut()
418    }
419
420    pub fn typing_env(&self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
421        match self.phase {
422            // FIXME(#132279): we should reveal the opaques defined in the body during analysis.
423            MirPhase::Built | MirPhase::Analysis(_) => TypingEnv {
424                typing_mode: ty::TypingMode::non_body_analysis(),
425                param_env: tcx.param_env(self.source.def_id()),
426            },
427            MirPhase::Runtime(_) => TypingEnv::post_analysis(tcx, self.source.def_id()),
428        }
429    }
430
431    #[inline]
432    pub fn local_kind(&self, local: Local) -> LocalKind {
433        let index = local.as_usize();
434        if index == 0 {
435            debug_assert!(
436                self.local_decls[local].mutability == Mutability::Mut,
437                "return place should be mutable"
438            );
439
440            LocalKind::ReturnPointer
441        } else if index < self.arg_count + 1 {
442            LocalKind::Arg
443        } else {
444            LocalKind::Temp
445        }
446    }
447
448    /// Returns an iterator over all user-declared mutable locals.
449    #[inline]
450    pub fn mut_vars_iter(&self) -> impl Iterator<Item = Local> {
451        (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
452            let local = Local::new(index);
453            let decl = &self.local_decls[local];
454            (decl.is_user_variable() && decl.mutability.is_mut()).then_some(local)
455        })
456    }
457
458    /// Returns an iterator over all user-declared mutable arguments and locals.
459    #[inline]
460    pub fn mut_vars_and_args_iter(&self) -> impl Iterator<Item = Local> {
461        (1..self.local_decls.len()).filter_map(move |index| {
462            let local = Local::new(index);
463            let decl = &self.local_decls[local];
464            if (decl.is_user_variable() || index < self.arg_count + 1)
465                && decl.mutability == Mutability::Mut
466            {
467                Some(local)
468            } else {
469                None
470            }
471        })
472    }
473
474    /// Returns an iterator over all function arguments.
475    #[inline]
476    pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
477        (1..self.arg_count + 1).map(Local::new)
478    }
479
480    /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
481    /// locals that are neither arguments nor the return place).
482    #[inline]
483    pub fn vars_and_temps_iter(
484        &self,
485    ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
486        (self.arg_count + 1..self.local_decls.len()).map(Local::new)
487    }
488
489    #[inline]
490    pub fn drain_vars_and_temps(&mut self) -> impl Iterator<Item = LocalDecl<'tcx>> {
491        self.local_decls.drain(self.arg_count + 1..)
492    }
493
494    /// Returns the source info associated with `location`.
495    pub fn source_info(&self, location: Location) -> &SourceInfo {
496        let block = &self[location.block];
497        let stmts = &block.statements;
498        let idx = location.statement_index;
499        if idx < stmts.len() {
500            &stmts[idx].source_info
501        } else {
502            assert_eq!(idx, stmts.len());
503            &block.terminator().source_info
504        }
505    }
506
507    /// Returns the return type; it always return first element from `local_decls` array.
508    #[inline]
509    pub fn return_ty(&self) -> Ty<'tcx> {
510        self.local_decls[RETURN_PLACE].ty
511    }
512
513    /// Returns the return type; it always return first element from `local_decls` array.
514    #[inline]
515    pub fn bound_return_ty(&self) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
516        ty::EarlyBinder::bind(self.local_decls[RETURN_PLACE].ty)
517    }
518
519    /// Gets the location of the terminator for the given block.
520    #[inline]
521    pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
522        Location { block: bb, statement_index: self[bb].statements.len() }
523    }
524
525    pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
526        let Location { block, statement_index } = location;
527        let block_data = &self.basic_blocks[block];
528        block_data
529            .statements
530            .get(statement_index)
531            .map(Either::Left)
532            .unwrap_or_else(|| Either::Right(block_data.terminator()))
533    }
534
535    #[inline]
536    pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
537        self.coroutine.as_ref().and_then(|coroutine| coroutine.yield_ty)
538    }
539
540    #[inline]
541    pub fn resume_ty(&self) -> Option<Ty<'tcx>> {
542        self.coroutine.as_ref().and_then(|coroutine| coroutine.resume_ty)
543    }
544
545    /// Prefer going through [`TyCtxt::coroutine_layout`] rather than using this directly.
546    #[inline]
547    pub fn coroutine_layout_raw(&self) -> Option<&CoroutineLayout<'tcx>> {
548        self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_layout.as_ref())
549    }
550
551    #[inline]
552    pub fn coroutine_drop(&self) -> Option<&Body<'tcx>> {
553        self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_drop.as_ref())
554    }
555
556    #[inline]
557    pub fn coroutine_drop_async(&self) -> Option<&Body<'tcx>> {
558        self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_drop_async.as_ref())
559    }
560
561    #[inline]
562    pub fn coroutine_requires_async_drop(&self) -> bool {
563        self.coroutine_drop_async().is_some()
564    }
565
566    #[inline]
567    pub fn future_drop_poll(&self) -> Option<&Body<'tcx>> {
568        self.coroutine.as_ref().and_then(|coroutine| {
569            coroutine
570                .coroutine_drop_async
571                .as_ref()
572                .or(coroutine.coroutine_drop_proxy_async.as_ref())
573        })
574    }
575
576    #[inline]
577    pub fn coroutine_kind(&self) -> Option<CoroutineKind> {
578        self.coroutine.as_ref().map(|coroutine| coroutine.coroutine_kind)
579    }
580
581    #[inline]
582    pub fn should_skip(&self) -> bool {
583        let Some(injection_phase) = self.injection_phase else {
584            return false;
585        };
586        injection_phase > self.phase
587    }
588
589    #[inline]
590    pub fn is_custom_mir(&self) -> bool {
591        self.injection_phase.is_some()
592    }
593
594    /// If this basic block ends with a [`TerminatorKind::SwitchInt`] for which we can evaluate the
595    /// discriminant in monomorphization, we return the discriminant bits and the
596    /// [`SwitchTargets`], just so the caller doesn't also have to match on the terminator.
597    fn try_const_mono_switchint<'a>(
598        tcx: TyCtxt<'tcx>,
599        instance: Instance<'tcx>,
600        block: &'a BasicBlockData<'tcx>,
601    ) -> Option<(u128, &'a SwitchTargets)> {
602        // There are two places here we need to evaluate a constant.
603        let eval_mono_const = |constant: &ConstOperand<'tcx>| {
604            // FIXME(#132279): what is this, why are we using an empty environment here.
605            let typing_env = ty::TypingEnv::fully_monomorphized();
606            let mono_literal = instance.instantiate_mir_and_normalize_erasing_regions(
607                tcx,
608                typing_env,
609                crate::ty::EarlyBinder::bind(constant.const_),
610            );
611            mono_literal.try_eval_bits(tcx, typing_env)
612        };
613
614        let TerminatorKind::SwitchInt { discr, targets } = &block.terminator().kind else {
615            return None;
616        };
617
618        // If this is a SwitchInt(const _), then we can just evaluate the constant and return.
619        let discr = match discr {
620            Operand::Constant(constant) => {
621                let bits = eval_mono_const(constant)?;
622                return Some((bits, targets));
623            }
624            Operand::Move(place) | Operand::Copy(place) => place,
625        };
626
627        // MIR for `if false` actually looks like this:
628        // _1 = const _
629        // SwitchInt(_1)
630        //
631        // And MIR for if intrinsics::ub_checks() looks like this:
632        // _1 = UbChecks()
633        // SwitchInt(_1)
634        //
635        // So we're going to try to recognize this pattern.
636        //
637        // If we have a SwitchInt on a non-const place, we find the most recent statement that
638        // isn't a storage marker. If that statement is an assignment of a const to our
639        // discriminant place, we evaluate and return the const, as if we've const-propagated it
640        // into the SwitchInt.
641
642        let last_stmt = block.statements.iter().rev().find(|stmt| {
643            !matches!(stmt.kind, StatementKind::StorageDead(_) | StatementKind::StorageLive(_))
644        })?;
645
646        let (place, rvalue) = last_stmt.kind.as_assign()?;
647
648        if discr != place {
649            return None;
650        }
651
652        match rvalue {
653            Rvalue::NullaryOp(NullOp::UbChecks, _) => Some((tcx.sess.ub_checks() as u128, targets)),
654            Rvalue::Use(Operand::Constant(constant)) => {
655                let bits = eval_mono_const(constant)?;
656                Some((bits, targets))
657            }
658            _ => None,
659        }
660    }
661
662    /// For a `Location` in this scope, determine what the "caller location" at that point is. This
663    /// is interesting because of inlining: the `#[track_caller]` attribute of inlined functions
664    /// must be honored. Falls back to the `tracked_caller` value for `#[track_caller]` functions,
665    /// or the function's scope.
666    pub fn caller_location_span<T>(
667        &self,
668        mut source_info: SourceInfo,
669        caller_location: Option<T>,
670        tcx: TyCtxt<'tcx>,
671        from_span: impl FnOnce(Span) -> T,
672    ) -> T {
673        loop {
674            let scope_data = &self.source_scopes[source_info.scope];
675
676            if let Some((callee, callsite_span)) = scope_data.inlined {
677                // Stop inside the most nested non-`#[track_caller]` function,
678                // before ever reaching its caller (which is irrelevant).
679                if !callee.def.requires_caller_location(tcx) {
680                    return from_span(source_info.span);
681                }
682                source_info.span = callsite_span;
683            }
684
685            // Skip past all of the parents with `inlined: None`.
686            match scope_data.inlined_parent_scope {
687                Some(parent) => source_info.scope = parent,
688                None => break,
689            }
690        }
691
692        // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
693        caller_location.unwrap_or_else(|| from_span(source_info.span))
694    }
695
696    #[track_caller]
697    pub fn set_required_consts(&mut self, required_consts: Vec<ConstOperand<'tcx>>) {
698        assert!(
699            self.required_consts.is_none(),
700            "required_consts for {:?} have already been set",
701            self.source.def_id()
702        );
703        self.required_consts = Some(required_consts);
704    }
705    #[track_caller]
706    pub fn required_consts(&self) -> &[ConstOperand<'tcx>] {
707        match &self.required_consts {
708            Some(l) => l,
709            None => panic!("required_consts for {:?} have not yet been set", self.source.def_id()),
710        }
711    }
712
713    #[track_caller]
714    pub fn set_mentioned_items(&mut self, mentioned_items: Vec<Spanned<MentionedItem<'tcx>>>) {
715        assert!(
716            self.mentioned_items.is_none(),
717            "mentioned_items for {:?} have already been set",
718            self.source.def_id()
719        );
720        self.mentioned_items = Some(mentioned_items);
721    }
722    #[track_caller]
723    pub fn mentioned_items(&self) -> &[Spanned<MentionedItem<'tcx>>] {
724        match &self.mentioned_items {
725            Some(l) => l,
726            None => panic!("mentioned_items for {:?} have not yet been set", self.source.def_id()),
727        }
728    }
729}
730
731impl<'tcx> Index<BasicBlock> for Body<'tcx> {
732    type Output = BasicBlockData<'tcx>;
733
734    #[inline]
735    fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
736        &self.basic_blocks[index]
737    }
738}
739
740impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
741    #[inline]
742    fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
743        &mut self.basic_blocks.as_mut()[index]
744    }
745}
746
747#[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)]
748pub enum ClearCrossCrate<T> {
749    Clear,
750    Set(T),
751}
752
753impl<T> ClearCrossCrate<T> {
754    pub fn as_ref(&self) -> ClearCrossCrate<&T> {
755        match self {
756            ClearCrossCrate::Clear => ClearCrossCrate::Clear,
757            ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
758        }
759    }
760
761    pub fn as_mut(&mut self) -> ClearCrossCrate<&mut T> {
762        match self {
763            ClearCrossCrate::Clear => ClearCrossCrate::Clear,
764            ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
765        }
766    }
767
768    pub fn unwrap_crate_local(self) -> T {
769        match self {
770            ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
771            ClearCrossCrate::Set(v) => v,
772        }
773    }
774}
775
776const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
777const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
778
779impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
780    #[inline]
781    fn encode(&self, e: &mut E) {
782        if E::CLEAR_CROSS_CRATE {
783            return;
784        }
785
786        match *self {
787            ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
788            ClearCrossCrate::Set(ref val) => {
789                TAG_CLEAR_CROSS_CRATE_SET.encode(e);
790                val.encode(e);
791            }
792        }
793    }
794}
795impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
796    #[inline]
797    fn decode(d: &mut D) -> ClearCrossCrate<T> {
798        if D::CLEAR_CROSS_CRATE {
799            return ClearCrossCrate::Clear;
800        }
801
802        let discr = u8::decode(d);
803
804        match discr {
805            TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
806            TAG_CLEAR_CROSS_CRATE_SET => {
807                let val = T::decode(d);
808                ClearCrossCrate::Set(val)
809            }
810            tag => panic!("Invalid tag for ClearCrossCrate: {tag:?}"),
811        }
812    }
813}
814
815/// Grouped information about the source code origin of a MIR entity.
816/// Intended to be inspected by diagnostics and debuginfo.
817/// Most passes can work with it as a whole, within a single function.
818// The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
819// `Hash`. Please ping @bjorn3 if removing them.
820#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
821pub struct SourceInfo {
822    /// The source span for the AST pertaining to this MIR entity.
823    pub span: Span,
824
825    /// The source scope, keeping track of which bindings can be
826    /// seen by debuginfo, active lint levels, etc.
827    pub scope: SourceScope,
828}
829
830impl SourceInfo {
831    #[inline]
832    pub fn outermost(span: Span) -> Self {
833        SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
834    }
835}
836
837///////////////////////////////////////////////////////////////////////////
838// Variables and temps
839
840rustc_index::newtype_index! {
841    #[derive(HashStable)]
842    #[encodable]
843    #[orderable]
844    #[debug_format = "_{}"]
845    pub struct Local {
846        const RETURN_PLACE = 0;
847    }
848}
849
850impl Atom for Local {
851    fn index(self) -> usize {
852        Idx::index(self)
853    }
854}
855
856/// Classifies locals into categories. See `Body::local_kind`.
857#[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
858pub enum LocalKind {
859    /// User-declared variable binding or compiler-introduced temporary.
860    Temp,
861    /// Function argument.
862    Arg,
863    /// Location of function's return value.
864    ReturnPointer,
865}
866
867#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
868pub struct VarBindingForm<'tcx> {
869    /// Is variable bound via `x`, `mut x`, `ref x`, `ref mut x`, `mut ref x`, or `mut ref mut x`?
870    pub binding_mode: BindingMode,
871    /// If an explicit type was provided for this variable binding,
872    /// this holds the source Span of that type.
873    ///
874    /// NOTE: if you want to change this to a `HirId`, be wary that
875    /// doing so breaks incremental compilation (as of this writing),
876    /// while a `Span` does not cause our tests to fail.
877    pub opt_ty_info: Option<Span>,
878    /// Place of the RHS of the =, or the subject of the `match` where this
879    /// variable is initialized. None in the case of `let PATTERN;`.
880    /// Some((None, ..)) in the case of and `let [mut] x = ...` because
881    /// (a) the right-hand side isn't evaluated as a place expression.
882    /// (b) it gives a way to separate this case from the remaining cases
883    ///     for diagnostics.
884    pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
885    /// The span of the pattern in which this variable was bound.
886    pub pat_span: Span,
887}
888
889#[derive(Clone, Debug, TyEncodable, TyDecodable)]
890pub enum BindingForm<'tcx> {
891    /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
892    Var(VarBindingForm<'tcx>),
893    /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
894    ImplicitSelf(ImplicitSelfKind),
895    /// Reference used in a guard expression to ensure immutability.
896    RefForGuard,
897}
898
899mod binding_form_impl {
900    use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
901    use rustc_query_system::ich::StableHashingContext;
902
903    impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
904        fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
905            use super::BindingForm::*;
906            std::mem::discriminant(self).hash_stable(hcx, hasher);
907
908            match self {
909                Var(binding) => binding.hash_stable(hcx, hasher),
910                ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
911                RefForGuard => (),
912            }
913        }
914    }
915}
916
917/// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
918/// created during evaluation of expressions in a block tail
919/// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
920///
921/// It is used to improve diagnostics when such temporaries are
922/// involved in borrow_check errors, e.g., explanations of where the
923/// temporaries come from, when their destructors are run, and/or how
924/// one might revise the code to satisfy the borrow checker's rules.
925#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
926pub struct BlockTailInfo {
927    /// If `true`, then the value resulting from evaluating this tail
928    /// expression is ignored by the block's expression context.
929    ///
930    /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
931    /// but not e.g., `let _x = { ...; tail };`
932    pub tail_result_is_ignored: bool,
933
934    /// `Span` of the tail expression.
935    pub span: Span,
936}
937
938/// A MIR local.
939///
940/// This can be a binding declared by the user, a temporary inserted by the compiler, a function
941/// argument, or the return place.
942#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
943pub struct LocalDecl<'tcx> {
944    /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
945    ///
946    /// Temporaries and the return place are always mutable.
947    pub mutability: Mutability,
948
949    pub local_info: ClearCrossCrate<Box<LocalInfo<'tcx>>>,
950
951    /// The type of this local.
952    pub ty: Ty<'tcx>,
953
954    /// If the user manually ascribed a type to this variable,
955    /// e.g., via `let x: T`, then we carry that type here. The MIR
956    /// borrow checker needs this information since it can affect
957    /// region inference.
958    pub user_ty: Option<Box<UserTypeProjections>>,
959
960    /// The *syntactic* (i.e., not visibility) source scope the local is defined
961    /// in. If the local was defined in a let-statement, this
962    /// is *within* the let-statement, rather than outside
963    /// of it.
964    ///
965    /// This is needed because the visibility source scope of locals within
966    /// a let-statement is weird.
967    ///
968    /// The reason is that we want the local to be *within* the let-statement
969    /// for lint purposes, but we want the local to be *after* the let-statement
970    /// for names-in-scope purposes.
971    ///
972    /// That's it, if we have a let-statement like the one in this
973    /// function:
974    ///
975    /// ```
976    /// fn foo(x: &str) {
977    ///     #[allow(unused_mut)]
978    ///     let mut x: u32 = {
979    ///         //^ one unused mut
980    ///         let mut y: u32 = x.parse().unwrap();
981    ///         y + 2
982    ///     };
983    ///     drop(x);
984    /// }
985    /// ```
986    ///
987    /// Then, from a lint point of view, the declaration of `x: u32`
988    /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
989    /// lint scopes are the same as the AST/HIR nesting.
990    ///
991    /// However, from a name lookup point of view, the scopes look more like
992    /// as if the let-statements were `match` expressions:
993    ///
994    /// ```
995    /// fn foo(x: &str) {
996    ///     match {
997    ///         match x.parse::<u32>().unwrap() {
998    ///             y => y + 2
999    ///         }
1000    ///     } {
1001    ///         x => drop(x)
1002    ///     };
1003    /// }
1004    /// ```
1005    ///
1006    /// We care about the name-lookup scopes for debuginfo - if the
1007    /// debuginfo instruction pointer is at the call to `x.parse()`, we
1008    /// want `x` to refer to `x: &str`, but if it is at the call to
1009    /// `drop(x)`, we want it to refer to `x: u32`.
1010    ///
1011    /// To allow both uses to work, we need to have more than a single scope
1012    /// for a local. We have the `source_info.scope` represent the "syntactic"
1013    /// lint scope (with a variable being under its let block) while the
1014    /// `var_debug_info.source_info.scope` represents the "local variable"
1015    /// scope (where the "rest" of a block is under all prior let-statements).
1016    ///
1017    /// The end result looks like this:
1018    ///
1019    /// ```text
1020    /// ROOT SCOPE
1021    ///  │{ argument x: &str }
1022    ///  │
1023    ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
1024    ///  │ │                         // in practice because I'm lazy.
1025    ///  │ │
1026    ///  │ │← x.source_info.scope
1027    ///  │ │← `x.parse().unwrap()`
1028    ///  │ │
1029    ///  │ │ │← y.source_info.scope
1030    ///  │ │
1031    ///  │ │ │{ let y: u32 }
1032    ///  │ │ │
1033    ///  │ │ │← y.var_debug_info.source_info.scope
1034    ///  │ │ │← `y + 2`
1035    ///  │
1036    ///  │ │{ let x: u32 }
1037    ///  │ │← x.var_debug_info.source_info.scope
1038    ///  │ │← `drop(x)` // This accesses `x: u32`.
1039    /// ```
1040    pub source_info: SourceInfo,
1041}
1042
1043/// Extra information about a some locals that's used for diagnostics and for
1044/// classifying variables into local variables, statics, etc, which is needed e.g.
1045/// for borrow checking.
1046///
1047/// Not used for non-StaticRef temporaries, the return place, or anonymous
1048/// function parameters.
1049#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1050pub enum LocalInfo<'tcx> {
1051    /// A user-defined local variable or function parameter
1052    ///
1053    /// The `BindingForm` is solely used for local diagnostics when generating
1054    /// warnings/errors when compiling the current crate, and therefore it need
1055    /// not be visible across crates.
1056    User(BindingForm<'tcx>),
1057    /// A temporary created that references the static with the given `DefId`.
1058    StaticRef { def_id: DefId, is_thread_local: bool },
1059    /// A temporary created that references the const with the given `DefId`
1060    ConstRef { def_id: DefId },
1061    /// A temporary created during the creation of an aggregate
1062    /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
1063    AggregateTemp,
1064    /// A temporary created for evaluation of some subexpression of some block's tail expression
1065    /// (with no intervening statement context).
1066    BlockTailTemp(BlockTailInfo),
1067    /// A temporary created during evaluating `if` predicate, possibly for pattern matching for `let`s,
1068    /// and subject to Edition 2024 temporary lifetime rules
1069    IfThenRescopeTemp { if_then: HirId },
1070    /// A temporary created during the pass `Derefer` to avoid it's retagging
1071    DerefTemp,
1072    /// A temporary created for borrow checking.
1073    FakeBorrow,
1074    /// A local without anything interesting about it.
1075    Boring,
1076}
1077
1078impl<'tcx> LocalDecl<'tcx> {
1079    pub fn local_info(&self) -> &LocalInfo<'tcx> {
1080        self.local_info.as_ref().unwrap_crate_local()
1081    }
1082
1083    /// Returns `true` only if local is a binding that can itself be
1084    /// made mutable via the addition of the `mut` keyword, namely
1085    /// something like the occurrences of `x` in:
1086    /// - `fn foo(x: Type) { ... }`,
1087    /// - `let x = ...`,
1088    /// - or `match ... { C(x) => ... }`
1089    pub fn can_be_made_mutable(&self) -> bool {
1090        matches!(
1091            self.local_info(),
1092            LocalInfo::User(
1093                BindingForm::Var(VarBindingForm {
1094                    binding_mode: BindingMode(ByRef::No, _),
1095                    opt_ty_info: _,
1096                    opt_match_place: _,
1097                    pat_span: _,
1098                }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
1099            )
1100        )
1101    }
1102
1103    /// Returns `true` if local is definitely not a `ref ident` or
1104    /// `ref mut ident` binding. (Such bindings cannot be made into
1105    /// mutable bindings, but the inverse does not necessarily hold).
1106    pub fn is_nonref_binding(&self) -> bool {
1107        matches!(
1108            self.local_info(),
1109            LocalInfo::User(
1110                BindingForm::Var(VarBindingForm {
1111                    binding_mode: BindingMode(ByRef::No, _),
1112                    opt_ty_info: _,
1113                    opt_match_place: _,
1114                    pat_span: _,
1115                }) | BindingForm::ImplicitSelf(_),
1116            )
1117        )
1118    }
1119
1120    /// Returns `true` if this variable is a named variable or function
1121    /// parameter declared by the user.
1122    #[inline]
1123    pub fn is_user_variable(&self) -> bool {
1124        matches!(self.local_info(), LocalInfo::User(_))
1125    }
1126
1127    /// Returns `true` if this is a reference to a variable bound in a `match`
1128    /// expression that is used to access said variable for the guard of the
1129    /// match arm.
1130    pub fn is_ref_for_guard(&self) -> bool {
1131        matches!(self.local_info(), LocalInfo::User(BindingForm::RefForGuard))
1132    }
1133
1134    /// Returns `Some` if this is a reference to a static item that is used to
1135    /// access that static.
1136    pub fn is_ref_to_static(&self) -> bool {
1137        matches!(self.local_info(), LocalInfo::StaticRef { .. })
1138    }
1139
1140    /// Returns `Some` if this is a reference to a thread-local static item that is used to
1141    /// access that static.
1142    pub fn is_ref_to_thread_local(&self) -> bool {
1143        match self.local_info() {
1144            LocalInfo::StaticRef { is_thread_local, .. } => *is_thread_local,
1145            _ => false,
1146        }
1147    }
1148
1149    /// Returns `true` if this is a DerefTemp
1150    pub fn is_deref_temp(&self) -> bool {
1151        match self.local_info() {
1152            LocalInfo::DerefTemp => true,
1153            _ => false,
1154        }
1155    }
1156
1157    /// Returns `true` is the local is from a compiler desugaring, e.g.,
1158    /// `__next` from a `for` loop.
1159    #[inline]
1160    pub fn from_compiler_desugaring(&self) -> bool {
1161        self.source_info.span.desugaring_kind().is_some()
1162    }
1163
1164    /// Creates a new `LocalDecl` for a temporary, mutable.
1165    #[inline]
1166    pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1167        Self::with_source_info(ty, SourceInfo::outermost(span))
1168    }
1169
1170    /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1171    #[inline]
1172    pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1173        LocalDecl {
1174            mutability: Mutability::Mut,
1175            local_info: ClearCrossCrate::Set(Box::new(LocalInfo::Boring)),
1176            ty,
1177            user_ty: None,
1178            source_info,
1179        }
1180    }
1181
1182    /// Converts `self` into same `LocalDecl` except tagged as immutable.
1183    #[inline]
1184    pub fn immutable(mut self) -> Self {
1185        self.mutability = Mutability::Not;
1186        self
1187    }
1188}
1189
1190#[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1191pub enum VarDebugInfoContents<'tcx> {
1192    /// This `Place` only contains projection which satisfy `can_use_in_debuginfo`.
1193    Place(Place<'tcx>),
1194    Const(ConstOperand<'tcx>),
1195}
1196
1197impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1198    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1199        match self {
1200            VarDebugInfoContents::Const(c) => write!(fmt, "{c}"),
1201            VarDebugInfoContents::Place(p) => write!(fmt, "{p:?}"),
1202        }
1203    }
1204}
1205
1206#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1207pub struct VarDebugInfoFragment<'tcx> {
1208    /// Type of the original user variable.
1209    /// This cannot contain a union or an enum.
1210    pub ty: Ty<'tcx>,
1211
1212    /// Where in the composite user variable this fragment is,
1213    /// represented as a "projection" into the composite variable.
1214    /// At lower levels, this corresponds to a byte/bit range.
1215    ///
1216    /// This can only contain `PlaceElem::Field`.
1217    // FIXME support this for `enum`s by either using DWARF's
1218    // more advanced control-flow features (unsupported by LLVM?)
1219    // to match on the discriminant, or by using custom type debuginfo
1220    // with non-overlapping variants for the composite variable.
1221    pub projection: Vec<PlaceElem<'tcx>>,
1222}
1223
1224/// Debug information pertaining to a user variable.
1225#[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1226pub struct VarDebugInfo<'tcx> {
1227    pub name: Symbol,
1228
1229    /// Source info of the user variable, including the scope
1230    /// within which the variable is visible (to debuginfo)
1231    /// (see `LocalDecl`'s `source_info` field for more details).
1232    pub source_info: SourceInfo,
1233
1234    /// The user variable's data is split across several fragments,
1235    /// each described by a `VarDebugInfoFragment`.
1236    /// See DWARF 5's "2.6.1.2 Composite Location Descriptions"
1237    /// and LLVM's `DW_OP_LLVM_fragment` for more details on
1238    /// the underlying debuginfo feature this relies on.
1239    pub composite: Option<Box<VarDebugInfoFragment<'tcx>>>,
1240
1241    /// Where the data for this user variable is to be found.
1242    pub value: VarDebugInfoContents<'tcx>,
1243
1244    /// When present, indicates what argument number this variable is in the function that it
1245    /// originated from (starting from 1). Note, if MIR inlining is enabled, then this is the
1246    /// argument number in the original function before it was inlined.
1247    pub argument_index: Option<u16>,
1248}
1249
1250///////////////////////////////////////////////////////////////////////////
1251// BasicBlock
1252
1253rustc_index::newtype_index! {
1254    /// A node in the MIR [control-flow graph][CFG].
1255    ///
1256    /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1257    /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1258    /// as an edge in a graph between basic blocks.
1259    ///
1260    /// Basic blocks consist of a series of [statements][Statement], ending with a
1261    /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1262    /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1263    /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1264    /// needed because some analyses require that there are no critical edges in the CFG.
1265    ///
1266    /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1267    /// the actual data that a basic block holds is in [`BasicBlockData`].
1268    ///
1269    /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1270    ///
1271    /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1272    /// [data-flow analyses]:
1273    ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1274    /// [`CriticalCallEdges`]: ../../rustc_mir_transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1275    /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1276    #[derive(HashStable)]
1277    #[encodable]
1278    #[orderable]
1279    #[debug_format = "bb{}"]
1280    pub struct BasicBlock {
1281        const START_BLOCK = 0;
1282    }
1283}
1284
1285impl BasicBlock {
1286    pub fn start_location(self) -> Location {
1287        Location { block: self, statement_index: 0 }
1288    }
1289}
1290
1291///////////////////////////////////////////////////////////////////////////
1292// BasicBlockData
1293
1294/// Data for a basic block, including a list of its statements.
1295///
1296/// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1297#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1298#[non_exhaustive]
1299pub struct BasicBlockData<'tcx> {
1300    /// List of statements in this block.
1301    pub statements: Vec<Statement<'tcx>>,
1302
1303    /// Terminator for this block.
1304    ///
1305    /// N.B., this should generally ONLY be `None` during construction.
1306    /// Therefore, you should generally access it via the
1307    /// `terminator()` or `terminator_mut()` methods. The only
1308    /// exception is that certain passes, such as `simplify_cfg`, swap
1309    /// out the terminator temporarily with `None` while they continue
1310    /// to recurse over the set of basic blocks.
1311    pub terminator: Option<Terminator<'tcx>>,
1312
1313    /// If true, this block lies on an unwind path. This is used
1314    /// during codegen where distinct kinds of basic blocks may be
1315    /// generated (particularly for MSVC cleanup). Unwind blocks must
1316    /// only branch to other unwind blocks.
1317    pub is_cleanup: bool,
1318}
1319
1320impl<'tcx> BasicBlockData<'tcx> {
1321    pub fn new(terminator: Option<Terminator<'tcx>>, is_cleanup: bool) -> BasicBlockData<'tcx> {
1322        BasicBlockData::new_stmts(Vec::new(), terminator, is_cleanup)
1323    }
1324
1325    pub fn new_stmts(
1326        statements: Vec<Statement<'tcx>>,
1327        terminator: Option<Terminator<'tcx>>,
1328        is_cleanup: bool,
1329    ) -> BasicBlockData<'tcx> {
1330        BasicBlockData { statements, terminator, is_cleanup }
1331    }
1332
1333    /// Accessor for terminator.
1334    ///
1335    /// Terminator may not be None after construction of the basic block is complete. This accessor
1336    /// provides a convenient way to reach the terminator.
1337    #[inline]
1338    pub fn terminator(&self) -> &Terminator<'tcx> {
1339        self.terminator.as_ref().expect("invalid terminator state")
1340    }
1341
1342    #[inline]
1343    pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1344        self.terminator.as_mut().expect("invalid terminator state")
1345    }
1346
1347    /// Does the block have no statements and an unreachable terminator?
1348    #[inline]
1349    pub fn is_empty_unreachable(&self) -> bool {
1350        self.statements.is_empty() && matches!(self.terminator().kind, TerminatorKind::Unreachable)
1351    }
1352
1353    /// Like [`Terminator::successors`] but tries to use information available from the [`Instance`]
1354    /// to skip successors like the `false` side of an `if const {`.
1355    ///
1356    /// This is used to implement [`traversal::mono_reachable`] and
1357    /// [`traversal::mono_reachable_reverse_postorder`].
1358    pub fn mono_successors(&self, tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Successors<'_> {
1359        if let Some((bits, targets)) = Body::try_const_mono_switchint(tcx, instance, self) {
1360            targets.successors_for_value(bits)
1361        } else {
1362            self.terminator().successors()
1363        }
1364    }
1365}
1366
1367///////////////////////////////////////////////////////////////////////////
1368// Scopes
1369
1370rustc_index::newtype_index! {
1371    #[derive(HashStable)]
1372    #[encodable]
1373    #[debug_format = "scope[{}]"]
1374    pub struct SourceScope {
1375        const OUTERMOST_SOURCE_SCOPE = 0;
1376    }
1377}
1378
1379impl SourceScope {
1380    /// Finds the original HirId this MIR item came from.
1381    /// This is necessary after MIR optimizations, as otherwise we get a HirId
1382    /// from the function that was inlined instead of the function call site.
1383    pub fn lint_root(
1384        self,
1385        source_scopes: &IndexSlice<SourceScope, SourceScopeData<'_>>,
1386    ) -> Option<HirId> {
1387        let mut data = &source_scopes[self];
1388        // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
1389        // does not work as I thought it would. Needs more investigation and documentation.
1390        while data.inlined.is_some() {
1391            trace!(?data);
1392            data = &source_scopes[data.parent_scope.unwrap()];
1393        }
1394        trace!(?data);
1395        match &data.local_data {
1396            ClearCrossCrate::Set(data) => Some(data.lint_root),
1397            ClearCrossCrate::Clear => None,
1398        }
1399    }
1400
1401    /// The instance this source scope was inlined from, if any.
1402    #[inline]
1403    pub fn inlined_instance<'tcx>(
1404        self,
1405        source_scopes: &IndexSlice<SourceScope, SourceScopeData<'tcx>>,
1406    ) -> Option<ty::Instance<'tcx>> {
1407        let scope_data = &source_scopes[self];
1408        if let Some((inlined_instance, _)) = scope_data.inlined {
1409            Some(inlined_instance)
1410        } else if let Some(inlined_scope) = scope_data.inlined_parent_scope {
1411            Some(source_scopes[inlined_scope].inlined.unwrap().0)
1412        } else {
1413            None
1414        }
1415    }
1416}
1417
1418#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1419pub struct SourceScopeData<'tcx> {
1420    pub span: Span,
1421    pub parent_scope: Option<SourceScope>,
1422
1423    /// Whether this scope is the root of a scope tree of another body,
1424    /// inlined into this body by the MIR inliner.
1425    /// `ty::Instance` is the callee, and the `Span` is the call site.
1426    pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1427
1428    /// Nearest (transitive) parent scope (if any) which is inlined.
1429    /// This is an optimization over walking up `parent_scope`
1430    /// until a scope with `inlined: Some(...)` is found.
1431    pub inlined_parent_scope: Option<SourceScope>,
1432
1433    /// Crate-local information for this source scope, that can't (and
1434    /// needn't) be tracked across crates.
1435    pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1436}
1437
1438#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1439pub struct SourceScopeLocalData {
1440    /// An `HirId` with lint levels equivalent to this scope's lint levels.
1441    pub lint_root: HirId,
1442}
1443
1444/// A collection of projections into user types.
1445///
1446/// They are projections because a binding can occur a part of a
1447/// parent pattern that has been ascribed a type.
1448///
1449/// It's a collection because there can be multiple type ascriptions on
1450/// the path from the root of the pattern down to the binding itself.
1451///
1452/// An example:
1453///
1454/// ```ignore (illustrative)
1455/// struct S<'a>((i32, &'a str), String);
1456/// let S((_, w): (i32, &'static str), _): S = ...;
1457/// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
1458/// //  ---------------------------------  ^ (2)
1459/// ```
1460///
1461/// The highlights labelled `(1)` show the subpattern `(_, w)` being
1462/// ascribed the type `(i32, &'static str)`.
1463///
1464/// The highlights labelled `(2)` show the whole pattern being
1465/// ascribed the type `S`.
1466///
1467/// In this example, when we descend to `w`, we will have built up the
1468/// following two projected types:
1469///
1470///   * base: `S`,                   projection: `(base.0).1`
1471///   * base: `(i32, &'static str)`, projection: `base.1`
1472///
1473/// The first will lead to the constraint `w: &'1 str` (for some
1474/// inferred region `'1`). The second will lead to the constraint `w:
1475/// &'static str`.
1476#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1477pub struct UserTypeProjections {
1478    pub contents: Vec<UserTypeProjection>,
1479}
1480
1481impl UserTypeProjections {
1482    pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
1483        self.contents.iter()
1484    }
1485}
1486
1487/// Encodes the effect of a user-supplied type annotation on the
1488/// subcomponents of a pattern. The effect is determined by applying the
1489/// given list of projections to some underlying base type. Often,
1490/// the projection element list `projs` is empty, in which case this
1491/// directly encodes a type in `base`. But in the case of complex patterns with
1492/// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
1493/// in which case the `projs` vector is used.
1494///
1495/// Examples:
1496///
1497/// * `let x: T = ...` -- here, the `projs` vector is empty.
1498///
1499/// * `let (x, _): T = ...` -- here, the `projs` vector would contain
1500///   `field[0]` (aka `.0`), indicating that the type of `s` is
1501///   determined by finding the type of the `.0` field from `T`.
1502#[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
1503#[derive(TypeFoldable, TypeVisitable)]
1504pub struct UserTypeProjection {
1505    pub base: UserTypeAnnotationIndex,
1506    pub projs: Vec<ProjectionKind>,
1507}
1508
1509rustc_index::newtype_index! {
1510    #[derive(HashStable)]
1511    #[encodable]
1512    #[orderable]
1513    #[debug_format = "promoted[{}]"]
1514    pub struct Promoted {}
1515}
1516
1517/// `Location` represents the position of the start of the statement; or, if
1518/// `statement_index` equals the number of statements, then the start of the
1519/// terminator.
1520#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
1521pub struct Location {
1522    /// The block that the location is within.
1523    pub block: BasicBlock,
1524
1525    pub statement_index: usize,
1526}
1527
1528impl fmt::Debug for Location {
1529    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1530        write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1531    }
1532}
1533
1534impl Location {
1535    pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
1536
1537    /// Returns the location immediately after this one within the enclosing block.
1538    ///
1539    /// Note that if this location represents a terminator, then the
1540    /// resulting location would be out of bounds and invalid.
1541    #[inline]
1542    pub fn successor_within_block(&self) -> Location {
1543        Location { block: self.block, statement_index: self.statement_index + 1 }
1544    }
1545
1546    /// Returns `true` if `other` is earlier in the control flow graph than `self`.
1547    pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
1548        // If we are in the same block as the other location and are an earlier statement
1549        // then we are a predecessor of `other`.
1550        if self.block == other.block && self.statement_index < other.statement_index {
1551            return true;
1552        }
1553
1554        let predecessors = body.basic_blocks.predecessors();
1555
1556        // If we're in another block, then we want to check that block is a predecessor of `other`.
1557        let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
1558        let mut visited = FxHashSet::default();
1559
1560        while let Some(block) = queue.pop() {
1561            // If we haven't visited this block before, then make sure we visit its predecessors.
1562            if visited.insert(block) {
1563                queue.extend(predecessors[block].iter().cloned());
1564            } else {
1565                continue;
1566            }
1567
1568            // If we found the block that `self` is in, then we are a predecessor of `other` (since
1569            // we found that block by looking at the predecessors of `other`).
1570            if self.block == block {
1571                return true;
1572            }
1573        }
1574
1575        false
1576    }
1577
1578    #[inline]
1579    pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
1580        if self.block == other.block {
1581            self.statement_index <= other.statement_index
1582        } else {
1583            dominators.dominates(self.block, other.block)
1584        }
1585    }
1586}
1587
1588/// `DefLocation` represents the location of a definition - either an argument or an assignment
1589/// within MIR body.
1590#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1591pub enum DefLocation {
1592    Argument,
1593    Assignment(Location),
1594    CallReturn { call: BasicBlock, target: Option<BasicBlock> },
1595}
1596
1597impl DefLocation {
1598    #[inline]
1599    pub fn dominates(self, location: Location, dominators: &Dominators<BasicBlock>) -> bool {
1600        match self {
1601            DefLocation::Argument => true,
1602            DefLocation::Assignment(def) => {
1603                def.successor_within_block().dominates(location, dominators)
1604            }
1605            DefLocation::CallReturn { target: None, .. } => false,
1606            DefLocation::CallReturn { call, target: Some(target) } => {
1607                // The definition occurs on the call -> target edge. The definition dominates a use
1608                // if and only if the edge is on all paths from the entry to the use.
1609                //
1610                // Note that a call terminator has only one edge that can reach the target, so when
1611                // the call strongly dominates the target, all paths from the entry to the target
1612                // go through the call -> target edge.
1613                call != target
1614                    && dominators.dominates(call, target)
1615                    && dominators.dominates(target, location.block)
1616            }
1617        }
1618    }
1619}
1620
1621/// Checks if the specified `local` is used as the `self` parameter of a method call
1622/// in the provided `BasicBlock`. If it is, then the `DefId` of the called method is
1623/// returned.
1624pub fn find_self_call<'tcx>(
1625    tcx: TyCtxt<'tcx>,
1626    body: &Body<'tcx>,
1627    local: Local,
1628    block: BasicBlock,
1629) -> Option<(DefId, GenericArgsRef<'tcx>)> {
1630    debug!("find_self_call(local={:?}): terminator={:?}", local, body[block].terminator);
1631    if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) =
1632        &body[block].terminator
1633        && let Operand::Constant(box ConstOperand { const_, .. }) = func
1634        && let ty::FnDef(def_id, fn_args) = *const_.ty().kind()
1635        && let Some(item) = tcx.opt_associated_item(def_id)
1636        && item.is_method()
1637        && let [Spanned { node: Operand::Move(self_place) | Operand::Copy(self_place), .. }, ..] =
1638            **args
1639    {
1640        if self_place.as_local() == Some(local) {
1641            return Some((def_id, fn_args));
1642        }
1643
1644        // Handle the case where `self_place` gets reborrowed.
1645        // This happens when the receiver is `&T`.
1646        for stmt in &body[block].statements {
1647            if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind
1648                && let Some(reborrow_local) = place.as_local()
1649                && self_place.as_local() == Some(reborrow_local)
1650                && let Rvalue::Ref(_, _, deref_place) = rvalue
1651                && let PlaceRef { local: deref_local, projection: [ProjectionElem::Deref] } =
1652                    deref_place.as_ref()
1653                && deref_local == local
1654            {
1655                return Some((def_id, fn_args));
1656            }
1657        }
1658    }
1659    None
1660}
1661
1662// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1663#[cfg(target_pointer_width = "64")]
1664mod size_asserts {
1665    use rustc_data_structures::static_assert_size;
1666
1667    use super::*;
1668    // tidy-alphabetical-start
1669    static_assert_size!(BasicBlockData<'_>, 128);
1670    static_assert_size!(LocalDecl<'_>, 40);
1671    static_assert_size!(SourceScopeData<'_>, 64);
1672    static_assert_size!(Statement<'_>, 32);
1673    static_assert_size!(Terminator<'_>, 96);
1674    static_assert_size!(VarDebugInfo<'_>, 88);
1675    // tidy-alphabetical-end
1676}