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