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