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