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