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