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