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