]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
797836f166173f0366e7838afe7ce65cb3cca6b2
[rust.git] / src / librustc / mir / mod.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! MIR datatypes and passes. See the [rustc guide] for more info.
12 //!
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir/index.html
14
15 use hir::def::CtorKind;
16 use hir::def_id::DefId;
17 use hir::{self, HirId, InlineAsm};
18 use middle::region;
19 use mir::interpret::{ConstValue, EvalErrorKind, Scalar};
20 use mir::visit::MirVisitable;
21 use rustc_apfloat::ieee::{Double, Single};
22 use rustc_apfloat::Float;
23 use rustc_data_structures::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
25 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_data_structures::sync::MappedReadGuard;
28 use rustc_serialize as serialize;
29 use smallvec::SmallVec;
30 use std::borrow::Cow;
31 use std::fmt::{self, Debug, Formatter, Write};
32 use std::ops::{Index, IndexMut};
33 use std::slice;
34 use std::vec::IntoIter;
35 use std::{iter, mem, option, u32};
36 use syntax::ast::{self, Name};
37 use syntax::symbol::InternedString;
38 use syntax_pos::{Span, DUMMY_SP};
39 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
40 use ty::subst::{CanonicalUserSubsts, Subst, Substs};
41 use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
42 use util::ppaux;
43
44 pub use mir::interpret::AssertMessage;
45
46 mod cache;
47 pub mod interpret;
48 pub mod mono;
49 pub mod tcx;
50 pub mod traversal;
51 pub mod visit;
52
53 /// Types for locals
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55
56 pub trait HasLocalDecls<'tcx> {
57     fn local_decls(&self) -> &LocalDecls<'tcx>;
58 }
59
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61     fn local_decls(&self) -> &LocalDecls<'tcx> {
62         self
63     }
64 }
65
66 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
67     fn local_decls(&self) -> &LocalDecls<'tcx> {
68         &self.local_decls
69     }
70 }
71
72 /// The various "big phases" that MIR goes through.
73 ///
74 /// Warning: ordering of variants is significant
75 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
76 pub enum MirPhase {
77     Build,
78     Const,
79     Validated,
80     Optimized,
81 }
82
83 /// Lowered representation of a single function.
84 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
85 pub struct Mir<'tcx> {
86     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
87     /// that indexes into this vector.
88     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
89
90     /// Records how far through the "desugaring and optimization" process this particular
91     /// MIR has traversed. This is particularly useful when inlining, since in that context
92     /// we instantiate the promoted constants and add them to our promoted vector -- but those
93     /// promoted items have already been optimized, whereas ours have not. This field allows
94     /// us to see the difference and forego optimization on the inlined promoted items.
95     pub phase: MirPhase,
96
97     /// List of source scopes; these are referenced by statements
98     /// and used for debuginfo. Indexed by a `SourceScope`.
99     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
100
101     /// Crate-local information for each source scope, that can't (and
102     /// needn't) be tracked across crates.
103     pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
104
105     /// Rvalues promoted from this function, such as borrows of constants.
106     /// Each of them is the Mir of a constant with the fn's type parameters
107     /// in scope, but a separate set of locals.
108     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
109
110     /// Yield type of the function, if it is a generator.
111     pub yield_ty: Option<Ty<'tcx>>,
112
113     /// Generator drop glue
114     pub generator_drop: Option<Box<Mir<'tcx>>>,
115
116     /// The layout of a generator. Produced by the state transformation.
117     pub generator_layout: Option<GeneratorLayout<'tcx>>,
118
119     /// Declarations of locals.
120     ///
121     /// The first local is the return value pointer, followed by `arg_count`
122     /// locals for the function arguments, followed by any user-declared
123     /// variables and temporaries.
124     pub local_decls: LocalDecls<'tcx>,
125
126     /// Number of arguments this function takes.
127     ///
128     /// Starting at local 1, `arg_count` locals will be provided by the caller
129     /// and can be assumed to be initialized.
130     ///
131     /// If this MIR was built for a constant, this will be 0.
132     pub arg_count: usize,
133
134     /// Names and capture modes of all the closure upvars, assuming
135     /// the first argument is either the closure or a reference to it.
136     pub upvar_decls: Vec<UpvarDecl>,
137
138     /// Mark an argument local (which must be a tuple) as getting passed as
139     /// its individual components at the LLVM level.
140     ///
141     /// This is used for the "rust-call" ABI.
142     pub spread_arg: Option<Local>,
143
144     /// A span representing this MIR, for error reporting
145     pub span: Span,
146
147     /// A cache for various calculations
148     cache: cache::Cache,
149 }
150
151 impl<'tcx> Mir<'tcx> {
152     pub fn new(
153         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
154         source_scopes: IndexVec<SourceScope, SourceScopeData>,
155         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
156         promoted: IndexVec<Promoted, Mir<'tcx>>,
157         yield_ty: Option<Ty<'tcx>>,
158         local_decls: IndexVec<Local, LocalDecl<'tcx>>,
159         arg_count: usize,
160         upvar_decls: Vec<UpvarDecl>,
161         span: Span,
162     ) -> Self {
163         // We need `arg_count` locals, and one for the return place
164         assert!(
165             local_decls.len() >= arg_count + 1,
166             "expected at least {} locals, got {}",
167             arg_count + 1,
168             local_decls.len()
169         );
170
171         Mir {
172             phase: MirPhase::Build,
173             basic_blocks,
174             source_scopes,
175             source_scope_local_data,
176             promoted,
177             yield_ty,
178             generator_drop: None,
179             generator_layout: None,
180             local_decls,
181             arg_count,
182             upvar_decls,
183             spread_arg: None,
184             span,
185             cache: cache::Cache::new(),
186         }
187     }
188
189     #[inline]
190     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
191         &self.basic_blocks
192     }
193
194     #[inline]
195     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
196         self.cache.invalidate();
197         &mut self.basic_blocks
198     }
199
200     #[inline]
201     pub fn basic_blocks_and_local_decls_mut(
202         &mut self,
203     ) -> (
204         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
205         &mut LocalDecls<'tcx>,
206     ) {
207         self.cache.invalidate();
208         (&mut self.basic_blocks, &mut self.local_decls)
209     }
210
211     #[inline]
212     pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
213         self.cache.predecessors(self)
214     }
215
216     #[inline]
217     pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
218         MappedReadGuard::map(self.predecessors(), |p| &p[bb])
219     }
220
221     #[inline]
222     pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
223         let if_zero_locations = if loc.statement_index == 0 {
224             let predecessor_blocks = self.predecessors_for(loc.block);
225             let num_predecessor_blocks = predecessor_blocks.len();
226             Some(
227                 (0..num_predecessor_blocks)
228                     .map(move |i| predecessor_blocks[i])
229                     .map(move |bb| self.terminator_loc(bb)),
230             )
231         } else {
232             None
233         };
234
235         let if_not_zero_locations = if loc.statement_index == 0 {
236             None
237         } else {
238             Some(Location {
239                 block: loc.block,
240                 statement_index: loc.statement_index - 1,
241             })
242         };
243
244         if_zero_locations
245             .into_iter()
246             .flatten()
247             .chain(if_not_zero_locations)
248     }
249
250     #[inline]
251     pub fn dominators(&self) -> Dominators<BasicBlock> {
252         dominators(self)
253     }
254
255     #[inline]
256     pub fn local_kind(&self, local: Local) -> LocalKind {
257         let index = local.as_usize();
258         if index == 0 {
259             debug_assert!(
260                 self.local_decls[local].mutability == Mutability::Mut,
261                 "return place should be mutable"
262             );
263
264             LocalKind::ReturnPointer
265         } else if index < self.arg_count + 1 {
266             LocalKind::Arg
267         } else if self.local_decls[local].name.is_some() {
268             LocalKind::Var
269         } else {
270             LocalKind::Temp
271         }
272     }
273
274     /// Returns an iterator over all temporaries.
275     #[inline]
276     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
277         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
278             let local = Local::new(index);
279             if self.local_decls[local].is_user_variable.is_some() {
280                 None
281             } else {
282                 Some(local)
283             }
284         })
285     }
286
287     /// Returns an iterator over all user-declared locals.
288     #[inline]
289     pub fn vars_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.is_some() {
293                 Some(local)
294             } else {
295                 None
296             }
297         })
298     }
299
300     /// Returns an iterator over all user-declared mutable arguments and locals.
301     #[inline]
302     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
303         (1..self.local_decls.len()).filter_map(move |index| {
304             let local = Local::new(index);
305             let decl = &self.local_decls[local];
306             if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
307                 && decl.mutability == Mutability::Mut
308             {
309                 Some(local)
310             } else {
311                 None
312             }
313         })
314     }
315
316     /// Returns an iterator over all function arguments.
317     #[inline]
318     pub fn args_iter(&self) -> impl Iterator<Item = Local> {
319         let arg_count = self.arg_count;
320         (1..arg_count + 1).map(Local::new)
321     }
322
323     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
324     /// locals that are neither arguments nor the return place).
325     #[inline]
326     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
327         let arg_count = self.arg_count;
328         let local_count = self.local_decls.len();
329         (arg_count + 1..local_count).map(Local::new)
330     }
331
332     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
333     /// invalidating statement indices in `Location`s.
334     pub fn make_statement_nop(&mut self, location: Location) {
335         let block = &mut self[location.block];
336         debug_assert!(location.statement_index < block.statements.len());
337         block.statements[location.statement_index].make_nop()
338     }
339
340     /// Returns the source info associated with `location`.
341     pub fn source_info(&self, location: Location) -> &SourceInfo {
342         let block = &self[location.block];
343         let stmts = &block.statements;
344         let idx = location.statement_index;
345         if idx < stmts.len() {
346             &stmts[idx].source_info
347         } else {
348             assert_eq!(idx, stmts.len());
349             &block.terminator().source_info
350         }
351     }
352
353     /// Check if `sub` is a sub scope of `sup`
354     pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
355         while sub != sup {
356             match self.source_scopes[sub].parent_scope {
357                 None => return false,
358                 Some(p) => sub = p,
359             }
360         }
361         true
362     }
363
364     /// Return the return type, it always return first element from `local_decls` array
365     pub fn return_ty(&self) -> Ty<'tcx> {
366         self.local_decls[RETURN_PLACE].ty
367     }
368
369     /// Get the location of the terminator for the given block
370     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
371         Location {
372             block: bb,
373             statement_index: self[bb].statements.len(),
374         }
375     }
376 }
377
378 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
379 pub enum Safety {
380     Safe,
381     /// Unsafe because of a PushUnsafeBlock
382     BuiltinUnsafe,
383     /// Unsafe because of an unsafe fn
384     FnUnsafe,
385     /// Unsafe because of an `unsafe` block
386     ExplicitUnsafe(ast::NodeId),
387 }
388
389 impl_stable_hash_for!(struct Mir<'tcx> {
390     phase,
391     basic_blocks,
392     source_scopes,
393     source_scope_local_data,
394     promoted,
395     yield_ty,
396     generator_drop,
397     generator_layout,
398     local_decls,
399     arg_count,
400     upvar_decls,
401     spread_arg,
402     span,
403     cache
404 });
405
406 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
407     type Output = BasicBlockData<'tcx>;
408
409     #[inline]
410     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
411         &self.basic_blocks()[index]
412     }
413 }
414
415 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
416     #[inline]
417     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
418         &mut self.basic_blocks_mut()[index]
419     }
420 }
421
422 #[derive(Copy, Clone, Debug)]
423 pub enum ClearCrossCrate<T> {
424     Clear,
425     Set(T),
426 }
427
428 impl<T> ClearCrossCrate<T> {
429     pub fn assert_crate_local(self) -> T {
430         match self {
431             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
432             ClearCrossCrate::Set(v) => v,
433         }
434     }
435 }
436
437 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
438 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
439
440 /// Grouped information about the source code origin of a MIR entity.
441 /// Intended to be inspected by diagnostics and debuginfo.
442 /// Most passes can work with it as a whole, within a single function.
443 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
444 pub struct SourceInfo {
445     /// Source span for the AST pertaining to this MIR entity.
446     pub span: Span,
447
448     /// The source scope, keeping track of which bindings can be
449     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
450     pub scope: SourceScope,
451 }
452
453 ///////////////////////////////////////////////////////////////////////////
454 // Mutability and borrow kinds
455
456 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
457 pub enum Mutability {
458     Mut,
459     Not,
460 }
461
462 impl From<Mutability> for hir::Mutability {
463     fn from(m: Mutability) -> Self {
464         match m {
465             Mutability::Mut => hir::MutMutable,
466             Mutability::Not => hir::MutImmutable,
467         }
468     }
469 }
470
471 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
472 pub enum BorrowKind {
473     /// Data must be immutable and is aliasable.
474     Shared,
475
476     /// The immediately borrowed place must be immutable, but projections from
477     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
478     /// conflict with a mutable borrow of `a.b.c`.
479     ///
480     /// This is used when lowering matches: when matching on a place we want to
481     /// ensure that place have the same value from the start of the match until
482     /// an arm is selected. This prevents this code from compiling:
483     ///
484     ///     let mut x = &Some(0);
485     ///     match *x {
486     ///         None => (),
487     ///         Some(_) if { x = &None; false } => (),
488     ///         Some(_) => (),
489     ///     }
490     ///
491     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
492     /// should not prevent `if let None = x { ... }`, for example, becase the
493     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
494     /// We can also report errors with this kind of borrow differently.
495     Shallow,
496
497     /// Data must be immutable but not aliasable.  This kind of borrow
498     /// cannot currently be expressed by the user and is used only in
499     /// implicit closure bindings. It is needed when the closure is
500     /// borrowing or mutating a mutable referent, e.g.:
501     ///
502     ///    let x: &mut isize = ...;
503     ///    let y = || *x += 5;
504     ///
505     /// If we were to try to translate this closure into a more explicit
506     /// form, we'd encounter an error with the code as written:
507     ///
508     ///    struct Env { x: & &mut isize }
509     ///    let x: &mut isize = ...;
510     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
511     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
512     ///
513     /// This is then illegal because you cannot mutate an `&mut` found
514     /// in an aliasable location. To solve, you'd have to translate with
515     /// an `&mut` borrow:
516     ///
517     ///    struct Env { x: & &mut isize }
518     ///    let x: &mut isize = ...;
519     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
520     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
521     ///
522     /// Now the assignment to `**env.x` is legal, but creating a
523     /// mutable pointer to `x` is not because `x` is not mutable. We
524     /// could fix this by declaring `x` as `let mut x`. This is ok in
525     /// user code, if awkward, but extra weird for closures, since the
526     /// borrow is hidden.
527     ///
528     /// So we introduce a "unique imm" borrow -- the referent is
529     /// immutable, but not aliasable. This solves the problem. For
530     /// simplicity, we don't give users the way to express this
531     /// borrow, it's just used when translating closures.
532     Unique,
533
534     /// Data is mutable and not aliasable.
535     Mut {
536         /// True if this borrow arose from method-call auto-ref
537         /// (i.e. `adjustment::Adjust::Borrow`)
538         allow_two_phase_borrow: bool,
539     },
540 }
541
542 impl BorrowKind {
543     pub fn allows_two_phase_borrow(&self) -> bool {
544         match *self {
545             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
546             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
547         }
548     }
549 }
550
551 ///////////////////////////////////////////////////////////////////////////
552 // Variables and temps
553
554 newtype_index! {
555     pub struct Local {
556         DEBUG_FORMAT = "_{}",
557         const RETURN_PLACE = 0,
558     }
559 }
560
561 /// Classifies locals into categories. See `Mir::local_kind`.
562 #[derive(PartialEq, Eq, Debug)]
563 pub enum LocalKind {
564     /// User-declared variable binding
565     Var,
566     /// Compiler-introduced temporary
567     Temp,
568     /// Function argument
569     Arg,
570     /// Location of function's return value
571     ReturnPointer,
572 }
573
574 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
575 pub struct VarBindingForm<'tcx> {
576     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
577     pub binding_mode: ty::BindingMode,
578     /// If an explicit type was provided for this variable binding,
579     /// this holds the source Span of that type.
580     ///
581     /// NOTE: If you want to change this to a `HirId`, be wary that
582     /// doing so breaks incremental compilation (as of this writing),
583     /// while a `Span` does not cause our tests to fail.
584     pub opt_ty_info: Option<Span>,
585     /// Place of the RHS of the =, or the subject of the `match` where this
586     /// variable is initialized. None in the case of `let PATTERN;`.
587     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
588     /// (a) the right-hand side isn't evaluated as a place expression.
589     /// (b) it gives a way to separate this case from the remaining cases
590     ///     for diagnostics.
591     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
592     /// Span of the pattern in which this variable was bound.
593     pub pat_span: Span,
594 }
595
596 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
597 pub enum BindingForm<'tcx> {
598     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
599     Var(VarBindingForm<'tcx>),
600     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
601     ImplicitSelf(ImplicitSelfKind),
602     /// Reference used in a guard expression to ensure immutability.
603     RefForGuard,
604 }
605
606 /// Represents what type of implicit self a function has, if any.
607 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
608 pub enum ImplicitSelfKind {
609     /// Represents a `fn x(self);`.
610     Imm,
611     /// Represents a `fn x(mut self);`.
612     Mut,
613     /// Represents a `fn x(&self);`.
614     ImmRef,
615     /// Represents a `fn x(&mut self);`.
616     MutRef,
617     /// Represents when a function does not have a self argument or
618     /// when a function has a `self: X` argument.
619     None
620 }
621
622 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
623
624 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
625     binding_mode,
626     opt_ty_info,
627     opt_match_place,
628     pat_span
629 });
630
631 impl_stable_hash_for!(enum self::ImplicitSelfKind {
632     Imm,
633     Mut,
634     ImmRef,
635     MutRef,
636     None
637 });
638
639 impl_stable_hash_for!(enum self::MirPhase {
640     Build,
641     Const,
642     Validated,
643     Optimized,
644 });
645
646 mod binding_form_impl {
647     use ich::StableHashingContext;
648     use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
649
650     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
651         fn hash_stable<W: StableHasherResult>(
652             &self,
653             hcx: &mut StableHashingContext<'a>,
654             hasher: &mut StableHasher<W>,
655         ) {
656             use super::BindingForm::*;
657             ::std::mem::discriminant(self).hash_stable(hcx, hasher);
658
659             match self {
660                 Var(binding) => binding.hash_stable(hcx, hasher),
661                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
662                 RefForGuard => (),
663             }
664         }
665     }
666 }
667
668 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
669 /// created during evaluation of expressions in a block tail
670 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
671 ///
672 /// It is used to improve diagnostics when such temporaries are
673 /// involved in borrow_check errors, e.g. explanations of where the
674 /// temporaries come from, when their destructors are run, and/or how
675 /// one might revise the code to satisfy the borrow checker's rules.
676 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
677 pub struct BlockTailInfo {
678     /// If `true`, then the value resulting from evaluating this tail
679     /// expression is ignored by the block's expression context.
680     ///
681     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
682     /// but not e.g. `let _x = { ...; tail };`
683     pub tail_result_is_ignored: bool,
684 }
685
686 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
687
688 /// A MIR local.
689 ///
690 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
691 /// argument, or the return place.
692 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
693 pub struct LocalDecl<'tcx> {
694     /// `let mut x` vs `let x`.
695     ///
696     /// Temporaries and the return place are always mutable.
697     pub mutability: Mutability,
698
699     /// Some(binding_mode) if this corresponds to a user-declared local variable.
700     ///
701     /// This is solely used for local diagnostics when generating
702     /// warnings/errors when compiling the current crate, and
703     /// therefore it need not be visible across crates. pnkfelix
704     /// currently hypothesized we *need* to wrap this in a
705     /// `ClearCrossCrate` as long as it carries as `HirId`.
706     pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
707
708     /// True if this is an internal local
709     ///
710     /// These locals are not based on types in the source code and are only used
711     /// for a few desugarings at the moment.
712     ///
713     /// The generator transformation will sanity check the locals which are live
714     /// across a suspension point against the type components of the generator
715     /// which type checking knows are live across a suspension point. We need to
716     /// flag drop flags to avoid triggering this check as they are introduced
717     /// after typeck.
718     ///
719     /// Unsafety checking will also ignore dereferences of these locals,
720     /// so they can be used for raw pointers only used in a desugaring.
721     ///
722     /// This should be sound because the drop flags are fully algebraic, and
723     /// therefore don't affect the OIBIT or outlives properties of the
724     /// generator.
725     pub internal: bool,
726
727     /// If this local is a temporary and `is_block_tail` is `Some`,
728     /// then it is a temporary created for evaluation of some
729     /// subexpression of some block's tail expression (with no
730     /// intervening statement context).
731     pub is_block_tail: Option<BlockTailInfo>,
732
733     /// Type of this local.
734     pub ty: Ty<'tcx>,
735
736     /// If the user manually ascribed a type to this variable,
737     /// e.g. via `let x: T`, then we carry that type here. The MIR
738     /// borrow checker needs this information since it can affect
739     /// region inference.
740     pub user_ty: Option<(UserTypeAnnotation<'tcx>, Span)>,
741
742     /// Name of the local, used in debuginfo and pretty-printing.
743     ///
744     /// Note that function arguments can also have this set to `Some(_)`
745     /// to generate better debuginfo.
746     pub name: Option<Name>,
747
748     /// The *syntactic* (i.e. not visibility) source scope the local is defined
749     /// in. If the local was defined in a let-statement, this
750     /// is *within* the let-statement, rather than outside
751     /// of it.
752     ///
753     /// This is needed because the visibility source scope of locals within
754     /// a let-statement is weird.
755     ///
756     /// The reason is that we want the local to be *within* the let-statement
757     /// for lint purposes, but we want the local to be *after* the let-statement
758     /// for names-in-scope purposes.
759     ///
760     /// That's it, if we have a let-statement like the one in this
761     /// function:
762     ///
763     /// ```
764     /// fn foo(x: &str) {
765     ///     #[allow(unused_mut)]
766     ///     let mut x: u32 = { // <- one unused mut
767     ///         let mut y: u32 = x.parse().unwrap();
768     ///         y + 2
769     ///     };
770     ///     drop(x);
771     /// }
772     /// ```
773     ///
774     /// Then, from a lint point of view, the declaration of `x: u32`
775     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
776     /// lint scopes are the same as the AST/HIR nesting.
777     ///
778     /// However, from a name lookup point of view, the scopes look more like
779     /// as if the let-statements were `match` expressions:
780     ///
781     /// ```
782     /// fn foo(x: &str) {
783     ///     match {
784     ///         match x.parse().unwrap() {
785     ///             y => y + 2
786     ///         }
787     ///     } {
788     ///         x => drop(x)
789     ///     };
790     /// }
791     /// ```
792     ///
793     /// We care about the name-lookup scopes for debuginfo - if the
794     /// debuginfo instruction pointer is at the call to `x.parse()`, we
795     /// want `x` to refer to `x: &str`, but if it is at the call to
796     /// `drop(x)`, we want it to refer to `x: u32`.
797     ///
798     /// To allow both uses to work, we need to have more than a single scope
799     /// for a local. We have the `source_info.scope` represent the
800     /// "syntactic" lint scope (with a variable being under its let
801     /// block) while the `visibility_scope` represents the "local variable"
802     /// scope (where the "rest" of a block is under all prior let-statements).
803     ///
804     /// The end result looks like this:
805     ///
806     /// ```text
807     /// ROOT SCOPE
808     ///  │{ argument x: &str }
809     ///  │
810     ///  │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
811     ///  │ │                        // in practice because I'm lazy.
812     ///  │ │
813     ///  │ │← x.source_info.scope
814     ///  │ │← `x.parse().unwrap()`
815     ///  │ │
816     ///  │ │ │← y.source_info.scope
817     ///  │ │
818     ///  │ │ │{ let y: u32 }
819     ///  │ │ │
820     ///  │ │ │← y.visibility_scope
821     ///  │ │ │← `y + 2`
822     ///  │
823     ///  │ │{ let x: u32 }
824     ///  │ │← x.visibility_scope
825     ///  │ │← `drop(x)` // this accesses `x: u32`
826     /// ```
827     pub source_info: SourceInfo,
828
829     /// Source scope within which the local is visible (for debuginfo)
830     /// (see `source_info` for more details).
831     pub visibility_scope: SourceScope,
832 }
833
834 impl<'tcx> LocalDecl<'tcx> {
835     /// Returns true only if local is a binding that can itself be
836     /// made mutable via the addition of the `mut` keyword, namely
837     /// something like the occurrences of `x` in:
838     /// - `fn foo(x: Type) { ... }`,
839     /// - `let x = ...`,
840     /// - or `match ... { C(x) => ... }`
841     pub fn can_be_made_mutable(&self) -> bool {
842         match self.is_user_variable {
843             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
844                 binding_mode: ty::BindingMode::BindByValue(_),
845                 opt_ty_info: _,
846                 opt_match_place: _,
847                 pat_span: _,
848             }))) => true,
849
850             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
851                 => true,
852
853             _ => false,
854         }
855     }
856
857     /// Returns true if local is definitely not a `ref ident` or
858     /// `ref mut ident` binding. (Such bindings cannot be made into
859     /// mutable bindings, but the inverse does not necessarily hold).
860     pub fn is_nonref_binding(&self) -> bool {
861         match self.is_user_variable {
862             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
863                 binding_mode: ty::BindingMode::BindByValue(_),
864                 opt_ty_info: _,
865                 opt_match_place: _,
866                 pat_span: _,
867             }))) => true,
868
869             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
870
871             _ => false,
872         }
873     }
874
875     /// Create a new `LocalDecl` for a temporary.
876     #[inline]
877     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
878         Self::new_local(ty, Mutability::Mut, false, span)
879     }
880
881     /// Converts `self` into same `LocalDecl` except tagged as immutable.
882     #[inline]
883     pub fn immutable(mut self) -> Self {
884         self.mutability = Mutability::Not;
885         self
886     }
887
888     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
889     #[inline]
890     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
891         assert!(self.is_block_tail.is_none());
892         self.is_block_tail = Some(info);
893         self
894     }
895
896     /// Create a new `LocalDecl` for a internal temporary.
897     #[inline]
898     pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
899         Self::new_local(ty, Mutability::Mut, true, span)
900     }
901
902     #[inline]
903     fn new_local(
904         ty: Ty<'tcx>,
905         mutability: Mutability,
906         internal: bool,
907         span: Span,
908     ) -> Self {
909         LocalDecl {
910             mutability,
911             ty,
912             user_ty: None,
913             name: None,
914             source_info: SourceInfo {
915                 span,
916                 scope: OUTERMOST_SOURCE_SCOPE,
917             },
918             visibility_scope: OUTERMOST_SOURCE_SCOPE,
919             internal,
920             is_user_variable: None,
921             is_block_tail: None,
922         }
923     }
924
925     /// Builds a `LocalDecl` for the return place.
926     ///
927     /// This must be inserted into the `local_decls` list as the first local.
928     #[inline]
929     pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
930         LocalDecl {
931             mutability: Mutability::Mut,
932             ty: return_ty,
933             user_ty: None,
934             source_info: SourceInfo {
935                 span,
936                 scope: OUTERMOST_SOURCE_SCOPE,
937             },
938             visibility_scope: OUTERMOST_SOURCE_SCOPE,
939             internal: false,
940             is_block_tail: None,
941             name: None, // FIXME maybe we do want some name here?
942             is_user_variable: None,
943         }
944     }
945 }
946
947 /// A closure capture, with its name and mode.
948 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
949 pub struct UpvarDecl {
950     pub debug_name: Name,
951
952     /// `HirId` of the captured variable
953     pub var_hir_id: ClearCrossCrate<HirId>,
954
955     /// If true, the capture is behind a reference.
956     pub by_ref: bool,
957
958     pub mutability: Mutability,
959 }
960
961 ///////////////////////////////////////////////////////////////////////////
962 // BasicBlock
963
964 newtype_index! {
965     pub struct BasicBlock {
966         DEBUG_FORMAT = "bb{}",
967         const START_BLOCK = 0,
968     }
969 }
970
971 impl BasicBlock {
972     pub fn start_location(self) -> Location {
973         Location {
974             block: self,
975             statement_index: 0,
976         }
977     }
978 }
979
980 ///////////////////////////////////////////////////////////////////////////
981 // BasicBlockData and Terminator
982
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
984 pub struct BasicBlockData<'tcx> {
985     /// List of statements in this block.
986     pub statements: Vec<Statement<'tcx>>,
987
988     /// Terminator for this block.
989     ///
990     /// NB. This should generally ONLY be `None` during construction.
991     /// Therefore, you should generally access it via the
992     /// `terminator()` or `terminator_mut()` methods. The only
993     /// exception is that certain passes, such as `simplify_cfg`, swap
994     /// out the terminator temporarily with `None` while they continue
995     /// to recurse over the set of basic blocks.
996     pub terminator: Option<Terminator<'tcx>>,
997
998     /// If true, this block lies on an unwind path. This is used
999     /// during codegen where distinct kinds of basic blocks may be
1000     /// generated (particularly for MSVC cleanup). Unwind blocks must
1001     /// only branch to other unwind blocks.
1002     pub is_cleanup: bool,
1003 }
1004
1005 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1006 pub struct Terminator<'tcx> {
1007     pub source_info: SourceInfo,
1008     pub kind: TerminatorKind<'tcx>,
1009 }
1010
1011 #[derive(Clone, RustcEncodable, RustcDecodable)]
1012 pub enum TerminatorKind<'tcx> {
1013     /// block should have one successor in the graph; we jump there
1014     Goto { target: BasicBlock },
1015
1016     /// operand evaluates to an integer; jump depending on its value
1017     /// to one of the targets, and otherwise fallback to `otherwise`
1018     SwitchInt {
1019         /// discriminant value being tested
1020         discr: Operand<'tcx>,
1021
1022         /// type of value being tested
1023         switch_ty: Ty<'tcx>,
1024
1025         /// Possible values. The locations to branch to in each case
1026         /// are found in the corresponding indices from the `targets` vector.
1027         values: Cow<'tcx, [u128]>,
1028
1029         /// Possible branch sites. The last element of this vector is used
1030         /// for the otherwise branch, so targets.len() == values.len() + 1
1031         /// should hold.
1032         // This invariant is quite non-obvious and also could be improved.
1033         // One way to make this invariant is to have something like this instead:
1034         //
1035         // branches: Vec<(ConstInt, BasicBlock)>,
1036         // otherwise: Option<BasicBlock> // exhaustive if None
1037         //
1038         // However we’ve decided to keep this as-is until we figure a case
1039         // where some other approach seems to be strictly better than other.
1040         targets: Vec<BasicBlock>,
1041     },
1042
1043     /// Indicates that the landing pad is finished and unwinding should
1044     /// continue. Emitted by build::scope::diverge_cleanup.
1045     Resume,
1046
1047     /// Indicates that the landing pad is finished and that the process
1048     /// should abort. Used to prevent unwinding for foreign items.
1049     Abort,
1050
1051     /// Indicates a normal return. The return place should have
1052     /// been filled in by now. This should occur at most once.
1053     Return,
1054
1055     /// Indicates a terminator that can never be reached.
1056     Unreachable,
1057
1058     /// Drop the Place
1059     Drop {
1060         location: Place<'tcx>,
1061         target: BasicBlock,
1062         unwind: Option<BasicBlock>,
1063     },
1064
1065     /// Drop the Place and assign the new value over it. This ensures
1066     /// that the assignment to `P` occurs *even if* the destructor for
1067     /// place unwinds. Its semantics are best explained by the
1068     /// elaboration:
1069     ///
1070     /// ```
1071     /// BB0 {
1072     ///   DropAndReplace(P <- V, goto BB1, unwind BB2)
1073     /// }
1074     /// ```
1075     ///
1076     /// becomes
1077     ///
1078     /// ```
1079     /// BB0 {
1080     ///   Drop(P, goto BB1, unwind BB2)
1081     /// }
1082     /// BB1 {
1083     ///   // P is now uninitialized
1084     ///   P <- V
1085     /// }
1086     /// BB2 {
1087     ///   // P is now uninitialized -- its dtor panicked
1088     ///   P <- V
1089     /// }
1090     /// ```
1091     DropAndReplace {
1092         location: Place<'tcx>,
1093         value: Operand<'tcx>,
1094         target: BasicBlock,
1095         unwind: Option<BasicBlock>,
1096     },
1097
1098     /// Block ends with a call of a converging function
1099     Call {
1100         /// The function that’s being called
1101         func: Operand<'tcx>,
1102         /// Arguments the function is called with.
1103         /// These are owned by the callee, which is free to modify them.
1104         /// This allows the memory occupied by "by-value" arguments to be
1105         /// reused across function calls without duplicating the contents.
1106         args: Vec<Operand<'tcx>>,
1107         /// Destination for the return value. If some, the call is converging.
1108         destination: Option<(Place<'tcx>, BasicBlock)>,
1109         /// Cleanups to be done if the call unwinds.
1110         cleanup: Option<BasicBlock>,
1111         /// Whether this is from a call in HIR, rather than from an overloaded
1112         /// operator. True for overloaded function call.
1113         from_hir_call: bool,
1114     },
1115
1116     /// Jump to the target if the condition has the expected value,
1117     /// otherwise panic with a message and a cleanup target.
1118     Assert {
1119         cond: Operand<'tcx>,
1120         expected: bool,
1121         msg: AssertMessage<'tcx>,
1122         target: BasicBlock,
1123         cleanup: Option<BasicBlock>,
1124     },
1125
1126     /// A suspend point
1127     Yield {
1128         /// The value to return
1129         value: Operand<'tcx>,
1130         /// Where to resume to
1131         resume: BasicBlock,
1132         /// Cleanup to be done if the generator is dropped at this suspend point
1133         drop: Option<BasicBlock>,
1134     },
1135
1136     /// Indicates the end of the dropping of a generator
1137     GeneratorDrop,
1138
1139     /// A block where control flow only ever takes one real path, but borrowck
1140     /// needs to be more conservative.
1141     FalseEdges {
1142         /// The target normal control flow will take
1143         real_target: BasicBlock,
1144         /// The list of blocks control flow could conceptually take, but won't
1145         /// in practice
1146         imaginary_targets: Vec<BasicBlock>,
1147     },
1148     /// A terminator for blocks that only take one path in reality, but where we
1149     /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1150     /// This can arise in infinite loops with no function calls for example.
1151     FalseUnwind {
1152         /// The target normal control flow will take
1153         real_target: BasicBlock,
1154         /// The imaginary cleanup block link. This particular path will never be taken
1155         /// in practice, but in order to avoid fragility we want to always
1156         /// consider it in borrowck. We don't want to accept programs which
1157         /// pass borrowck only when panic=abort or some assertions are disabled
1158         /// due to release vs. debug mode builds. This needs to be an Option because
1159         /// of the remove_noop_landing_pads and no_landing_pads passes
1160         unwind: Option<BasicBlock>,
1161     },
1162 }
1163
1164 pub type Successors<'a> =
1165     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1166 pub type SuccessorsMut<'a> =
1167     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1168
1169 impl<'tcx> Terminator<'tcx> {
1170     pub fn successors(&self) -> Successors<'_> {
1171         self.kind.successors()
1172     }
1173
1174     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1175         self.kind.successors_mut()
1176     }
1177
1178     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1179         self.kind.unwind()
1180     }
1181
1182     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1183         self.kind.unwind_mut()
1184     }
1185 }
1186
1187 impl<'tcx> TerminatorKind<'tcx> {
1188     pub fn if_<'a, 'gcx>(
1189         tcx: TyCtxt<'a, 'gcx, 'tcx>,
1190         cond: Operand<'tcx>,
1191         t: BasicBlock,
1192         f: BasicBlock,
1193     ) -> TerminatorKind<'tcx> {
1194         static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1195         TerminatorKind::SwitchInt {
1196             discr: cond,
1197             switch_ty: tcx.types.bool,
1198             values: From::from(BOOL_SWITCH_FALSE),
1199             targets: vec![f, t],
1200         }
1201     }
1202
1203     pub fn successors(&self) -> Successors<'_> {
1204         use self::TerminatorKind::*;
1205         match *self {
1206             Resume
1207             | Abort
1208             | GeneratorDrop
1209             | Return
1210             | Unreachable
1211             | Call {
1212                 destination: None,
1213                 cleanup: None,
1214                 ..
1215             } => None.into_iter().chain(&[]),
1216             Goto { target: ref t }
1217             | Call {
1218                 destination: None,
1219                 cleanup: Some(ref t),
1220                 ..
1221             }
1222             | Call {
1223                 destination: Some((_, ref t)),
1224                 cleanup: None,
1225                 ..
1226             }
1227             | Yield {
1228                 resume: ref t,
1229                 drop: None,
1230                 ..
1231             }
1232             | DropAndReplace {
1233                 target: ref t,
1234                 unwind: None,
1235                 ..
1236             }
1237             | Drop {
1238                 target: ref t,
1239                 unwind: None,
1240                 ..
1241             }
1242             | Assert {
1243                 target: ref t,
1244                 cleanup: None,
1245                 ..
1246             }
1247             | FalseUnwind {
1248                 real_target: ref t,
1249                 unwind: None,
1250             } => Some(t).into_iter().chain(&[]),
1251             Call {
1252                 destination: Some((_, ref t)),
1253                 cleanup: Some(ref u),
1254                 ..
1255             }
1256             | Yield {
1257                 resume: ref t,
1258                 drop: Some(ref u),
1259                 ..
1260             }
1261             | DropAndReplace {
1262                 target: ref t,
1263                 unwind: Some(ref u),
1264                 ..
1265             }
1266             | Drop {
1267                 target: ref t,
1268                 unwind: Some(ref u),
1269                 ..
1270             }
1271             | Assert {
1272                 target: ref t,
1273                 cleanup: Some(ref u),
1274                 ..
1275             }
1276             | FalseUnwind {
1277                 real_target: ref t,
1278                 unwind: Some(ref u),
1279             } => Some(t).into_iter().chain(slice::from_ref(u)),
1280             SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1281             FalseEdges {
1282                 ref real_target,
1283                 ref imaginary_targets,
1284             } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1285         }
1286     }
1287
1288     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1289         use self::TerminatorKind::*;
1290         match *self {
1291             Resume
1292             | Abort
1293             | GeneratorDrop
1294             | Return
1295             | Unreachable
1296             | Call {
1297                 destination: None,
1298                 cleanup: None,
1299                 ..
1300             } => None.into_iter().chain(&mut []),
1301             Goto { target: ref mut t }
1302             | Call {
1303                 destination: None,
1304                 cleanup: Some(ref mut t),
1305                 ..
1306             }
1307             | Call {
1308                 destination: Some((_, ref mut t)),
1309                 cleanup: None,
1310                 ..
1311             }
1312             | Yield {
1313                 resume: ref mut t,
1314                 drop: None,
1315                 ..
1316             }
1317             | DropAndReplace {
1318                 target: ref mut t,
1319                 unwind: None,
1320                 ..
1321             }
1322             | Drop {
1323                 target: ref mut t,
1324                 unwind: None,
1325                 ..
1326             }
1327             | Assert {
1328                 target: ref mut t,
1329                 cleanup: None,
1330                 ..
1331             }
1332             | FalseUnwind {
1333                 real_target: ref mut t,
1334                 unwind: None,
1335             } => Some(t).into_iter().chain(&mut []),
1336             Call {
1337                 destination: Some((_, ref mut t)),
1338                 cleanup: Some(ref mut u),
1339                 ..
1340             }
1341             | Yield {
1342                 resume: ref mut t,
1343                 drop: Some(ref mut u),
1344                 ..
1345             }
1346             | DropAndReplace {
1347                 target: ref mut t,
1348                 unwind: Some(ref mut u),
1349                 ..
1350             }
1351             | Drop {
1352                 target: ref mut t,
1353                 unwind: Some(ref mut u),
1354                 ..
1355             }
1356             | Assert {
1357                 target: ref mut t,
1358                 cleanup: Some(ref mut u),
1359                 ..
1360             }
1361             | FalseUnwind {
1362                 real_target: ref mut t,
1363                 unwind: Some(ref mut u),
1364             } => Some(t).into_iter().chain(slice::from_mut(u)),
1365             SwitchInt {
1366                 ref mut targets, ..
1367             } => None.into_iter().chain(&mut targets[..]),
1368             FalseEdges {
1369                 ref mut real_target,
1370                 ref mut imaginary_targets,
1371             } => Some(real_target)
1372                 .into_iter()
1373                 .chain(&mut imaginary_targets[..]),
1374         }
1375     }
1376
1377     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1378         match *self {
1379             TerminatorKind::Goto { .. }
1380             | TerminatorKind::Resume
1381             | TerminatorKind::Abort
1382             | TerminatorKind::Return
1383             | TerminatorKind::Unreachable
1384             | TerminatorKind::GeneratorDrop
1385             | TerminatorKind::Yield { .. }
1386             | TerminatorKind::SwitchInt { .. }
1387             | TerminatorKind::FalseEdges { .. } => None,
1388             TerminatorKind::Call {
1389                 cleanup: ref unwind,
1390                 ..
1391             }
1392             | TerminatorKind::Assert {
1393                 cleanup: ref unwind,
1394                 ..
1395             }
1396             | TerminatorKind::DropAndReplace { ref unwind, .. }
1397             | TerminatorKind::Drop { ref unwind, .. }
1398             | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1399         }
1400     }
1401
1402     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1403         match *self {
1404             TerminatorKind::Goto { .. }
1405             | TerminatorKind::Resume
1406             | TerminatorKind::Abort
1407             | TerminatorKind::Return
1408             | TerminatorKind::Unreachable
1409             | TerminatorKind::GeneratorDrop
1410             | TerminatorKind::Yield { .. }
1411             | TerminatorKind::SwitchInt { .. }
1412             | TerminatorKind::FalseEdges { .. } => None,
1413             TerminatorKind::Call {
1414                 cleanup: ref mut unwind,
1415                 ..
1416             }
1417             | TerminatorKind::Assert {
1418                 cleanup: ref mut unwind,
1419                 ..
1420             }
1421             | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1422             | TerminatorKind::Drop { ref mut unwind, .. }
1423             | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1424         }
1425     }
1426 }
1427
1428 impl<'tcx> BasicBlockData<'tcx> {
1429     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1430         BasicBlockData {
1431             statements: vec![],
1432             terminator,
1433             is_cleanup: false,
1434         }
1435     }
1436
1437     /// Accessor for terminator.
1438     ///
1439     /// Terminator may not be None after construction of the basic block is complete. This accessor
1440     /// provides a convenience way to reach the terminator.
1441     pub fn terminator(&self) -> &Terminator<'tcx> {
1442         self.terminator.as_ref().expect("invalid terminator state")
1443     }
1444
1445     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1446         self.terminator.as_mut().expect("invalid terminator state")
1447     }
1448
1449     pub fn retain_statements<F>(&mut self, mut f: F)
1450     where
1451         F: FnMut(&mut Statement<'_>) -> bool,
1452     {
1453         for s in &mut self.statements {
1454             if !f(s) {
1455                 s.make_nop();
1456             }
1457         }
1458     }
1459
1460     pub fn expand_statements<F, I>(&mut self, mut f: F)
1461     where
1462         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1463         I: iter::TrustedLen<Item = Statement<'tcx>>,
1464     {
1465         // Gather all the iterators we'll need to splice in, and their positions.
1466         let mut splices: Vec<(usize, I)> = vec![];
1467         let mut extra_stmts = 0;
1468         for (i, s) in self.statements.iter_mut().enumerate() {
1469             if let Some(mut new_stmts) = f(s) {
1470                 if let Some(first) = new_stmts.next() {
1471                     // We can already store the first new statement.
1472                     *s = first;
1473
1474                     // Save the other statements for optimized splicing.
1475                     let remaining = new_stmts.size_hint().0;
1476                     if remaining > 0 {
1477                         splices.push((i + 1 + extra_stmts, new_stmts));
1478                         extra_stmts += remaining;
1479                     }
1480                 } else {
1481                     s.make_nop();
1482                 }
1483             }
1484         }
1485
1486         // Splice in the new statements, from the end of the block.
1487         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1488         // where a range of elements ("gap") is left uninitialized, with
1489         // splicing adding new elements to the end of that gap and moving
1490         // existing elements from before the gap to the end of the gap.
1491         // For now, this is safe code, emulating a gap but initializing it.
1492         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1493         self.statements.resize(
1494             gap.end,
1495             Statement {
1496                 source_info: SourceInfo {
1497                     span: DUMMY_SP,
1498                     scope: OUTERMOST_SOURCE_SCOPE,
1499                 },
1500                 kind: StatementKind::Nop,
1501             },
1502         );
1503         for (splice_start, new_stmts) in splices.into_iter().rev() {
1504             let splice_end = splice_start + new_stmts.size_hint().0;
1505             while gap.end > splice_end {
1506                 gap.start -= 1;
1507                 gap.end -= 1;
1508                 self.statements.swap(gap.start, gap.end);
1509             }
1510             self.statements.splice(splice_start..splice_end, new_stmts);
1511             gap.end = splice_start;
1512         }
1513     }
1514
1515     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1516         if index < self.statements.len() {
1517             &self.statements[index]
1518         } else {
1519             &self.terminator
1520         }
1521     }
1522 }
1523
1524 impl<'tcx> Debug for TerminatorKind<'tcx> {
1525     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1526         self.fmt_head(fmt)?;
1527         let successor_count = self.successors().count();
1528         let labels = self.fmt_successor_labels();
1529         assert_eq!(successor_count, labels.len());
1530
1531         match successor_count {
1532             0 => Ok(()),
1533
1534             1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1535
1536             _ => {
1537                 write!(fmt, " -> [")?;
1538                 for (i, target) in self.successors().enumerate() {
1539                     if i > 0 {
1540                         write!(fmt, ", ")?;
1541                     }
1542                     write!(fmt, "{}: {:?}", labels[i], target)?;
1543                 }
1544                 write!(fmt, "]")
1545             }
1546         }
1547     }
1548 }
1549
1550 impl<'tcx> TerminatorKind<'tcx> {
1551     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1552     /// successor basic block, if any. The only information not included is the list of possible
1553     /// successors, which may be rendered differently between the text and the graphviz format.
1554     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1555         use self::TerminatorKind::*;
1556         match *self {
1557             Goto { .. } => write!(fmt, "goto"),
1558             SwitchInt {
1559                 discr: ref place, ..
1560             } => write!(fmt, "switchInt({:?})", place),
1561             Return => write!(fmt, "return"),
1562             GeneratorDrop => write!(fmt, "generator_drop"),
1563             Resume => write!(fmt, "resume"),
1564             Abort => write!(fmt, "abort"),
1565             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1566             Unreachable => write!(fmt, "unreachable"),
1567             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1568             DropAndReplace {
1569                 ref location,
1570                 ref value,
1571                 ..
1572             } => write!(fmt, "replace({:?} <- {:?})", location, value),
1573             Call {
1574                 ref func,
1575                 ref args,
1576                 ref destination,
1577                 ..
1578             } => {
1579                 if let Some((ref destination, _)) = *destination {
1580                     write!(fmt, "{:?} = ", destination)?;
1581                 }
1582                 write!(fmt, "{:?}(", func)?;
1583                 for (index, arg) in args.iter().enumerate() {
1584                     if index > 0 {
1585                         write!(fmt, ", ")?;
1586                     }
1587                     write!(fmt, "{:?}", arg)?;
1588                 }
1589                 write!(fmt, ")")
1590             }
1591             Assert {
1592                 ref cond,
1593                 expected,
1594                 ref msg,
1595                 ..
1596             } => {
1597                 write!(fmt, "assert(")?;
1598                 if !expected {
1599                     write!(fmt, "!")?;
1600                 }
1601                 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1602             }
1603             FalseEdges { .. } => write!(fmt, "falseEdges"),
1604             FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1605         }
1606     }
1607
1608     /// Return the list of labels for the edges to the successor basic blocks.
1609     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1610         use self::TerminatorKind::*;
1611         match *self {
1612             Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1613             Goto { .. } => vec!["".into()],
1614             SwitchInt {
1615                 ref values,
1616                 switch_ty,
1617                 ..
1618             } => {
1619                 let size = ty::tls::with(|tcx| {
1620                     let param_env = ty::ParamEnv::empty();
1621                     let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1622                     tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1623                 });
1624                 values
1625                     .iter()
1626                     .map(|&u| {
1627                         let mut s = String::new();
1628                         let c = ty::Const {
1629                             val: ConstValue::Scalar(
1630                                 Scalar::Bits {
1631                                     bits: u,
1632                                     size: size.bytes() as u8,
1633                                 }.into(),
1634                             ),
1635                             ty: switch_ty,
1636                         };
1637                         fmt_const_val(&mut s, &c).unwrap();
1638                         s.into()
1639                     }).chain(iter::once("otherwise".into()))
1640                     .collect()
1641             }
1642             Call {
1643                 destination: Some(_),
1644                 cleanup: Some(_),
1645                 ..
1646             } => vec!["return".into(), "unwind".into()],
1647             Call {
1648                 destination: Some(_),
1649                 cleanup: None,
1650                 ..
1651             } => vec!["return".into()],
1652             Call {
1653                 destination: None,
1654                 cleanup: Some(_),
1655                 ..
1656             } => vec!["unwind".into()],
1657             Call {
1658                 destination: None,
1659                 cleanup: None,
1660                 ..
1661             } => vec![],
1662             Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1663             Yield { drop: None, .. } => vec!["resume".into()],
1664             DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1665                 vec!["return".into()]
1666             }
1667             DropAndReplace {
1668                 unwind: Some(_), ..
1669             }
1670             | Drop {
1671                 unwind: Some(_), ..
1672             } => vec!["return".into(), "unwind".into()],
1673             Assert { cleanup: None, .. } => vec!["".into()],
1674             Assert { .. } => vec!["success".into(), "unwind".into()],
1675             FalseEdges {
1676                 ref imaginary_targets,
1677                 ..
1678             } => {
1679                 let mut l = vec!["real".into()];
1680                 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1681                 l
1682             }
1683             FalseUnwind {
1684                 unwind: Some(_), ..
1685             } => vec!["real".into(), "cleanup".into()],
1686             FalseUnwind { unwind: None, .. } => vec!["real".into()],
1687         }
1688     }
1689 }
1690
1691 ///////////////////////////////////////////////////////////////////////////
1692 // Statements
1693
1694 #[derive(Clone, RustcEncodable, RustcDecodable)]
1695 pub struct Statement<'tcx> {
1696     pub source_info: SourceInfo,
1697     pub kind: StatementKind<'tcx>,
1698 }
1699
1700 impl<'tcx> Statement<'tcx> {
1701     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1702     /// invalidating statement indices in `Location`s.
1703     pub fn make_nop(&mut self) {
1704         self.kind = StatementKind::Nop
1705     }
1706
1707     /// Changes a statement to a nop and returns the original statement.
1708     pub fn replace_nop(&mut self) -> Self {
1709         Statement {
1710             source_info: self.source_info,
1711             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1712         }
1713     }
1714 }
1715
1716 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1717 pub enum StatementKind<'tcx> {
1718     /// Write the RHS Rvalue to the LHS Place.
1719     Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1720
1721     /// This represents all the reading that a pattern match may do
1722     /// (e.g. inspecting constants and discriminant values), and the
1723     /// kind of pattern it comes from. This is in order to adapt potential
1724     /// error messages to these specific patterns.
1725     FakeRead(FakeReadCause, Place<'tcx>),
1726
1727     /// Write the discriminant for a variant to the enum Place.
1728     SetDiscriminant {
1729         place: Place<'tcx>,
1730         variant_index: usize,
1731     },
1732
1733     /// Start a live range for the storage of the local.
1734     StorageLive(Local),
1735
1736     /// End the current live range for the storage of the local.
1737     StorageDead(Local),
1738
1739     /// Execute a piece of inline Assembly.
1740     InlineAsm {
1741         asm: Box<InlineAsm>,
1742         outputs: Box<[Place<'tcx>]>,
1743         inputs: Box<[Operand<'tcx>]>,
1744     },
1745
1746     /// Assert the given places to be valid inhabitants of their type.  These statements are
1747     /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1748     /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1749     Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1750
1751     /// Mark one terminating point of a region scope (i.e. static region).
1752     /// (The starting point(s) arise implicitly from borrows.)
1753     EndRegion(region::Scope),
1754
1755     /// Encodes a user's type ascription. These need to be preserved
1756     /// intact so that NLL can respect them. For example:
1757     ///
1758     ///     let a: T = y;
1759     ///
1760     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1761     /// to the user-given type `T`. The effect depends on the specified variance:
1762     ///
1763     /// - `Covariant` -- requires that `T_y <: T`
1764     /// - `Contravariant` -- requires that `T_y :> T`
1765     /// - `Invariant` -- requires that `T_y == T`
1766     /// - `Bivariant` -- no effect
1767     AscribeUserType(Place<'tcx>, ty::Variance, UserTypeAnnotation<'tcx>),
1768
1769     /// No-op. Useful for deleting instructions without affecting statement indices.
1770     Nop,
1771 }
1772
1773 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1774 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1775 pub enum FakeReadCause {
1776     /// Inject a fake read of the borrowed input at the start of each arm's
1777     /// pattern testing code.
1778     ///
1779     /// This should ensure that you cannot change the variant for an enum
1780     /// while you are in the midst of matching on it.
1781     ForMatchGuard,
1782
1783     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1784     /// generate a read of x to check that it is initialized and safe.
1785     ForMatchedPlace,
1786
1787     /// Officially, the semantics of
1788     ///
1789     /// `let pattern = <expr>;`
1790     ///
1791     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1792     /// into the pattern.
1793     ///
1794     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1795     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1796     /// but in some cases it can affect the borrow checker, as in #53695.
1797     /// Therefore, we insert a "fake read" here to ensure that we get
1798     /// appropriate errors.
1799     ForLet,
1800 }
1801
1802 /// The `ValidationOp` describes what happens with each of the operands of a
1803 /// `Validate` statement.
1804 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1805 pub enum ValidationOp {
1806     /// Recursively traverse the place following the type and validate that all type
1807     /// invariants are maintained.  Furthermore, acquire exclusive/read-only access to the
1808     /// memory reachable from the place.
1809     Acquire,
1810     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1811     /// access.
1812     Release,
1813     /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1814     /// access *until* the given region ends.  Then, access will be recovered.
1815     Suspend(region::Scope),
1816 }
1817
1818 impl Debug for ValidationOp {
1819     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1820         use self::ValidationOp::*;
1821         match *self {
1822             Acquire => write!(fmt, "Acquire"),
1823             Release => write!(fmt, "Release"),
1824             // (reuse lifetime rendering policy from ppaux.)
1825             Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1826         }
1827     }
1828 }
1829
1830 // This is generic so that it can be reused by miri
1831 #[derive(Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1832 pub struct ValidationOperand<'tcx, T> {
1833     pub place: T,
1834     pub ty: Ty<'tcx>,
1835     pub re: Option<region::Scope>,
1836     pub mutbl: hir::Mutability,
1837 }
1838
1839 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1840     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1841         write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1842         if let Some(ce) = self.re {
1843             // (reuse lifetime rendering policy from ppaux.)
1844             write!(fmt, "/{}", ty::ReScope(ce))?;
1845         }
1846         if let hir::MutImmutable = self.mutbl {
1847             write!(fmt, " (imm)")?;
1848         }
1849         Ok(())
1850     }
1851 }
1852
1853 impl<'tcx> Debug for Statement<'tcx> {
1854     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1855         use self::StatementKind::*;
1856         match self.kind {
1857             Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1858             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1859             // (reuse lifetime rendering policy from ppaux.)
1860             EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1861             Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1862             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1863             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1864             SetDiscriminant {
1865                 ref place,
1866                 variant_index,
1867             } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1868             InlineAsm {
1869                 ref asm,
1870                 ref outputs,
1871                 ref inputs,
1872             } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1873             AscribeUserType(ref place, ref variance, ref c_ty) => {
1874                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1875             }
1876             Nop => write!(fmt, "nop"),
1877         }
1878     }
1879 }
1880
1881 ///////////////////////////////////////////////////////////////////////////
1882 // Places
1883
1884 /// A path to a value; something that can be evaluated without
1885 /// changing or disturbing program state.
1886 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1887 pub enum Place<'tcx> {
1888     /// local variable
1889     Local(Local),
1890
1891     /// static or static mut variable
1892     Static(Box<Static<'tcx>>),
1893
1894     /// Constant code promoted to an injected static
1895     Promoted(Box<(Promoted, Ty<'tcx>)>),
1896
1897     /// projection out of a place (access a field, deref a pointer, etc)
1898     Projection(Box<PlaceProjection<'tcx>>),
1899 }
1900
1901 /// The def-id of a static, along with its normalized type (which is
1902 /// stored to avoid requiring normalization when reading MIR).
1903 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1904 pub struct Static<'tcx> {
1905     pub def_id: DefId,
1906     pub ty: Ty<'tcx>,
1907 }
1908
1909 impl_stable_hash_for!(struct Static<'tcx> {
1910     def_id,
1911     ty
1912 });
1913
1914 /// The `Projection` data structure defines things of the form `B.x`
1915 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1916 /// shared between `Constant` and `Place`. See the aliases
1917 /// `PlaceProjection` etc below.
1918 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1919 pub struct Projection<'tcx, B, V, T> {
1920     pub base: B,
1921     pub elem: ProjectionElem<'tcx, V, T>,
1922 }
1923
1924 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1925 pub enum ProjectionElem<'tcx, V, T> {
1926     Deref,
1927     Field(Field, T),
1928     Index(V),
1929
1930     /// These indices are generated by slice patterns. Easiest to explain
1931     /// by example:
1932     ///
1933     /// ```
1934     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1935     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1936     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1937     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1938     /// ```
1939     ConstantIndex {
1940         /// index or -index (in Python terms), depending on from_end
1941         offset: u32,
1942         /// thing being indexed must be at least this long
1943         min_length: u32,
1944         /// counting backwards from end?
1945         from_end: bool,
1946     },
1947
1948     /// These indices are generated by slice patterns.
1949     ///
1950     /// slice[from:-to] in Python terms.
1951     Subslice {
1952         from: u32,
1953         to: u32,
1954     },
1955
1956     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1957     /// this for ADTs with more than one variant. It may be better to
1958     /// just introduce it always, or always for enums.
1959     Downcast(&'tcx AdtDef, usize),
1960 }
1961
1962 /// Alias for projections as they appear in places, where the base is a place
1963 /// and the index is a local.
1964 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1965
1966 /// Alias for projections as they appear in places, where the base is a place
1967 /// and the index is a local.
1968 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1969
1970 newtype_index! {
1971     pub struct Field {
1972         DEBUG_FORMAT = "field[{}]"
1973     }
1974 }
1975
1976 impl<'tcx> Place<'tcx> {
1977     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1978         self.elem(ProjectionElem::Field(f, ty))
1979     }
1980
1981     pub fn deref(self) -> Place<'tcx> {
1982         self.elem(ProjectionElem::Deref)
1983     }
1984
1985     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1986         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1987     }
1988
1989     pub fn index(self, index: Local) -> Place<'tcx> {
1990         self.elem(ProjectionElem::Index(index))
1991     }
1992
1993     pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1994         Place::Projection(Box::new(PlaceProjection { base: self, elem }))
1995     }
1996
1997     /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
1998     /// a single deref of a local.
1999     ///
2000     /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2001     pub fn local(&self) -> Option<Local> {
2002         match self {
2003             Place::Local(local) |
2004             Place::Projection(box Projection {
2005                 base: Place::Local(local),
2006                 elem: ProjectionElem::Deref,
2007             }) => Some(*local),
2008             _ => None,
2009         }
2010     }
2011
2012     /// Find the innermost `Local` from this `Place`.
2013     pub fn base_local(&self) -> Option<Local> {
2014         match self {
2015             Place::Local(local) => Some(*local),
2016             Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2017             Place::Promoted(..) | Place::Static(..) => None,
2018         }
2019     }
2020 }
2021
2022 impl<'tcx> Debug for Place<'tcx> {
2023     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2024         use self::Place::*;
2025
2026         match *self {
2027             Local(id) => write!(fmt, "{:?}", id),
2028             Static(box self::Static { def_id, ty }) => write!(
2029                 fmt,
2030                 "({}: {:?})",
2031                 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2032                 ty
2033             ),
2034             Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2035             Projection(ref data) => match data.elem {
2036                 ProjectionElem::Downcast(ref adt_def, index) => {
2037                     write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2038                 }
2039                 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2040                 ProjectionElem::Field(field, ty) => {
2041                     write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2042                 }
2043                 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2044                 ProjectionElem::ConstantIndex {
2045                     offset,
2046                     min_length,
2047                     from_end: false,
2048                 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2049                 ProjectionElem::ConstantIndex {
2050                     offset,
2051                     min_length,
2052                     from_end: true,
2053                 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2054                 ProjectionElem::Subslice { from, to } if to == 0 => {
2055                     write!(fmt, "{:?}[{:?}:]", data.base, from)
2056                 }
2057                 ProjectionElem::Subslice { from, to } if from == 0 => {
2058                     write!(fmt, "{:?}[:-{:?}]", data.base, to)
2059                 }
2060                 ProjectionElem::Subslice { from, to } => {
2061                     write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2062                 }
2063             },
2064         }
2065     }
2066 }
2067
2068 ///////////////////////////////////////////////////////////////////////////
2069 // Scopes
2070
2071 newtype_index! {
2072     pub struct SourceScope {
2073         DEBUG_FORMAT = "scope[{}]",
2074         const OUTERMOST_SOURCE_SCOPE = 0,
2075     }
2076 }
2077
2078 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2079 pub struct SourceScopeData {
2080     pub span: Span,
2081     pub parent_scope: Option<SourceScope>,
2082 }
2083
2084 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2085 pub struct SourceScopeLocalData {
2086     /// A NodeId with lint levels equivalent to this scope's lint levels.
2087     pub lint_root: ast::NodeId,
2088     /// The unsafe block that contains this node.
2089     pub safety: Safety,
2090 }
2091
2092 ///////////////////////////////////////////////////////////////////////////
2093 // Operands
2094
2095 /// These are values that can appear inside an rvalue (or an index
2096 /// place). They are intentionally limited to prevent rvalues from
2097 /// being nested in one another.
2098 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
2099 pub enum Operand<'tcx> {
2100     /// Copy: The value must be available for use afterwards.
2101     ///
2102     /// This implies that the type of the place must be `Copy`; this is true
2103     /// by construction during build, but also checked by the MIR type checker.
2104     Copy(Place<'tcx>),
2105
2106     /// Move: The value (including old borrows of it) will not be used again.
2107     ///
2108     /// Safe for values of all types (modulo future developments towards `?Move`).
2109     /// Correct usage patterns are enforced by the borrow checker for safe code.
2110     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2111     Move(Place<'tcx>),
2112
2113     /// Synthesizes a constant value.
2114     Constant(Box<Constant<'tcx>>),
2115 }
2116
2117 impl<'tcx> Debug for Operand<'tcx> {
2118     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2119         use self::Operand::*;
2120         match *self {
2121             Constant(ref a) => write!(fmt, "{:?}", a),
2122             Copy(ref place) => write!(fmt, "{:?}", place),
2123             Move(ref place) => write!(fmt, "move {:?}", place),
2124         }
2125     }
2126 }
2127
2128 impl<'tcx> Operand<'tcx> {
2129     /// Convenience helper to make a constant that refers to the fn
2130     /// with given def-id and substs. Since this is used to synthesize
2131     /// MIR, assumes `user_ty` is None.
2132     pub fn function_handle<'a>(
2133         tcx: TyCtxt<'a, 'tcx, 'tcx>,
2134         def_id: DefId,
2135         substs: &'tcx Substs<'tcx>,
2136         span: Span,
2137     ) -> Self {
2138         let ty = tcx.type_of(def_id).subst(tcx, substs);
2139         Operand::Constant(box Constant {
2140             span,
2141             ty,
2142             user_ty: None,
2143             literal: ty::Const::zero_sized(tcx, ty),
2144         })
2145     }
2146
2147     pub fn to_copy(&self) -> Self {
2148         match *self {
2149             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2150             Operand::Move(ref place) => Operand::Copy(place.clone()),
2151         }
2152     }
2153 }
2154
2155 ///////////////////////////////////////////////////////////////////////////
2156 /// Rvalues
2157
2158 #[derive(Clone, RustcEncodable, RustcDecodable)]
2159 pub enum Rvalue<'tcx> {
2160     /// x (either a move or copy, depending on type of x)
2161     Use(Operand<'tcx>),
2162
2163     /// [x; 32]
2164     Repeat(Operand<'tcx>, u64),
2165
2166     /// &x or &mut x
2167     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2168
2169     /// length of a [X] or [X;n] value
2170     Len(Place<'tcx>),
2171
2172     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2173
2174     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2175     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2176
2177     NullaryOp(NullOp, Ty<'tcx>),
2178     UnaryOp(UnOp, Operand<'tcx>),
2179
2180     /// Read the discriminant of an ADT.
2181     ///
2182     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
2183     /// be defined to return, say, a 0) if ADT is not an enum.
2184     Discriminant(Place<'tcx>),
2185
2186     /// Create an aggregate value, like a tuple or struct.  This is
2187     /// only needed because we want to distinguish `dest = Foo { x:
2188     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2189     /// that `Foo` has a destructor. These rvalues can be optimized
2190     /// away after type-checking and before lowering.
2191     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2192 }
2193
2194 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2195 pub enum CastKind {
2196     Misc,
2197
2198     /// Convert unique, zero-sized type for a fn to fn()
2199     ReifyFnPointer,
2200
2201     /// Convert non capturing closure to fn()
2202     ClosureFnPointer,
2203
2204     /// Convert safe fn() to unsafe fn()
2205     UnsafeFnPointer,
2206
2207     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2208     /// codegen must figure out the details once full monomorphization
2209     /// is known. For example, this could be used to cast from a
2210     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
2211     /// (presuming `T: Trait`).
2212     Unsize,
2213 }
2214
2215 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2216 pub enum AggregateKind<'tcx> {
2217     /// The type is of the element
2218     Array(Ty<'tcx>),
2219     Tuple,
2220
2221     /// The second field is the variant index. It's equal to 0 for struct
2222     /// and union expressions. The fourth field is
2223     /// active field number and is present only for union expressions
2224     /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
2225     /// active field index would identity the field `c`
2226     Adt(
2227         &'tcx AdtDef,
2228         usize,
2229         &'tcx Substs<'tcx>,
2230         Option<UserTypeAnnotation<'tcx>>,
2231         Option<usize>,
2232     ),
2233
2234     Closure(DefId, ClosureSubsts<'tcx>),
2235     Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2236 }
2237
2238 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2239 pub enum BinOp {
2240     /// The `+` operator (addition)
2241     Add,
2242     /// The `-` operator (subtraction)
2243     Sub,
2244     /// The `*` operator (multiplication)
2245     Mul,
2246     /// The `/` operator (division)
2247     Div,
2248     /// The `%` operator (modulus)
2249     Rem,
2250     /// The `^` operator (bitwise xor)
2251     BitXor,
2252     /// The `&` operator (bitwise and)
2253     BitAnd,
2254     /// The `|` operator (bitwise or)
2255     BitOr,
2256     /// The `<<` operator (shift left)
2257     Shl,
2258     /// The `>>` operator (shift right)
2259     Shr,
2260     /// The `==` operator (equality)
2261     Eq,
2262     /// The `<` operator (less than)
2263     Lt,
2264     /// The `<=` operator (less than or equal to)
2265     Le,
2266     /// The `!=` operator (not equal to)
2267     Ne,
2268     /// The `>=` operator (greater than or equal to)
2269     Ge,
2270     /// The `>` operator (greater than)
2271     Gt,
2272     /// The `ptr.offset` operator
2273     Offset,
2274 }
2275
2276 impl BinOp {
2277     pub fn is_checkable(self) -> bool {
2278         use self::BinOp::*;
2279         match self {
2280             Add | Sub | Mul | Shl | Shr => true,
2281             _ => false,
2282         }
2283     }
2284 }
2285
2286 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2287 pub enum NullOp {
2288     /// Return the size of a value of that type
2289     SizeOf,
2290     /// Create a new uninitialized box for a value of that type
2291     Box,
2292 }
2293
2294 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2295 pub enum UnOp {
2296     /// The `!` operator for logical inversion
2297     Not,
2298     /// The `-` operator for negation
2299     Neg,
2300 }
2301
2302 impl<'tcx> Debug for Rvalue<'tcx> {
2303     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2304         use self::Rvalue::*;
2305
2306         match *self {
2307             Use(ref place) => write!(fmt, "{:?}", place),
2308             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2309             Len(ref a) => write!(fmt, "Len({:?})", a),
2310             Cast(ref kind, ref place, ref ty) => {
2311                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2312             }
2313             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2314             CheckedBinaryOp(ref op, ref a, ref b) => {
2315                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2316             }
2317             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2318             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2319             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2320             Ref(region, borrow_kind, ref place) => {
2321                 let kind_str = match borrow_kind {
2322                     BorrowKind::Shared => "",
2323                     BorrowKind::Shallow => "shallow ",
2324                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2325                 };
2326
2327                 // When printing regions, add trailing space if necessary.
2328                 let region = if ppaux::verbose() || ppaux::identify_regions() {
2329                     let mut region = region.to_string();
2330                     if region.len() > 0 {
2331                         region.push(' ');
2332                     }
2333                     region
2334                 } else {
2335                     // Do not even print 'static
2336                     String::new()
2337                 };
2338                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2339             }
2340
2341             Aggregate(ref kind, ref places) => {
2342                 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2343                     let mut tuple_fmt = fmt.debug_tuple("");
2344                     for place in places {
2345                         tuple_fmt.field(place);
2346                     }
2347                     tuple_fmt.finish()
2348                 }
2349
2350                 match **kind {
2351                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2352
2353                     AggregateKind::Tuple => match places.len() {
2354                         0 => write!(fmt, "()"),
2355                         1 => write!(fmt, "({:?},)", places[0]),
2356                         _ => fmt_tuple(fmt, places),
2357                     },
2358
2359                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2360                         let variant_def = &adt_def.variants[variant];
2361
2362                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
2363
2364                         match variant_def.ctor_kind {
2365                             CtorKind::Const => Ok(()),
2366                             CtorKind::Fn => fmt_tuple(fmt, places),
2367                             CtorKind::Fictive => {
2368                                 let mut struct_fmt = fmt.debug_struct("");
2369                                 for (field, place) in variant_def.fields.iter().zip(places) {
2370                                     struct_fmt.field(&field.ident.as_str(), place);
2371                                 }
2372                                 struct_fmt.finish()
2373                             }
2374                         }
2375                     }
2376
2377                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2378                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2379                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2380                                 format!("[closure@{:?}]", node_id)
2381                             } else {
2382                                 format!("[closure@{:?}]", tcx.hir.span(node_id))
2383                             };
2384                             let mut struct_fmt = fmt.debug_struct(&name);
2385
2386                             tcx.with_freevars(node_id, |freevars| {
2387                                 for (freevar, place) in freevars.iter().zip(places) {
2388                                     let var_name = tcx.hir.name(freevar.var_id());
2389                                     struct_fmt.field(&var_name.as_str(), place);
2390                                 }
2391                             });
2392
2393                             struct_fmt.finish()
2394                         } else {
2395                             write!(fmt, "[closure]")
2396                         }
2397                     }),
2398
2399                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2400                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2401                             let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
2402                             let mut struct_fmt = fmt.debug_struct(&name);
2403
2404                             tcx.with_freevars(node_id, |freevars| {
2405                                 for (freevar, place) in freevars.iter().zip(places) {
2406                                     let var_name = tcx.hir.name(freevar.var_id());
2407                                     struct_fmt.field(&var_name.as_str(), place);
2408                                 }
2409                                 struct_fmt.field("$state", &places[freevars.len()]);
2410                                 for i in (freevars.len() + 1)..places.len() {
2411                                     struct_fmt
2412                                         .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2413                                 }
2414                             });
2415
2416                             struct_fmt.finish()
2417                         } else {
2418                             write!(fmt, "[generator]")
2419                         }
2420                     }),
2421                 }
2422             }
2423         }
2424     }
2425 }
2426
2427 ///////////////////////////////////////////////////////////////////////////
2428 /// Constants
2429 ///
2430 /// Two constants are equal if they are the same constant. Note that
2431 /// this does not necessarily mean that they are "==" in Rust -- in
2432 /// particular one must be wary of `NaN`!
2433
2434 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2435 pub struct Constant<'tcx> {
2436     pub span: Span,
2437     pub ty: Ty<'tcx>,
2438
2439     /// Optional user-given type: for something like
2440     /// `collect::<Vec<_>>`, this would be present and would
2441     /// indicate that `Vec<_>` was explicitly specified.
2442     ///
2443     /// Needed for NLL to impose user-given type constraints.
2444     pub user_ty: Option<UserTypeAnnotation<'tcx>>,
2445
2446     pub literal: &'tcx ty::Const<'tcx>,
2447 }
2448
2449 /// A user-given type annotation attached to a constant.  These arise
2450 /// from constants that are named via paths, like `Foo::<A>::new` and
2451 /// so forth.
2452 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2453 pub enum UserTypeAnnotation<'tcx> {
2454     Ty(CanonicalTy<'tcx>),
2455
2456     /// The canonical type is the result of `type_of(def_id)` with the
2457     /// given substitutions applied.
2458     TypeOf(DefId, CanonicalUserSubsts<'tcx>),
2459 }
2460
2461 EnumTypeFoldableImpl! {
2462     impl<'tcx> TypeFoldable<'tcx> for UserTypeAnnotation<'tcx> {
2463         (UserTypeAnnotation::Ty)(ty),
2464         (UserTypeAnnotation::TypeOf)(def, substs),
2465     }
2466 }
2467
2468 newtype_index! {
2469     pub struct Promoted {
2470         DEBUG_FORMAT = "promoted[{}]"
2471     }
2472 }
2473
2474 impl<'tcx> Debug for Constant<'tcx> {
2475     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2476         write!(fmt, "const ")?;
2477         fmt_const_val(fmt, self.literal)
2478     }
2479 }
2480
2481 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2482 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2483     use ty::TyKind::*;
2484     let value = const_val.val;
2485     let ty = const_val.ty;
2486     // print some primitives
2487     if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2488         match ty.sty {
2489             Bool if bits == 0 => return write!(f, "false"),
2490             Bool if bits == 1 => return write!(f, "true"),
2491             Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2492             Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2493             Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2494             Int(i) => {
2495                 let bit_width = ty::tls::with(|tcx| {
2496                     let ty = tcx.lift_to_global(&ty).unwrap();
2497                     tcx.layout_of(ty::ParamEnv::empty().and(ty))
2498                         .unwrap()
2499                         .size
2500                         .bits()
2501                 });
2502                 let shift = 128 - bit_width;
2503                 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2504             }
2505             Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2506             _ => {}
2507         }
2508     }
2509     // print function definitons
2510     if let FnDef(did, _) = ty.sty {
2511         return write!(f, "{}", item_path_str(did));
2512     }
2513     // print string literals
2514     if let ConstValue::ScalarPair(ptr, len) = value {
2515         if let Scalar::Ptr(ptr) = ptr {
2516             if let Scalar::Bits { bits: len, .. } = len {
2517                 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2518                     return ty::tls::with(|tcx| {
2519                         let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2520                         if let Some(interpret::AllocType::Memory(alloc)) = alloc {
2521                             assert_eq!(len as usize as u128, len);
2522                             let slice =
2523                                 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2524                             let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2525                             write!(f, "{:?}", s)
2526                         } else {
2527                             write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2528                         }
2529                     });
2530                 }
2531             }
2532         }
2533     }
2534     // just raw dump everything else
2535     write!(f, "{:?}:{}", value, ty)
2536 }
2537
2538 fn item_path_str(def_id: DefId) -> String {
2539     ty::tls::with(|tcx| tcx.item_path_str(def_id))
2540 }
2541
2542 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2543     type Node = BasicBlock;
2544 }
2545
2546 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2547     fn num_nodes(&self) -> usize {
2548         self.basic_blocks.len()
2549     }
2550 }
2551
2552 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2553     fn start_node(&self) -> Self::Node {
2554         START_BLOCK
2555     }
2556 }
2557
2558 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2559     fn predecessors<'graph>(
2560         &'graph self,
2561         node: Self::Node,
2562     ) -> <Self as GraphPredecessors<'graph>>::Iter {
2563         self.predecessors_for(node).clone().into_iter()
2564     }
2565 }
2566
2567 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2568     fn successors<'graph>(
2569         &'graph self,
2570         node: Self::Node,
2571     ) -> <Self as GraphSuccessors<'graph>>::Iter {
2572         self.basic_blocks[node].terminator().successors().cloned()
2573     }
2574 }
2575
2576 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2577     type Item = BasicBlock;
2578     type Iter = IntoIter<BasicBlock>;
2579 }
2580
2581 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2582     type Item = BasicBlock;
2583     type Iter = iter::Cloned<Successors<'b>>;
2584 }
2585
2586 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2587 pub struct Location {
2588     /// the location is within this block
2589     pub block: BasicBlock,
2590
2591     /// the location is the start of the statement; or, if `statement_index`
2592     /// == num-statements, then the start of the terminator.
2593     pub statement_index: usize,
2594 }
2595
2596 impl fmt::Debug for Location {
2597     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2598         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2599     }
2600 }
2601
2602 impl Location {
2603     pub const START: Location = Location {
2604         block: START_BLOCK,
2605         statement_index: 0,
2606     };
2607
2608     /// Returns the location immediately after this one within the enclosing block.
2609     ///
2610     /// Note that if this location represents a terminator, then the
2611     /// resulting location would be out of bounds and invalid.
2612     pub fn successor_within_block(&self) -> Location {
2613         Location {
2614             block: self.block,
2615             statement_index: self.statement_index + 1,
2616         }
2617     }
2618
2619     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2620         if self.block == other.block {
2621             self.statement_index <= other.statement_index
2622         } else {
2623             dominators.is_dominated_by(other.block, self.block)
2624         }
2625     }
2626 }
2627
2628 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2629 pub enum UnsafetyViolationKind {
2630     General,
2631     /// unsafety is not allowed at all in min const fn
2632     MinConstFn,
2633     ExternStatic(ast::NodeId),
2634     BorrowPacked(ast::NodeId),
2635 }
2636
2637 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2638 pub struct UnsafetyViolation {
2639     pub source_info: SourceInfo,
2640     pub description: InternedString,
2641     pub details: InternedString,
2642     pub kind: UnsafetyViolationKind,
2643 }
2644
2645 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2646 pub struct UnsafetyCheckResult {
2647     /// Violations that are propagated *upwards* from this function
2648     pub violations: Lrc<[UnsafetyViolation]>,
2649     /// unsafe blocks in this function, along with whether they are used. This is
2650     /// used for the "unused_unsafe" lint.
2651     pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2652 }
2653
2654 /// The layout of generator state
2655 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2656 pub struct GeneratorLayout<'tcx> {
2657     pub fields: Vec<LocalDecl<'tcx>>,
2658 }
2659
2660 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2661 pub struct BorrowCheckResult<'gcx> {
2662     pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2663     pub used_mut_upvars: SmallVec<[Field; 8]>,
2664 }
2665
2666 /// After we borrow check a closure, we are left with various
2667 /// requirements that we have inferred between the free regions that
2668 /// appear in the closure's signature or on its field types.  These
2669 /// requirements are then verified and proved by the closure's
2670 /// creating function. This struct encodes those requirements.
2671 ///
2672 /// The requirements are listed as being between various
2673 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2674 /// vids refer to the free regions that appear in the closure (or
2675 /// generator's) type, in order of appearance. (This numbering is
2676 /// actually defined by the `UniversalRegions` struct in the NLL
2677 /// region checker. See for example
2678 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2679 /// regions in the closure's type "as if" they were erased, so their
2680 /// precise identity is not important, only their position.
2681 ///
2682 /// Example: If type check produces a closure with the closure substs:
2683 ///
2684 /// ```text
2685 /// ClosureSubsts = [
2686 ///     i8,                                  // the "closure kind"
2687 ///     for<'x> fn(&'a &'x u32) -> &'x u32,  // the "closure signature"
2688 ///     &'a String,                          // some upvar
2689 /// ]
2690 /// ```
2691 ///
2692 /// here, there is one unique free region (`'a`) but it appears
2693 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2694 ///
2695 /// ```text
2696 /// ClosureSubsts = [
2697 ///     i8,                                  // the "closure kind"
2698 ///     for<'x> fn(&'1 &'x u32) -> &'x u32,  // the "closure signature"
2699 ///     &'2 String,                          // some upvar
2700 /// ]
2701 /// ```
2702 ///
2703 /// Now the code might impose a requirement like `'1: '2`. When an
2704 /// instance of the closure is created, the corresponding free regions
2705 /// can be extracted from its type and constrained to have the given
2706 /// outlives relationship.
2707 ///
2708 /// In some cases, we have to record outlives requirements between
2709 /// types and regions as well. In that case, if those types include
2710 /// any regions, those regions are recorded as `ReClosureBound`
2711 /// instances assigned one of these same indices. Those regions will
2712 /// be substituted away by the creator. We use `ReClosureBound` in
2713 /// that case because the regions must be allocated in the global
2714 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2715 /// internally within the rest of the NLL code).
2716 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2717 pub struct ClosureRegionRequirements<'gcx> {
2718     /// The number of external regions defined on the closure.  In our
2719     /// example above, it would be 3 -- one for `'static`, then `'1`
2720     /// and `'2`. This is just used for a sanity check later on, to
2721     /// make sure that the number of regions we see at the callsite
2722     /// matches.
2723     pub num_external_vids: usize,
2724
2725     /// Requirements between the various free regions defined in
2726     /// indices.
2727     pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2728 }
2729
2730 /// Indicates an outlives constraint between a type or between two
2731 /// free-regions declared on the closure.
2732 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2733 pub struct ClosureOutlivesRequirement<'tcx> {
2734     // This region or type ...
2735     pub subject: ClosureOutlivesSubject<'tcx>,
2736
2737     // ... must outlive this one.
2738     pub outlived_free_region: ty::RegionVid,
2739
2740     // If not, report an error here ...
2741     pub blame_span: Span,
2742
2743     // ... due to this reason.
2744     pub category: ConstraintCategory,
2745 }
2746
2747 /// Outlives constraints can be categorized to determine whether and why they
2748 /// are interesting (for error reporting). Order of variants indicates sort
2749 /// order of the category, thereby influencing diagnostic output.
2750 ///
2751 /// See also [rustc_mir::borrow_check::nll::constraints]
2752 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2753 pub enum ConstraintCategory {
2754     Return,
2755     TypeAnnotation,
2756     Cast,
2757
2758     /// A constraint that came from checking the body of a closure.
2759     ///
2760     /// We try to get the category that the closure used when reporting this.
2761     ClosureBounds,
2762     CallArgument,
2763     CopyBound,
2764     SizedBound,
2765     Assignment,
2766     OpaqueType,
2767
2768     /// A "boring" constraint (caused by the given location) is one that
2769     /// the user probably doesn't want to see described in diagnostics,
2770     /// because it is kind of an artifact of the type system setup.
2771     /// Example: `x = Foo { field: y }` technically creates
2772     /// intermediate regions representing the "type of `Foo { field: y
2773     /// }`", and data flows from `y` into those variables, but they
2774     /// are not very interesting. The assignment into `x` on the other
2775     /// hand might be.
2776     Boring,
2777     // Boring and applicable everywhere.
2778     BoringNoLocation,
2779
2780     /// A constraint that doesn't correspond to anything the user sees.
2781     Internal,
2782 }
2783
2784 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2785 /// that must outlive some region.
2786 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2787 pub enum ClosureOutlivesSubject<'tcx> {
2788     /// Subject is a type, typically a type parameter, but could also
2789     /// be a projection. Indicates a requirement like `T: 'a` being
2790     /// passed to the caller, where the type here is `T`.
2791     ///
2792     /// The type here is guaranteed not to contain any free regions at
2793     /// present.
2794     Ty(Ty<'tcx>),
2795
2796     /// Subject is a free region from the closure. Indicates a requirement
2797     /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2798     Region(ty::RegionVid),
2799 }
2800
2801 /*
2802  * TypeFoldable implementations for MIR types
2803  */
2804
2805 CloneTypeFoldableAndLiftImpls! {
2806     BlockTailInfo,
2807     MirPhase,
2808     Mutability,
2809     SourceInfo,
2810     UpvarDecl,
2811     FakeReadCause,
2812     ValidationOp,
2813     SourceScope,
2814     SourceScopeData,
2815     SourceScopeLocalData,
2816 }
2817
2818 BraceStructTypeFoldableImpl! {
2819     impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2820         phase,
2821         basic_blocks,
2822         source_scopes,
2823         source_scope_local_data,
2824         promoted,
2825         yield_ty,
2826         generator_drop,
2827         generator_layout,
2828         local_decls,
2829         arg_count,
2830         upvar_decls,
2831         spread_arg,
2832         span,
2833         cache,
2834     }
2835 }
2836
2837 BraceStructTypeFoldableImpl! {
2838     impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2839         fields
2840     }
2841 }
2842
2843 BraceStructTypeFoldableImpl! {
2844     impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2845         mutability,
2846         is_user_variable,
2847         internal,
2848         ty,
2849         user_ty,
2850         name,
2851         source_info,
2852         is_block_tail,
2853         visibility_scope,
2854     }
2855 }
2856
2857 BraceStructTypeFoldableImpl! {
2858     impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2859         statements,
2860         terminator,
2861         is_cleanup,
2862     }
2863 }
2864
2865 BraceStructTypeFoldableImpl! {
2866     impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
2867         place, ty, re, mutbl
2868     }
2869 }
2870
2871 BraceStructTypeFoldableImpl! {
2872     impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2873         source_info, kind
2874     }
2875 }
2876
2877 EnumTypeFoldableImpl! {
2878     impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
2879         (StatementKind::Assign)(a, b),
2880         (StatementKind::FakeRead)(cause, place),
2881         (StatementKind::SetDiscriminant) { place, variant_index },
2882         (StatementKind::StorageLive)(a),
2883         (StatementKind::StorageDead)(a),
2884         (StatementKind::InlineAsm) { asm, outputs, inputs },
2885         (StatementKind::Validate)(a, b),
2886         (StatementKind::EndRegion)(a),
2887         (StatementKind::AscribeUserType)(a, v, b),
2888         (StatementKind::Nop),
2889     }
2890 }
2891
2892 EnumTypeFoldableImpl! {
2893     impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
2894         (ClearCrossCrate::Clear),
2895         (ClearCrossCrate::Set)(a),
2896     } where T: TypeFoldable<'tcx>
2897 }
2898
2899 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2900     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2901         use mir::TerminatorKind::*;
2902
2903         let kind = match self.kind {
2904             Goto { target } => Goto { target: target },
2905             SwitchInt {
2906                 ref discr,
2907                 switch_ty,
2908                 ref values,
2909                 ref targets,
2910             } => SwitchInt {
2911                 discr: discr.fold_with(folder),
2912                 switch_ty: switch_ty.fold_with(folder),
2913                 values: values.clone(),
2914                 targets: targets.clone(),
2915             },
2916             Drop {
2917                 ref location,
2918                 target,
2919                 unwind,
2920             } => Drop {
2921                 location: location.fold_with(folder),
2922                 target,
2923                 unwind,
2924             },
2925             DropAndReplace {
2926                 ref location,
2927                 ref value,
2928                 target,
2929                 unwind,
2930             } => DropAndReplace {
2931                 location: location.fold_with(folder),
2932                 value: value.fold_with(folder),
2933                 target,
2934                 unwind,
2935             },
2936             Yield {
2937                 ref value,
2938                 resume,
2939                 drop,
2940             } => Yield {
2941                 value: value.fold_with(folder),
2942                 resume: resume,
2943                 drop: drop,
2944             },
2945             Call {
2946                 ref func,
2947                 ref args,
2948                 ref destination,
2949                 cleanup,
2950                 from_hir_call,
2951             } => {
2952                 let dest = destination
2953                     .as_ref()
2954                     .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2955
2956                 Call {
2957                     func: func.fold_with(folder),
2958                     args: args.fold_with(folder),
2959                     destination: dest,
2960                     cleanup,
2961                     from_hir_call,
2962                 }
2963             }
2964             Assert {
2965                 ref cond,
2966                 expected,
2967                 ref msg,
2968                 target,
2969                 cleanup,
2970             } => {
2971                 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
2972                     EvalErrorKind::BoundsCheck {
2973                         len: len.fold_with(folder),
2974                         index: index.fold_with(folder),
2975                     }
2976                 } else {
2977                     msg.clone()
2978                 };
2979                 Assert {
2980                     cond: cond.fold_with(folder),
2981                     expected,
2982                     msg,
2983                     target,
2984                     cleanup,
2985                 }
2986             }
2987             GeneratorDrop => GeneratorDrop,
2988             Resume => Resume,
2989             Abort => Abort,
2990             Return => Return,
2991             Unreachable => Unreachable,
2992             FalseEdges {
2993                 real_target,
2994                 ref imaginary_targets,
2995             } => FalseEdges {
2996                 real_target,
2997                 imaginary_targets: imaginary_targets.clone(),
2998             },
2999             FalseUnwind {
3000                 real_target,
3001                 unwind,
3002             } => FalseUnwind {
3003                 real_target,
3004                 unwind,
3005             },
3006         };
3007         Terminator {
3008             source_info: self.source_info,
3009             kind,
3010         }
3011     }
3012
3013     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3014         use mir::TerminatorKind::*;
3015
3016         match self.kind {
3017             SwitchInt {
3018                 ref discr,
3019                 switch_ty,
3020                 ..
3021             } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3022             Drop { ref location, .. } => location.visit_with(visitor),
3023             DropAndReplace {
3024                 ref location,
3025                 ref value,
3026                 ..
3027             } => location.visit_with(visitor) || value.visit_with(visitor),
3028             Yield { ref value, .. } => value.visit_with(visitor),
3029             Call {
3030                 ref func,
3031                 ref args,
3032                 ref destination,
3033                 ..
3034             } => {
3035                 let dest = if let Some((ref loc, _)) = *destination {
3036                     loc.visit_with(visitor)
3037                 } else {
3038                     false
3039                 };
3040                 dest || func.visit_with(visitor) || args.visit_with(visitor)
3041             }
3042             Assert {
3043                 ref cond, ref msg, ..
3044             } => {
3045                 if cond.visit_with(visitor) {
3046                     if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3047                         len.visit_with(visitor) || index.visit_with(visitor)
3048                     } else {
3049                         false
3050                     }
3051                 } else {
3052                     false
3053                 }
3054             }
3055             Goto { .. }
3056             | Resume
3057             | Abort
3058             | Return
3059             | GeneratorDrop
3060             | Unreachable
3061             | FalseEdges { .. }
3062             | FalseUnwind { .. } => false,
3063         }
3064     }
3065 }
3066
3067 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3068     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3069         match self {
3070             &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3071             _ => self.clone(),
3072         }
3073     }
3074
3075     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3076         if let &Place::Projection(ref p) = self {
3077             p.visit_with(visitor)
3078         } else {
3079             false
3080         }
3081     }
3082 }
3083
3084 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3085     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3086         use mir::Rvalue::*;
3087         match *self {
3088             Use(ref op) => Use(op.fold_with(folder)),
3089             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3090             Ref(region, bk, ref place) => {
3091                 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3092             }
3093             Len(ref place) => Len(place.fold_with(folder)),
3094             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3095             BinaryOp(op, ref rhs, ref lhs) => {
3096                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3097             }
3098             CheckedBinaryOp(op, ref rhs, ref lhs) => {
3099                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3100             }
3101             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3102             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3103             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3104             Aggregate(ref kind, ref fields) => {
3105                 let kind = box match **kind {
3106                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3107                     AggregateKind::Tuple => AggregateKind::Tuple,
3108                     AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3109                         def,
3110                         v,
3111                         substs.fold_with(folder),
3112                         user_ty.fold_with(folder),
3113                         n,
3114                     ),
3115                     AggregateKind::Closure(id, substs) => {
3116                         AggregateKind::Closure(id, substs.fold_with(folder))
3117                     }
3118                     AggregateKind::Generator(id, substs, movablity) => {
3119                         AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3120                     }
3121                 };
3122                 Aggregate(kind, fields.fold_with(folder))
3123             }
3124         }
3125     }
3126
3127     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3128         use mir::Rvalue::*;
3129         match *self {
3130             Use(ref op) => op.visit_with(visitor),
3131             Repeat(ref op, _) => op.visit_with(visitor),
3132             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3133             Len(ref place) => place.visit_with(visitor),
3134             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3135             BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3136                 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3137             }
3138             UnaryOp(_, ref val) => val.visit_with(visitor),
3139             Discriminant(ref place) => place.visit_with(visitor),
3140             NullaryOp(_, ty) => ty.visit_with(visitor),
3141             Aggregate(ref kind, ref fields) => {
3142                 (match **kind {
3143                     AggregateKind::Array(ty) => ty.visit_with(visitor),
3144                     AggregateKind::Tuple => false,
3145                     AggregateKind::Adt(_, _, substs, user_ty, _) => {
3146                         substs.visit_with(visitor) || user_ty.visit_with(visitor)
3147                     }
3148                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3149                     AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3150                 }) || fields.visit_with(visitor)
3151             }
3152         }
3153     }
3154 }
3155
3156 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3157     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3158         match *self {
3159             Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3160             Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3161             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3162         }
3163     }
3164
3165     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3166         match *self {
3167             Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3168             Operand::Constant(ref c) => c.visit_with(visitor),
3169         }
3170     }
3171 }
3172
3173 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3174 where
3175     B: TypeFoldable<'tcx>,
3176     V: TypeFoldable<'tcx>,
3177     T: TypeFoldable<'tcx>,
3178 {
3179     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3180         use mir::ProjectionElem::*;
3181
3182         let base = self.base.fold_with(folder);
3183         let elem = match self.elem {
3184             Deref => Deref,
3185             Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3186             Index(ref v) => Index(v.fold_with(folder)),
3187             ref elem => elem.clone(),
3188         };
3189
3190         Projection { base, elem }
3191     }
3192
3193     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3194         use mir::ProjectionElem::*;
3195
3196         self.base.visit_with(visitor) || match self.elem {
3197             Field(_, ref ty) => ty.visit_with(visitor),
3198             Index(ref v) => v.visit_with(visitor),
3199             _ => false,
3200         }
3201     }
3202 }
3203
3204 impl<'tcx> TypeFoldable<'tcx> for Field {
3205     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3206         *self
3207     }
3208     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3209         false
3210     }
3211 }
3212
3213 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3214     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3215         Constant {
3216             span: self.span.clone(),
3217             ty: self.ty.fold_with(folder),
3218             user_ty: self.user_ty.fold_with(folder),
3219             literal: self.literal.fold_with(folder),
3220         }
3221     }
3222     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3223         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
3224     }
3225 }