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