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