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