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