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