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