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