]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
Auto merge of #104610 - ouz-a:revert-overflow, r=compiler-errors
[rust.git] / compiler / rustc_middle / src / 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
5 use crate::mir::interpret::{
6     AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, LitToConstInput, Scalar,
7 };
8 use crate::mir::visit::MirVisitable;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::visit::{TypeVisitable, TypeVisitor};
13 use crate::ty::{self, DefIdTree, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex};
15 use crate::ty::{GenericArg, InternalSubsts, SubstsRef};
16
17 use rustc_data_structures::captures::Captures;
18 use rustc_errors::ErrorGuaranteed;
19 use rustc_hir::def::{CtorKind, Namespace};
20 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
21 use rustc_hir::{self, GeneratorKind, ImplicitSelfKind};
22 use rustc_hir::{self as hir, HirId};
23 use rustc_session::Session;
24 use rustc_target::abi::{Size, VariantIdx};
25
26 use polonius_engine::Atom;
27 pub use rustc_ast::Mutability;
28 use rustc_data_structures::fx::FxHashSet;
29 use rustc_data_structures::graph::dominators::Dominators;
30 use rustc_index::bit_set::BitMatrix;
31 use rustc_index::vec::{Idx, IndexVec};
32 use rustc_serialize::{Decodable, Encodable};
33 use rustc_span::symbol::Symbol;
34 use rustc_span::{Span, DUMMY_SP};
35
36 use either::Either;
37
38 use std::borrow::Cow;
39 use std::convert::TryInto;
40 use std::fmt::{self, Debug, Display, Formatter, Write};
41 use std::ops::{ControlFlow, Index, IndexMut};
42 use std::{iter, mem};
43
44 pub use self::query::*;
45 pub use basic_blocks::BasicBlocks;
46
47 mod basic_blocks;
48 pub mod coverage;
49 mod generic_graph;
50 pub mod generic_graphviz;
51 mod graph_cyclic_cache;
52 pub mod graphviz;
53 pub mod interpret;
54 pub mod mono;
55 pub mod patch;
56 mod predecessors;
57 pub mod pretty;
58 mod query;
59 pub mod spanview;
60 mod syntax;
61 pub use syntax::*;
62 mod switch_sources;
63 pub mod tcx;
64 pub mod terminator;
65 pub use terminator::*;
66
67 pub mod traversal;
68 mod type_foldable;
69 mod type_visitable;
70 pub mod visit;
71
72 pub use self::generic_graph::graphviz_safe_def_name;
73 pub use self::graphviz::write_mir_graphviz;
74 pub use self::pretty::{
75     create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere,
76 };
77
78 /// Types for locals
79 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
80
81 pub trait HasLocalDecls<'tcx> {
82     fn local_decls(&self) -> &LocalDecls<'tcx>;
83 }
84
85 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
86     #[inline]
87     fn local_decls(&self) -> &LocalDecls<'tcx> {
88         self
89     }
90 }
91
92 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
93     #[inline]
94     fn local_decls(&self) -> &LocalDecls<'tcx> {
95         &self.local_decls
96     }
97 }
98
99 /// A streamlined trait that you can implement to create a pass; the
100 /// pass will be named after the type, and it will consist of a main
101 /// loop that goes over each available MIR and applies `run_pass`.
102 pub trait MirPass<'tcx> {
103     fn name(&self) -> Cow<'_, str> {
104         let name = std::any::type_name::<Self>();
105         if let Some(tail) = name.rfind(':') {
106             Cow::from(&name[tail + 1..])
107         } else {
108             Cow::from(name)
109         }
110     }
111
112     /// Returns `true` if this pass is enabled with the current combination of compiler flags.
113     fn is_enabled(&self, _sess: &Session) -> bool {
114         true
115     }
116
117     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
118
119     fn is_mir_dump_enabled(&self) -> bool {
120         true
121     }
122 }
123
124 impl MirPhase {
125     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
126     ///
127     /// FIXME(JakobDegen): Return a `(usize, usize)` instead.
128     pub fn phase_index(&self) -> usize {
129         const BUILT_PHASE_COUNT: usize = 1;
130         const ANALYSIS_PHASE_COUNT: usize = 2;
131         match self {
132             MirPhase::Built => 1,
133             MirPhase::Analysis(analysis_phase) => {
134                 1 + BUILT_PHASE_COUNT + (*analysis_phase as usize)
135             }
136             MirPhase::Runtime(runtime_phase) => {
137                 1 + BUILT_PHASE_COUNT + ANALYSIS_PHASE_COUNT + (*runtime_phase as usize)
138             }
139         }
140     }
141
142     /// Parses an `MirPhase` from a pair of strings. Panics if this isn't possible for any reason.
143     pub fn parse(dialect: String, phase: Option<String>) -> Self {
144         match &*dialect.to_ascii_lowercase() {
145             "built" => {
146                 assert!(phase.is_none(), "Cannot specify a phase for `Built` MIR");
147                 MirPhase::Built
148             }
149             "analysis" => Self::Analysis(AnalysisPhase::parse(phase)),
150             "runtime" => Self::Runtime(RuntimePhase::parse(phase)),
151             _ => panic!("Unknown MIR dialect {}", dialect),
152         }
153     }
154 }
155
156 impl AnalysisPhase {
157     pub fn parse(phase: Option<String>) -> Self {
158         let Some(phase) = phase else {
159             return Self::Initial;
160         };
161
162         match &*phase.to_ascii_lowercase() {
163             "initial" => Self::Initial,
164             "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
165             _ => panic!("Unknown analysis phase {}", phase),
166         }
167     }
168 }
169
170 impl RuntimePhase {
171     pub fn parse(phase: Option<String>) -> Self {
172         let Some(phase) = phase else {
173             return Self::Initial;
174         };
175
176         match &*phase.to_ascii_lowercase() {
177             "initial" => Self::Initial,
178             "post_cleanup" | "post-cleanup" | "postcleanup" => Self::PostCleanup,
179             "optimized" => Self::Optimized,
180             _ => panic!("Unknown runtime phase {}", phase),
181         }
182     }
183 }
184
185 impl Display for MirPhase {
186     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
187         match self {
188             MirPhase::Built => write!(f, "built"),
189             MirPhase::Analysis(p) => write!(f, "analysis-{}", p),
190             MirPhase::Runtime(p) => write!(f, "runtime-{}", p),
191         }
192     }
193 }
194
195 impl Display for AnalysisPhase {
196     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
197         match self {
198             AnalysisPhase::Initial => write!(f, "initial"),
199             AnalysisPhase::PostCleanup => write!(f, "post_cleanup"),
200         }
201     }
202 }
203
204 impl Display for RuntimePhase {
205     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
206         match self {
207             RuntimePhase::Initial => write!(f, "initial"),
208             RuntimePhase::PostCleanup => write!(f, "post_cleanup"),
209             RuntimePhase::Optimized => write!(f, "optimized"),
210         }
211     }
212 }
213
214 /// Where a specific `mir::Body` comes from.
215 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
216 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
217 pub struct MirSource<'tcx> {
218     pub instance: InstanceDef<'tcx>,
219
220     /// If `Some`, this is a promoted rvalue within the parent function.
221     pub promoted: Option<Promoted>,
222 }
223
224 impl<'tcx> MirSource<'tcx> {
225     pub fn item(def_id: DefId) -> Self {
226         MirSource {
227             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
228             promoted: None,
229         }
230     }
231
232     pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
233         MirSource { instance, promoted: None }
234     }
235
236     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
237         self.instance.with_opt_param()
238     }
239
240     #[inline]
241     pub fn def_id(&self) -> DefId {
242         self.instance.def_id()
243     }
244 }
245
246 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
247 pub struct GeneratorInfo<'tcx> {
248     /// The yield type of the function, if it is a generator.
249     pub yield_ty: Option<Ty<'tcx>>,
250
251     /// Generator drop glue.
252     pub generator_drop: Option<Body<'tcx>>,
253
254     /// The layout of a generator. Produced by the state transformation.
255     pub generator_layout: Option<GeneratorLayout<'tcx>>,
256
257     /// If this is a generator then record the type of source expression that caused this generator
258     /// to be created.
259     pub generator_kind: GeneratorKind,
260 }
261
262 /// The lowered representation of a single function.
263 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)]
264 pub struct Body<'tcx> {
265     /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
266     /// that indexes into this vector.
267     pub basic_blocks: BasicBlocks<'tcx>,
268
269     /// Records how far through the "desugaring and optimization" process this particular
270     /// MIR has traversed. This is particularly useful when inlining, since in that context
271     /// we instantiate the promoted constants and add them to our promoted vector -- but those
272     /// promoted items have already been optimized, whereas ours have not. This field allows
273     /// us to see the difference and forego optimization on the inlined promoted items.
274     pub phase: MirPhase,
275
276     /// How many passses we have executed since starting the current phase. Used for debug output.
277     pub pass_count: usize,
278
279     pub source: MirSource<'tcx>,
280
281     /// A list of source scopes; these are referenced by statements
282     /// and used for debuginfo. Indexed by a `SourceScope`.
283     pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
284
285     pub generator: Option<Box<GeneratorInfo<'tcx>>>,
286
287     /// Declarations of locals.
288     ///
289     /// The first local is the return value pointer, followed by `arg_count`
290     /// locals for the function arguments, followed by any user-declared
291     /// variables and temporaries.
292     pub local_decls: LocalDecls<'tcx>,
293
294     /// User type annotations.
295     pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
296
297     /// The number of arguments this function takes.
298     ///
299     /// Starting at local 1, `arg_count` locals will be provided by the caller
300     /// and can be assumed to be initialized.
301     ///
302     /// If this MIR was built for a constant, this will be 0.
303     pub arg_count: usize,
304
305     /// Mark an argument local (which must be a tuple) as getting passed as
306     /// its individual components at the LLVM level.
307     ///
308     /// This is used for the "rust-call" ABI.
309     pub spread_arg: Option<Local>,
310
311     /// Debug information pertaining to user variables, including captures.
312     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
313
314     /// A span representing this MIR, for error reporting.
315     pub span: Span,
316
317     /// Constants that are required to evaluate successfully for this MIR to be well-formed.
318     /// We hold in this field all the constants we are not able to evaluate yet.
319     pub required_consts: Vec<Constant<'tcx>>,
320
321     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
322     ///
323     /// Note that this does not actually mean that this body is not computable right now.
324     /// The repeat count in the following example is polymorphic, but can still be evaluated
325     /// without knowing anything about the type parameter `T`.
326     ///
327     /// ```rust
328     /// fn test<T>() {
329     ///     let _ = [0; std::mem::size_of::<*mut T>()];
330     /// }
331     /// ```
332     ///
333     /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
334     /// removed the last mention of all generic params. We do not want to rely on optimizations and
335     /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
336     pub is_polymorphic: bool,
337
338     /// The phase at which this MIR should be "injected" into the compilation process.
339     ///
340     /// Everything that comes before this `MirPhase` should be skipped.
341     ///
342     /// This is only `Some` if the function that this body comes from was annotated with `rustc_custom_mir`.
343     pub injection_phase: Option<MirPhase>,
344
345     pub tainted_by_errors: Option<ErrorGuaranteed>,
346 }
347
348 impl<'tcx> Body<'tcx> {
349     pub fn new(
350         source: MirSource<'tcx>,
351         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
352         source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
353         local_decls: LocalDecls<'tcx>,
354         user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
355         arg_count: usize,
356         var_debug_info: Vec<VarDebugInfo<'tcx>>,
357         span: Span,
358         generator_kind: Option<GeneratorKind>,
359         tainted_by_errors: Option<ErrorGuaranteed>,
360     ) -> Self {
361         // We need `arg_count` locals, and one for the return place.
362         assert!(
363             local_decls.len() > arg_count,
364             "expected at least {} locals, got {}",
365             arg_count + 1,
366             local_decls.len()
367         );
368
369         let mut body = Body {
370             phase: MirPhase::Built,
371             pass_count: 1,
372             source,
373             basic_blocks: BasicBlocks::new(basic_blocks),
374             source_scopes,
375             generator: generator_kind.map(|generator_kind| {
376                 Box::new(GeneratorInfo {
377                     yield_ty: None,
378                     generator_drop: None,
379                     generator_layout: None,
380                     generator_kind,
381                 })
382             }),
383             local_decls,
384             user_type_annotations,
385             arg_count,
386             spread_arg: None,
387             var_debug_info,
388             span,
389             required_consts: Vec::new(),
390             is_polymorphic: false,
391             injection_phase: None,
392             tainted_by_errors,
393         };
394         body.is_polymorphic = body.has_non_region_param();
395         body
396     }
397
398     /// Returns a partially initialized MIR body containing only a list of basic blocks.
399     ///
400     /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
401     /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
402     /// crate.
403     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
404         let mut body = Body {
405             phase: MirPhase::Built,
406             pass_count: 1,
407             source: MirSource::item(CRATE_DEF_ID.to_def_id()),
408             basic_blocks: BasicBlocks::new(basic_blocks),
409             source_scopes: IndexVec::new(),
410             generator: None,
411             local_decls: IndexVec::new(),
412             user_type_annotations: IndexVec::new(),
413             arg_count: 0,
414             spread_arg: None,
415             span: DUMMY_SP,
416             required_consts: Vec::new(),
417             var_debug_info: Vec::new(),
418             is_polymorphic: false,
419             injection_phase: None,
420             tainted_by_errors: None,
421         };
422         body.is_polymorphic = body.has_non_region_param();
423         body
424     }
425
426     #[inline]
427     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
428         self.basic_blocks.as_mut()
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 if self.local_decls[local].is_user_variable() {
444             LocalKind::Var
445         } else {
446             LocalKind::Temp
447         }
448     }
449
450     /// Returns an iterator over all user-declared mutable locals.
451     #[inline]
452     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
453         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
454             let local = Local::new(index);
455             let decl = &self.local_decls[local];
456             if decl.is_user_variable() && decl.mutability == Mutability::Mut {
457                 Some(local)
458             } else {
459                 None
460             }
461         })
462     }
463
464     /// Returns an iterator over all user-declared mutable arguments and locals.
465     #[inline]
466     pub fn mut_vars_and_args_iter<'a>(
467         &'a self,
468     ) -> impl Iterator<Item = Local> + Captures<'tcx> + 'a {
469         (1..self.local_decls.len()).filter_map(move |index| {
470             let local = Local::new(index);
471             let decl = &self.local_decls[local];
472             if (decl.is_user_variable() || index < self.arg_count + 1)
473                 && decl.mutability == Mutability::Mut
474             {
475                 Some(local)
476             } else {
477                 None
478             }
479         })
480     }
481
482     /// Returns an iterator over all function arguments.
483     #[inline]
484     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
485         (1..self.arg_count + 1).map(Local::new)
486     }
487
488     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
489     /// locals that are neither arguments nor the return place).
490     #[inline]
491     pub fn vars_and_temps_iter(
492         &self,
493     ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
494         (self.arg_count + 1..self.local_decls.len()).map(Local::new)
495     }
496
497     #[inline]
498     pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator<Item = LocalDecl<'tcx>> + 'a {
499         self.local_decls.drain(self.arg_count + 1..)
500     }
501
502     /// Returns the source info associated with `location`.
503     pub fn source_info(&self, location: Location) -> &SourceInfo {
504         let block = &self[location.block];
505         let stmts = &block.statements;
506         let idx = location.statement_index;
507         if idx < stmts.len() {
508             &stmts[idx].source_info
509         } else {
510             assert_eq!(idx, stmts.len());
511             &block.terminator().source_info
512         }
513     }
514
515     /// Returns the return type; it always return first element from `local_decls` array.
516     #[inline]
517     pub fn return_ty(&self) -> Ty<'tcx> {
518         self.local_decls[RETURN_PLACE].ty
519     }
520
521     /// Returns the return type; it always return first element from `local_decls` array.
522     #[inline]
523     pub fn bound_return_ty(&self) -> ty::EarlyBinder<Ty<'tcx>> {
524         ty::EarlyBinder(self.local_decls[RETURN_PLACE].ty)
525     }
526
527     /// Gets the location of the terminator for the given block.
528     #[inline]
529     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
530         Location { block: bb, statement_index: self[bb].statements.len() }
531     }
532
533     pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
534         let Location { block, statement_index } = location;
535         let block_data = &self.basic_blocks[block];
536         block_data
537             .statements
538             .get(statement_index)
539             .map(Either::Left)
540             .unwrap_or_else(|| Either::Right(block_data.terminator()))
541     }
542
543     #[inline]
544     pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
545         self.generator.as_ref().and_then(|generator| generator.yield_ty)
546     }
547
548     #[inline]
549     pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
550         self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
551     }
552
553     #[inline]
554     pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
555         self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
556     }
557
558     #[inline]
559     pub fn generator_kind(&self) -> Option<GeneratorKind> {
560         self.generator.as_ref().map(|generator| generator.generator_kind)
561     }
562
563     #[inline]
564     pub fn should_skip(&self) -> bool {
565         let Some(injection_phase) = self.injection_phase else {
566             return false;
567         };
568         injection_phase > self.phase
569     }
570 }
571
572 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
573 pub enum Safety {
574     Safe,
575     /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
576     BuiltinUnsafe,
577     /// Unsafe because of an unsafe fn
578     FnUnsafe,
579     /// Unsafe because of an `unsafe` block
580     ExplicitUnsafe(hir::HirId),
581 }
582
583 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
584     type Output = BasicBlockData<'tcx>;
585
586     #[inline]
587     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
588         &self.basic_blocks[index]
589     }
590 }
591
592 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
593     #[inline]
594     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
595         &mut self.basic_blocks.as_mut()[index]
596     }
597 }
598
599 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)]
600 pub enum ClearCrossCrate<T> {
601     Clear,
602     Set(T),
603 }
604
605 impl<T> ClearCrossCrate<T> {
606     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
607         match self {
608             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
609             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
610         }
611     }
612
613     pub fn assert_crate_local(self) -> T {
614         match self {
615             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
616             ClearCrossCrate::Set(v) => v,
617         }
618     }
619 }
620
621 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
622 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
623
624 impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
625     #[inline]
626     fn encode(&self, e: &mut E) {
627         if E::CLEAR_CROSS_CRATE {
628             return;
629         }
630
631         match *self {
632             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
633             ClearCrossCrate::Set(ref val) => {
634                 TAG_CLEAR_CROSS_CRATE_SET.encode(e);
635                 val.encode(e);
636             }
637         }
638     }
639 }
640 impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
641     #[inline]
642     fn decode(d: &mut D) -> ClearCrossCrate<T> {
643         if D::CLEAR_CROSS_CRATE {
644             return ClearCrossCrate::Clear;
645         }
646
647         let discr = u8::decode(d);
648
649         match discr {
650             TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
651             TAG_CLEAR_CROSS_CRATE_SET => {
652                 let val = T::decode(d);
653                 ClearCrossCrate::Set(val)
654             }
655             tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
656         }
657     }
658 }
659
660 /// Grouped information about the source code origin of a MIR entity.
661 /// Intended to be inspected by diagnostics and debuginfo.
662 /// Most passes can work with it as a whole, within a single function.
663 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
664 // `Hash`. Please ping @bjorn3 if removing them.
665 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
666 pub struct SourceInfo {
667     /// The source span for the AST pertaining to this MIR entity.
668     pub span: Span,
669
670     /// The source scope, keeping track of which bindings can be
671     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
672     pub scope: SourceScope,
673 }
674
675 impl SourceInfo {
676     #[inline]
677     pub fn outermost(span: Span) -> Self {
678         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
679     }
680 }
681
682 ///////////////////////////////////////////////////////////////////////////
683 // Variables and temps
684
685 rustc_index::newtype_index! {
686     pub struct Local {
687         derive [HashStable]
688         DEBUG_FORMAT = "_{}",
689         const RETURN_PLACE = 0,
690     }
691 }
692
693 impl Atom for Local {
694     fn index(self) -> usize {
695         Idx::index(self)
696     }
697 }
698
699 /// Classifies locals into categories. See `Body::local_kind`.
700 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
701 pub enum LocalKind {
702     /// User-declared variable binding.
703     Var,
704     /// Compiler-introduced temporary.
705     Temp,
706     /// Function argument.
707     Arg,
708     /// Location of function's return value.
709     ReturnPointer,
710 }
711
712 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
713 pub struct VarBindingForm<'tcx> {
714     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
715     pub binding_mode: ty::BindingMode,
716     /// If an explicit type was provided for this variable binding,
717     /// this holds the source Span of that type.
718     ///
719     /// NOTE: if you want to change this to a `HirId`, be wary that
720     /// doing so breaks incremental compilation (as of this writing),
721     /// while a `Span` does not cause our tests to fail.
722     pub opt_ty_info: Option<Span>,
723     /// Place of the RHS of the =, or the subject of the `match` where this
724     /// variable is initialized. None in the case of `let PATTERN;`.
725     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
726     /// (a) the right-hand side isn't evaluated as a place expression.
727     /// (b) it gives a way to separate this case from the remaining cases
728     ///     for diagnostics.
729     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
730     /// The span of the pattern in which this variable was bound.
731     pub pat_span: Span,
732 }
733
734 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
735 pub enum BindingForm<'tcx> {
736     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
737     Var(VarBindingForm<'tcx>),
738     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
739     ImplicitSelf(ImplicitSelfKind),
740     /// Reference used in a guard expression to ensure immutability.
741     RefForGuard,
742 }
743
744 TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx>, }
745
746 mod binding_form_impl {
747     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
748     use rustc_query_system::ich::StableHashingContext;
749
750     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
751         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
752             use super::BindingForm::*;
753             std::mem::discriminant(self).hash_stable(hcx, hasher);
754
755             match self {
756                 Var(binding) => binding.hash_stable(hcx, hasher),
757                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
758                 RefForGuard => (),
759             }
760         }
761     }
762 }
763
764 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
765 /// created during evaluation of expressions in a block tail
766 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
767 ///
768 /// It is used to improve diagnostics when such temporaries are
769 /// involved in borrow_check errors, e.g., explanations of where the
770 /// temporaries come from, when their destructors are run, and/or how
771 /// one might revise the code to satisfy the borrow checker's rules.
772 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
773 pub struct BlockTailInfo {
774     /// If `true`, then the value resulting from evaluating this tail
775     /// expression is ignored by the block's expression context.
776     ///
777     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
778     /// but not e.g., `let _x = { ...; tail };`
779     pub tail_result_is_ignored: bool,
780
781     /// `Span` of the tail expression.
782     pub span: Span,
783 }
784
785 /// A MIR local.
786 ///
787 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
788 /// argument, or the return place.
789 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
790 pub struct LocalDecl<'tcx> {
791     /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
792     ///
793     /// Temporaries and the return place are always mutable.
794     pub mutability: Mutability,
795
796     // FIXME(matthewjasper) Don't store in this in `Body`
797     pub local_info: Option<Box<LocalInfo<'tcx>>>,
798
799     /// `true` if this is an internal local.
800     ///
801     /// These locals are not based on types in the source code and are only used
802     /// for a few desugarings at the moment.
803     ///
804     /// The generator transformation will sanity check the locals which are live
805     /// across a suspension point against the type components of the generator
806     /// which type checking knows are live across a suspension point. We need to
807     /// flag drop flags to avoid triggering this check as they are introduced
808     /// outside of type inference.
809     ///
810     /// This should be sound because the drop flags are fully algebraic, and
811     /// therefore don't affect the auto-trait or outlives properties of the
812     /// generator.
813     pub internal: bool,
814
815     /// If this local is a temporary and `is_block_tail` is `Some`,
816     /// then it is a temporary created for evaluation of some
817     /// subexpression of some block's tail expression (with no
818     /// intervening statement context).
819     // FIXME(matthewjasper) Don't store in this in `Body`
820     pub is_block_tail: Option<BlockTailInfo>,
821
822     /// The type of this local.
823     pub ty: Ty<'tcx>,
824
825     /// If the user manually ascribed a type to this variable,
826     /// e.g., via `let x: T`, then we carry that type here. The MIR
827     /// borrow checker needs this information since it can affect
828     /// region inference.
829     // FIXME(matthewjasper) Don't store in this in `Body`
830     pub user_ty: Option<Box<UserTypeProjections>>,
831
832     /// The *syntactic* (i.e., not visibility) source scope the local is defined
833     /// in. If the local was defined in a let-statement, this
834     /// is *within* the let-statement, rather than outside
835     /// of it.
836     ///
837     /// This is needed because the visibility source scope of locals within
838     /// a let-statement is weird.
839     ///
840     /// The reason is that we want the local to be *within* the let-statement
841     /// for lint purposes, but we want the local to be *after* the let-statement
842     /// for names-in-scope purposes.
843     ///
844     /// That's it, if we have a let-statement like the one in this
845     /// function:
846     ///
847     /// ```
848     /// fn foo(x: &str) {
849     ///     #[allow(unused_mut)]
850     ///     let mut x: u32 = { // <- one unused mut
851     ///         let mut y: u32 = x.parse().unwrap();
852     ///         y + 2
853     ///     };
854     ///     drop(x);
855     /// }
856     /// ```
857     ///
858     /// Then, from a lint point of view, the declaration of `x: u32`
859     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
860     /// lint scopes are the same as the AST/HIR nesting.
861     ///
862     /// However, from a name lookup point of view, the scopes look more like
863     /// as if the let-statements were `match` expressions:
864     ///
865     /// ```
866     /// fn foo(x: &str) {
867     ///     match {
868     ///         match x.parse::<u32>().unwrap() {
869     ///             y => y + 2
870     ///         }
871     ///     } {
872     ///         x => drop(x)
873     ///     };
874     /// }
875     /// ```
876     ///
877     /// We care about the name-lookup scopes for debuginfo - if the
878     /// debuginfo instruction pointer is at the call to `x.parse()`, we
879     /// want `x` to refer to `x: &str`, but if it is at the call to
880     /// `drop(x)`, we want it to refer to `x: u32`.
881     ///
882     /// To allow both uses to work, we need to have more than a single scope
883     /// for a local. We have the `source_info.scope` represent the "syntactic"
884     /// lint scope (with a variable being under its let block) while the
885     /// `var_debug_info.source_info.scope` represents the "local variable"
886     /// scope (where the "rest" of a block is under all prior let-statements).
887     ///
888     /// The end result looks like this:
889     ///
890     /// ```text
891     /// ROOT SCOPE
892     ///  │{ argument x: &str }
893     ///  │
894     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
895     ///  │ │                         // in practice because I'm lazy.
896     ///  │ │
897     ///  │ │← x.source_info.scope
898     ///  │ │← `x.parse().unwrap()`
899     ///  │ │
900     ///  │ │ │← y.source_info.scope
901     ///  │ │
902     ///  │ │ │{ let y: u32 }
903     ///  │ │ │
904     ///  │ │ │← y.var_debug_info.source_info.scope
905     ///  │ │ │← `y + 2`
906     ///  │
907     ///  │ │{ let x: u32 }
908     ///  │ │← x.var_debug_info.source_info.scope
909     ///  │ │← `drop(x)` // This accesses `x: u32`.
910     /// ```
911     pub source_info: SourceInfo,
912 }
913
914 /// Extra information about a some locals that's used for diagnostics and for
915 /// classifying variables into local variables, statics, etc, which is needed e.g.
916 /// for unsafety checking.
917 ///
918 /// Not used for non-StaticRef temporaries, the return place, or anonymous
919 /// function parameters.
920 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
921 pub enum LocalInfo<'tcx> {
922     /// A user-defined local variable or function parameter
923     ///
924     /// The `BindingForm` is solely used for local diagnostics when generating
925     /// warnings/errors when compiling the current crate, and therefore it need
926     /// not be visible across crates.
927     User(ClearCrossCrate<BindingForm<'tcx>>),
928     /// A temporary created that references the static with the given `DefId`.
929     StaticRef { def_id: DefId, is_thread_local: bool },
930     /// A temporary created that references the const with the given `DefId`
931     ConstRef { def_id: DefId },
932     /// A temporary created during the creation of an aggregate
933     /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
934     AggregateTemp,
935     /// A temporary created during the pass `Derefer` to avoid it's retagging
936     DerefTemp,
937 }
938
939 impl<'tcx> LocalDecl<'tcx> {
940     /// Returns `true` only if local is a binding that can itself be
941     /// made mutable via the addition of the `mut` keyword, namely
942     /// something like the occurrences of `x` in:
943     /// - `fn foo(x: Type) { ... }`,
944     /// - `let x = ...`,
945     /// - or `match ... { C(x) => ... }`
946     pub fn can_be_made_mutable(&self) -> bool {
947         matches!(
948             self.local_info,
949             Some(box LocalInfo::User(ClearCrossCrate::Set(
950                 BindingForm::Var(VarBindingForm {
951                     binding_mode: ty::BindingMode::BindByValue(_),
952                     opt_ty_info: _,
953                     opt_match_place: _,
954                     pat_span: _,
955                 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
956             )))
957         )
958     }
959
960     /// Returns `true` if local is definitely not a `ref ident` or
961     /// `ref mut ident` binding. (Such bindings cannot be made into
962     /// mutable bindings, but the inverse does not necessarily hold).
963     pub fn is_nonref_binding(&self) -> bool {
964         matches!(
965             self.local_info,
966             Some(box LocalInfo::User(ClearCrossCrate::Set(
967                 BindingForm::Var(VarBindingForm {
968                     binding_mode: ty::BindingMode::BindByValue(_),
969                     opt_ty_info: _,
970                     opt_match_place: _,
971                     pat_span: _,
972                 }) | BindingForm::ImplicitSelf(_),
973             )))
974         )
975     }
976
977     /// Returns `true` if this variable is a named variable or function
978     /// parameter declared by the user.
979     #[inline]
980     pub fn is_user_variable(&self) -> bool {
981         matches!(self.local_info, Some(box LocalInfo::User(_)))
982     }
983
984     /// Returns `true` if this is a reference to a variable bound in a `match`
985     /// expression that is used to access said variable for the guard of the
986     /// match arm.
987     pub fn is_ref_for_guard(&self) -> bool {
988         matches!(
989             self.local_info,
990             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
991         )
992     }
993
994     /// Returns `Some` if this is a reference to a static item that is used to
995     /// access that static.
996     pub fn is_ref_to_static(&self) -> bool {
997         matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
998     }
999
1000     /// Returns `Some` if this is a reference to a thread-local static item that is used to
1001     /// access that static.
1002     pub fn is_ref_to_thread_local(&self) -> bool {
1003         match self.local_info {
1004             Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1005             _ => false,
1006         }
1007     }
1008
1009     /// Returns `true` if this is a DerefTemp
1010     pub fn is_deref_temp(&self) -> bool {
1011         match self.local_info {
1012             Some(box LocalInfo::DerefTemp) => return true,
1013             _ => (),
1014         }
1015         return false;
1016     }
1017
1018     /// Returns `true` is the local is from a compiler desugaring, e.g.,
1019     /// `__next` from a `for` loop.
1020     #[inline]
1021     pub fn from_compiler_desugaring(&self) -> bool {
1022         self.source_info.span.desugaring_kind().is_some()
1023     }
1024
1025     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1026     #[inline]
1027     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1028         Self::with_source_info(ty, SourceInfo::outermost(span))
1029     }
1030
1031     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1032     #[inline]
1033     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1034         LocalDecl {
1035             mutability: Mutability::Mut,
1036             local_info: None,
1037             internal: false,
1038             is_block_tail: None,
1039             ty,
1040             user_ty: None,
1041             source_info,
1042         }
1043     }
1044
1045     /// Converts `self` into same `LocalDecl` except tagged as internal.
1046     #[inline]
1047     pub fn internal(mut self) -> Self {
1048         self.internal = true;
1049         self
1050     }
1051
1052     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1053     #[inline]
1054     pub fn immutable(mut self) -> Self {
1055         self.mutability = Mutability::Not;
1056         self
1057     }
1058
1059     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1060     #[inline]
1061     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1062         assert!(self.is_block_tail.is_none());
1063         self.is_block_tail = Some(info);
1064         self
1065     }
1066 }
1067
1068 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1069 pub enum VarDebugInfoContents<'tcx> {
1070     /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1071     /// based on a `Local`, not a `Static`, and contains no indexing.
1072     Place(Place<'tcx>),
1073     Const(Constant<'tcx>),
1074     /// The user variable's data is split across several fragments,
1075     /// each described by a `VarDebugInfoFragment`.
1076     /// See DWARF 5's "2.6.1.2 Composite Location Descriptions"
1077     /// and LLVM's `DW_OP_LLVM_fragment` for more details on
1078     /// the underlying debuginfo feature this relies on.
1079     Composite {
1080         /// Type of the original user variable.
1081         ty: Ty<'tcx>,
1082         /// All the parts of the original user variable, which ended
1083         /// up in disjoint places, due to optimizations.
1084         fragments: Vec<VarDebugInfoFragment<'tcx>>,
1085     },
1086 }
1087
1088 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1089     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1090         match self {
1091             VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1092             VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1093             VarDebugInfoContents::Composite { ty, fragments } => {
1094                 write!(fmt, "{:?}{{ ", ty)?;
1095                 for f in fragments.iter() {
1096                     write!(fmt, "{:?}, ", f)?;
1097                 }
1098                 write!(fmt, "}}")
1099             }
1100         }
1101     }
1102 }
1103
1104 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1105 pub struct VarDebugInfoFragment<'tcx> {
1106     /// Where in the composite user variable this fragment is,
1107     /// represented as a "projection" into the composite variable.
1108     /// At lower levels, this corresponds to a byte/bit range.
1109     // NOTE(eddyb) there's an unenforced invariant that this contains
1110     // only `Field`s, and not into `enum` variants or `union`s.
1111     // FIXME(eddyb) support this for `enum`s by either using DWARF's
1112     // more advanced control-flow features (unsupported by LLVM?)
1113     // to match on the discriminant, or by using custom type debuginfo
1114     // with non-overlapping variants for the composite variable.
1115     pub projection: Vec<PlaceElem<'tcx>>,
1116
1117     /// Where the data for this fragment can be found.
1118     // NOTE(eddyb) There's an unenforced invariant that this `Place` is
1119     // contains no indexing (with a non-constant index).
1120     pub contents: Place<'tcx>,
1121 }
1122
1123 impl Debug for VarDebugInfoFragment<'_> {
1124     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1125         for elem in self.projection.iter() {
1126             match elem {
1127                 ProjectionElem::Field(field, _) => {
1128                     write!(fmt, ".{:?}", field.index())?;
1129                 }
1130                 _ => bug!("unsupported fragment projection `{:?}`", elem),
1131             }
1132         }
1133
1134         write!(fmt, " => {:?}", self.contents)
1135     }
1136 }
1137
1138 /// Debug information pertaining to a user variable.
1139 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1140 pub struct VarDebugInfo<'tcx> {
1141     pub name: Symbol,
1142
1143     /// Source info of the user variable, including the scope
1144     /// within which the variable is visible (to debuginfo)
1145     /// (see `LocalDecl`'s `source_info` field for more details).
1146     pub source_info: SourceInfo,
1147
1148     /// Where the data for this user variable is to be found.
1149     pub value: VarDebugInfoContents<'tcx>,
1150 }
1151
1152 ///////////////////////////////////////////////////////////////////////////
1153 // BasicBlock
1154
1155 rustc_index::newtype_index! {
1156     /// A node in the MIR [control-flow graph][CFG].
1157     ///
1158     /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1159     /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1160     /// as an edge in a graph between basic blocks.
1161     ///
1162     /// Basic blocks consist of a series of [statements][Statement], ending with a
1163     /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1164     /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1165     /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1166     /// needed because some analyses require that there are no critical edges in the CFG.
1167     ///
1168     /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1169     /// the actual data that a basic block holds is in [`BasicBlockData`].
1170     ///
1171     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1172     ///
1173     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1174     /// [data-flow analyses]:
1175     ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1176     /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1177     /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1178     pub struct BasicBlock {
1179         derive [HashStable]
1180         DEBUG_FORMAT = "bb{}",
1181         const START_BLOCK = 0,
1182     }
1183 }
1184
1185 impl BasicBlock {
1186     pub fn start_location(self) -> Location {
1187         Location { block: self, statement_index: 0 }
1188     }
1189 }
1190
1191 ///////////////////////////////////////////////////////////////////////////
1192 // BasicBlockData
1193
1194 /// Data for a basic block, including a list of its statements.
1195 ///
1196 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1197 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1198 pub struct BasicBlockData<'tcx> {
1199     /// List of statements in this block.
1200     pub statements: Vec<Statement<'tcx>>,
1201
1202     /// Terminator for this block.
1203     ///
1204     /// N.B., this should generally ONLY be `None` during construction.
1205     /// Therefore, you should generally access it via the
1206     /// `terminator()` or `terminator_mut()` methods. The only
1207     /// exception is that certain passes, such as `simplify_cfg`, swap
1208     /// out the terminator temporarily with `None` while they continue
1209     /// to recurse over the set of basic blocks.
1210     pub terminator: Option<Terminator<'tcx>>,
1211
1212     /// If true, this block lies on an unwind path. This is used
1213     /// during codegen where distinct kinds of basic blocks may be
1214     /// generated (particularly for MSVC cleanup). Unwind blocks must
1215     /// only branch to other unwind blocks.
1216     pub is_cleanup: bool,
1217 }
1218
1219 impl<'tcx> BasicBlockData<'tcx> {
1220     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1221         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1222     }
1223
1224     /// Accessor for terminator.
1225     ///
1226     /// Terminator may not be None after construction of the basic block is complete. This accessor
1227     /// provides a convenient way to reach the terminator.
1228     #[inline]
1229     pub fn terminator(&self) -> &Terminator<'tcx> {
1230         self.terminator.as_ref().expect("invalid terminator state")
1231     }
1232
1233     #[inline]
1234     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1235         self.terminator.as_mut().expect("invalid terminator state")
1236     }
1237
1238     pub fn retain_statements<F>(&mut self, mut f: F)
1239     where
1240         F: FnMut(&mut Statement<'_>) -> bool,
1241     {
1242         for s in &mut self.statements {
1243             if !f(s) {
1244                 s.make_nop();
1245             }
1246         }
1247     }
1248
1249     pub fn expand_statements<F, I>(&mut self, mut f: F)
1250     where
1251         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1252         I: iter::TrustedLen<Item = Statement<'tcx>>,
1253     {
1254         // Gather all the iterators we'll need to splice in, and their positions.
1255         let mut splices: Vec<(usize, I)> = vec![];
1256         let mut extra_stmts = 0;
1257         for (i, s) in self.statements.iter_mut().enumerate() {
1258             if let Some(mut new_stmts) = f(s) {
1259                 if let Some(first) = new_stmts.next() {
1260                     // We can already store the first new statement.
1261                     *s = first;
1262
1263                     // Save the other statements for optimized splicing.
1264                     let remaining = new_stmts.size_hint().0;
1265                     if remaining > 0 {
1266                         splices.push((i + 1 + extra_stmts, new_stmts));
1267                         extra_stmts += remaining;
1268                     }
1269                 } else {
1270                     s.make_nop();
1271                 }
1272             }
1273         }
1274
1275         // Splice in the new statements, from the end of the block.
1276         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1277         // where a range of elements ("gap") is left uninitialized, with
1278         // splicing adding new elements to the end of that gap and moving
1279         // existing elements from before the gap to the end of the gap.
1280         // For now, this is safe code, emulating a gap but initializing it.
1281         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1282         self.statements.resize(
1283             gap.end,
1284             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1285         );
1286         for (splice_start, new_stmts) in splices.into_iter().rev() {
1287             let splice_end = splice_start + new_stmts.size_hint().0;
1288             while gap.end > splice_end {
1289                 gap.start -= 1;
1290                 gap.end -= 1;
1291                 self.statements.swap(gap.start, gap.end);
1292             }
1293             self.statements.splice(splice_start..splice_end, new_stmts);
1294             gap.end = splice_start;
1295         }
1296     }
1297
1298     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1299         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1300     }
1301
1302     /// Does the block have no statements and an unreachable terminator?
1303     pub fn is_empty_unreachable(&self) -> bool {
1304         self.statements.is_empty() && matches!(self.terminator().kind, TerminatorKind::Unreachable)
1305     }
1306 }
1307
1308 impl<O> AssertKind<O> {
1309     /// Getting a description does not require `O` to be printable, and does not
1310     /// require allocation.
1311     /// The caller is expected to handle `BoundsCheck` separately.
1312     pub fn description(&self) -> &'static str {
1313         use AssertKind::*;
1314         match self {
1315             Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1316             Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1317             Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1318             Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1319             Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1320             OverflowNeg(_) => "attempt to negate with overflow",
1321             Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1322             Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1323             Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1324             DivisionByZero(_) => "attempt to divide by zero",
1325             RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1326             ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1327             ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1328             ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1329             ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1330             BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1331         }
1332     }
1333
1334     /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1335     pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1336     where
1337         O: Debug,
1338     {
1339         use AssertKind::*;
1340         match self {
1341             BoundsCheck { ref len, ref index } => write!(
1342                 f,
1343                 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1344                 len, index
1345             ),
1346
1347             OverflowNeg(op) => {
1348                 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1349             }
1350             DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1351             RemainderByZero(op) => write!(
1352                 f,
1353                 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1354                 op
1355             ),
1356             Overflow(BinOp::Add, l, r) => write!(
1357                 f,
1358                 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1359                 l, r
1360             ),
1361             Overflow(BinOp::Sub, l, r) => write!(
1362                 f,
1363                 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1364                 l, r
1365             ),
1366             Overflow(BinOp::Mul, l, r) => write!(
1367                 f,
1368                 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1369                 l, r
1370             ),
1371             Overflow(BinOp::Div, l, r) => write!(
1372                 f,
1373                 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1374                 l, r
1375             ),
1376             Overflow(BinOp::Rem, l, r) => write!(
1377                 f,
1378                 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1379                 l, r
1380             ),
1381             Overflow(BinOp::Shr, _, r) => {
1382                 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1383             }
1384             Overflow(BinOp::Shl, _, r) => {
1385                 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1386             }
1387             _ => write!(f, "\"{}\"", self.description()),
1388         }
1389     }
1390 }
1391
1392 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1393     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1394         use AssertKind::*;
1395         match self {
1396             BoundsCheck { ref len, ref index } => write!(
1397                 f,
1398                 "index out of bounds: the length is {:?} but the index is {:?}",
1399                 len, index
1400             ),
1401             OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1402             DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1403             RemainderByZero(op) => write!(
1404                 f,
1405                 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1406                 op
1407             ),
1408             Overflow(BinOp::Add, l, r) => {
1409                 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1410             }
1411             Overflow(BinOp::Sub, l, r) => {
1412                 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1413             }
1414             Overflow(BinOp::Mul, l, r) => {
1415                 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1416             }
1417             Overflow(BinOp::Div, l, r) => {
1418                 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1419             }
1420             Overflow(BinOp::Rem, l, r) => write!(
1421                 f,
1422                 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1423                 l, r
1424             ),
1425             Overflow(BinOp::Shr, _, r) => {
1426                 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1427             }
1428             Overflow(BinOp::Shl, _, r) => {
1429                 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1430             }
1431             _ => write!(f, "{}", self.description()),
1432         }
1433     }
1434 }
1435
1436 ///////////////////////////////////////////////////////////////////////////
1437 // Statements
1438
1439 /// A statement in a basic block, including information about its source code.
1440 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1441 pub struct Statement<'tcx> {
1442     pub source_info: SourceInfo,
1443     pub kind: StatementKind<'tcx>,
1444 }
1445
1446 impl Statement<'_> {
1447     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1448     /// invalidating statement indices in `Location`s.
1449     pub fn make_nop(&mut self) {
1450         self.kind = StatementKind::Nop
1451     }
1452
1453     /// Changes a statement to a nop and returns the original statement.
1454     #[must_use = "If you don't need the statement, use `make_nop` instead"]
1455     pub fn replace_nop(&mut self) -> Self {
1456         Statement {
1457             source_info: self.source_info,
1458             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1459         }
1460     }
1461 }
1462
1463 impl Debug for Statement<'_> {
1464     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1465         use self::StatementKind::*;
1466         match self.kind {
1467             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1468             FakeRead(box (ref cause, ref place)) => {
1469                 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1470             }
1471             Retag(ref kind, ref place) => write!(
1472                 fmt,
1473                 "Retag({}{:?})",
1474                 match kind {
1475                     RetagKind::FnEntry => "[fn entry] ",
1476                     RetagKind::TwoPhase => "[2phase] ",
1477                     RetagKind::Raw => "[raw] ",
1478                     RetagKind::Default => "",
1479                 },
1480                 place,
1481             ),
1482             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1483             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1484             SetDiscriminant { ref place, variant_index } => {
1485                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1486             }
1487             Deinit(ref place) => write!(fmt, "Deinit({:?})", place),
1488             AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1489                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1490             }
1491             Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1492                 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1493             }
1494             Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1495             Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
1496             Nop => write!(fmt, "nop"),
1497         }
1498     }
1499 }
1500
1501 impl<'tcx> StatementKind<'tcx> {
1502     pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1503         match self {
1504             StatementKind::Assign(x) => Some(x),
1505             _ => None,
1506         }
1507     }
1508
1509     pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1510         match self {
1511             StatementKind::Assign(x) => Some(x),
1512             _ => None,
1513         }
1514     }
1515 }
1516
1517 ///////////////////////////////////////////////////////////////////////////
1518 // Places
1519
1520 impl<V, T> ProjectionElem<V, T> {
1521     /// Returns `true` if the target of this projection may refer to a different region of memory
1522     /// than the base.
1523     fn is_indirect(&self) -> bool {
1524         match self {
1525             Self::Deref => true,
1526
1527             Self::Field(_, _)
1528             | Self::Index(_)
1529             | Self::OpaqueCast(_)
1530             | Self::ConstantIndex { .. }
1531             | Self::Subslice { .. }
1532             | Self::Downcast(_, _) => false,
1533         }
1534     }
1535
1536     /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
1537     pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
1538         matches!(*self, Self::Downcast(_, x) if x == v)
1539     }
1540
1541     /// Returns `true` if this is a `Field` projection with the given index.
1542     pub fn is_field_to(&self, f: Field) -> bool {
1543         matches!(*self, Self::Field(x, _) if x == f)
1544     }
1545 }
1546
1547 /// Alias for projections as they appear in `UserTypeProjection`, where we
1548 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1549 pub type ProjectionKind = ProjectionElem<(), ()>;
1550
1551 rustc_index::newtype_index! {
1552     /// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
1553     ///
1554     /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
1555     /// rustc can identify that a field projection refers to either two different regions of memory
1556     /// or the same one between the base and the 'projection element'.
1557     /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
1558     ///
1559     /// [wrapper]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html#newtype
1560     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1561     /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
1562     pub struct Field {
1563         derive [HashStable]
1564         DEBUG_FORMAT = "field[{}]"
1565     }
1566 }
1567
1568 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1569 pub struct PlaceRef<'tcx> {
1570     pub local: Local,
1571     pub projection: &'tcx [PlaceElem<'tcx>],
1572 }
1573
1574 // Once we stop implementing `Ord` for `DefId`,
1575 // this impl will be unnecessary. Until then, we'll
1576 // leave this impl in place to prevent re-adding a
1577 // dependency on the `Ord` impl for `DefId`
1578 impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
1579
1580 impl<'tcx> Place<'tcx> {
1581     // FIXME change this to a const fn by also making List::empty a const fn.
1582     pub fn return_place() -> Place<'tcx> {
1583         Place { local: RETURN_PLACE, projection: List::empty() }
1584     }
1585
1586     /// Returns `true` if this `Place` contains a `Deref` projection.
1587     ///
1588     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1589     /// same region of memory as its base.
1590     pub fn is_indirect(&self) -> bool {
1591         self.projection.iter().any(|elem| elem.is_indirect())
1592     }
1593
1594     /// If MirPhase >= Derefered and if projection contains Deref,
1595     /// It's guaranteed to be in the first place
1596     pub fn has_deref(&self) -> bool {
1597         // To make sure this is not accidentally used in wrong mir phase
1598         debug_assert!(
1599             self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
1600         );
1601         self.projection.first() == Some(&PlaceElem::Deref)
1602     }
1603
1604     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1605     /// a single deref of a local.
1606     #[inline(always)]
1607     pub fn local_or_deref_local(&self) -> Option<Local> {
1608         self.as_ref().local_or_deref_local()
1609     }
1610
1611     /// If this place represents a local variable like `_X` with no
1612     /// projections, return `Some(_X)`.
1613     #[inline(always)]
1614     pub fn as_local(&self) -> Option<Local> {
1615         self.as_ref().as_local()
1616     }
1617
1618     #[inline]
1619     pub fn as_ref(&self) -> PlaceRef<'tcx> {
1620         PlaceRef { local: self.local, projection: &self.projection }
1621     }
1622
1623     /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1624     /// its projection and then subsequently more projections are added.
1625     /// As a concrete example, given the place a.b.c, this would yield:
1626     /// - (a, .b)
1627     /// - (a.b, .c)
1628     ///
1629     /// Given a place without projections, the iterator is empty.
1630     #[inline]
1631     pub fn iter_projections(
1632         self,
1633     ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1634         self.as_ref().iter_projections()
1635     }
1636
1637     /// Generates a new place by appending `more_projections` to the existing ones
1638     /// and interning the result.
1639     pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
1640         if more_projections.is_empty() {
1641             return self;
1642         }
1643
1644         let mut v: Vec<PlaceElem<'tcx>>;
1645
1646         let new_projections = if self.projection.is_empty() {
1647             more_projections
1648         } else {
1649             v = Vec::with_capacity(self.projection.len() + more_projections.len());
1650             v.extend(self.projection);
1651             v.extend(more_projections);
1652             &v
1653         };
1654
1655         Place { local: self.local, projection: tcx.intern_place_elems(new_projections) }
1656     }
1657 }
1658
1659 impl From<Local> for Place<'_> {
1660     #[inline]
1661     fn from(local: Local) -> Self {
1662         Place { local, projection: List::empty() }
1663     }
1664 }
1665
1666 impl<'tcx> PlaceRef<'tcx> {
1667     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1668     /// a single deref of a local.
1669     pub fn local_or_deref_local(&self) -> Option<Local> {
1670         match *self {
1671             PlaceRef { local, projection: [] }
1672             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1673             _ => None,
1674         }
1675     }
1676
1677     /// If MirPhase >= Derefered and if projection contains Deref,
1678     /// It's guaranteed to be in the first place
1679     pub fn has_deref(&self) -> bool {
1680         self.projection.first() == Some(&PlaceElem::Deref)
1681     }
1682
1683     /// If this place represents a local variable like `_X` with no
1684     /// projections, return `Some(_X)`.
1685     #[inline]
1686     pub fn as_local(&self) -> Option<Local> {
1687         match *self {
1688             PlaceRef { local, projection: [] } => Some(local),
1689             _ => None,
1690         }
1691     }
1692
1693     #[inline]
1694     pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
1695         if let &[ref proj_base @ .., elem] = self.projection {
1696             Some((PlaceRef { local: self.local, projection: proj_base }, elem))
1697         } else {
1698             None
1699         }
1700     }
1701
1702     /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1703     /// its projection and then subsequently more projections are added.
1704     /// As a concrete example, given the place a.b.c, this would yield:
1705     /// - (a, .b)
1706     /// - (a.b, .c)
1707     ///
1708     /// Given a place without projections, the iterator is empty.
1709     #[inline]
1710     pub fn iter_projections(
1711         self,
1712     ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1713         self.projection.iter().enumerate().map(move |(i, proj)| {
1714             let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1715             (base, *proj)
1716         })
1717     }
1718 }
1719
1720 impl Debug for Place<'_> {
1721     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1722         for elem in self.projection.iter().rev() {
1723             match elem {
1724                 ProjectionElem::OpaqueCast(_)
1725                 | ProjectionElem::Downcast(_, _)
1726                 | ProjectionElem::Field(_, _) => {
1727                     write!(fmt, "(").unwrap();
1728                 }
1729                 ProjectionElem::Deref => {
1730                     write!(fmt, "(*").unwrap();
1731                 }
1732                 ProjectionElem::Index(_)
1733                 | ProjectionElem::ConstantIndex { .. }
1734                 | ProjectionElem::Subslice { .. } => {}
1735             }
1736         }
1737
1738         write!(fmt, "{:?}", self.local)?;
1739
1740         for elem in self.projection.iter() {
1741             match elem {
1742                 ProjectionElem::OpaqueCast(ty) => {
1743                     write!(fmt, " as {})", ty)?;
1744                 }
1745                 ProjectionElem::Downcast(Some(name), _index) => {
1746                     write!(fmt, " as {})", name)?;
1747                 }
1748                 ProjectionElem::Downcast(None, index) => {
1749                     write!(fmt, " as variant#{:?})", index)?;
1750                 }
1751                 ProjectionElem::Deref => {
1752                     write!(fmt, ")")?;
1753                 }
1754                 ProjectionElem::Field(field, ty) => {
1755                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1756                 }
1757                 ProjectionElem::Index(ref index) => {
1758                     write!(fmt, "[{:?}]", index)?;
1759                 }
1760                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1761                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1762                 }
1763                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1764                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1765                 }
1766                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1767                     write!(fmt, "[{:?}:]", from)?;
1768                 }
1769                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1770                     write!(fmt, "[:-{:?}]", to)?;
1771                 }
1772                 ProjectionElem::Subslice { from, to, from_end: true } => {
1773                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
1774                 }
1775                 ProjectionElem::Subslice { from, to, from_end: false } => {
1776                     write!(fmt, "[{:?}..{:?}]", from, to)?;
1777                 }
1778             }
1779         }
1780
1781         Ok(())
1782     }
1783 }
1784
1785 ///////////////////////////////////////////////////////////////////////////
1786 // Scopes
1787
1788 rustc_index::newtype_index! {
1789     pub struct SourceScope {
1790         derive [HashStable]
1791         DEBUG_FORMAT = "scope[{}]",
1792         const OUTERMOST_SOURCE_SCOPE = 0,
1793     }
1794 }
1795
1796 impl SourceScope {
1797     /// Finds the original HirId this MIR item came from.
1798     /// This is necessary after MIR optimizations, as otherwise we get a HirId
1799     /// from the function that was inlined instead of the function call site.
1800     pub fn lint_root<'tcx>(
1801         self,
1802         source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1803     ) -> Option<HirId> {
1804         let mut data = &source_scopes[self];
1805         // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
1806         // does not work as I thought it would. Needs more investigation and documentation.
1807         while data.inlined.is_some() {
1808             trace!(?data);
1809             data = &source_scopes[data.parent_scope.unwrap()];
1810         }
1811         trace!(?data);
1812         match &data.local_data {
1813             ClearCrossCrate::Set(data) => Some(data.lint_root),
1814             ClearCrossCrate::Clear => None,
1815         }
1816     }
1817
1818     /// The instance this source scope was inlined from, if any.
1819     #[inline]
1820     pub fn inlined_instance<'tcx>(
1821         self,
1822         source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
1823     ) -> Option<ty::Instance<'tcx>> {
1824         let scope_data = &source_scopes[self];
1825         if let Some((inlined_instance, _)) = scope_data.inlined {
1826             Some(inlined_instance)
1827         } else if let Some(inlined_scope) = scope_data.inlined_parent_scope {
1828             Some(source_scopes[inlined_scope].inlined.unwrap().0)
1829         } else {
1830             None
1831         }
1832     }
1833 }
1834
1835 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1836 pub struct SourceScopeData<'tcx> {
1837     pub span: Span,
1838     pub parent_scope: Option<SourceScope>,
1839
1840     /// Whether this scope is the root of a scope tree of another body,
1841     /// inlined into this body by the MIR inliner.
1842     /// `ty::Instance` is the callee, and the `Span` is the call site.
1843     pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1844
1845     /// Nearest (transitive) parent scope (if any) which is inlined.
1846     /// This is an optimization over walking up `parent_scope`
1847     /// until a scope with `inlined: Some(...)` is found.
1848     pub inlined_parent_scope: Option<SourceScope>,
1849
1850     /// Crate-local information for this source scope, that can't (and
1851     /// needn't) be tracked across crates.
1852     pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1853 }
1854
1855 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1856 pub struct SourceScopeLocalData {
1857     /// An `HirId` with lint levels equivalent to this scope's lint levels.
1858     pub lint_root: hir::HirId,
1859     /// The unsafe block that contains this node.
1860     pub safety: Safety,
1861 }
1862
1863 ///////////////////////////////////////////////////////////////////////////
1864 // Operands
1865
1866 impl<'tcx> Debug for Operand<'tcx> {
1867     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1868         use self::Operand::*;
1869         match *self {
1870             Constant(ref a) => write!(fmt, "{:?}", a),
1871             Copy(ref place) => write!(fmt, "{:?}", place),
1872             Move(ref place) => write!(fmt, "move {:?}", place),
1873         }
1874     }
1875 }
1876
1877 impl<'tcx> Operand<'tcx> {
1878     /// Convenience helper to make a constant that refers to the fn
1879     /// with given `DefId` and substs. Since this is used to synthesize
1880     /// MIR, assumes `user_ty` is None.
1881     pub fn function_handle(
1882         tcx: TyCtxt<'tcx>,
1883         def_id: DefId,
1884         substs: SubstsRef<'tcx>,
1885         span: Span,
1886     ) -> Self {
1887         let ty = tcx.mk_fn_def(def_id, substs);
1888         Operand::Constant(Box::new(Constant {
1889             span,
1890             user_ty: None,
1891             literal: ConstantKind::Val(ConstValue::ZeroSized, ty),
1892         }))
1893     }
1894
1895     pub fn is_move(&self) -> bool {
1896         matches!(self, Operand::Move(..))
1897     }
1898
1899     /// Convenience helper to make a literal-like constant from a given scalar value.
1900     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1901     pub fn const_from_scalar(
1902         tcx: TyCtxt<'tcx>,
1903         ty: Ty<'tcx>,
1904         val: Scalar,
1905         span: Span,
1906     ) -> Operand<'tcx> {
1907         debug_assert!({
1908             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1909             let type_size = tcx
1910                 .layout_of(param_env_and_ty)
1911                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1912                 .size;
1913             let scalar_size = match val {
1914                 Scalar::Int(int) => int.size(),
1915                 _ => panic!("Invalid scalar type {:?}", val),
1916             };
1917             scalar_size == type_size
1918         });
1919         Operand::Constant(Box::new(Constant {
1920             span,
1921             user_ty: None,
1922             literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
1923         }))
1924     }
1925
1926     pub fn to_copy(&self) -> Self {
1927         match *self {
1928             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1929             Operand::Move(place) => Operand::Copy(place),
1930         }
1931     }
1932
1933     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1934     /// constant.
1935     pub fn place(&self) -> Option<Place<'tcx>> {
1936         match self {
1937             Operand::Copy(place) | Operand::Move(place) => Some(*place),
1938             Operand::Constant(_) => None,
1939         }
1940     }
1941
1942     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
1943     /// place.
1944     pub fn constant(&self) -> Option<&Constant<'tcx>> {
1945         match self {
1946             Operand::Constant(x) => Some(&**x),
1947             Operand::Copy(_) | Operand::Move(_) => None,
1948         }
1949     }
1950
1951     /// Gets the `ty::FnDef` from an operand if it's a constant function item.
1952     ///
1953     /// While this is unlikely in general, it's the normal case of what you'll
1954     /// find as the `func` in a [`TerminatorKind::Call`].
1955     pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> {
1956         let const_ty = self.constant()?.literal.ty();
1957         if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None }
1958     }
1959 }
1960
1961 ///////////////////////////////////////////////////////////////////////////
1962 /// Rvalues
1963
1964 impl<'tcx> Rvalue<'tcx> {
1965     /// Returns true if rvalue can be safely removed when the result is unused.
1966     #[inline]
1967     pub fn is_safe_to_remove(&self) -> bool {
1968         match self {
1969             // Pointer to int casts may be side-effects due to exposing the provenance.
1970             // While the model is undecided, we should be conservative. See
1971             // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
1972             Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => false,
1973
1974             Rvalue::Use(_)
1975             | Rvalue::CopyForDeref(_)
1976             | Rvalue::Repeat(_, _)
1977             | Rvalue::Ref(_, _, _)
1978             | Rvalue::ThreadLocalRef(_)
1979             | Rvalue::AddressOf(_, _)
1980             | Rvalue::Len(_)
1981             | Rvalue::Cast(
1982                 CastKind::IntToInt
1983                 | CastKind::FloatToInt
1984                 | CastKind::FloatToFloat
1985                 | CastKind::IntToFloat
1986                 | CastKind::FnPtrToPtr
1987                 | CastKind::PtrToPtr
1988                 | CastKind::Pointer(_)
1989                 | CastKind::PointerFromExposedAddress
1990                 | CastKind::DynStar,
1991                 _,
1992                 _,
1993             )
1994             | Rvalue::BinaryOp(_, _)
1995             | Rvalue::CheckedBinaryOp(_, _)
1996             | Rvalue::NullaryOp(_, _)
1997             | Rvalue::UnaryOp(_, _)
1998             | Rvalue::Discriminant(_)
1999             | Rvalue::Aggregate(_, _)
2000             | Rvalue::ShallowInitBox(_, _) => true,
2001         }
2002     }
2003 }
2004
2005 impl BorrowKind {
2006     pub fn allows_two_phase_borrow(&self) -> bool {
2007         match *self {
2008             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
2009             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
2010         }
2011     }
2012
2013     // FIXME: won't be used after diagnostic migration
2014     pub fn describe_mutability(&self) -> &str {
2015         match *self {
2016             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => "immutable",
2017             BorrowKind::Mut { .. } => "mutable",
2018         }
2019     }
2020 }
2021
2022 impl BinOp {
2023     pub fn is_checkable(self) -> bool {
2024         use self::BinOp::*;
2025         matches!(self, Add | Sub | Mul | Shl | Shr)
2026     }
2027 }
2028
2029 impl<'tcx> Debug for Rvalue<'tcx> {
2030     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2031         use self::Rvalue::*;
2032
2033         match *self {
2034             Use(ref place) => write!(fmt, "{:?}", place),
2035             Repeat(ref a, b) => {
2036                 write!(fmt, "[{:?}; ", a)?;
2037                 pretty_print_const(b, fmt, false)?;
2038                 write!(fmt, "]")
2039             }
2040             Len(ref a) => write!(fmt, "Len({:?})", a),
2041             Cast(ref kind, ref place, ref ty) => {
2042                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2043             }
2044             BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2045             CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2046                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2047             }
2048             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2049             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2050             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2051             ThreadLocalRef(did) => ty::tls::with(|tcx| {
2052                 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2053                 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2054             }),
2055             Ref(region, borrow_kind, ref place) => {
2056                 let kind_str = match borrow_kind {
2057                     BorrowKind::Shared => "",
2058                     BorrowKind::Shallow => "shallow ",
2059                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2060                 };
2061
2062                 // When printing regions, add trailing space if necessary.
2063                 let print_region = ty::tls::with(|tcx| {
2064                     tcx.sess.verbose() || tcx.sess.opts.unstable_opts.identify_regions
2065                 });
2066                 let region = if print_region {
2067                     let mut region = region.to_string();
2068                     if !region.is_empty() {
2069                         region.push(' ');
2070                     }
2071                     region
2072                 } else {
2073                     // Do not even print 'static
2074                     String::new()
2075                 };
2076                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2077             }
2078
2079             CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place),
2080
2081             AddressOf(mutability, ref place) => {
2082                 let kind_str = match mutability {
2083                     Mutability::Mut => "mut",
2084                     Mutability::Not => "const",
2085                 };
2086
2087                 write!(fmt, "&raw {} {:?}", kind_str, place)
2088             }
2089
2090             Aggregate(ref kind, ref places) => {
2091                 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2092                     let mut tuple_fmt = fmt.debug_tuple(name);
2093                     for place in places {
2094                         tuple_fmt.field(place);
2095                     }
2096                     tuple_fmt.finish()
2097                 };
2098
2099                 match **kind {
2100                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2101
2102                     AggregateKind::Tuple => {
2103                         if places.is_empty() {
2104                             write!(fmt, "()")
2105                         } else {
2106                             fmt_tuple(fmt, "")
2107                         }
2108                     }
2109
2110                     AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => {
2111                         ty::tls::with(|tcx| {
2112                             let variant_def = &tcx.adt_def(adt_did).variant(variant);
2113                             let substs = tcx.lift(substs).expect("could not lift for printing");
2114                             let name = FmtPrinter::new(tcx, Namespace::ValueNS)
2115                                 .print_def_path(variant_def.def_id, substs)?
2116                                 .into_buffer();
2117
2118                             match variant_def.ctor_kind() {
2119                                 Some(CtorKind::Const) => fmt.write_str(&name),
2120                                 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
2121                                 None => {
2122                                     let mut struct_fmt = fmt.debug_struct(&name);
2123                                     for (field, place) in iter::zip(&variant_def.fields, places) {
2124                                         struct_fmt.field(field.name.as_str(), place);
2125                                     }
2126                                     struct_fmt.finish()
2127                                 }
2128                             }
2129                         })
2130                     }
2131
2132                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2133                         let name = if tcx.sess.opts.unstable_opts.span_free_formats {
2134                             let substs = tcx.lift(substs).unwrap();
2135                             format!(
2136                                 "[closure@{}]",
2137                                 tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2138                             )
2139                         } else {
2140                             let span = tcx.def_span(def_id);
2141                             format!(
2142                                 "[closure@{}]",
2143                                 tcx.sess.source_map().span_to_diagnostic_string(span)
2144                             )
2145                         };
2146                         let mut struct_fmt = fmt.debug_struct(&name);
2147
2148                         // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2149                         if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2150                             for (&var_id, place) in iter::zip(upvars.keys(), places) {
2151                                 let var_name = tcx.hir().name(var_id);
2152                                 struct_fmt.field(var_name.as_str(), place);
2153                             }
2154                         }
2155
2156                         struct_fmt.finish()
2157                     }),
2158
2159                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2160                         let name = format!("[generator@{:?}]", tcx.def_span(def_id));
2161                         let mut struct_fmt = fmt.debug_struct(&name);
2162
2163                         // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2164                         if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2165                             for (&var_id, place) in iter::zip(upvars.keys(), places) {
2166                                 let var_name = tcx.hir().name(var_id);
2167                                 struct_fmt.field(var_name.as_str(), place);
2168                             }
2169                         }
2170
2171                         struct_fmt.finish()
2172                     }),
2173                 }
2174             }
2175
2176             ShallowInitBox(ref place, ref ty) => {
2177                 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2178             }
2179         }
2180     }
2181 }
2182
2183 ///////////////////////////////////////////////////////////////////////////
2184 /// Constants
2185 ///
2186 /// Two constants are equal if they are the same constant. Note that
2187 /// this does not necessarily mean that they are `==` in Rust. In
2188 /// particular, one must be wary of `NaN`!
2189
2190 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2191 #[derive(TypeFoldable, TypeVisitable)]
2192 pub struct Constant<'tcx> {
2193     pub span: Span,
2194
2195     /// Optional user-given type: for something like
2196     /// `collect::<Vec<_>>`, this would be present and would
2197     /// indicate that `Vec<_>` was explicitly specified.
2198     ///
2199     /// Needed for NLL to impose user-given type constraints.
2200     pub user_ty: Option<UserTypeAnnotationIndex>,
2201
2202     pub literal: ConstantKind<'tcx>,
2203 }
2204
2205 #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2206 #[derive(Lift, TypeFoldable, TypeVisitable)]
2207 pub enum ConstantKind<'tcx> {
2208     /// This constant came from the type system
2209     Ty(ty::Const<'tcx>),
2210
2211     /// An unevaluated mir constant which is not part of the type system.
2212     Unevaluated(UnevaluatedConst<'tcx>, Ty<'tcx>),
2213
2214     /// This constant cannot go back into the type system, as it represents
2215     /// something the type system cannot handle (e.g. pointers).
2216     Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2217 }
2218
2219 impl<'tcx> Constant<'tcx> {
2220     pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2221         match self.literal.try_to_scalar() {
2222             Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2223                 GlobalAlloc::Static(def_id) => {
2224                     assert!(!tcx.is_thread_local_static(def_id));
2225                     Some(def_id)
2226                 }
2227                 _ => None,
2228             },
2229             _ => None,
2230         }
2231     }
2232     #[inline]
2233     pub fn ty(&self) -> Ty<'tcx> {
2234         self.literal.ty()
2235     }
2236 }
2237
2238 impl<'tcx> ConstantKind<'tcx> {
2239     #[inline(always)]
2240     pub fn ty(&self) -> Ty<'tcx> {
2241         match self {
2242             ConstantKind::Ty(c) => c.ty(),
2243             ConstantKind::Val(_, ty) | ConstantKind::Unevaluated(_, ty) => *ty,
2244         }
2245     }
2246
2247     #[inline]
2248     pub fn try_to_value(self, tcx: TyCtxt<'tcx>) -> Option<interpret::ConstValue<'tcx>> {
2249         match self {
2250             ConstantKind::Ty(c) => match c.kind() {
2251                 ty::ConstKind::Value(valtree) => Some(tcx.valtree_to_const_val((c.ty(), valtree))),
2252                 _ => None,
2253             },
2254             ConstantKind::Val(val, _) => Some(val),
2255             ConstantKind::Unevaluated(..) => None,
2256         }
2257     }
2258
2259     #[inline]
2260     pub fn try_to_scalar(self) -> Option<Scalar> {
2261         match self {
2262             ConstantKind::Ty(c) => match c.kind() {
2263                 ty::ConstKind::Value(valtree) => match valtree {
2264                     ty::ValTree::Leaf(scalar_int) => Some(Scalar::Int(scalar_int)),
2265                     ty::ValTree::Branch(_) => None,
2266                 },
2267                 _ => None,
2268             },
2269             ConstantKind::Val(val, _) => val.try_to_scalar(),
2270             ConstantKind::Unevaluated(..) => None,
2271         }
2272     }
2273
2274     #[inline]
2275     pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2276         Some(self.try_to_scalar()?.assert_int())
2277     }
2278
2279     #[inline]
2280     pub fn try_to_bits(self, size: Size) -> Option<u128> {
2281         self.try_to_scalar_int()?.to_bits(size).ok()
2282     }
2283
2284     #[inline]
2285     pub fn try_to_bool(self) -> Option<bool> {
2286         self.try_to_scalar_int()?.try_into().ok()
2287     }
2288
2289     #[inline]
2290     pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
2291         match self {
2292             Self::Ty(c) => {
2293                 if let Some(val) = c.kind().try_eval_for_mir(tcx, param_env) {
2294                     match val {
2295                         Ok(val) => Self::Val(val, c.ty()),
2296                         Err(_) => Self::Ty(tcx.const_error(self.ty())),
2297                     }
2298                 } else {
2299                     self
2300                 }
2301             }
2302             Self::Val(_, _) => self,
2303             Self::Unevaluated(uneval, ty) => {
2304                 // FIXME: We might want to have a `try_eval`-like function on `Unevaluated`
2305                 match tcx.const_eval_resolve(param_env, uneval, None) {
2306                     Ok(val) => Self::Val(val, ty),
2307                     Err(ErrorHandled::TooGeneric) => self,
2308                     Err(ErrorHandled::Reported(guar)) => {
2309                         Self::Ty(tcx.const_error_with_guaranteed(ty, guar))
2310                     }
2311                 }
2312             }
2313         }
2314     }
2315
2316     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
2317     #[inline]
2318     pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
2319         self.try_eval_bits(tcx, param_env, ty)
2320             .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
2321     }
2322
2323     #[inline]
2324     pub fn try_eval_bits(
2325         &self,
2326         tcx: TyCtxt<'tcx>,
2327         param_env: ty::ParamEnv<'tcx>,
2328         ty: Ty<'tcx>,
2329     ) -> Option<u128> {
2330         match self {
2331             Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
2332             Self::Val(val, t) => {
2333                 assert_eq!(*t, ty);
2334                 let size =
2335                     tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
2336                 val.try_to_bits(size)
2337             }
2338             Self::Unevaluated(uneval, ty) => {
2339                 match tcx.const_eval_resolve(param_env, *uneval, None) {
2340                     Ok(val) => {
2341                         let size = tcx
2342                             .layout_of(param_env.with_reveal_all_normalized(tcx).and(*ty))
2343                             .ok()?
2344                             .size;
2345                         val.try_to_bits(size)
2346                     }
2347                     Err(_) => None,
2348                 }
2349             }
2350         }
2351     }
2352
2353     #[inline]
2354     pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
2355         match self {
2356             Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
2357             Self::Val(val, _) => val.try_to_bool(),
2358             Self::Unevaluated(uneval, _) => {
2359                 match tcx.const_eval_resolve(param_env, *uneval, None) {
2360                     Ok(val) => val.try_to_bool(),
2361                     Err(_) => None,
2362                 }
2363             }
2364         }
2365     }
2366
2367     #[inline]
2368     pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
2369         match self {
2370             Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
2371             Self::Val(val, _) => val.try_to_machine_usize(tcx),
2372             Self::Unevaluated(uneval, _) => {
2373                 match tcx.const_eval_resolve(param_env, *uneval, None) {
2374                     Ok(val) => val.try_to_machine_usize(tcx),
2375                     Err(_) => None,
2376                 }
2377             }
2378         }
2379     }
2380
2381     #[inline]
2382     pub fn from_value(val: ConstValue<'tcx>, ty: Ty<'tcx>) -> Self {
2383         Self::Val(val, ty)
2384     }
2385
2386     pub fn from_bits(
2387         tcx: TyCtxt<'tcx>,
2388         bits: u128,
2389         param_env_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
2390     ) -> Self {
2391         let size = tcx
2392             .layout_of(param_env_ty)
2393             .unwrap_or_else(|e| {
2394                 bug!("could not compute layout for {:?}: {:?}", param_env_ty.value, e)
2395             })
2396             .size;
2397         let cv = ConstValue::Scalar(Scalar::from_uint(bits, size));
2398
2399         Self::Val(cv, param_env_ty.value)
2400     }
2401
2402     #[inline]
2403     pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
2404         let cv = ConstValue::from_bool(v);
2405         Self::Val(cv, tcx.types.bool)
2406     }
2407
2408     #[inline]
2409     pub fn zero_sized(ty: Ty<'tcx>) -> Self {
2410         let cv = ConstValue::ZeroSized;
2411         Self::Val(cv, ty)
2412     }
2413
2414     pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
2415         let ty = tcx.types.usize;
2416         Self::from_bits(tcx, n as u128, ty::ParamEnv::empty().and(ty))
2417     }
2418
2419     #[inline]
2420     pub fn from_scalar(_tcx: TyCtxt<'tcx>, s: Scalar, ty: Ty<'tcx>) -> Self {
2421         let val = ConstValue::Scalar(s);
2422         Self::Val(val, ty)
2423     }
2424
2425     /// Literals are converted to `ConstantKindVal`, const generic parameters are eagerly
2426     /// converted to a constant, everything else becomes `Unevaluated`.
2427     pub fn from_anon_const(
2428         tcx: TyCtxt<'tcx>,
2429         def_id: LocalDefId,
2430         param_env: ty::ParamEnv<'tcx>,
2431     ) -> Self {
2432         Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id), param_env)
2433     }
2434
2435     #[instrument(skip(tcx), level = "debug", ret)]
2436     pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2437         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2438         let body_id = match tcx.hir().get(hir_id) {
2439             hir::Node::AnonConst(ac) => ac.body,
2440             _ => span_bug!(
2441                 tcx.def_span(def_id.to_def_id()),
2442                 "from_inline_const can only process anonymous constants"
2443             ),
2444         };
2445         let expr = &tcx.hir().body(body_id).value;
2446         let ty = tcx.typeck(def_id).node_type(hir_id);
2447
2448         let lit_input = match expr.kind {
2449             hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2450             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
2451                 hir::ExprKind::Lit(ref lit) => {
2452                     Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2453                 }
2454                 _ => None,
2455             },
2456             _ => None,
2457         };
2458         if let Some(lit_input) = lit_input {
2459             // If an error occurred, ignore that it's a literal and leave reporting the error up to
2460             // mir.
2461             match tcx.at(expr.span).lit_to_mir_constant(lit_input) {
2462                 Ok(c) => return c,
2463                 Err(_) => {}
2464             }
2465         }
2466
2467         let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
2468         let parent_substs =
2469             tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
2470         let substs =
2471             ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty })
2472                 .substs;
2473
2474         let uneval = UnevaluatedConst {
2475             def: ty::WithOptConstParam::unknown(def_id).to_global(),
2476             substs,
2477             promoted: None,
2478         };
2479         debug_assert!(!uneval.has_free_regions());
2480
2481         Self::Unevaluated(uneval, ty)
2482     }
2483
2484     #[instrument(skip(tcx), level = "debug", ret)]
2485     fn from_opt_const_arg_anon_const(
2486         tcx: TyCtxt<'tcx>,
2487         def: ty::WithOptConstParam<LocalDefId>,
2488         param_env: ty::ParamEnv<'tcx>,
2489     ) -> Self {
2490         let body_id = match tcx.hir().get_by_def_id(def.did) {
2491             hir::Node::AnonConst(ac) => ac.body,
2492             _ => span_bug!(
2493                 tcx.def_span(def.did.to_def_id()),
2494                 "from_anon_const can only process anonymous constants"
2495             ),
2496         };
2497
2498         let expr = &tcx.hir().body(body_id).value;
2499         debug!(?expr);
2500
2501         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2502         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2503         let expr = match &expr.kind {
2504             hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2505                 block.expr.as_ref().unwrap()
2506             }
2507             _ => expr,
2508         };
2509         debug!("expr.kind: {:?}", expr.kind);
2510
2511         let ty = tcx.type_of(def.def_id_for_type_of());
2512         debug!(?ty);
2513
2514         // FIXME(const_generics): We currently have to special case parameters because `min_const_generics`
2515         // does not provide the parents generics to anonymous constants. We still allow generic const
2516         // parameters by themselves however, e.g. `N`.  These constants would cause an ICE if we were to
2517         // ever try to substitute the generic parameters in their bodies.
2518         //
2519         // While this doesn't happen as these constants are always used as `ty::ConstKind::Param`, it does
2520         // cause issues if we were to remove that special-case and try to evaluate the constant instead.
2521         use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
2522         match expr.kind {
2523             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
2524                 // Find the name and index of the const parameter by indexing the generics of
2525                 // the parent item and construct a `ParamConst`.
2526                 let item_def_id = tcx.parent(def_id);
2527                 let generics = tcx.generics_of(item_def_id);
2528                 let index = generics.param_def_id_to_index[&def_id];
2529                 let name = tcx.item_name(def_id);
2530                 let ty_const =
2531                     tcx.mk_const(ty::ConstKind::Param(ty::ParamConst::new(index, name)), ty);
2532                 debug!(?ty_const);
2533
2534                 return Self::Ty(ty_const);
2535             }
2536             _ => {}
2537         }
2538
2539         let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2540         let parent_substs = if let Some(parent_hir_id) = tcx.hir().find_parent_node(hir_id) {
2541             if let Some(parent_did) = tcx.hir().opt_local_def_id(parent_hir_id) {
2542                 InternalSubsts::identity_for_item(tcx, parent_did.to_def_id())
2543             } else {
2544                 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2545             }
2546         } else {
2547             tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
2548         };
2549         debug!(?parent_substs);
2550
2551         let did = def.did.to_def_id();
2552         let child_substs = InternalSubsts::identity_for_item(tcx, did);
2553         let substs = tcx.mk_substs(parent_substs.into_iter().chain(child_substs.into_iter()));
2554         debug!(?substs);
2555
2556         let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
2557         let span = tcx.hir().span(hir_id);
2558         let uneval = UnevaluatedConst::new(def.to_global(), substs);
2559         debug!(?span, ?param_env);
2560
2561         match tcx.const_eval_resolve(param_env, uneval, Some(span)) {
2562             Ok(val) => {
2563                 debug!("evaluated const value");
2564                 Self::Val(val, ty)
2565             }
2566             Err(_) => {
2567                 debug!("error encountered during evaluation");
2568                 // Error was handled in `const_eval_resolve`. Here we just create a
2569                 // new unevaluated const and error hard later in codegen
2570                 Self::Unevaluated(
2571                     UnevaluatedConst {
2572                         def: def.to_global(),
2573                         substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
2574                         promoted: None,
2575                     },
2576                     ty,
2577                 )
2578             }
2579         }
2580     }
2581
2582     pub fn from_const(c: ty::Const<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
2583         match c.kind() {
2584             ty::ConstKind::Value(valtree) => {
2585                 let const_val = tcx.valtree_to_const_val((c.ty(), valtree));
2586                 Self::Val(const_val, c.ty())
2587             }
2588             ty::ConstKind::Unevaluated(uv) => Self::Unevaluated(uv.expand(), c.ty()),
2589             _ => Self::Ty(c),
2590         }
2591     }
2592 }
2593
2594 /// An unevaluated (potentially generic) constant used in MIR.
2595 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
2596 #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
2597 pub struct UnevaluatedConst<'tcx> {
2598     pub def: ty::WithOptConstParam<DefId>,
2599     pub substs: SubstsRef<'tcx>,
2600     pub promoted: Option<Promoted>,
2601 }
2602
2603 impl<'tcx> UnevaluatedConst<'tcx> {
2604     // FIXME: probably should get rid of this method. It's also wrong to
2605     // shrink and then later expand a promoted.
2606     #[inline]
2607     pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> {
2608         ty::UnevaluatedConst { def: self.def, substs: self.substs }
2609     }
2610 }
2611
2612 impl<'tcx> UnevaluatedConst<'tcx> {
2613     #[inline]
2614     pub fn new(
2615         def: ty::WithOptConstParam<DefId>,
2616         substs: SubstsRef<'tcx>,
2617     ) -> UnevaluatedConst<'tcx> {
2618         UnevaluatedConst { def, substs, promoted: Default::default() }
2619     }
2620 }
2621
2622 /// A collection of projections into user types.
2623 ///
2624 /// They are projections because a binding can occur a part of a
2625 /// parent pattern that has been ascribed a type.
2626 ///
2627 /// Its a collection because there can be multiple type ascriptions on
2628 /// the path from the root of the pattern down to the binding itself.
2629 ///
2630 /// An example:
2631 ///
2632 /// ```ignore (illustrative)
2633 /// struct S<'a>((i32, &'a str), String);
2634 /// let S((_, w): (i32, &'static str), _): S = ...;
2635 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2636 /// //  ---------------------------------  ^ (2)
2637 /// ```
2638 ///
2639 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2640 /// ascribed the type `(i32, &'static str)`.
2641 ///
2642 /// The highlights labelled `(2)` show the whole pattern being
2643 /// ascribed the type `S`.
2644 ///
2645 /// In this example, when we descend to `w`, we will have built up the
2646 /// following two projected types:
2647 ///
2648 ///   * base: `S`,                   projection: `(base.0).1`
2649 ///   * base: `(i32, &'static str)`, projection: `base.1`
2650 ///
2651 /// The first will lead to the constraint `w: &'1 str` (for some
2652 /// inferred region `'1`). The second will lead to the constraint `w:
2653 /// &'static str`.
2654 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
2655 pub struct UserTypeProjections {
2656     pub contents: Vec<(UserTypeProjection, Span)>,
2657 }
2658
2659 impl<'tcx> UserTypeProjections {
2660     pub fn none() -> Self {
2661         UserTypeProjections { contents: vec![] }
2662     }
2663
2664     pub fn is_empty(&self) -> bool {
2665         self.contents.is_empty()
2666     }
2667
2668     pub fn projections_and_spans(
2669         &self,
2670     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2671         self.contents.iter()
2672     }
2673
2674     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2675         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2676     }
2677
2678     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2679         self.contents.push((user_ty.clone(), span));
2680         self
2681     }
2682
2683     fn map_projections(
2684         mut self,
2685         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2686     ) -> Self {
2687         self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
2688         self
2689     }
2690
2691     pub fn index(self) -> Self {
2692         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2693     }
2694
2695     pub fn subslice(self, from: u64, to: u64) -> Self {
2696         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2697     }
2698
2699     pub fn deref(self) -> Self {
2700         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2701     }
2702
2703     pub fn leaf(self, field: Field) -> Self {
2704         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2705     }
2706
2707     pub fn variant(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx, field: Field) -> Self {
2708         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2709     }
2710 }
2711
2712 /// Encodes the effect of a user-supplied type annotation on the
2713 /// subcomponents of a pattern. The effect is determined by applying the
2714 /// given list of projections to some underlying base type. Often,
2715 /// the projection element list `projs` is empty, in which case this
2716 /// directly encodes a type in `base`. But in the case of complex patterns with
2717 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2718 /// in which case the `projs` vector is used.
2719 ///
2720 /// Examples:
2721 ///
2722 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2723 ///
2724 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2725 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2726 ///   determined by finding the type of the `.0` field from `T`.
2727 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2728 pub struct UserTypeProjection {
2729     pub base: UserTypeAnnotationIndex,
2730     pub projs: Vec<ProjectionKind>,
2731 }
2732
2733 impl Copy for ProjectionKind {}
2734
2735 impl UserTypeProjection {
2736     pub(crate) fn index(mut self) -> Self {
2737         self.projs.push(ProjectionElem::Index(()));
2738         self
2739     }
2740
2741     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2742         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2743         self
2744     }
2745
2746     pub(crate) fn deref(mut self) -> Self {
2747         self.projs.push(ProjectionElem::Deref);
2748         self
2749     }
2750
2751     pub(crate) fn leaf(mut self, field: Field) -> Self {
2752         self.projs.push(ProjectionElem::Field(field, ()));
2753         self
2754     }
2755
2756     pub(crate) fn variant(
2757         mut self,
2758         adt_def: AdtDef<'_>,
2759         variant_index: VariantIdx,
2760         field: Field,
2761     ) -> Self {
2762         self.projs.push(ProjectionElem::Downcast(
2763             Some(adt_def.variant(variant_index).name),
2764             variant_index,
2765         ));
2766         self.projs.push(ProjectionElem::Field(field, ()));
2767         self
2768     }
2769 }
2770
2771 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2772     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
2773         Ok(UserTypeProjection {
2774             base: self.base.try_fold_with(folder)?,
2775             projs: self.projs.try_fold_with(folder)?,
2776         })
2777     }
2778 }
2779
2780 impl<'tcx> TypeVisitable<'tcx> for UserTypeProjection {
2781     fn visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> ControlFlow<Vs::BreakTy> {
2782         self.base.visit_with(visitor)
2783         // Note: there's nothing in `self.proj` to visit.
2784     }
2785 }
2786
2787 rustc_index::newtype_index! {
2788     pub struct Promoted {
2789         derive [HashStable]
2790         DEBUG_FORMAT = "promoted[{}]"
2791     }
2792 }
2793
2794 impl<'tcx> Debug for Constant<'tcx> {
2795     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2796         write!(fmt, "{}", self)
2797     }
2798 }
2799
2800 impl<'tcx> Display for Constant<'tcx> {
2801     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2802         match self.ty().kind() {
2803             ty::FnDef(..) => {}
2804             _ => write!(fmt, "const ")?,
2805         }
2806         Display::fmt(&self.literal, fmt)
2807     }
2808 }
2809
2810 impl<'tcx> Display for ConstantKind<'tcx> {
2811     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2812         match *self {
2813             ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
2814             ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2815             // FIXME(valtrees): Correctly print mir constants.
2816             ConstantKind::Unevaluated(..) => {
2817                 fmt.write_str("_")?;
2818                 Ok(())
2819             }
2820         }
2821     }
2822 }
2823
2824 fn pretty_print_const<'tcx>(
2825     c: ty::Const<'tcx>,
2826     fmt: &mut Formatter<'_>,
2827     print_types: bool,
2828 ) -> fmt::Result {
2829     use crate::ty::print::PrettyPrinter;
2830     ty::tls::with(|tcx| {
2831         let literal = tcx.lift(c).unwrap();
2832         let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2833         cx.print_alloc_ids = true;
2834         let cx = cx.pretty_print_const(literal, print_types)?;
2835         fmt.write_str(&cx.into_buffer())?;
2836         Ok(())
2837     })
2838 }
2839
2840 fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
2841     write!(fmt, "b\"{}\"", byte_str.escape_ascii())
2842 }
2843
2844 fn comma_sep<'tcx>(fmt: &mut Formatter<'_>, elems: Vec<ConstantKind<'tcx>>) -> fmt::Result {
2845     let mut first = true;
2846     for elem in elems {
2847         if !first {
2848             fmt.write_str(", ")?;
2849         }
2850         fmt.write_str(&format!("{}", elem))?;
2851         first = false;
2852     }
2853     Ok(())
2854 }
2855
2856 // FIXME: Move that into `mir/pretty.rs`.
2857 fn pretty_print_const_value<'tcx>(
2858     ct: ConstValue<'tcx>,
2859     ty: Ty<'tcx>,
2860     fmt: &mut Formatter<'_>,
2861     print_ty: bool,
2862 ) -> fmt::Result {
2863     use crate::ty::print::PrettyPrinter;
2864
2865     ty::tls::with(|tcx| {
2866         let ct = tcx.lift(ct).unwrap();
2867         let ty = tcx.lift(ty).unwrap();
2868
2869         if tcx.sess.verbose() {
2870             fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?;
2871             return Ok(());
2872         }
2873
2874         let u8_type = tcx.types.u8;
2875         match (ct, ty.kind()) {
2876             // Byte/string slices, printed as (byte) string literals.
2877             (ConstValue::Slice { data, start, end }, ty::Ref(_, inner, _)) => {
2878                 match inner.kind() {
2879                     ty::Slice(t) => {
2880                         if *t == u8_type {
2881                             // The `inspect` here is okay since we checked the bounds, and `u8` carries
2882                             // no provenance (we have an active slice reference here). We don't use
2883                             // this result to affect interpreter execution.
2884                             let byte_str = data
2885                                 .inner()
2886                                 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2887                             pretty_print_byte_str(fmt, byte_str)?;
2888                             return Ok(());
2889                         }
2890                     }
2891                     ty::Str => {
2892                         // The `inspect` here is okay since we checked the bounds, and `str` carries
2893                         // no provenance (we have an active `str` reference here). We don't use this
2894                         // result to affect interpreter execution.
2895                         let slice = data
2896                             .inner()
2897                             .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
2898                         fmt.write_str(&format!("{:?}", String::from_utf8_lossy(slice)))?;
2899                         return Ok(());
2900                     }
2901                     _ => {}
2902                 }
2903             }
2904             (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
2905                 let n = n.kind().try_to_bits(tcx.data_layout.pointer_size).unwrap();
2906                 // cast is ok because we already checked for pointer size (32 or 64 bit) above
2907                 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
2908                 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
2909                 fmt.write_str("*")?;
2910                 pretty_print_byte_str(fmt, byte_str)?;
2911                 return Ok(());
2912             }
2913             // Aggregates, printed as array/tuple/struct/variant construction syntax.
2914             //
2915             // NB: the `has_non_region_param` check ensures that we can use
2916             // the `destructure_const` query with an empty `ty::ParamEnv` without
2917             // introducing ICEs (e.g. via `layout_of`) from missing bounds.
2918             // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
2919             // to be able to destructure the tuple into `(0u8, *mut T)
2920             //
2921             // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
2922             // correct `ty::ParamEnv` to allow printing *all* constant values.
2923             (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
2924                 let ct = tcx.lift(ct).unwrap();
2925                 let ty = tcx.lift(ty).unwrap();
2926                 if let Some(contents) = tcx.try_destructure_mir_constant(
2927                     ty::ParamEnv::reveal_all().and(ConstantKind::Val(ct, ty)),
2928                 ) {
2929                     let fields = contents.fields.iter().copied().collect::<Vec<_>>();
2930                     match *ty.kind() {
2931                         ty::Array(..) => {
2932                             fmt.write_str("[")?;
2933                             comma_sep(fmt, fields)?;
2934                             fmt.write_str("]")?;
2935                         }
2936                         ty::Tuple(..) => {
2937                             fmt.write_str("(")?;
2938                             comma_sep(fmt, fields)?;
2939                             if contents.fields.len() == 1 {
2940                                 fmt.write_str(",")?;
2941                             }
2942                             fmt.write_str(")")?;
2943                         }
2944                         ty::Adt(def, _) if def.variants().is_empty() => {
2945                             fmt.write_str(&format!("{{unreachable(): {}}}", ty))?;
2946                         }
2947                         ty::Adt(def, substs) => {
2948                             let variant_idx = contents
2949                                 .variant
2950                                 .expect("destructed mir constant of adt without variant idx");
2951                             let variant_def = &def.variant(variant_idx);
2952                             let substs = tcx.lift(substs).unwrap();
2953                             let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2954                             cx.print_alloc_ids = true;
2955                             let cx = cx.print_value_path(variant_def.def_id, substs)?;
2956                             fmt.write_str(&cx.into_buffer())?;
2957
2958                             match variant_def.ctor_kind() {
2959                                 Some(CtorKind::Const) => {}
2960                                 Some(CtorKind::Fn) => {
2961                                     fmt.write_str("(")?;
2962                                     comma_sep(fmt, fields)?;
2963                                     fmt.write_str(")")?;
2964                                 }
2965                                 None => {
2966                                     fmt.write_str(" {{ ")?;
2967                                     let mut first = true;
2968                                     for (field_def, field) in iter::zip(&variant_def.fields, fields)
2969                                     {
2970                                         if !first {
2971                                             fmt.write_str(", ")?;
2972                                         }
2973                                         fmt.write_str(&format!("{}: {}", field_def.name, field))?;
2974                                         first = false;
2975                                     }
2976                                     fmt.write_str(" }}")?;
2977                                 }
2978                             }
2979                         }
2980                         _ => unreachable!(),
2981                     }
2982                     return Ok(());
2983                 } else {
2984                     // Fall back to debug pretty printing for invalid constants.
2985                     fmt.write_str(&format!("{:?}", ct))?;
2986                     if print_ty {
2987                         fmt.write_str(&format!(": {}", ty))?;
2988                     }
2989                     return Ok(());
2990                 };
2991             }
2992             (ConstValue::Scalar(scalar), _) => {
2993                 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2994                 cx.print_alloc_ids = true;
2995                 let ty = tcx.lift(ty).unwrap();
2996                 cx = cx.pretty_print_const_scalar(scalar, ty, print_ty)?;
2997                 fmt.write_str(&cx.into_buffer())?;
2998                 return Ok(());
2999             }
3000             (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
3001                 let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
3002                 cx.print_alloc_ids = true;
3003                 let cx = cx.print_value_path(*d, s)?;
3004                 fmt.write_str(&cx.into_buffer())?;
3005                 return Ok(());
3006             }
3007             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
3008             // their fields instead of just dumping the memory.
3009             _ => {}
3010         }
3011         // fallback
3012         fmt.write_str(&format!("{:?}", ct))?;
3013         if print_ty {
3014             fmt.write_str(&format!(": {}", ty))?;
3015         }
3016         Ok(())
3017     })
3018 }
3019
3020 /// `Location` represents the position of the start of the statement; or, if
3021 /// `statement_index` equals the number of statements, then the start of the
3022 /// terminator.
3023 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
3024 pub struct Location {
3025     /// The block that the location is within.
3026     pub block: BasicBlock,
3027
3028     pub statement_index: usize,
3029 }
3030
3031 impl fmt::Debug for Location {
3032     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3033         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
3034     }
3035 }
3036
3037 impl Location {
3038     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
3039
3040     /// Returns the location immediately after this one within the enclosing block.
3041     ///
3042     /// Note that if this location represents a terminator, then the
3043     /// resulting location would be out of bounds and invalid.
3044     pub fn successor_within_block(&self) -> Location {
3045         Location { block: self.block, statement_index: self.statement_index + 1 }
3046     }
3047
3048     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
3049     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
3050         // If we are in the same block as the other location and are an earlier statement
3051         // then we are a predecessor of `other`.
3052         if self.block == other.block && self.statement_index < other.statement_index {
3053             return true;
3054         }
3055
3056         let predecessors = body.basic_blocks.predecessors();
3057
3058         // If we're in another block, then we want to check that block is a predecessor of `other`.
3059         let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
3060         let mut visited = FxHashSet::default();
3061
3062         while let Some(block) = queue.pop() {
3063             // If we haven't visited this block before, then make sure we visit its predecessors.
3064             if visited.insert(block) {
3065                 queue.extend(predecessors[block].iter().cloned());
3066             } else {
3067                 continue;
3068             }
3069
3070             // If we found the block that `self` is in, then we are a predecessor of `other` (since
3071             // we found that block by looking at the predecessors of `other`).
3072             if self.block == block {
3073                 return true;
3074             }
3075         }
3076
3077         false
3078     }
3079
3080     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3081         if self.block == other.block {
3082             self.statement_index <= other.statement_index
3083         } else {
3084             dominators.is_dominated_by(other.block, self.block)
3085         }
3086     }
3087 }
3088
3089 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3090 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3091 mod size_asserts {
3092     use super::*;
3093     use rustc_data_structures::static_assert_size;
3094     // tidy-alphabetical-start
3095     static_assert_size!(BasicBlockData<'_>, 144);
3096     static_assert_size!(LocalDecl<'_>, 56);
3097     static_assert_size!(Statement<'_>, 32);
3098     static_assert_size!(StatementKind<'_>, 16);
3099     static_assert_size!(Terminator<'_>, 112);
3100     static_assert_size!(TerminatorKind<'_>, 96);
3101     // tidy-alphabetical-end
3102 }