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