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