]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
Merge commit '63734fcdd718cca089f84c42f3a42c0096cfd431' into sync_cg_clif-2022-05-15
[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::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{ConstAllocation, ConstValue, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
13 use crate::ty::{self, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, Region, ScalarInt, UserTypeAnnotationIndex};
15
16 use rustc_errors::ErrorGuaranteed;
17 use rustc_hir::def::{CtorKind, Namespace};
18 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
19 use rustc_hir::{self, GeneratorKind};
20 use rustc_hir::{self as hir, HirId};
21 use rustc_session::Session;
22 use rustc_target::abi::{Size, VariantIdx};
23
24 use polonius_engine::Atom;
25 pub use rustc_ast::Mutability;
26 use rustc_data_structures::fx::FxHashSet;
27 use rustc_data_structures::graph::dominators::{dominators, Dominators};
28 use rustc_data_structures::graph::{self, GraphSuccessors};
29 use rustc_index::bit_set::BitMatrix;
30 use rustc_index::vec::{Idx, IndexVec};
31 use rustc_serialize::{Decodable, Encodable};
32 use rustc_span::symbol::Symbol;
33 use rustc_span::{Span, DUMMY_SP};
34 use rustc_target::asm::InlineAsmRegOrRegClass;
35
36 use either::Either;
37
38 use std::borrow::Cow;
39 use std::convert::TryInto;
40 use std::fmt::{self, Debug, Display, Formatter, Write};
41 use std::ops::{ControlFlow, Index, IndexMut};
42 use std::slice;
43 use std::{iter, mem, option};
44
45 use self::graph_cyclic_cache::GraphIsCyclicCache;
46 use self::predecessors::{PredecessorCache, Predecessors};
47 pub use self::query::*;
48 use self::switch_sources::{SwitchSourceCache, SwitchSources};
49
50 pub mod coverage;
51 mod generic_graph;
52 pub mod generic_graphviz;
53 mod graph_cyclic_cache;
54 pub mod graphviz;
55 pub mod interpret;
56 pub mod mono;
57 pub mod patch;
58 mod predecessors;
59 pub mod pretty;
60 mod query;
61 pub mod spanview;
62 mod switch_sources;
63 pub mod tcx;
64 pub mod terminator;
65 use crate::mir::traversal::PostorderCache;
66 pub use terminator::*;
67
68 pub mod traversal;
69 mod type_foldable;
70 pub mod visit;
71
72 pub use self::generic_graph::graphviz_safe_def_name;
73 pub use self::graphviz::write_mir_graphviz;
74 pub use self::pretty::{
75     create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere,
76 };
77
78 /// Types for locals
79 pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
80
81 pub trait HasLocalDecls<'tcx> {
82     fn local_decls(&self) -> &LocalDecls<'tcx>;
83 }
84
85 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
86     #[inline]
87     fn local_decls(&self) -> &LocalDecls<'tcx> {
88         self
89     }
90 }
91
92 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
93     #[inline]
94     fn local_decls(&self) -> &LocalDecls<'tcx> {
95         &self.local_decls
96     }
97 }
98
99 /// A streamlined trait that you can implement to create a pass; the
100 /// pass will be named after the type, and it will consist of a main
101 /// loop that goes over each available MIR and applies `run_pass`.
102 pub trait MirPass<'tcx> {
103     fn name(&self) -> Cow<'_, str> {
104         let name = std::any::type_name::<Self>();
105         if let Some(tail) = name.rfind(':') {
106             Cow::from(&name[tail + 1..])
107         } else {
108             Cow::from(name)
109         }
110     }
111
112     /// Returns `true` if this pass is enabled with the current combination of compiler flags.
113     fn is_enabled(&self, _sess: &Session) -> bool {
114         true
115     }
116
117     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
118
119     /// If this pass causes the MIR to enter a new phase, return that phase.
120     fn phase_change(&self) -> Option<MirPhase> {
121         None
122     }
123
124     fn is_mir_dump_enabled(&self) -> bool {
125         true
126     }
127 }
128
129 /// The various "big phases" that MIR goes through.
130 ///
131 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
132 /// dialects forbid certain variants or values in certain phases. The sections below summarize the
133 /// changes, but do not document them thoroughly. The full documentation is found in the appropriate
134 /// documentation for the thing the change is affecting.
135 ///
136 /// Warning: ordering of variants is significant.
137 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
138 #[derive(HashStable)]
139 pub enum MirPhase {
140     /// The dialect of MIR used during all phases before `DropsLowered` is the same. This is also
141     /// the MIR that analysis such as borrowck uses.
142     ///
143     /// One important thing to remember about the behavior of this section of MIR is that drop terminators
144     /// (including drop and replace) are *conditional*. The elaborate drops pass will then replace each
145     /// instance of a drop terminator with a nop, an unconditional drop, or a drop conditioned on a drop
146     /// flag. Of course, this means that it is important that the drop elaboration can accurately recognize
147     /// when things are initialized and when things are de-initialized. That means any code running on this
148     /// version of MIR must be sure to produce output that drop elaboration can reason about. See the
149     /// section on the drop terminatorss for more details.
150     Built = 0,
151     // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
152     // We used to have this for pre-miri MIR based const eval.
153     Const = 1,
154     /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
155     /// by creating a new MIR body per promoted element. After this phase (and thus the termination
156     /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
157     /// query.
158     ConstsPromoted = 2,
159     /// Beginning with this phase, the following variants are disallowed:
160     /// * [`TerminatorKind::DropAndReplace`](terminator::TerminatorKind::DropAndReplace)
161     /// * [`TerminatorKind::FalseUnwind`](terminator::TerminatorKind::FalseUnwind)
162     /// * [`TerminatorKind::FalseEdge`](terminator::TerminatorKind::FalseEdge)
163     /// * [`StatementKind::FakeRead`]
164     /// * [`StatementKind::AscribeUserType`]
165     /// * [`Rvalue::Ref`] with `BorrowKind::Shallow`
166     ///
167     /// And the following variant is allowed:
168     /// * [`StatementKind::Retag`]
169     ///
170     /// Furthermore, `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop`
171     /// terminator means that the auto-generated drop glue will be invoked. Also, `Copy` operands
172     /// are allowed for non-`Copy` types.
173     DropsLowered = 3,
174     /// Beginning with this phase, the following variant is disallowed:
175     /// * [`Rvalue::Aggregate`] for any `AggregateKind` except `Array`
176     ///
177     /// And the following variant is allowed:
178     /// * [`StatementKind::SetDiscriminant`]
179     Deaggregated = 4,
180     /// Before this phase, generators are in the "source code" form, featuring `yield` statements
181     /// and such. With this phase change, they are transformed into a proper state machine. Running
182     /// optimizations before this change can be potentially dangerous because the source code is to
183     /// some extent a "lie." In particular, `yield` terminators effectively make the value of all
184     /// locals visible to the caller. This means that dead store elimination before them, or code
185     /// motion across them, is not correct in general. This is also exasperated by type checking
186     /// having pre-computed a list of the types that it thinks are ok to be live across a yield
187     /// point - this is necessary to decide eg whether autotraits are implemented. Introducing new
188     /// types across a yield point will lead to ICEs becaues of this.
189     ///
190     /// Beginning with this phase, the following variants are disallowed:
191     /// * [`TerminatorKind::Yield`](terminator::TerminatorKind::Yield)
192     /// * [`TerminatorKind::GeneratorDrop](terminator::TerminatorKind::GeneratorDrop)
193     GeneratorsLowered = 5,
194     Optimized = 6,
195 }
196
197 impl MirPhase {
198     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
199     pub fn phase_index(&self) -> usize {
200         *self as usize
201     }
202 }
203
204 /// Where a specific `mir::Body` comes from.
205 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
206 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
207 pub struct MirSource<'tcx> {
208     pub instance: InstanceDef<'tcx>,
209
210     /// If `Some`, this is a promoted rvalue within the parent function.
211     pub promoted: Option<Promoted>,
212 }
213
214 impl<'tcx> MirSource<'tcx> {
215     pub fn item(def_id: DefId) -> Self {
216         MirSource {
217             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
218             promoted: None,
219         }
220     }
221
222     pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
223         MirSource { instance, promoted: None }
224     }
225
226     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
227         self.instance.with_opt_param()
228     }
229
230     #[inline]
231     pub fn def_id(&self) -> DefId {
232         self.instance.def_id()
233     }
234 }
235
236 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
237 pub struct GeneratorInfo<'tcx> {
238     /// The yield type of the function, if it is a generator.
239     pub yield_ty: Option<Ty<'tcx>>,
240
241     /// Generator drop glue.
242     pub generator_drop: Option<Body<'tcx>>,
243
244     /// The layout of a generator. Produced by the state transformation.
245     pub generator_layout: Option<GeneratorLayout<'tcx>>,
246
247     /// If this is a generator then record the type of source expression that caused this generator
248     /// to be created.
249     pub generator_kind: GeneratorKind,
250 }
251
252 /// The lowered representation of a single function.
253 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
254 pub struct Body<'tcx> {
255     /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
256     /// that indexes into this vector.
257     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
258
259     /// Records how far through the "desugaring and optimization" process this particular
260     /// MIR has traversed. This is particularly useful when inlining, since in that context
261     /// we instantiate the promoted constants and add them to our promoted vector -- but those
262     /// promoted items have already been optimized, whereas ours have not. This field allows
263     /// us to see the difference and forego optimization on the inlined promoted items.
264     pub phase: MirPhase,
265
266     pub source: MirSource<'tcx>,
267
268     /// A list of source scopes; these are referenced by statements
269     /// and used for debuginfo. Indexed by a `SourceScope`.
270     pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
271
272     pub generator: Option<Box<GeneratorInfo<'tcx>>>,
273
274     /// Declarations of locals.
275     ///
276     /// The first local is the return value pointer, followed by `arg_count`
277     /// locals for the function arguments, followed by any user-declared
278     /// variables and temporaries.
279     pub local_decls: LocalDecls<'tcx>,
280
281     /// User type annotations.
282     pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
283
284     /// The number of arguments this function takes.
285     ///
286     /// Starting at local 1, `arg_count` locals will be provided by the caller
287     /// and can be assumed to be initialized.
288     ///
289     /// If this MIR was built for a constant, this will be 0.
290     pub arg_count: usize,
291
292     /// Mark an argument local (which must be a tuple) as getting passed as
293     /// its individual components at the LLVM level.
294     ///
295     /// This is used for the "rust-call" ABI.
296     pub spread_arg: Option<Local>,
297
298     /// Debug information pertaining to user variables, including captures.
299     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
300
301     /// A span representing this MIR, for error reporting.
302     pub span: Span,
303
304     /// Constants that are required to evaluate successfully for this MIR to be well-formed.
305     /// We hold in this field all the constants we are not able to evaluate yet.
306     pub required_consts: Vec<Constant<'tcx>>,
307
308     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
309     ///
310     /// Note that this does not actually mean that this body is not computable right now.
311     /// The repeat count in the following example is polymorphic, but can still be evaluated
312     /// without knowing anything about the type parameter `T`.
313     ///
314     /// ```rust
315     /// fn test<T>() {
316     ///     let _ = [0; std::mem::size_of::<*mut T>()];
317     /// }
318     /// ```
319     ///
320     /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
321     /// removed the last mention of all generic params. We do not want to rely on optimizations and
322     /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
323     pub is_polymorphic: bool,
324
325     predecessor_cache: PredecessorCache,
326     switch_source_cache: SwitchSourceCache,
327     is_cyclic: GraphIsCyclicCache,
328     postorder_cache: PostorderCache,
329
330     pub tainted_by_errors: Option<ErrorGuaranteed>,
331 }
332
333 impl<'tcx> Body<'tcx> {
334     pub fn new(
335         source: MirSource<'tcx>,
336         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
337         source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
338         local_decls: LocalDecls<'tcx>,
339         user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
340         arg_count: usize,
341         var_debug_info: Vec<VarDebugInfo<'tcx>>,
342         span: Span,
343         generator_kind: Option<GeneratorKind>,
344         tainted_by_errors: Option<ErrorGuaranteed>,
345     ) -> Self {
346         // We need `arg_count` locals, and one for the return place.
347         assert!(
348             local_decls.len() > arg_count,
349             "expected at least {} locals, got {}",
350             arg_count + 1,
351             local_decls.len()
352         );
353
354         let mut body = Body {
355             phase: MirPhase::Built,
356             source,
357             basic_blocks,
358             source_scopes,
359             generator: generator_kind.map(|generator_kind| {
360                 Box::new(GeneratorInfo {
361                     yield_ty: None,
362                     generator_drop: None,
363                     generator_layout: None,
364                     generator_kind,
365                 })
366             }),
367             local_decls,
368             user_type_annotations,
369             arg_count,
370             spread_arg: None,
371             var_debug_info,
372             span,
373             required_consts: Vec::new(),
374             is_polymorphic: false,
375             predecessor_cache: PredecessorCache::new(),
376             switch_source_cache: SwitchSourceCache::new(),
377             is_cyclic: GraphIsCyclicCache::new(),
378             postorder_cache: PostorderCache::new(),
379             tainted_by_errors,
380         };
381         body.is_polymorphic = body.has_param_types_or_consts();
382         body
383     }
384
385     /// Returns a partially initialized MIR body containing only a list of basic blocks.
386     ///
387     /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
388     /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
389     /// crate.
390     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
391         let mut body = Body {
392             phase: MirPhase::Built,
393             source: MirSource::item(CRATE_DEF_ID.to_def_id()),
394             basic_blocks,
395             source_scopes: IndexVec::new(),
396             generator: None,
397             local_decls: IndexVec::new(),
398             user_type_annotations: IndexVec::new(),
399             arg_count: 0,
400             spread_arg: None,
401             span: DUMMY_SP,
402             required_consts: Vec::new(),
403             var_debug_info: Vec::new(),
404             is_polymorphic: false,
405             predecessor_cache: PredecessorCache::new(),
406             switch_source_cache: SwitchSourceCache::new(),
407             is_cyclic: GraphIsCyclicCache::new(),
408             postorder_cache: PostorderCache::new(),
409             tainted_by_errors: None,
410         };
411         body.is_polymorphic = body.has_param_types_or_consts();
412         body
413     }
414
415     #[inline]
416     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
417         &self.basic_blocks
418     }
419
420     #[inline]
421     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
422         // Because the user could mutate basic block terminators via this reference, we need to
423         // invalidate the caches.
424         //
425         // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
426         // invalidate the caches.
427         self.predecessor_cache.invalidate();
428         self.switch_source_cache.invalidate();
429         self.is_cyclic.invalidate();
430         self.postorder_cache.invalidate();
431         &mut self.basic_blocks
432     }
433
434     #[inline]
435     pub fn basic_blocks_and_local_decls_mut(
436         &mut self,
437     ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
438         self.predecessor_cache.invalidate();
439         self.switch_source_cache.invalidate();
440         self.is_cyclic.invalidate();
441         self.postorder_cache.invalidate();
442         (&mut self.basic_blocks, &mut self.local_decls)
443     }
444
445     #[inline]
446     pub fn basic_blocks_local_decls_mut_and_var_debug_info(
447         &mut self,
448     ) -> (
449         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
450         &mut LocalDecls<'tcx>,
451         &mut Vec<VarDebugInfo<'tcx>>,
452     ) {
453         self.predecessor_cache.invalidate();
454         self.switch_source_cache.invalidate();
455         self.is_cyclic.invalidate();
456         self.postorder_cache.invalidate();
457         (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
458     }
459
460     /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
461     /// `START_BLOCK`.
462     pub fn is_cfg_cyclic(&self) -> bool {
463         self.is_cyclic.is_cyclic(self)
464     }
465
466     #[inline]
467     pub fn local_kind(&self, local: Local) -> LocalKind {
468         let index = local.as_usize();
469         if index == 0 {
470             debug_assert!(
471                 self.local_decls[local].mutability == Mutability::Mut,
472                 "return place should be mutable"
473             );
474
475             LocalKind::ReturnPointer
476         } else if index < self.arg_count + 1 {
477             LocalKind::Arg
478         } else if self.local_decls[local].is_user_variable() {
479             LocalKind::Var
480         } else {
481             LocalKind::Temp
482         }
483     }
484
485     /// Returns an iterator over all user-declared mutable locals.
486     #[inline]
487     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
488         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
489             let local = Local::new(index);
490             let decl = &self.local_decls[local];
491             if decl.is_user_variable() && decl.mutability == Mutability::Mut {
492                 Some(local)
493             } else {
494                 None
495             }
496         })
497     }
498
499     /// Returns an iterator over all user-declared mutable arguments and locals.
500     #[inline]
501     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
502         (1..self.local_decls.len()).filter_map(move |index| {
503             let local = Local::new(index);
504             let decl = &self.local_decls[local];
505             if (decl.is_user_variable() || index < self.arg_count + 1)
506                 && decl.mutability == Mutability::Mut
507             {
508                 Some(local)
509             } else {
510                 None
511             }
512         })
513     }
514
515     /// Returns an iterator over all function arguments.
516     #[inline]
517     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
518         (1..self.arg_count + 1).map(Local::new)
519     }
520
521     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
522     /// locals that are neither arguments nor the return place).
523     #[inline]
524     pub fn vars_and_temps_iter(
525         &self,
526     ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
527         (self.arg_count + 1..self.local_decls.len()).map(Local::new)
528     }
529
530     #[inline]
531     pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator<Item = LocalDecl<'tcx>> + 'a {
532         self.local_decls.drain(self.arg_count + 1..)
533     }
534
535     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
536     /// invalidating statement indices in `Location`s.
537     pub fn make_statement_nop(&mut self, location: Location) {
538         let block = &mut self.basic_blocks[location.block];
539         debug_assert!(location.statement_index < block.statements.len());
540         block.statements[location.statement_index].make_nop()
541     }
542
543     /// Returns the source info associated with `location`.
544     pub fn source_info(&self, location: Location) -> &SourceInfo {
545         let block = &self[location.block];
546         let stmts = &block.statements;
547         let idx = location.statement_index;
548         if idx < stmts.len() {
549             &stmts[idx].source_info
550         } else {
551             assert_eq!(idx, stmts.len());
552             &block.terminator().source_info
553         }
554     }
555
556     /// Returns the return type; it always return first element from `local_decls` array.
557     #[inline]
558     pub fn return_ty(&self) -> Ty<'tcx> {
559         self.local_decls[RETURN_PLACE].ty
560     }
561
562     /// Gets the location of the terminator for the given block.
563     #[inline]
564     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
565         Location { block: bb, statement_index: self[bb].statements.len() }
566     }
567
568     pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> {
569         let Location { block, statement_index } = location;
570         let block_data = &self.basic_blocks[block];
571         block_data
572             .statements
573             .get(statement_index)
574             .map(Either::Left)
575             .unwrap_or_else(|| Either::Right(block_data.terminator()))
576     }
577
578     #[inline]
579     pub fn predecessors(&self) -> &Predecessors {
580         self.predecessor_cache.compute(&self.basic_blocks)
581     }
582
583     /// `body.switch_sources()[&(target, switch)]` returns a list of switch
584     /// values that lead to a `target` block from a `switch` block.
585     #[inline]
586     pub fn switch_sources(&self) -> &SwitchSources {
587         self.switch_source_cache.compute(&self.basic_blocks)
588     }
589
590     #[inline]
591     pub fn dominators(&self) -> Dominators<BasicBlock> {
592         dominators(self)
593     }
594
595     #[inline]
596     pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
597         self.generator.as_ref().and_then(|generator| generator.yield_ty)
598     }
599
600     #[inline]
601     pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
602         self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
603     }
604
605     #[inline]
606     pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
607         self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
608     }
609
610     #[inline]
611     pub fn generator_kind(&self) -> Option<GeneratorKind> {
612         self.generator.as_ref().map(|generator| generator.generator_kind)
613     }
614 }
615
616 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
617 pub enum Safety {
618     Safe,
619     /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
620     BuiltinUnsafe,
621     /// Unsafe because of an unsafe fn
622     FnUnsafe,
623     /// Unsafe because of an `unsafe` block
624     ExplicitUnsafe(hir::HirId),
625 }
626
627 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
628     type Output = BasicBlockData<'tcx>;
629
630     #[inline]
631     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
632         &self.basic_blocks()[index]
633     }
634 }
635
636 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
637     #[inline]
638     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
639         &mut self.basic_blocks_mut()[index]
640     }
641 }
642
643 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
644 pub enum ClearCrossCrate<T> {
645     Clear,
646     Set(T),
647 }
648
649 impl<T> ClearCrossCrate<T> {
650     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
651         match self {
652             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
653             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
654         }
655     }
656
657     pub fn assert_crate_local(self) -> T {
658         match self {
659             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
660             ClearCrossCrate::Set(v) => v,
661         }
662     }
663 }
664
665 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
666 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
667
668 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
669     #[inline]
670     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
671         if E::CLEAR_CROSS_CRATE {
672             return Ok(());
673         }
674
675         match *self {
676             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
677             ClearCrossCrate::Set(ref val) => {
678                 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
679                 val.encode(e)
680             }
681         }
682     }
683 }
684 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
685     #[inline]
686     fn decode(d: &mut D) -> ClearCrossCrate<T> {
687         if D::CLEAR_CROSS_CRATE {
688             return ClearCrossCrate::Clear;
689         }
690
691         let discr = u8::decode(d);
692
693         match discr {
694             TAG_CLEAR_CROSS_CRATE_CLEAR => ClearCrossCrate::Clear,
695             TAG_CLEAR_CROSS_CRATE_SET => {
696                 let val = T::decode(d);
697                 ClearCrossCrate::Set(val)
698             }
699             tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag),
700         }
701     }
702 }
703
704 /// Grouped information about the source code origin of a MIR entity.
705 /// Intended to be inspected by diagnostics and debuginfo.
706 /// Most passes can work with it as a whole, within a single function.
707 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
708 // `Hash`. Please ping @bjorn3 if removing them.
709 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
710 pub struct SourceInfo {
711     /// The source span for the AST pertaining to this MIR entity.
712     pub span: Span,
713
714     /// The source scope, keeping track of which bindings can be
715     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
716     pub scope: SourceScope,
717 }
718
719 impl SourceInfo {
720     #[inline]
721     pub fn outermost(span: Span) -> Self {
722         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
723     }
724 }
725
726 ///////////////////////////////////////////////////////////////////////////
727 // Borrow kinds
728
729 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
730 #[derive(Hash, HashStable)]
731 pub enum BorrowKind {
732     /// Data must be immutable and is aliasable.
733     Shared,
734
735     /// The immediately borrowed place must be immutable, but projections from
736     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
737     /// conflict with a mutable borrow of `a.b.c`.
738     ///
739     /// This is used when lowering matches: when matching on a place we want to
740     /// ensure that place have the same value from the start of the match until
741     /// an arm is selected. This prevents this code from compiling:
742     /// ```compile_fail,E0510
743     /// let mut x = &Some(0);
744     /// match *x {
745     ///     None => (),
746     ///     Some(_) if { x = &None; false } => (),
747     ///     Some(_) => (),
748     /// }
749     /// ```
750     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
751     /// should not prevent `if let None = x { ... }`, for example, because the
752     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
753     /// We can also report errors with this kind of borrow differently.
754     Shallow,
755
756     /// Data must be immutable but not aliasable. This kind of borrow
757     /// cannot currently be expressed by the user and is used only in
758     /// implicit closure bindings. It is needed when the closure is
759     /// borrowing or mutating a mutable referent, e.g.:
760     /// ```
761     /// let mut z = 3;
762     /// let x: &mut isize = &mut z;
763     /// let y = || *x += 5;
764     /// ```
765     /// If we were to try to translate this closure into a more explicit
766     /// form, we'd encounter an error with the code as written:
767     /// ```compile_fail,E0594
768     /// struct Env<'a> { x: &'a &'a mut isize }
769     /// let mut z = 3;
770     /// let x: &mut isize = &mut z;
771     /// let y = (&mut Env { x: &x }, fn_ptr);  // Closure is pair of env and fn
772     /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
773     /// ```
774     /// This is then illegal because you cannot mutate an `&mut` found
775     /// in an aliasable location. To solve, you'd have to translate with
776     /// an `&mut` borrow:
777     /// ```compile_fail,E0596
778     /// struct Env<'a> { x: &'a mut &'a mut isize }
779     /// let mut z = 3;
780     /// let x: &mut isize = &mut z;
781     /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
782     /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
783     /// ```
784     /// Now the assignment to `**env.x` is legal, but creating a
785     /// mutable pointer to `x` is not because `x` is not mutable. We
786     /// could fix this by declaring `x` as `let mut x`. This is ok in
787     /// user code, if awkward, but extra weird for closures, since the
788     /// borrow is hidden.
789     ///
790     /// So we introduce a "unique imm" borrow -- the referent is
791     /// immutable, but not aliasable. This solves the problem. For
792     /// simplicity, we don't give users the way to express this
793     /// borrow, it's just used when translating closures.
794     Unique,
795
796     /// Data is mutable and not aliasable.
797     Mut {
798         /// `true` if this borrow arose from method-call auto-ref
799         /// (i.e., `adjustment::Adjust::Borrow`).
800         allow_two_phase_borrow: bool,
801     },
802 }
803
804 impl BorrowKind {
805     pub fn allows_two_phase_borrow(&self) -> bool {
806         match *self {
807             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
808             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
809         }
810     }
811
812     pub fn describe_mutability(&self) -> String {
813         match *self {
814             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => {
815                 "immutable".to_string()
816             }
817             BorrowKind::Mut { .. } => "mutable".to_string(),
818         }
819     }
820 }
821
822 ///////////////////////////////////////////////////////////////////////////
823 // Variables and temps
824
825 rustc_index::newtype_index! {
826     pub struct Local {
827         derive [HashStable]
828         DEBUG_FORMAT = "_{}",
829         const RETURN_PLACE = 0,
830     }
831 }
832
833 impl Atom for Local {
834     fn index(self) -> usize {
835         Idx::index(self)
836     }
837 }
838
839 /// Classifies locals into categories. See `Body::local_kind`.
840 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
841 pub enum LocalKind {
842     /// User-declared variable binding.
843     Var,
844     /// Compiler-introduced temporary.
845     Temp,
846     /// Function argument.
847     Arg,
848     /// Location of function's return value.
849     ReturnPointer,
850 }
851
852 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
853 pub struct VarBindingForm<'tcx> {
854     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
855     pub binding_mode: ty::BindingMode,
856     /// If an explicit type was provided for this variable binding,
857     /// this holds the source Span of that type.
858     ///
859     /// NOTE: if you want to change this to a `HirId`, be wary that
860     /// doing so breaks incremental compilation (as of this writing),
861     /// while a `Span` does not cause our tests to fail.
862     pub opt_ty_info: Option<Span>,
863     /// Place of the RHS of the =, or the subject of the `match` where this
864     /// variable is initialized. None in the case of `let PATTERN;`.
865     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
866     /// (a) the right-hand side isn't evaluated as a place expression.
867     /// (b) it gives a way to separate this case from the remaining cases
868     ///     for diagnostics.
869     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
870     /// The span of the pattern in which this variable was bound.
871     pub pat_span: Span,
872 }
873
874 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
875 pub enum BindingForm<'tcx> {
876     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
877     Var(VarBindingForm<'tcx>),
878     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
879     ImplicitSelf(ImplicitSelfKind),
880     /// Reference used in a guard expression to ensure immutability.
881     RefForGuard,
882 }
883
884 /// Represents what type of implicit self a function has, if any.
885 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
886 pub enum ImplicitSelfKind {
887     /// Represents a `fn x(self);`.
888     Imm,
889     /// Represents a `fn x(mut self);`.
890     Mut,
891     /// Represents a `fn x(&self);`.
892     ImmRef,
893     /// Represents a `fn x(&mut self);`.
894     MutRef,
895     /// Represents when a function does not have a self argument or
896     /// when a function has a `self: X` argument.
897     None,
898 }
899
900 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
901
902 mod binding_form_impl {
903     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
904     use rustc_query_system::ich::StableHashingContext;
905
906     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
907         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
908             use super::BindingForm::*;
909             std::mem::discriminant(self).hash_stable(hcx, hasher);
910
911             match self {
912                 Var(binding) => binding.hash_stable(hcx, hasher),
913                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
914                 RefForGuard => (),
915             }
916         }
917     }
918 }
919
920 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
921 /// created during evaluation of expressions in a block tail
922 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
923 ///
924 /// It is used to improve diagnostics when such temporaries are
925 /// involved in borrow_check errors, e.g., explanations of where the
926 /// temporaries come from, when their destructors are run, and/or how
927 /// one might revise the code to satisfy the borrow checker's rules.
928 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
929 pub struct BlockTailInfo {
930     /// If `true`, then the value resulting from evaluating this tail
931     /// expression is ignored by the block's expression context.
932     ///
933     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
934     /// but not e.g., `let _x = { ...; tail };`
935     pub tail_result_is_ignored: bool,
936
937     /// `Span` of the tail expression.
938     pub span: Span,
939 }
940
941 /// A MIR local.
942 ///
943 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
944 /// argument, or the return place.
945 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
946 pub struct LocalDecl<'tcx> {
947     /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
948     ///
949     /// Temporaries and the return place are always mutable.
950     pub mutability: Mutability,
951
952     // FIXME(matthewjasper) Don't store in this in `Body`
953     pub local_info: Option<Box<LocalInfo<'tcx>>>,
954
955     /// `true` if this is an internal local.
956     ///
957     /// These locals are not based on types in the source code and are only used
958     /// for a few desugarings at the moment.
959     ///
960     /// The generator transformation will sanity check the locals which are live
961     /// across a suspension point against the type components of the generator
962     /// which type checking knows are live across a suspension point. We need to
963     /// flag drop flags to avoid triggering this check as they are introduced
964     /// outside of type inference.
965     ///
966     /// This should be sound because the drop flags are fully algebraic, and
967     /// therefore don't affect the auto-trait or outlives properties of the
968     /// generator.
969     pub internal: bool,
970
971     /// If this local is a temporary and `is_block_tail` is `Some`,
972     /// then it is a temporary created for evaluation of some
973     /// subexpression of some block's tail expression (with no
974     /// intervening statement context).
975     // FIXME(matthewjasper) Don't store in this in `Body`
976     pub is_block_tail: Option<BlockTailInfo>,
977
978     /// The type of this local.
979     pub ty: Ty<'tcx>,
980
981     /// If the user manually ascribed a type to this variable,
982     /// e.g., via `let x: T`, then we carry that type here. The MIR
983     /// borrow checker needs this information since it can affect
984     /// region inference.
985     // FIXME(matthewjasper) Don't store in this in `Body`
986     pub user_ty: Option<Box<UserTypeProjections>>,
987
988     /// The *syntactic* (i.e., not visibility) source scope the local is defined
989     /// in. If the local was defined in a let-statement, this
990     /// is *within* the let-statement, rather than outside
991     /// of it.
992     ///
993     /// This is needed because the visibility source scope of locals within
994     /// a let-statement is weird.
995     ///
996     /// The reason is that we want the local to be *within* the let-statement
997     /// for lint purposes, but we want the local to be *after* the let-statement
998     /// for names-in-scope purposes.
999     ///
1000     /// That's it, if we have a let-statement like the one in this
1001     /// function:
1002     ///
1003     /// ```
1004     /// fn foo(x: &str) {
1005     ///     #[allow(unused_mut)]
1006     ///     let mut x: u32 = { // <- one unused mut
1007     ///         let mut y: u32 = x.parse().unwrap();
1008     ///         y + 2
1009     ///     };
1010     ///     drop(x);
1011     /// }
1012     /// ```
1013     ///
1014     /// Then, from a lint point of view, the declaration of `x: u32`
1015     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
1016     /// lint scopes are the same as the AST/HIR nesting.
1017     ///
1018     /// However, from a name lookup point of view, the scopes look more like
1019     /// as if the let-statements were `match` expressions:
1020     ///
1021     /// ```
1022     /// fn foo(x: &str) {
1023     ///     match {
1024     ///         match x.parse::<u32>().unwrap() {
1025     ///             y => y + 2
1026     ///         }
1027     ///     } {
1028     ///         x => drop(x)
1029     ///     };
1030     /// }
1031     /// ```
1032     ///
1033     /// We care about the name-lookup scopes for debuginfo - if the
1034     /// debuginfo instruction pointer is at the call to `x.parse()`, we
1035     /// want `x` to refer to `x: &str`, but if it is at the call to
1036     /// `drop(x)`, we want it to refer to `x: u32`.
1037     ///
1038     /// To allow both uses to work, we need to have more than a single scope
1039     /// for a local. We have the `source_info.scope` represent the "syntactic"
1040     /// lint scope (with a variable being under its let block) while the
1041     /// `var_debug_info.source_info.scope` represents the "local variable"
1042     /// scope (where the "rest" of a block is under all prior let-statements).
1043     ///
1044     /// The end result looks like this:
1045     ///
1046     /// ```text
1047     /// ROOT SCOPE
1048     ///  │{ argument x: &str }
1049     ///  │
1050     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
1051     ///  │ │                         // in practice because I'm lazy.
1052     ///  │ │
1053     ///  │ │← x.source_info.scope
1054     ///  │ │← `x.parse().unwrap()`
1055     ///  │ │
1056     ///  │ │ │← y.source_info.scope
1057     ///  │ │
1058     ///  │ │ │{ let y: u32 }
1059     ///  │ │ │
1060     ///  │ │ │← y.var_debug_info.source_info.scope
1061     ///  │ │ │← `y + 2`
1062     ///  │
1063     ///  │ │{ let x: u32 }
1064     ///  │ │← x.var_debug_info.source_info.scope
1065     ///  │ │← `drop(x)` // This accesses `x: u32`.
1066     /// ```
1067     pub source_info: SourceInfo,
1068 }
1069
1070 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
1071 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1072 static_assert_size!(LocalDecl<'_>, 56);
1073
1074 /// Extra information about a some locals that's used for diagnostics and for
1075 /// classifying variables into local variables, statics, etc, which is needed e.g.
1076 /// for unsafety checking.
1077 ///
1078 /// Not used for non-StaticRef temporaries, the return place, or anonymous
1079 /// function parameters.
1080 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1081 pub enum LocalInfo<'tcx> {
1082     /// A user-defined local variable or function parameter
1083     ///
1084     /// The `BindingForm` is solely used for local diagnostics when generating
1085     /// warnings/errors when compiling the current crate, and therefore it need
1086     /// not be visible across crates.
1087     User(ClearCrossCrate<BindingForm<'tcx>>),
1088     /// A temporary created that references the static with the given `DefId`.
1089     StaticRef { def_id: DefId, is_thread_local: bool },
1090     /// A temporary created that references the const with the given `DefId`
1091     ConstRef { def_id: DefId },
1092     /// A temporary created during the creation of an aggregate
1093     /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`)
1094     AggregateTemp,
1095     /// A temporary created during the pass `Derefer` to avoid it's retagging
1096     DerefTemp,
1097 }
1098
1099 impl<'tcx> LocalDecl<'tcx> {
1100     /// Returns `true` only if local is a binding that can itself be
1101     /// made mutable via the addition of the `mut` keyword, namely
1102     /// something like the occurrences of `x` in:
1103     /// - `fn foo(x: Type) { ... }`,
1104     /// - `let x = ...`,
1105     /// - or `match ... { C(x) => ... }`
1106     pub fn can_be_made_mutable(&self) -> bool {
1107         matches!(
1108             self.local_info,
1109             Some(box LocalInfo::User(ClearCrossCrate::Set(
1110                 BindingForm::Var(VarBindingForm {
1111                     binding_mode: ty::BindingMode::BindByValue(_),
1112                     opt_ty_info: _,
1113                     opt_match_place: _,
1114                     pat_span: _,
1115                 }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
1116             )))
1117         )
1118     }
1119
1120     /// Returns `true` if local is definitely not a `ref ident` or
1121     /// `ref mut ident` binding. (Such bindings cannot be made into
1122     /// mutable bindings, but the inverse does not necessarily hold).
1123     pub fn is_nonref_binding(&self) -> bool {
1124         matches!(
1125             self.local_info,
1126             Some(box LocalInfo::User(ClearCrossCrate::Set(
1127                 BindingForm::Var(VarBindingForm {
1128                     binding_mode: ty::BindingMode::BindByValue(_),
1129                     opt_ty_info: _,
1130                     opt_match_place: _,
1131                     pat_span: _,
1132                 }) | BindingForm::ImplicitSelf(_),
1133             )))
1134         )
1135     }
1136
1137     /// Returns `true` if this variable is a named variable or function
1138     /// parameter declared by the user.
1139     #[inline]
1140     pub fn is_user_variable(&self) -> bool {
1141         matches!(self.local_info, Some(box LocalInfo::User(_)))
1142     }
1143
1144     /// Returns `true` if this is a reference to a variable bound in a `match`
1145     /// expression that is used to access said variable for the guard of the
1146     /// match arm.
1147     pub fn is_ref_for_guard(&self) -> bool {
1148         matches!(
1149             self.local_info,
1150             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
1151         )
1152     }
1153
1154     /// Returns `Some` if this is a reference to a static item that is used to
1155     /// access that static.
1156     pub fn is_ref_to_static(&self) -> bool {
1157         matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1158     }
1159
1160     /// Returns `Some` if this is a reference to a thread-local static item that is used to
1161     /// access that static.
1162     pub fn is_ref_to_thread_local(&self) -> bool {
1163         match self.local_info {
1164             Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1165             _ => false,
1166         }
1167     }
1168
1169     /// Returns `true` is the local is from a compiler desugaring, e.g.,
1170     /// `__next` from a `for` loop.
1171     #[inline]
1172     pub fn from_compiler_desugaring(&self) -> bool {
1173         self.source_info.span.desugaring_kind().is_some()
1174     }
1175
1176     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1177     #[inline]
1178     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1179         Self::with_source_info(ty, SourceInfo::outermost(span))
1180     }
1181
1182     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1183     #[inline]
1184     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1185         LocalDecl {
1186             mutability: Mutability::Mut,
1187             local_info: None,
1188             internal: false,
1189             is_block_tail: None,
1190             ty,
1191             user_ty: None,
1192             source_info,
1193         }
1194     }
1195
1196     /// Converts `self` into same `LocalDecl` except tagged as internal.
1197     #[inline]
1198     pub fn internal(mut self) -> Self {
1199         self.internal = true;
1200         self
1201     }
1202
1203     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1204     #[inline]
1205     pub fn immutable(mut self) -> Self {
1206         self.mutability = Mutability::Not;
1207         self
1208     }
1209
1210     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1211     #[inline]
1212     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1213         assert!(self.is_block_tail.is_none());
1214         self.is_block_tail = Some(info);
1215         self
1216     }
1217 }
1218
1219 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1220 pub enum VarDebugInfoContents<'tcx> {
1221     /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1222     /// based on a `Local`, not a `Static`, and contains no indexing.
1223     Place(Place<'tcx>),
1224     Const(Constant<'tcx>),
1225 }
1226
1227 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1228     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1229         match self {
1230             VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1231             VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1232         }
1233     }
1234 }
1235
1236 /// Debug information pertaining to a user variable.
1237 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1238 pub struct VarDebugInfo<'tcx> {
1239     pub name: Symbol,
1240
1241     /// Source info of the user variable, including the scope
1242     /// within which the variable is visible (to debuginfo)
1243     /// (see `LocalDecl`'s `source_info` field for more details).
1244     pub source_info: SourceInfo,
1245
1246     /// Where the data for this user variable is to be found.
1247     pub value: VarDebugInfoContents<'tcx>,
1248 }
1249
1250 ///////////////////////////////////////////////////////////////////////////
1251 // BasicBlock
1252
1253 rustc_index::newtype_index! {
1254     /// A node in the MIR [control-flow graph][CFG].
1255     ///
1256     /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1257     /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1258     /// as an edge in a graph between basic blocks.
1259     ///
1260     /// Basic blocks consist of a series of [statements][Statement], ending with a
1261     /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1262     /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1263     /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1264     /// needed because some analyses require that there are no critical edges in the CFG.
1265     ///
1266     /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1267     /// the actual data that a basic block holds is in [`BasicBlockData`].
1268     ///
1269     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1270     ///
1271     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1272     /// [data-flow analyses]:
1273     ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1274     /// [`CriticalCallEdges`]: ../../rustc_const_eval/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1275     /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1276     pub struct BasicBlock {
1277         derive [HashStable]
1278         DEBUG_FORMAT = "bb{}",
1279         const START_BLOCK = 0,
1280     }
1281 }
1282
1283 impl BasicBlock {
1284     pub fn start_location(self) -> Location {
1285         Location { block: self, statement_index: 0 }
1286     }
1287 }
1288
1289 ///////////////////////////////////////////////////////////////////////////
1290 // BasicBlockData and Terminator
1291
1292 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1293 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1294 pub struct BasicBlockData<'tcx> {
1295     /// List of statements in this block.
1296     pub statements: Vec<Statement<'tcx>>,
1297
1298     /// Terminator for this block.
1299     ///
1300     /// N.B., this should generally ONLY be `None` during construction.
1301     /// Therefore, you should generally access it via the
1302     /// `terminator()` or `terminator_mut()` methods. The only
1303     /// exception is that certain passes, such as `simplify_cfg`, swap
1304     /// out the terminator temporarily with `None` while they continue
1305     /// to recurse over the set of basic blocks.
1306     pub terminator: Option<Terminator<'tcx>>,
1307
1308     /// If true, this block lies on an unwind path. This is used
1309     /// during codegen where distinct kinds of basic blocks may be
1310     /// generated (particularly for MSVC cleanup). Unwind blocks must
1311     /// only branch to other unwind blocks.
1312     pub is_cleanup: bool,
1313 }
1314
1315 /// Information about an assertion failure.
1316 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
1317 pub enum AssertKind<O> {
1318     BoundsCheck { len: O, index: O },
1319     Overflow(BinOp, O, O),
1320     OverflowNeg(O),
1321     DivisionByZero(O),
1322     RemainderByZero(O),
1323     ResumedAfterReturn(GeneratorKind),
1324     ResumedAfterPanic(GeneratorKind),
1325 }
1326
1327 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1328 pub enum InlineAsmOperand<'tcx> {
1329     In {
1330         reg: InlineAsmRegOrRegClass,
1331         value: Operand<'tcx>,
1332     },
1333     Out {
1334         reg: InlineAsmRegOrRegClass,
1335         late: bool,
1336         place: Option<Place<'tcx>>,
1337     },
1338     InOut {
1339         reg: InlineAsmRegOrRegClass,
1340         late: bool,
1341         in_value: Operand<'tcx>,
1342         out_place: Option<Place<'tcx>>,
1343     },
1344     Const {
1345         value: Box<Constant<'tcx>>,
1346     },
1347     SymFn {
1348         value: Box<Constant<'tcx>>,
1349     },
1350     SymStatic {
1351         def_id: DefId,
1352     },
1353 }
1354
1355 /// Type for MIR `Assert` terminator error messages.
1356 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1357
1358 // FIXME: Change `Successors` to `impl Iterator<Item = BasicBlock>`.
1359 #[allow(rustc::pass_by_value)]
1360 pub type Successors<'a> =
1361     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1362 pub type SuccessorsMut<'a> =
1363     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1364
1365 impl<'tcx> BasicBlockData<'tcx> {
1366     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1367         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1368     }
1369
1370     /// Accessor for terminator.
1371     ///
1372     /// Terminator may not be None after construction of the basic block is complete. This accessor
1373     /// provides a convenience way to reach the terminator.
1374     #[inline]
1375     pub fn terminator(&self) -> &Terminator<'tcx> {
1376         self.terminator.as_ref().expect("invalid terminator state")
1377     }
1378
1379     #[inline]
1380     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1381         self.terminator.as_mut().expect("invalid terminator state")
1382     }
1383
1384     pub fn retain_statements<F>(&mut self, mut f: F)
1385     where
1386         F: FnMut(&mut Statement<'_>) -> bool,
1387     {
1388         for s in &mut self.statements {
1389             if !f(s) {
1390                 s.make_nop();
1391             }
1392         }
1393     }
1394
1395     pub fn expand_statements<F, I>(&mut self, mut f: F)
1396     where
1397         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1398         I: iter::TrustedLen<Item = Statement<'tcx>>,
1399     {
1400         // Gather all the iterators we'll need to splice in, and their positions.
1401         let mut splices: Vec<(usize, I)> = vec![];
1402         let mut extra_stmts = 0;
1403         for (i, s) in self.statements.iter_mut().enumerate() {
1404             if let Some(mut new_stmts) = f(s) {
1405                 if let Some(first) = new_stmts.next() {
1406                     // We can already store the first new statement.
1407                     *s = first;
1408
1409                     // Save the other statements for optimized splicing.
1410                     let remaining = new_stmts.size_hint().0;
1411                     if remaining > 0 {
1412                         splices.push((i + 1 + extra_stmts, new_stmts));
1413                         extra_stmts += remaining;
1414                     }
1415                 } else {
1416                     s.make_nop();
1417                 }
1418             }
1419         }
1420
1421         // Splice in the new statements, from the end of the block.
1422         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1423         // where a range of elements ("gap") is left uninitialized, with
1424         // splicing adding new elements to the end of that gap and moving
1425         // existing elements from before the gap to the end of the gap.
1426         // For now, this is safe code, emulating a gap but initializing it.
1427         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1428         self.statements.resize(
1429             gap.end,
1430             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1431         );
1432         for (splice_start, new_stmts) in splices.into_iter().rev() {
1433             let splice_end = splice_start + new_stmts.size_hint().0;
1434             while gap.end > splice_end {
1435                 gap.start -= 1;
1436                 gap.end -= 1;
1437                 self.statements.swap(gap.start, gap.end);
1438             }
1439             self.statements.splice(splice_start..splice_end, new_stmts);
1440             gap.end = splice_start;
1441         }
1442     }
1443
1444     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1445         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1446     }
1447 }
1448
1449 impl<O> AssertKind<O> {
1450     /// Getting a description does not require `O` to be printable, and does not
1451     /// require allocation.
1452     /// The caller is expected to handle `BoundsCheck` separately.
1453     pub fn description(&self) -> &'static str {
1454         use AssertKind::*;
1455         match self {
1456             Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1457             Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1458             Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1459             Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1460             Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1461             OverflowNeg(_) => "attempt to negate with overflow",
1462             Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1463             Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1464             Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1465             DivisionByZero(_) => "attempt to divide by zero",
1466             RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1467             ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1468             ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1469             ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1470             ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1471             BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1472         }
1473     }
1474
1475     /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1476     pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1477     where
1478         O: Debug,
1479     {
1480         use AssertKind::*;
1481         match self {
1482             BoundsCheck { ref len, ref index } => write!(
1483                 f,
1484                 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1485                 len, index
1486             ),
1487
1488             OverflowNeg(op) => {
1489                 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1490             }
1491             DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1492             RemainderByZero(op) => write!(
1493                 f,
1494                 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1495                 op
1496             ),
1497             Overflow(BinOp::Add, l, r) => write!(
1498                 f,
1499                 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1500                 l, r
1501             ),
1502             Overflow(BinOp::Sub, l, r) => write!(
1503                 f,
1504                 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1505                 l, r
1506             ),
1507             Overflow(BinOp::Mul, l, r) => write!(
1508                 f,
1509                 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1510                 l, r
1511             ),
1512             Overflow(BinOp::Div, l, r) => write!(
1513                 f,
1514                 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1515                 l, r
1516             ),
1517             Overflow(BinOp::Rem, l, r) => write!(
1518                 f,
1519                 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1520                 l, r
1521             ),
1522             Overflow(BinOp::Shr, _, r) => {
1523                 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1524             }
1525             Overflow(BinOp::Shl, _, r) => {
1526                 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1527             }
1528             _ => write!(f, "\"{}\"", self.description()),
1529         }
1530     }
1531 }
1532
1533 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1534     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535         use AssertKind::*;
1536         match self {
1537             BoundsCheck { ref len, ref index } => write!(
1538                 f,
1539                 "index out of bounds: the length is {:?} but the index is {:?}",
1540                 len, index
1541             ),
1542             OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1543             DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1544             RemainderByZero(op) => write!(
1545                 f,
1546                 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1547                 op
1548             ),
1549             Overflow(BinOp::Add, l, r) => {
1550                 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1551             }
1552             Overflow(BinOp::Sub, l, r) => {
1553                 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1554             }
1555             Overflow(BinOp::Mul, l, r) => {
1556                 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1557             }
1558             Overflow(BinOp::Div, l, r) => {
1559                 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1560             }
1561             Overflow(BinOp::Rem, l, r) => write!(
1562                 f,
1563                 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1564                 l, r
1565             ),
1566             Overflow(BinOp::Shr, _, r) => {
1567                 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1568             }
1569             Overflow(BinOp::Shl, _, r) => {
1570                 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1571             }
1572             _ => write!(f, "{}", self.description()),
1573         }
1574     }
1575 }
1576
1577 ///////////////////////////////////////////////////////////////////////////
1578 // Statements
1579
1580 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1581 pub struct Statement<'tcx> {
1582     pub source_info: SourceInfo,
1583     pub kind: StatementKind<'tcx>,
1584 }
1585
1586 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1587 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1588 static_assert_size!(Statement<'_>, 32);
1589
1590 impl Statement<'_> {
1591     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1592     /// invalidating statement indices in `Location`s.
1593     pub fn make_nop(&mut self) {
1594         self.kind = StatementKind::Nop
1595     }
1596
1597     /// Changes a statement to a nop and returns the original statement.
1598     #[must_use = "If you don't need the statement, use `make_nop` instead"]
1599     pub fn replace_nop(&mut self) -> Self {
1600         Statement {
1601             source_info: self.source_info,
1602             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1603         }
1604     }
1605 }
1606
1607 /// The various kinds of statements that can appear in MIR.
1608 ///
1609 /// Not all of these are allowed at every [`MirPhase`]. Check the documentation there to see which
1610 /// ones you do not have to worry about. The MIR validator will generally enforce such restrictions,
1611 /// causing an ICE if they are violated.
1612 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1613 pub enum StatementKind<'tcx> {
1614     /// Assign statements roughly correspond to an assignment in Rust proper (`x = ...`) except
1615     /// without the possibility of dropping the previous value (that must be done separately, if at
1616     /// all). The *exact* way this works is undecided. It probably does something like evaluating
1617     /// the LHS to a place and the RHS to a value, and then storing the value to the place. Various
1618     /// parts of this may do type specific things that are more complicated than simply copying
1619     /// bytes.
1620     ///
1621     /// **Needs clarification**: The implication of the above idea would be that assignment implies
1622     /// that the resulting value is initialized. I believe we could commit to this separately from
1623     /// committing to whatever part of the memory model we would need to decide on to make the above
1624     /// paragragh precise. Do we want to?
1625     ///
1626     /// Assignments in which the types of the place and rvalue differ are not well-formed.
1627     ///
1628     /// **Needs clarification**: Do we ever want to worry about non-free (in the body) lifetimes for
1629     /// the typing requirement in post drop-elaboration MIR? I think probably not - I'm not sure we
1630     /// could meaningfully require this anyway. How about free lifetimes? Is ignoring this
1631     /// interesting for optimizations? Do we want to allow such optimizations?
1632     ///
1633     /// **Needs clarification**: We currently require that the LHS place not overlap with any place
1634     /// read as part of computation of the RHS for some rvalues (generally those not producing
1635     /// primitives). This requirement is under discussion in [#68364]. As a part of this discussion,
1636     /// it is also unclear in what order the components are evaluated.
1637     ///
1638     /// [#68364]: https://github.com/rust-lang/rust/issues/68364
1639     ///
1640     /// See [`Rvalue`] documentation for details on each of those.
1641     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1642
1643     /// This represents all the reading that a pattern match may do (e.g., inspecting constants and
1644     /// discriminant values), and the kind of pattern it comes from. This is in order to adapt
1645     /// potential error messages to these specific patterns.
1646     ///
1647     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1648     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1649     ///
1650     /// When executed at runtime this is a nop.
1651     ///
1652     /// Disallowed after drop elaboration.
1653     FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
1654
1655     /// Write the discriminant for a variant to the enum Place.
1656     ///
1657     /// This is permitted for both generators and ADTs. This does not necessarily write to the
1658     /// entire place; instead, it writes to the minimum set of bytes as required by the layout for
1659     /// the type.
1660     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1661
1662     /// Deinitializes the place.
1663     ///
1664     /// This writes `uninit` bytes to the entire place.
1665     Deinit(Box<Place<'tcx>>),
1666
1667     /// `StorageLive` and `StorageDead` statements mark the live range of a local.
1668     ///
1669     /// Using a local before a `StorageLive` or after a `StorageDead` is not well-formed. These
1670     /// statements are not required. If the entire MIR body contains no `StorageLive`/`StorageDead`
1671     /// statements for a particular local, the local is always considered live.
1672     ///
1673     /// More precisely, the MIR validator currently does a `MaybeStorageLiveLocals` analysis to
1674     /// check validity of each use of a local. I believe this is equivalent to requiring for every
1675     /// use of a local, there exist at least one path from the root to that use that contains a
1676     /// `StorageLive` more recently than a `StorageDead`.
1677     ///
1678     /// **Needs clarification**: Is it permitted to have two `StorageLive`s without an intervening
1679     /// `StorageDead`? Two `StorageDead`s without an intervening `StorageLive`? LLVM says poison,
1680     /// yes. If the answer to any of these is "no," is breaking that rule UB or is it an error to
1681     /// have a path in the CFG that might do this?
1682     StorageLive(Local),
1683
1684     /// See `StorageLive` above.
1685     StorageDead(Local),
1686
1687     /// Retag references in the given place, ensuring they got fresh tags.
1688     ///
1689     /// This is part of the Stacked Borrows model. These statements are currently only interpreted
1690     /// by miri and only generated when `-Z mir-emit-retag` is passed. See
1691     /// <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> for
1692     /// more details.
1693     ///
1694     /// For code that is not specific to stacked borrows, you should consider retags to read
1695     /// and modify the place in an opaque way.
1696     Retag(RetagKind, Box<Place<'tcx>>),
1697
1698     /// Encodes a user's type ascription. These need to be preserved
1699     /// intact so that NLL can respect them. For example:
1700     /// ```ignore (illustrative)
1701     /// let a: T = y;
1702     /// ```
1703     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1704     /// to the user-given type `T`. The effect depends on the specified variance:
1705     ///
1706     /// - `Covariant` -- requires that `T_y <: T`
1707     /// - `Contravariant` -- requires that `T_y :> T`
1708     /// - `Invariant` -- requires that `T_y == T`
1709     /// - `Bivariant` -- no effect
1710     ///
1711     /// When executed at runtime this is a nop.
1712     ///
1713     /// Disallowed after drop elaboration.
1714     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1715
1716     /// Marks the start of a "coverage region", injected with '-Cinstrument-coverage'. A
1717     /// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
1718     /// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
1719     /// executable code, to increment a counter variable at runtime, each time the code region is
1720     /// executed.
1721     Coverage(Box<Coverage>),
1722
1723     /// Denotes a call to the intrinsic function `copy_nonoverlapping`.
1724     ///
1725     /// First, all three operands are evaluated. `src` and `dest` must each be a reference, pointer,
1726     /// or `Box` pointing to the same type `T`. `count` must evaluate to a `usize`. Then, `src` and
1727     /// `dest` are dereferenced, and `count * size_of::<T>()` bytes beginning with the first byte of
1728     /// the `src` place are copied to the continguous range of bytes beginning with the first byte
1729     /// of `dest`.
1730     ///
1731     /// **Needs clarification**: In what order are operands computed and dereferenced? It should
1732     /// probably match the order for assignment, but that is also undecided.
1733     ///
1734     /// **Needs clarification**: Is this typed or not, ie is there a typed load and store involved?
1735     /// I vaguely remember Ralf saying somewhere that he thought it should not be.
1736     CopyNonOverlapping(Box<CopyNonOverlapping<'tcx>>),
1737
1738     /// No-op. Useful for deleting instructions without affecting statement indices.
1739     Nop,
1740 }
1741
1742 impl<'tcx> StatementKind<'tcx> {
1743     pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
1744         match self {
1745             StatementKind::Assign(x) => Some(x),
1746             _ => None,
1747         }
1748     }
1749
1750     pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1751         match self {
1752             StatementKind::Assign(x) => Some(x),
1753             _ => None,
1754         }
1755     }
1756 }
1757
1758 /// Describes what kind of retag is to be performed.
1759 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1760 pub enum RetagKind {
1761     /// The initial retag when entering a function.
1762     FnEntry,
1763     /// Retag preparing for a two-phase borrow.
1764     TwoPhase,
1765     /// Retagging raw pointers.
1766     Raw,
1767     /// A "normal" retag.
1768     Default,
1769 }
1770
1771 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1772 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1773 pub enum FakeReadCause {
1774     /// Inject a fake read of the borrowed input at the end of each guards
1775     /// code.
1776     ///
1777     /// This should ensure that you cannot change the variant for an enum while
1778     /// you are in the midst of matching on it.
1779     ForMatchGuard,
1780
1781     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1782     /// generate a read of x to check that it is initialized and safe.
1783     ///
1784     /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
1785     /// FakeRead for that Place outside the closure, in such a case this option would be
1786     /// Some(closure_def_id).
1787     /// Otherwise, the value of the optional DefId will be None.
1788     ForMatchedPlace(Option<DefId>),
1789
1790     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1791     /// in a match guard to ensure that its value hasn't change by the time
1792     /// we create the OutsideGuard version.
1793     ForGuardBinding,
1794
1795     /// Officially, the semantics of
1796     ///
1797     /// `let pattern = <expr>;`
1798     ///
1799     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1800     /// into the pattern.
1801     ///
1802     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1803     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1804     /// but in some cases it can affect the borrow checker, as in #53695.
1805     /// Therefore, we insert a "fake read" here to ensure that we get
1806     /// appropriate errors.
1807     ///
1808     /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
1809     /// FakeRead for that Place outside the closure, in such a case this option would be
1810     /// Some(closure_def_id).
1811     /// Otherwise, the value of the optional DefId will be None.
1812     ForLet(Option<DefId>),
1813
1814     /// If we have an index expression like
1815     ///
1816     /// (*x)[1][{ x = y; 4}]
1817     ///
1818     /// then the first bounds check is invalidated when we evaluate the second
1819     /// index expression. Thus we create a fake borrow of `x` across the second
1820     /// indexer, which will cause a borrow check error.
1821     ForIndex,
1822 }
1823
1824 impl Debug for Statement<'_> {
1825     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1826         use self::StatementKind::*;
1827         match self.kind {
1828             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1829             FakeRead(box (ref cause, ref place)) => {
1830                 write!(fmt, "FakeRead({:?}, {:?})", cause, place)
1831             }
1832             Retag(ref kind, ref place) => write!(
1833                 fmt,
1834                 "Retag({}{:?})",
1835                 match kind {
1836                     RetagKind::FnEntry => "[fn entry] ",
1837                     RetagKind::TwoPhase => "[2phase] ",
1838                     RetagKind::Raw => "[raw] ",
1839                     RetagKind::Default => "",
1840                 },
1841                 place,
1842             ),
1843             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1844             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1845             SetDiscriminant { ref place, variant_index } => {
1846                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1847             }
1848             Deinit(ref place) => write!(fmt, "Deinit({:?})", place),
1849             AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1850                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1851             }
1852             Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1853                 write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1854             }
1855             Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
1856             CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
1857                 ref src,
1858                 ref dst,
1859                 ref count,
1860             }) => {
1861                 write!(fmt, "copy_nonoverlapping(src={:?}, dst={:?}, count={:?})", src, dst, count)
1862             }
1863             Nop => write!(fmt, "nop"),
1864         }
1865     }
1866 }
1867
1868 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1869 pub struct Coverage {
1870     pub kind: CoverageKind,
1871     pub code_region: Option<CodeRegion>,
1872 }
1873
1874 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1875 pub struct CopyNonOverlapping<'tcx> {
1876     pub src: Operand<'tcx>,
1877     pub dst: Operand<'tcx>,
1878     /// Number of elements to copy from src to dest, not bytes.
1879     pub count: Operand<'tcx>,
1880 }
1881
1882 ///////////////////////////////////////////////////////////////////////////
1883 // Places
1884
1885 /// Places roughly correspond to a "location in memory." Places in MIR are the same mathematical
1886 /// object as places in Rust. This of course means that what exactly they are is undecided and part
1887 /// of the Rust memory model. However, they will likely contain at least the following pieces of
1888 /// information in some form:
1889 ///
1890 ///  1. The address in memory that the place refers to.
1891 ///  2. The provenance with which the place is being accessed.
1892 ///  3. The type of the place and an optional variant index. See [`PlaceTy`][tcx::PlaceTy].
1893 ///  4. Optionally, some metadata. This exists if and only if the type of the place is not `Sized`.
1894 ///
1895 /// We'll give a description below of how all pieces of the place except for the provenance are
1896 /// calculated. We cannot give a description of the provenance, because that is part of the
1897 /// undecided aliasing model - we only include it here at all to acknowledge its existence.
1898 ///
1899 /// Each local naturally corresponds to the place `Place { local, projection: [] }`. This place has
1900 /// the address of the local's allocation and the type of the local.
1901 ///
1902 /// **Needs clarification:** Unsized locals seem to present a bit of an issue. Their allocation
1903 /// can't actually be created on `StorageLive`, because it's unclear how big to make the allocation.
1904 /// Furthermore, MIR produces assignments to unsized locals, although that is not permitted under
1905 /// `#![feature(unsized_locals)]` in Rust. Besides just putting "unsized locals are special and
1906 /// different" in a bunch of places, I (JakobDegen) don't know how to incorporate this behavior into
1907 /// the current MIR semantics in a clean way - possibly this needs some design work first.
1908 ///
1909 /// For places that are not locals, ie they have a non-empty list of projections, we define the
1910 /// values as a function of the parent place, that is the place with its last [`ProjectionElem`]
1911 /// stripped. The way this is computed of course depends on the kind of that last projection
1912 /// element:
1913 ///
1914 ///  - [`Downcast`](ProjectionElem::Downcast): This projection sets the place's variant index to the
1915 ///    given one, and makes no other changes. A `Downcast` projection on a place with its variant
1916 ///    index already set is not well-formed.
1917 ///  - [`Field`](ProjectionElem::Field): `Field` projections take their parent place and create a
1918 ///    place referring to one of the fields of the type. The resulting address is the parent
1919 ///    address, plus the offset of the field. The type becomes the type of the field. If the parent
1920 ///    was unsized and so had metadata associated with it, then the metadata is retained if the
1921 ///    field is unsized and thrown out if it is sized.
1922 ///
1923 ///    These projections are only legal for tuples, ADTs, closures, and generators. If the ADT or
1924 ///    generator has more than one variant, the parent place's variant index must be set, indicating
1925 ///    which variant is being used. If it has just one variant, the variant index may or may not be
1926 ///    included - the single possible variant is inferred if it is not included.
1927 ///  - [`ConstantIndex`](ProjectionElem::ConstantIndex): Computes an offset in units of `T` into the
1928 ///    place as described in the documentation for the `ProjectionElem`. The resulting address is
1929 ///    the parent's address plus that offset, and the type is `T`. This is only legal if the parent
1930 ///    place has type `[T;  N]` or `[T]` (*not* `&[T]`). Since such a `T` is always sized, any
1931 ///    resulting metadata is thrown out.
1932 ///  - [`Subslice`](ProjectionElem::Subslice): This projection calculates an offset and a new
1933 ///    address in a similar manner as `ConstantIndex`. It is also only legal on `[T; N]` and `[T]`.
1934 ///    However, this yields a `Place` of type `[T]`, and additionally sets the metadata to be the
1935 ///    length of the subslice.
1936 ///  - [`Index`](ProjectionElem::Index): Like `ConstantIndex`, only legal on `[T; N]` or `[T]`.
1937 ///    However, `Index` additionally takes a local from which the value of the index is computed at
1938 ///    runtime. Computing the value of the index involves interpreting the `Local` as a
1939 ///    `Place { local, projection: [] }`, and then computing its value as if done via
1940 ///    [`Operand::Copy`]. The array/slice is then indexed with the resulting value. The local must
1941 ///    have type `usize`.
1942 ///  - [`Deref`](ProjectionElem::Deref): Derefs are the last type of projection, and the most
1943 ///    complicated. They are only legal on parent places that are references, pointers, or `Box`. A
1944 ///    `Deref` projection begins by loading a value from the parent place, as if by
1945 ///    [`Operand::Copy`]. It then dereferences the resulting pointer, creating a place of the
1946 ///    pointee's type. The resulting address is the address that was stored in the pointer. If the
1947 ///    pointee type is unsized, the pointer additionally stored the value of the metadata.
1948 ///
1949 /// Computing a place may cause UB. One possibility is that the pointer used for a `Deref` may not
1950 /// be suitably aligned. Another possibility is that the place is not in bounds, meaning it does not
1951 /// point to an actual allocation.
1952 ///
1953 /// However, if this is actually UB and when the UB kicks in is undecided. This is being discussed
1954 /// in [UCG#319]. The options include that every place must obey those rules, that only some places
1955 /// must obey them, or that places impose no rules of their own.
1956 ///
1957 /// [UCG#319]: https://github.com/rust-lang/unsafe-code-guidelines/issues/319
1958 ///
1959 /// Rust currently requires that every place obey those two rules. This is checked by MIRI and taken
1960 /// advantage of by codegen (via `gep inbounds`). That is possibly subject to change.
1961 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable)]
1962 pub struct Place<'tcx> {
1963     pub local: Local,
1964
1965     /// projection out of a place (access a field, deref a pointer, etc)
1966     pub projection: &'tcx List<PlaceElem<'tcx>>,
1967 }
1968
1969 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1970 static_assert_size!(Place<'_>, 16);
1971
1972 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1973 #[derive(TyEncodable, TyDecodable, HashStable)]
1974 pub enum ProjectionElem<V, T> {
1975     Deref,
1976     Field(Field, T),
1977     /// Index into a slice/array.
1978     ///
1979     /// Note that this does not also dereference, and so it does not exactly correspond to slice
1980     /// indexing in Rust. In other words, in the below Rust code:
1981     ///
1982     /// ```rust
1983     /// let x = &[1, 2, 3, 4];
1984     /// let i = 2;
1985     /// x[i];
1986     /// ```
1987     ///
1988     /// The `x[i]` is turned into a `Deref` followed by an `Index`, not just an `Index`. The same
1989     /// thing is true of the `ConstantIndex` and `Subslice` projections below.
1990     Index(V),
1991
1992     /// These indices are generated by slice patterns. Easiest to explain
1993     /// by example:
1994     ///
1995     /// ```ignore (illustrative)
1996     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1997     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1998     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1999     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
2000     /// ```
2001     ConstantIndex {
2002         /// index or -index (in Python terms), depending on from_end
2003         offset: u64,
2004         /// The thing being indexed must be at least this long. For arrays this
2005         /// is always the exact length.
2006         min_length: u64,
2007         /// Counting backwards from end? This is always false when indexing an
2008         /// array.
2009         from_end: bool,
2010     },
2011
2012     /// These indices are generated by slice patterns.
2013     ///
2014     /// If `from_end` is true `slice[from..slice.len() - to]`.
2015     /// Otherwise `array[from..to]`.
2016     Subslice {
2017         from: u64,
2018         to: u64,
2019         /// Whether `to` counts from the start or end of the array/slice.
2020         /// For `PlaceElem`s this is `true` if and only if the base is a slice.
2021         /// For `ProjectionKind`, this can also be `true` for arrays.
2022         from_end: bool,
2023     },
2024
2025     /// "Downcast" to a variant of an enum or a generator.
2026     ///
2027     /// The included Symbol is the name of the variant, used for printing MIR.
2028     Downcast(Option<Symbol>, VariantIdx),
2029 }
2030
2031 impl<V, T> ProjectionElem<V, T> {
2032     /// Returns `true` if the target of this projection may refer to a different region of memory
2033     /// than the base.
2034     fn is_indirect(&self) -> bool {
2035         match self {
2036             Self::Deref => true,
2037
2038             Self::Field(_, _)
2039             | Self::Index(_)
2040             | Self::ConstantIndex { .. }
2041             | Self::Subslice { .. }
2042             | Self::Downcast(_, _) => false,
2043         }
2044     }
2045
2046     /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
2047     pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
2048         matches!(*self, Self::Downcast(_, x) if x == v)
2049     }
2050
2051     /// Returns `true` if this is a `Field` projection with the given index.
2052     pub fn is_field_to(&self, f: Field) -> bool {
2053         matches!(*self, Self::Field(x, _) if x == f)
2054     }
2055 }
2056
2057 /// Alias for projections as they appear in places, where the base is a place
2058 /// and the index is a local.
2059 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
2060
2061 // This type is fairly frequently used, so we shouldn't unintentionally increase
2062 // its size.
2063 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2064 static_assert_size!(PlaceElem<'_>, 24);
2065
2066 /// Alias for projections as they appear in `UserTypeProjection`, where we
2067 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
2068 pub type ProjectionKind = ProjectionElem<(), ()>;
2069
2070 rustc_index::newtype_index! {
2071     /// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
2072     ///
2073     /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
2074     /// rustc can identify that a field projection refers to either two different regions of memory
2075     /// or the same one between the base and the 'projection element'.
2076     /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
2077     ///
2078     /// [wrapper]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html#newtype
2079     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
2080     /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
2081     pub struct Field {
2082         derive [HashStable]
2083         DEBUG_FORMAT = "field[{}]"
2084     }
2085 }
2086
2087 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2088 pub struct PlaceRef<'tcx> {
2089     pub local: Local,
2090     pub projection: &'tcx [PlaceElem<'tcx>],
2091 }
2092
2093 // Once we stop implementing `Ord` for `DefId`,
2094 // this impl will be unnecessary. Until then, we'll
2095 // leave this impl in place to prevent re-adding a
2096 // dependnecy on the `Ord` impl for `DefId`
2097 impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
2098
2099 impl<'tcx> Place<'tcx> {
2100     // FIXME change this to a const fn by also making List::empty a const fn.
2101     pub fn return_place() -> Place<'tcx> {
2102         Place { local: RETURN_PLACE, projection: List::empty() }
2103     }
2104
2105     /// Returns `true` if this `Place` contains a `Deref` projection.
2106     ///
2107     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
2108     /// same region of memory as its base.
2109     pub fn is_indirect(&self) -> bool {
2110         self.projection.iter().any(|elem| elem.is_indirect())
2111     }
2112
2113     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2114     /// a single deref of a local.
2115     #[inline(always)]
2116     pub fn local_or_deref_local(&self) -> Option<Local> {
2117         self.as_ref().local_or_deref_local()
2118     }
2119
2120     /// If this place represents a local variable like `_X` with no
2121     /// projections, return `Some(_X)`.
2122     #[inline(always)]
2123     pub fn as_local(&self) -> Option<Local> {
2124         self.as_ref().as_local()
2125     }
2126
2127     #[inline]
2128     pub fn as_ref(&self) -> PlaceRef<'tcx> {
2129         PlaceRef { local: self.local, projection: &self.projection }
2130     }
2131
2132     /// Iterate over the projections in evaluation order, i.e., the first element is the base with
2133     /// its projection and then subsequently more projections are added.
2134     /// As a concrete example, given the place a.b.c, this would yield:
2135     /// - (a, .b)
2136     /// - (a.b, .c)
2137     ///
2138     /// Given a place without projections, the iterator is empty.
2139     #[inline]
2140     pub fn iter_projections(
2141         self,
2142     ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
2143         self.projection.iter().enumerate().map(move |(i, proj)| {
2144             let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
2145             (base, proj)
2146         })
2147     }
2148
2149     /// Generates a new place by appending `more_projections` to the existing ones
2150     /// and interning the result.
2151     pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
2152         if more_projections.is_empty() {
2153             return self;
2154         }
2155
2156         let mut v: Vec<PlaceElem<'tcx>>;
2157
2158         let new_projections = if self.projection.is_empty() {
2159             more_projections
2160         } else {
2161             v = Vec::with_capacity(self.projection.len() + more_projections.len());
2162             v.extend(self.projection);
2163             v.extend(more_projections);
2164             &v
2165         };
2166
2167         Place { local: self.local, projection: tcx.intern_place_elems(new_projections) }
2168     }
2169 }
2170
2171 impl From<Local> for Place<'_> {
2172     fn from(local: Local) -> Self {
2173         Place { local, projection: List::empty() }
2174     }
2175 }
2176
2177 impl<'tcx> PlaceRef<'tcx> {
2178     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
2179     /// a single deref of a local.
2180     pub fn local_or_deref_local(&self) -> Option<Local> {
2181         match *self {
2182             PlaceRef { local, projection: [] }
2183             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
2184             _ => None,
2185         }
2186     }
2187
2188     /// If this place represents a local variable like `_X` with no
2189     /// projections, return `Some(_X)`.
2190     #[inline]
2191     pub fn as_local(&self) -> Option<Local> {
2192         match *self {
2193             PlaceRef { local, projection: [] } => Some(local),
2194             _ => None,
2195         }
2196     }
2197
2198     #[inline]
2199     pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
2200         if let &[ref proj_base @ .., elem] = self.projection {
2201             Some((PlaceRef { local: self.local, projection: proj_base }, elem))
2202         } else {
2203             None
2204         }
2205     }
2206 }
2207
2208 impl Debug for Place<'_> {
2209     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2210         for elem in self.projection.iter().rev() {
2211             match elem {
2212                 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
2213                     write!(fmt, "(").unwrap();
2214                 }
2215                 ProjectionElem::Deref => {
2216                     write!(fmt, "(*").unwrap();
2217                 }
2218                 ProjectionElem::Index(_)
2219                 | ProjectionElem::ConstantIndex { .. }
2220                 | ProjectionElem::Subslice { .. } => {}
2221             }
2222         }
2223
2224         write!(fmt, "{:?}", self.local)?;
2225
2226         for elem in self.projection.iter() {
2227             match elem {
2228                 ProjectionElem::Downcast(Some(name), _index) => {
2229                     write!(fmt, " as {})", name)?;
2230                 }
2231                 ProjectionElem::Downcast(None, index) => {
2232                     write!(fmt, " as variant#{:?})", index)?;
2233                 }
2234                 ProjectionElem::Deref => {
2235                     write!(fmt, ")")?;
2236                 }
2237                 ProjectionElem::Field(field, ty) => {
2238                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2239                 }
2240                 ProjectionElem::Index(ref index) => {
2241                     write!(fmt, "[{:?}]", index)?;
2242                 }
2243                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2244                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2245                 }
2246                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2247                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2248                 }
2249                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
2250                     write!(fmt, "[{:?}:]", from)?;
2251                 }
2252                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
2253                     write!(fmt, "[:-{:?}]", to)?;
2254                 }
2255                 ProjectionElem::Subslice { from, to, from_end: true } => {
2256                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
2257                 }
2258                 ProjectionElem::Subslice { from, to, from_end: false } => {
2259                     write!(fmt, "[{:?}..{:?}]", from, to)?;
2260                 }
2261             }
2262         }
2263
2264         Ok(())
2265     }
2266 }
2267
2268 ///////////////////////////////////////////////////////////////////////////
2269 // Scopes
2270
2271 rustc_index::newtype_index! {
2272     pub struct SourceScope {
2273         derive [HashStable]
2274         DEBUG_FORMAT = "scope[{}]",
2275         const OUTERMOST_SOURCE_SCOPE = 0,
2276     }
2277 }
2278
2279 impl SourceScope {
2280     /// Finds the original HirId this MIR item came from.
2281     /// This is necessary after MIR optimizations, as otherwise we get a HirId
2282     /// from the function that was inlined instead of the function call site.
2283     pub fn lint_root<'tcx>(
2284         self,
2285         source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
2286     ) -> Option<HirId> {
2287         let mut data = &source_scopes[self];
2288         // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
2289         // does not work as I thought it would. Needs more investigation and documentation.
2290         while data.inlined.is_some() {
2291             trace!(?data);
2292             data = &source_scopes[data.parent_scope.unwrap()];
2293         }
2294         trace!(?data);
2295         match &data.local_data {
2296             ClearCrossCrate::Set(data) => Some(data.lint_root),
2297             ClearCrossCrate::Clear => None,
2298         }
2299     }
2300 }
2301
2302 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2303 pub struct SourceScopeData<'tcx> {
2304     pub span: Span,
2305     pub parent_scope: Option<SourceScope>,
2306
2307     /// Whether this scope is the root of a scope tree of another body,
2308     /// inlined into this body by the MIR inliner.
2309     /// `ty::Instance` is the callee, and the `Span` is the call site.
2310     pub inlined: Option<(ty::Instance<'tcx>, Span)>,
2311
2312     /// Nearest (transitive) parent scope (if any) which is inlined.
2313     /// This is an optimization over walking up `parent_scope`
2314     /// until a scope with `inlined: Some(...)` is found.
2315     pub inlined_parent_scope: Option<SourceScope>,
2316
2317     /// Crate-local information for this source scope, that can't (and
2318     /// needn't) be tracked across crates.
2319     pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2320 }
2321
2322 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
2323 pub struct SourceScopeLocalData {
2324     /// An `HirId` with lint levels equivalent to this scope's lint levels.
2325     pub lint_root: hir::HirId,
2326     /// The unsafe block that contains this node.
2327     pub safety: Safety,
2328 }
2329
2330 ///////////////////////////////////////////////////////////////////////////
2331 // Operands
2332
2333 /// An operand in MIR represents a "value" in Rust, the definition of which is undecided and part of
2334 /// the memory model. One proposal for a definition of values can be found [on UCG][value-def].
2335 ///
2336 /// [value-def]: https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/value-domain.md
2337 ///
2338 /// The most common way to create values is via loading a place. Loading a place is an operation
2339 /// which reads the memory of the place and converts it to a value. This is a fundamentally *typed*
2340 /// operation. The nature of the value produced depends on the type of the conversion. Furthermore,
2341 /// there may be other effects: if the type has a validity constraint loading the place might be UB
2342 /// if the validity constraint is not met.
2343 ///
2344 /// **Needs clarification:** Ralf proposes that loading a place not have side-effects.
2345 /// This is what is implemented in miri today. Are these the semantics we want for MIR? Is this
2346 /// something we can even decide without knowing more about Rust's memory model?
2347 ///
2348 /// **Needs clarifiation:** Is loading a place that has its variant index set well-formed? Miri
2349 /// currently implements it, but it seems like this may be something to check against in the
2350 /// validator.
2351 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2352 pub enum Operand<'tcx> {
2353     /// Creates a value by loading the given place.
2354     ///
2355     /// Before drop elaboration, the type of the place must be `Copy`. After drop elaboration there
2356     /// is no such requirement.
2357     Copy(Place<'tcx>),
2358
2359     /// Creates a value by performing loading the place, just like the `Copy` operand.
2360     ///
2361     /// This *may* additionally overwrite the place with `uninit` bytes, depending on how we decide
2362     /// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this
2363     /// place without first re-initializing it.
2364     ///
2365     /// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188
2366     Move(Place<'tcx>),
2367
2368     /// Constants are already semantically values, and remain unchanged.
2369     Constant(Box<Constant<'tcx>>),
2370 }
2371
2372 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2373 static_assert_size!(Operand<'_>, 24);
2374
2375 impl<'tcx> Debug for Operand<'tcx> {
2376     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2377         use self::Operand::*;
2378         match *self {
2379             Constant(ref a) => write!(fmt, "{:?}", a),
2380             Copy(ref place) => write!(fmt, "{:?}", place),
2381             Move(ref place) => write!(fmt, "move {:?}", place),
2382         }
2383     }
2384 }
2385
2386 impl<'tcx> Operand<'tcx> {
2387     /// Convenience helper to make a constant that refers to the fn
2388     /// with given `DefId` and substs. Since this is used to synthesize
2389     /// MIR, assumes `user_ty` is None.
2390     pub fn function_handle(
2391         tcx: TyCtxt<'tcx>,
2392         def_id: DefId,
2393         substs: SubstsRef<'tcx>,
2394         span: Span,
2395     ) -> Self {
2396         let ty = tcx.bound_type_of(def_id).subst(tcx, substs);
2397         Operand::Constant(Box::new(Constant {
2398             span,
2399             user_ty: None,
2400             literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)),
2401         }))
2402     }
2403
2404     pub fn is_move(&self) -> bool {
2405         matches!(self, Operand::Move(..))
2406     }
2407
2408     /// Convenience helper to make a literal-like constant from a given scalar value.
2409     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
2410     pub fn const_from_scalar(
2411         tcx: TyCtxt<'tcx>,
2412         ty: Ty<'tcx>,
2413         val: Scalar,
2414         span: Span,
2415     ) -> Operand<'tcx> {
2416         debug_assert!({
2417             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
2418             let type_size = tcx
2419                 .layout_of(param_env_and_ty)
2420                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
2421                 .size;
2422             let scalar_size = match val {
2423                 Scalar::Int(int) => int.size(),
2424                 _ => panic!("Invalid scalar type {:?}", val),
2425             };
2426             scalar_size == type_size
2427         });
2428         Operand::Constant(Box::new(Constant {
2429             span,
2430             user_ty: None,
2431             literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
2432         }))
2433     }
2434
2435     pub fn to_copy(&self) -> Self {
2436         match *self {
2437             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2438             Operand::Move(place) => Operand::Copy(place),
2439         }
2440     }
2441
2442     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
2443     /// constant.
2444     pub fn place(&self) -> Option<Place<'tcx>> {
2445         match self {
2446             Operand::Copy(place) | Operand::Move(place) => Some(*place),
2447             Operand::Constant(_) => None,
2448         }
2449     }
2450
2451     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2452     /// place.
2453     pub fn constant(&self) -> Option<&Constant<'tcx>> {
2454         match self {
2455             Operand::Constant(x) => Some(&**x),
2456             Operand::Copy(_) | Operand::Move(_) => None,
2457         }
2458     }
2459
2460     /// Gets the `ty::FnDef` from an operand if it's a constant function item.
2461     ///
2462     /// While this is unlikely in general, it's the normal case of what you'll
2463     /// find as the `func` in a [`TerminatorKind::Call`].
2464     pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> {
2465         let const_ty = self.constant()?.literal.ty();
2466         if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None }
2467     }
2468 }
2469
2470 ///////////////////////////////////////////////////////////////////////////
2471 /// Rvalues
2472
2473 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2474 /// The various kinds of rvalues that can appear in MIR.
2475 ///
2476 /// Not all of these are allowed at every [`MirPhase`] - when this is the case, it's stated below.
2477 ///
2478 /// Computing any rvalue begins by evaluating the places and operands in some order (**Needs
2479 /// clarification**: Which order?). These are then used to produce a "value" - the same kind of
2480 /// value that an [`Operand`] produces.
2481 pub enum Rvalue<'tcx> {
2482     /// Yields the operand unchanged
2483     Use(Operand<'tcx>),
2484
2485     /// Creates an array where each element is the value of the operand.
2486     ///
2487     /// This is the cause of a bug in the case where the repetition count is zero because the value
2488     /// is not dropped, see [#74836].
2489     ///
2490     /// Corresponds to source code like `[x; 32]`.
2491     ///
2492     /// [#74836]: https://github.com/rust-lang/rust/issues/74836
2493     Repeat(Operand<'tcx>, ty::Const<'tcx>),
2494
2495     /// Creates a reference of the indicated kind to the place.
2496     ///
2497     /// There is not much to document here, because besides the obvious parts the semantics of this
2498     /// are essentially entirely a part of the aliasing model. There are many UCG issues discussing
2499     /// exactly what the behavior of this operation should be.
2500     ///
2501     /// `Shallow` borrows are disallowed after drop lowering.
2502     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2503
2504     /// Creates a pointer/reference to the given thread local.
2505     ///
2506     /// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a
2507     /// `*const T`, and if neither of those apply a `&T`.
2508     ///
2509     /// **Note:** This is a runtime operation that actually executes code and is in this sense more
2510     /// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to
2511     /// SIGILL for some reason that I (JakobDegen) never got a chance to look into.
2512     ///
2513     /// **Needs clarification**: Are there weird additional semantics here related to the runtime
2514     /// nature of this operation?
2515     ThreadLocalRef(DefId),
2516
2517     /// Creates a pointer with the indicated mutability to the place.
2518     ///
2519     /// This is generated by pointer casts like `&v as *const _` or raw address of expressions like
2520     /// `&raw v` or `addr_of!(v)`.
2521     ///
2522     /// Like with references, the semantics of this operation are heavily dependent on the aliasing
2523     /// model.
2524     AddressOf(Mutability, Place<'tcx>),
2525
2526     /// Yields the length of the place, as a `usize`.
2527     ///
2528     /// If the type of the place is an array, this is the array length. For slices (`[T]`, not
2529     /// `&[T]`) this accesses the place's metadata to determine the length. This rvalue is
2530     /// ill-formed for places of other types.
2531     Len(Place<'tcx>),
2532
2533     /// Performs essentially all of the casts that can be performed via `as`.
2534     ///
2535     /// This allows for casts from/to a variety of types.
2536     ///
2537     /// **FIXME**: Document exactly which `CastKind`s allow which types of casts. Figure out why
2538     /// `ArrayToPointer` and `MutToConstPointer` are special.
2539     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2540
2541     /// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second
2542     ///   parameter may be a `usize` as well.
2543     /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats,
2544     ///   raw pointers, or function pointers and return a `bool`. The types of the operands must be
2545     ///   matching, up to the usual caveat of the lifetimes in function pointers.
2546     /// * Left and right shift operations accept signed or unsigned integers not necessarily of the
2547     ///   same type and return a value of the same type as their LHS. Like in Rust, the RHS is
2548     ///   truncated as needed.
2549     /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching
2550     ///   types and return a value of that type.
2551     /// * The remaining operations accept signed integers, unsigned integers, or floats with
2552     ///   matching types and return a value of that type.
2553     BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2554
2555     /// Same as `BinaryOp`, but yields `(T, bool)` instead of `T`. In addition to performing the
2556     /// same computation as the matching `BinaryOp`, checks if the infinite precison result would be
2557     /// unequal to the actual result and sets the `bool` if this is the case.
2558     ///
2559     /// This only supports addition, subtraction, multiplication, and shift operations on integers.
2560     CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
2561
2562     /// Computes a value as described by the operation.
2563     NullaryOp(NullOp, Ty<'tcx>),
2564
2565     /// Exactly like `BinaryOp`, but less operands.
2566     ///
2567     /// Also does two's-complement arithmetic. Negation requires a signed integer or a float;
2568     /// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds
2569     /// return a value with the same type as their operand.
2570     UnaryOp(UnOp, Operand<'tcx>),
2571
2572     /// Computes the discriminant of the place, returning it as an integer of type
2573     /// [`discriminant_ty`]. Returns zero for types without discriminant.
2574     ///
2575     /// The validity requirements for the underlying value are undecided for this rvalue, see
2576     /// [#91095]. Note too that the value of the discriminant is not the same thing as the
2577     /// variant index; use [`discriminant_for_variant`] to convert.
2578     ///
2579     /// [`discriminant_ty`]: crate::ty::Ty::discriminant_ty
2580     /// [#91095]: https://github.com/rust-lang/rust/issues/91095
2581     /// [`discriminant_for_variant`]: crate::ty::Ty::discriminant_for_variant
2582     Discriminant(Place<'tcx>),
2583
2584     /// Creates an aggregate value, like a tuple or struct.
2585     ///
2586     /// This is needed because dataflow analysis needs to distinguish
2587     /// `dest = Foo { x: ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case that `Foo`
2588     /// has a destructor.
2589     ///
2590     /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Generator`. After
2591     /// generator lowering, `Generator` aggregate kinds are disallowed too.
2592     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2593
2594     /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
2595     ///
2596     /// This is different from a normal transmute because dataflow analysis will treat the box as
2597     /// initialized but its content as uninitialized. Like other pointer casts, this in general
2598     /// affects alias analysis.
2599     ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
2600 }
2601
2602 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2603 static_assert_size!(Rvalue<'_>, 40);
2604
2605 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2606 pub enum CastKind {
2607     Misc,
2608     Pointer(PointerCast),
2609 }
2610
2611 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2612 pub enum AggregateKind<'tcx> {
2613     /// The type is of the element
2614     Array(Ty<'tcx>),
2615     Tuple,
2616
2617     /// The second field is the variant index. It's equal to 0 for struct
2618     /// and union expressions. The fourth field is
2619     /// active field number and is present only for union expressions
2620     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2621     /// active field index would identity the field `c`
2622     Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2623
2624     Closure(DefId, SubstsRef<'tcx>),
2625     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2626 }
2627
2628 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2629 static_assert_size!(AggregateKind<'_>, 48);
2630
2631 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2632 pub enum BinOp {
2633     /// The `+` operator (addition)
2634     Add,
2635     /// The `-` operator (subtraction)
2636     Sub,
2637     /// The `*` operator (multiplication)
2638     Mul,
2639     /// The `/` operator (division)
2640     ///
2641     /// Division by zero is UB, because the compiler should have inserted checks
2642     /// prior to this.
2643     Div,
2644     /// The `%` operator (modulus)
2645     ///
2646     /// Using zero as the modulus (second operand) is UB, because the compiler
2647     /// should have inserted checks prior to this.
2648     Rem,
2649     /// The `^` operator (bitwise xor)
2650     BitXor,
2651     /// The `&` operator (bitwise and)
2652     BitAnd,
2653     /// The `|` operator (bitwise or)
2654     BitOr,
2655     /// The `<<` operator (shift left)
2656     ///
2657     /// The offset is truncated to the size of the first operand before shifting.
2658     Shl,
2659     /// The `>>` operator (shift right)
2660     ///
2661     /// The offset is truncated to the size of the first operand before shifting.
2662     Shr,
2663     /// The `==` operator (equality)
2664     Eq,
2665     /// The `<` operator (less than)
2666     Lt,
2667     /// The `<=` operator (less than or equal to)
2668     Le,
2669     /// The `!=` operator (not equal to)
2670     Ne,
2671     /// The `>=` operator (greater than or equal to)
2672     Ge,
2673     /// The `>` operator (greater than)
2674     Gt,
2675     /// The `ptr.offset` operator
2676     Offset,
2677 }
2678
2679 impl BinOp {
2680     pub fn is_checkable(self) -> bool {
2681         use self::BinOp::*;
2682         matches!(self, Add | Sub | Mul | Shl | Shr)
2683     }
2684 }
2685
2686 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2687 pub enum NullOp {
2688     /// Returns the size of a value of that type
2689     SizeOf,
2690     /// Returns the minimum alignment of a type
2691     AlignOf,
2692 }
2693
2694 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2695 pub enum UnOp {
2696     /// The `!` operator for logical inversion
2697     Not,
2698     /// The `-` operator for negation
2699     Neg,
2700 }
2701
2702 impl<'tcx> Debug for Rvalue<'tcx> {
2703     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2704         use self::Rvalue::*;
2705
2706         match *self {
2707             Use(ref place) => write!(fmt, "{:?}", place),
2708             Repeat(ref a, b) => {
2709                 write!(fmt, "[{:?}; ", a)?;
2710                 pretty_print_const(b, fmt, false)?;
2711                 write!(fmt, "]")
2712             }
2713             Len(ref a) => write!(fmt, "Len({:?})", a),
2714             Cast(ref kind, ref place, ref ty) => {
2715                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2716             }
2717             BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2718             CheckedBinaryOp(ref op, box (ref a, ref b)) => {
2719                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2720             }
2721             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2722             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2723             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2724             ThreadLocalRef(did) => ty::tls::with(|tcx| {
2725                 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2726                 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2727             }),
2728             Ref(region, borrow_kind, ref place) => {
2729                 let kind_str = match borrow_kind {
2730                     BorrowKind::Shared => "",
2731                     BorrowKind::Shallow => "shallow ",
2732                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2733                 };
2734
2735                 // When printing regions, add trailing space if necessary.
2736                 let print_region = ty::tls::with(|tcx| {
2737                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2738                 });
2739                 let region = if print_region {
2740                     let mut region = region.to_string();
2741                     if !region.is_empty() {
2742                         region.push(' ');
2743                     }
2744                     region
2745                 } else {
2746                     // Do not even print 'static
2747                     String::new()
2748                 };
2749                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2750             }
2751
2752             AddressOf(mutability, ref place) => {
2753                 let kind_str = match mutability {
2754                     Mutability::Mut => "mut",
2755                     Mutability::Not => "const",
2756                 };
2757
2758                 write!(fmt, "&raw {} {:?}", kind_str, place)
2759             }
2760
2761             Aggregate(ref kind, ref places) => {
2762                 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2763                     let mut tuple_fmt = fmt.debug_tuple(name);
2764                     for place in places {
2765                         tuple_fmt.field(place);
2766                     }
2767                     tuple_fmt.finish()
2768                 };
2769
2770                 match **kind {
2771                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2772
2773                     AggregateKind::Tuple => {
2774                         if places.is_empty() {
2775                             write!(fmt, "()")
2776                         } else {
2777                             fmt_tuple(fmt, "")
2778                         }
2779                     }
2780
2781                     AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => {
2782                         ty::tls::with(|tcx| {
2783                             let variant_def = &tcx.adt_def(adt_did).variant(variant);
2784                             let substs = tcx.lift(substs).expect("could not lift for printing");
2785                             let name = FmtPrinter::new(tcx, Namespace::ValueNS)
2786                                 .print_def_path(variant_def.def_id, substs)?
2787                                 .into_buffer();
2788
2789                             match variant_def.ctor_kind {
2790                                 CtorKind::Const => fmt.write_str(&name),
2791                                 CtorKind::Fn => fmt_tuple(fmt, &name),
2792                                 CtorKind::Fictive => {
2793                                     let mut struct_fmt = fmt.debug_struct(&name);
2794                                     for (field, place) in iter::zip(&variant_def.fields, places) {
2795                                         struct_fmt.field(field.name.as_str(), place);
2796                                     }
2797                                     struct_fmt.finish()
2798                                 }
2799                             }
2800                         })
2801                     }
2802
2803                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2804                         if let Some(def_id) = def_id.as_local() {
2805                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2806                                 let substs = tcx.lift(substs).unwrap();
2807                                 format!(
2808                                     "[closure@{}]",
2809                                     tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2810                                 )
2811                             } else {
2812                                 let span = tcx.def_span(def_id);
2813                                 format!(
2814                                     "[closure@{}]",
2815                                     tcx.sess.source_map().span_to_diagnostic_string(span)
2816                                 )
2817                             };
2818                             let mut struct_fmt = fmt.debug_struct(&name);
2819
2820                             // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2821                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2822                                 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2823                                     let var_name = tcx.hir().name(var_id);
2824                                     struct_fmt.field(var_name.as_str(), place);
2825                                 }
2826                             }
2827
2828                             struct_fmt.finish()
2829                         } else {
2830                             write!(fmt, "[closure]")
2831                         }
2832                     }),
2833
2834                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2835                         if let Some(def_id) = def_id.as_local() {
2836                             let name = format!("[generator@{:?}]", tcx.def_span(def_id));
2837                             let mut struct_fmt = fmt.debug_struct(&name);
2838
2839                             // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2840                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2841                                 for (&var_id, place) in iter::zip(upvars.keys(), places) {
2842                                     let var_name = tcx.hir().name(var_id);
2843                                     struct_fmt.field(var_name.as_str(), place);
2844                                 }
2845                             }
2846
2847                             struct_fmt.finish()
2848                         } else {
2849                             write!(fmt, "[generator]")
2850                         }
2851                     }),
2852                 }
2853             }
2854
2855             ShallowInitBox(ref place, ref ty) => {
2856                 write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
2857             }
2858         }
2859     }
2860 }
2861
2862 ///////////////////////////////////////////////////////////////////////////
2863 /// Constants
2864 ///
2865 /// Two constants are equal if they are the same constant. Note that
2866 /// this does not necessarily mean that they are `==` in Rust. In
2867 /// particular, one must be wary of `NaN`!
2868
2869 #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
2870 pub struct Constant<'tcx> {
2871     pub span: Span,
2872
2873     /// Optional user-given type: for something like
2874     /// `collect::<Vec<_>>`, this would be present and would
2875     /// indicate that `Vec<_>` was explicitly specified.
2876     ///
2877     /// Needed for NLL to impose user-given type constraints.
2878     pub user_ty: Option<UserTypeAnnotationIndex>,
2879
2880     pub literal: ConstantKind<'tcx>,
2881 }
2882
2883 #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
2884 #[derive(Lift)]
2885 pub enum ConstantKind<'tcx> {
2886     /// This constant came from the type system
2887     Ty(ty::Const<'tcx>),
2888     /// This constant cannot go back into the type system, as it represents
2889     /// something the type system cannot handle (e.g. pointers).
2890     Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
2891 }
2892
2893 impl<'tcx> Constant<'tcx> {
2894     pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2895         match self.literal.try_to_scalar() {
2896             Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2897                 GlobalAlloc::Static(def_id) => {
2898                     assert!(!tcx.is_thread_local_static(def_id));
2899                     Some(def_id)
2900                 }
2901                 _ => None,
2902             },
2903             _ => None,
2904         }
2905     }
2906     #[inline]
2907     pub fn ty(&self) -> Ty<'tcx> {
2908         self.literal.ty()
2909     }
2910 }
2911
2912 impl<'tcx> From<ty::Const<'tcx>> for ConstantKind<'tcx> {
2913     #[inline]
2914     fn from(ct: ty::Const<'tcx>) -> Self {
2915         match ct.val() {
2916             ty::ConstKind::Value(cv) => {
2917                 // FIXME Once valtrees are introduced we need to convert those
2918                 // into `ConstValue` instances here
2919                 Self::Val(cv, ct.ty())
2920             }
2921             _ => Self::Ty(ct),
2922         }
2923     }
2924 }
2925
2926 impl<'tcx> ConstantKind<'tcx> {
2927     /// Returns `None` if the constant is not trivially safe for use in the type system.
2928     pub fn const_for_ty(&self) -> Option<ty::Const<'tcx>> {
2929         match self {
2930             ConstantKind::Ty(c) => Some(*c),
2931             ConstantKind::Val(..) => None,
2932         }
2933     }
2934
2935     pub fn ty(&self) -> Ty<'tcx> {
2936         match self {
2937             ConstantKind::Ty(c) => c.ty(),
2938             ConstantKind::Val(_, ty) => *ty,
2939         }
2940     }
2941
2942     pub fn try_val(&self) -> Option<ConstValue<'tcx>> {
2943         match self {
2944             ConstantKind::Ty(c) => match c.val() {
2945                 ty::ConstKind::Value(v) => Some(v),
2946                 _ => None,
2947             },
2948             ConstantKind::Val(v, _) => Some(*v),
2949         }
2950     }
2951
2952     #[inline]
2953     pub fn try_to_value(self) -> Option<interpret::ConstValue<'tcx>> {
2954         match self {
2955             ConstantKind::Ty(c) => c.val().try_to_value(),
2956             ConstantKind::Val(val, _) => Some(val),
2957         }
2958     }
2959
2960     #[inline]
2961     pub fn try_to_scalar(self) -> Option<Scalar> {
2962         self.try_to_value()?.try_to_scalar()
2963     }
2964
2965     #[inline]
2966     pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2967         Some(self.try_to_value()?.try_to_scalar()?.assert_int())
2968     }
2969
2970     #[inline]
2971     pub fn try_to_bits(self, size: Size) -> Option<u128> {
2972         self.try_to_scalar_int()?.to_bits(size).ok()
2973     }
2974
2975     #[inline]
2976     pub fn try_to_bool(self) -> Option<bool> {
2977         self.try_to_scalar_int()?.try_into().ok()
2978     }
2979
2980     #[inline]
2981     pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
2982         match self {
2983             Self::Ty(c) => {
2984                 // FIXME Need to use a different evaluation function that directly returns a `ConstValue`
2985                 // if evaluation succeeds and does not create a ValTree first
2986                 if let Some(val) = c.val().try_eval(tcx, param_env) {
2987                     match val {
2988                         Ok(val) => Self::Val(val, c.ty()),
2989                         Err(_) => Self::Ty(tcx.const_error(self.ty())),
2990                     }
2991                 } else {
2992                     self
2993                 }
2994             }
2995             Self::Val(_, _) => self,
2996         }
2997     }
2998
2999     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
3000     #[inline]
3001     pub fn eval_bits(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
3002         self.try_eval_bits(tcx, param_env, ty)
3003             .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
3004     }
3005
3006     #[inline]
3007     pub fn try_eval_bits(
3008         &self,
3009         tcx: TyCtxt<'tcx>,
3010         param_env: ty::ParamEnv<'tcx>,
3011         ty: Ty<'tcx>,
3012     ) -> Option<u128> {
3013         match self {
3014             Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
3015             Self::Val(val, t) => {
3016                 assert_eq!(*t, ty);
3017                 let size =
3018                     tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
3019                 val.try_to_bits(size)
3020             }
3021         }
3022     }
3023
3024     #[inline]
3025     pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
3026         match self {
3027             Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
3028             Self::Val(val, _) => val.try_to_bool(),
3029         }
3030     }
3031
3032     #[inline]
3033     pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
3034         match self {
3035             Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
3036             Self::Val(val, _) => val.try_to_machine_usize(tcx),
3037         }
3038     }
3039
3040     pub fn from_bits(
3041         tcx: TyCtxt<'tcx>,
3042         bits: u128,
3043         param_env_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
3044     ) -> Self {
3045         let size = tcx
3046             .layout_of(param_env_ty)
3047             .unwrap_or_else(|e| {
3048                 bug!("could not compute layout for {:?}: {:?}", param_env_ty.value, e)
3049             })
3050             .size;
3051         let cv = ConstValue::Scalar(Scalar::from_uint(bits, size));
3052
3053         Self::Val(cv, param_env_ty.value)
3054     }
3055
3056     pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> Self {
3057         let cv = ConstValue::from_bool(v);
3058         Self::Val(cv, tcx.types.bool)
3059     }
3060
3061     pub fn zero_sized(ty: Ty<'tcx>) -> Self {
3062         let cv = ConstValue::Scalar(Scalar::ZST);
3063         Self::Val(cv, ty)
3064     }
3065
3066     pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> Self {
3067         let ty = tcx.types.usize;
3068         Self::from_bits(tcx, n as u128, ty::ParamEnv::empty().and(ty))
3069     }
3070
3071     /// Literals are converted to `ConstantKindVal`, const generic parameters are eagerly
3072     /// converted to a constant, everything else becomes `Unevaluated`.
3073     pub fn from_anon_const(
3074         tcx: TyCtxt<'tcx>,
3075         def_id: LocalDefId,
3076         param_env: ty::ParamEnv<'tcx>,
3077     ) -> Self {
3078         Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id), param_env)
3079     }
3080
3081     #[instrument(skip(tcx), level = "debug")]
3082     fn from_opt_const_arg_anon_const(
3083         tcx: TyCtxt<'tcx>,
3084         def: ty::WithOptConstParam<LocalDefId>,
3085         param_env: ty::ParamEnv<'tcx>,
3086     ) -> Self {
3087         let body_id = match tcx.hir().get_by_def_id(def.did) {
3088             hir::Node::AnonConst(ac) => ac.body,
3089             _ => span_bug!(
3090                 tcx.def_span(def.did.to_def_id()),
3091                 "from_anon_const can only process anonymous constants"
3092             ),
3093         };
3094
3095         let expr = &tcx.hir().body(body_id).value;
3096         debug!(?expr);
3097
3098         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
3099         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
3100         let expr = match &expr.kind {
3101             hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3102                 block.expr.as_ref().unwrap()
3103             }
3104             _ => expr,
3105         };
3106
3107         let ty = tcx.type_of(def.def_id_for_type_of());
3108
3109         // FIXME(const_generics): We currently have to special case parameters because `min_const_generics`
3110         // does not provide the parents generics to anonymous constants. We still allow generic const
3111         // parameters by themselves however, e.g. `N`.  These constants would cause an ICE if we were to
3112         // ever try to substitute the generic parameters in their bodies.
3113         //
3114         // While this doesn't happen as these constants are always used as `ty::ConstKind::Param`, it does
3115         // cause issues if we were to remove that special-case and try to evaluate the constant instead.
3116         use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
3117         match expr.kind {
3118             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
3119                 // Find the name and index of the const parameter by indexing the generics of
3120                 // the parent item and construct a `ParamConst`.
3121                 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
3122                 let item_id = tcx.hir().get_parent_node(hir_id);
3123                 let item_def_id = tcx.hir().local_def_id(item_id);
3124                 let generics = tcx.generics_of(item_def_id.to_def_id());
3125                 let index = generics.param_def_id_to_index[&def_id];
3126                 let name = tcx.hir().name(hir_id);
3127                 let ty_const = tcx.mk_const(ty::ConstS {
3128                     val: ty::ConstKind::Param(ty::ParamConst::new(index, name)),
3129                     ty,
3130                 });
3131
3132                 return Self::Ty(ty_const);
3133             }
3134             _ => {}
3135         }
3136
3137         let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
3138         let parent_substs = if let Some(parent_hir_id) = tcx.hir().find_parent_node(hir_id) {
3139             if let Some(parent_did) = tcx.hir().opt_local_def_id(parent_hir_id) {
3140                 InternalSubsts::identity_for_item(tcx, parent_did.to_def_id())
3141             } else {
3142                 tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
3143             }
3144         } else {
3145             tcx.mk_substs(Vec::<GenericArg<'tcx>>::new().into_iter())
3146         };
3147         debug!(?parent_substs);
3148
3149         let did = def.did.to_def_id();
3150         let child_substs = InternalSubsts::identity_for_item(tcx, did);
3151         let substs = tcx.mk_substs(parent_substs.into_iter().chain(child_substs.into_iter()));
3152         debug!(?substs);
3153
3154         let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
3155         let span = tcx.hir().span(hir_id);
3156         let uneval = ty::Unevaluated::new(def.to_global(), substs);
3157         debug!(?span, ?param_env);
3158
3159         match tcx.const_eval_resolve(param_env, uneval, Some(span)) {
3160             Ok(val) => Self::Val(val, ty),
3161             Err(_) => {
3162                 // Error was handled in `const_eval_resolve`. Here we just create a
3163                 // new unevaluated const and error hard later in codegen
3164                 let ty_const = tcx.mk_const(ty::ConstS {
3165                     val: ty::ConstKind::Unevaluated(ty::Unevaluated {
3166                         def: def.to_global(),
3167                         substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
3168                         promoted: None,
3169                     }),
3170                     ty,
3171                 });
3172
3173                 Self::Ty(ty_const)
3174             }
3175         }
3176     }
3177 }
3178
3179 /// A collection of projections into user types.
3180 ///
3181 /// They are projections because a binding can occur a part of a
3182 /// parent pattern that has been ascribed a type.
3183 ///
3184 /// Its a collection because there can be multiple type ascriptions on
3185 /// the path from the root of the pattern down to the binding itself.
3186 ///
3187 /// An example:
3188 ///
3189 /// ```ignore (illustrative)
3190 /// struct S<'a>((i32, &'a str), String);
3191 /// let S((_, w): (i32, &'static str), _): S = ...;
3192 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
3193 /// //  ---------------------------------  ^ (2)
3194 /// ```
3195 ///
3196 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
3197 /// ascribed the type `(i32, &'static str)`.
3198 ///
3199 /// The highlights labelled `(2)` show the whole pattern being
3200 /// ascribed the type `S`.
3201 ///
3202 /// In this example, when we descend to `w`, we will have built up the
3203 /// following two projected types:
3204 ///
3205 ///   * base: `S`,                   projection: `(base.0).1`
3206 ///   * base: `(i32, &'static str)`, projection: `base.1`
3207 ///
3208 /// The first will lead to the constraint `w: &'1 str` (for some
3209 /// inferred region `'1`). The second will lead to the constraint `w:
3210 /// &'static str`.
3211 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
3212 pub struct UserTypeProjections {
3213     pub contents: Vec<(UserTypeProjection, Span)>,
3214 }
3215
3216 impl<'tcx> UserTypeProjections {
3217     pub fn none() -> Self {
3218         UserTypeProjections { contents: vec![] }
3219     }
3220
3221     pub fn is_empty(&self) -> bool {
3222         self.contents.is_empty()
3223     }
3224
3225     pub fn projections_and_spans(
3226         &self,
3227     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
3228         self.contents.iter()
3229     }
3230
3231     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
3232         self.contents.iter().map(|&(ref user_type, _span)| user_type)
3233     }
3234
3235     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
3236         self.contents.push((user_ty.clone(), span));
3237         self
3238     }
3239
3240     fn map_projections(
3241         mut self,
3242         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
3243     ) -> Self {
3244         self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect();
3245         self
3246     }
3247
3248     pub fn index(self) -> Self {
3249         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
3250     }
3251
3252     pub fn subslice(self, from: u64, to: u64) -> Self {
3253         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
3254     }
3255
3256     pub fn deref(self) -> Self {
3257         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
3258     }
3259
3260     pub fn leaf(self, field: Field) -> Self {
3261         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
3262     }
3263
3264     pub fn variant(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx, field: Field) -> Self {
3265         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
3266     }
3267 }
3268
3269 /// Encodes the effect of a user-supplied type annotation on the
3270 /// subcomponents of a pattern. The effect is determined by applying the
3271 /// given list of projections to some underlying base type. Often,
3272 /// the projection element list `projs` is empty, in which case this
3273 /// directly encodes a type in `base`. But in the case of complex patterns with
3274 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
3275 /// in which case the `projs` vector is used.
3276 ///
3277 /// Examples:
3278 ///
3279 /// * `let x: T = ...` -- here, the `projs` vector is empty.
3280 ///
3281 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
3282 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
3283 ///   determined by finding the type of the `.0` field from `T`.
3284 #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
3285 pub struct UserTypeProjection {
3286     pub base: UserTypeAnnotationIndex,
3287     pub projs: Vec<ProjectionKind>,
3288 }
3289
3290 impl Copy for ProjectionKind {}
3291
3292 impl UserTypeProjection {
3293     pub(crate) fn index(mut self) -> Self {
3294         self.projs.push(ProjectionElem::Index(()));
3295         self
3296     }
3297
3298     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
3299         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
3300         self
3301     }
3302
3303     pub(crate) fn deref(mut self) -> Self {
3304         self.projs.push(ProjectionElem::Deref);
3305         self
3306     }
3307
3308     pub(crate) fn leaf(mut self, field: Field) -> Self {
3309         self.projs.push(ProjectionElem::Field(field, ()));
3310         self
3311     }
3312
3313     pub(crate) fn variant(
3314         mut self,
3315         adt_def: AdtDef<'_>,
3316         variant_index: VariantIdx,
3317         field: Field,
3318     ) -> Self {
3319         self.projs.push(ProjectionElem::Downcast(
3320             Some(adt_def.variant(variant_index).name),
3321             variant_index,
3322         ));
3323         self.projs.push(ProjectionElem::Field(field, ()));
3324         self
3325     }
3326 }
3327
3328 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
3329
3330 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
3331     fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
3332         self,
3333         folder: &mut F,
3334     ) -> Result<Self, F::Error> {
3335         Ok(UserTypeProjection {
3336             base: self.base.try_fold_with(folder)?,
3337             projs: self.projs.try_fold_with(folder)?,
3338         })
3339     }
3340
3341     fn super_visit_with<Vs: TypeVisitor<'tcx>>(
3342         &self,
3343         visitor: &mut Vs,
3344     ) -> ControlFlow<Vs::BreakTy> {
3345         self.base.visit_with(visitor)
3346         // Note: there's nothing in `self.proj` to visit.
3347     }
3348 }
3349
3350 rustc_index::newtype_index! {
3351     pub struct Promoted {
3352         derive [HashStable]
3353         DEBUG_FORMAT = "promoted[{}]"
3354     }
3355 }
3356
3357 impl<'tcx> Debug for Constant<'tcx> {
3358     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
3359         write!(fmt, "{}", self)
3360     }
3361 }
3362
3363 impl<'tcx> Display for Constant<'tcx> {
3364     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
3365         match self.ty().kind() {
3366             ty::FnDef(..) => {}
3367             _ => write!(fmt, "const ")?,
3368         }
3369         Display::fmt(&self.literal, fmt)
3370     }
3371 }
3372
3373 impl<'tcx> Display for ConstantKind<'tcx> {
3374     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
3375         match *self {
3376             ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
3377             ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
3378         }
3379     }
3380 }
3381
3382 fn pretty_print_const<'tcx>(
3383     c: ty::Const<'tcx>,
3384     fmt: &mut Formatter<'_>,
3385     print_types: bool,
3386 ) -> fmt::Result {
3387     use crate::ty::print::PrettyPrinter;
3388     ty::tls::with(|tcx| {
3389         let literal = tcx.lift(c).unwrap();
3390         let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
3391         cx.print_alloc_ids = true;
3392         let cx = cx.pretty_print_const(literal, print_types)?;
3393         fmt.write_str(&cx.into_buffer())?;
3394         Ok(())
3395     })
3396 }
3397
3398 fn pretty_print_const_value<'tcx>(
3399     val: interpret::ConstValue<'tcx>,
3400     ty: Ty<'tcx>,
3401     fmt: &mut Formatter<'_>,
3402     print_types: bool,
3403 ) -> fmt::Result {
3404     use crate::ty::print::PrettyPrinter;
3405     ty::tls::with(|tcx| {
3406         let val = tcx.lift(val).unwrap();
3407         let ty = tcx.lift(ty).unwrap();
3408         let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
3409         cx.print_alloc_ids = true;
3410         let cx = cx.pretty_print_const_value(val, ty, print_types)?;
3411         fmt.write_str(&cx.into_buffer())?;
3412         Ok(())
3413     })
3414 }
3415
3416 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
3417     type Node = BasicBlock;
3418 }
3419
3420 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
3421     #[inline]
3422     fn num_nodes(&self) -> usize {
3423         self.basic_blocks.len()
3424     }
3425 }
3426
3427 impl<'tcx> graph::WithStartNode for Body<'tcx> {
3428     #[inline]
3429     fn start_node(&self) -> Self::Node {
3430         START_BLOCK
3431     }
3432 }
3433
3434 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
3435     #[inline]
3436     fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
3437         self.basic_blocks[node].terminator().successors().cloned()
3438     }
3439 }
3440
3441 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
3442     type Item = BasicBlock;
3443     type Iter = iter::Cloned<Successors<'b>>;
3444 }
3445
3446 impl<'tcx, 'graph> graph::GraphPredecessors<'graph> for Body<'tcx> {
3447     type Item = BasicBlock;
3448     type Iter = std::iter::Copied<std::slice::Iter<'graph, BasicBlock>>;
3449 }
3450
3451 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
3452     #[inline]
3453     fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
3454         self.predecessors()[node].iter().copied()
3455     }
3456 }
3457
3458 /// `Location` represents the position of the start of the statement; or, if
3459 /// `statement_index` equals the number of statements, then the start of the
3460 /// terminator.
3461 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
3462 pub struct Location {
3463     /// The block that the location is within.
3464     pub block: BasicBlock,
3465
3466     pub statement_index: usize,
3467 }
3468
3469 impl fmt::Debug for Location {
3470     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3471         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
3472     }
3473 }
3474
3475 impl Location {
3476     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
3477
3478     /// Returns the location immediately after this one within the enclosing block.
3479     ///
3480     /// Note that if this location represents a terminator, then the
3481     /// resulting location would be out of bounds and invalid.
3482     pub fn successor_within_block(&self) -> Location {
3483         Location { block: self.block, statement_index: self.statement_index + 1 }
3484     }
3485
3486     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
3487     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
3488         // If we are in the same block as the other location and are an earlier statement
3489         // then we are a predecessor of `other`.
3490         if self.block == other.block && self.statement_index < other.statement_index {
3491             return true;
3492         }
3493
3494         let predecessors = body.predecessors();
3495
3496         // If we're in another block, then we want to check that block is a predecessor of `other`.
3497         let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
3498         let mut visited = FxHashSet::default();
3499
3500         while let Some(block) = queue.pop() {
3501             // If we haven't visited this block before, then make sure we visit its predecessors.
3502             if visited.insert(block) {
3503                 queue.extend(predecessors[block].iter().cloned());
3504             } else {
3505                 continue;
3506             }
3507
3508             // If we found the block that `self` is in, then we are a predecessor of `other` (since
3509             // we found that block by looking at the predecessors of `other`).
3510             if self.block == block {
3511                 return true;
3512             }
3513         }
3514
3515         false
3516     }
3517
3518     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
3519         if self.block == other.block {
3520             self.statement_index <= other.statement_index
3521         } else {
3522             dominators.is_dominated_by(other.block, self.block)
3523         }
3524     }
3525 }