1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! MIR datatypes and passes. See the [rustc guide] for more info.
13 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
15 use hir::def::CtorKind;
16 use hir::def_id::DefId;
17 use hir::{self, HirId, InlineAsm};
18 use mir::interpret::{ConstValue, EvalErrorKind, Scalar};
19 use mir::visit::MirVisitable;
20 use rustc_apfloat::ieee::{Double, Single};
21 use rustc_apfloat::Float;
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
25 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_data_structures::sync::MappedReadGuard;
28 use rustc_serialize::{self as serialize};
29 use smallvec::SmallVec;
31 use std::fmt::{self, Debug, Formatter, Write};
32 use std::ops::{Index, IndexMut};
34 use std::vec::IntoIter;
35 use std::{iter, mem, option, u32};
36 use syntax::ast::{self, Name};
37 use syntax::symbol::InternedString;
38 use syntax_pos::{Span, DUMMY_SP};
39 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
40 use ty::subst::{CanonicalUserSubsts, Subst, Substs};
41 use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
42 use ty::layout::VariantIdx;
45 pub use mir::interpret::AssertMessage;
55 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
57 pub trait HasLocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx>;
61 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
62 fn local_decls(&self) -> &LocalDecls<'tcx> {
67 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
68 fn local_decls(&self) -> &LocalDecls<'tcx> {
73 /// The various "big phases" that MIR goes through.
75 /// Warning: ordering of variants is significant
76 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
85 /// Gets the index of the current MirPhase within the set of all MirPhases.
86 pub fn phase_index(&self) -> usize {
91 /// Lowered representation of a single function.
92 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
93 pub struct Mir<'tcx> {
94 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
95 /// that indexes into this vector.
96 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
98 /// Records how far through the "desugaring and optimization" process this particular
99 /// MIR has traversed. This is particularly useful when inlining, since in that context
100 /// we instantiate the promoted constants and add them to our promoted vector -- but those
101 /// promoted items have already been optimized, whereas ours have not. This field allows
102 /// us to see the difference and forego optimization on the inlined promoted items.
105 /// List of source scopes; these are referenced by statements
106 /// and used for debuginfo. Indexed by a `SourceScope`.
107 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
109 /// Crate-local information for each source scope, that can't (and
110 /// needn't) be tracked across crates.
111 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
113 /// Rvalues promoted from this function, such as borrows of constants.
114 /// Each of them is the Mir of a constant with the fn's type parameters
115 /// in scope, but a separate set of locals.
116 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
118 /// Yield type of the function, if it is a generator.
119 pub yield_ty: Option<Ty<'tcx>>,
121 /// Generator drop glue
122 pub generator_drop: Option<Box<Mir<'tcx>>>,
124 /// The layout of a generator. Produced by the state transformation.
125 pub generator_layout: Option<GeneratorLayout<'tcx>>,
127 /// Declarations of locals.
129 /// The first local is the return value pointer, followed by `arg_count`
130 /// locals for the function arguments, followed by any user-declared
131 /// variables and temporaries.
132 pub local_decls: LocalDecls<'tcx>,
134 /// Number of arguments this function takes.
136 /// Starting at local 1, `arg_count` locals will be provided by the caller
137 /// and can be assumed to be initialized.
139 /// If this MIR was built for a constant, this will be 0.
140 pub arg_count: usize,
142 /// Names and capture modes of all the closure upvars, assuming
143 /// the first argument is either the closure or a reference to it.
144 pub upvar_decls: Vec<UpvarDecl>,
146 /// Mark an argument local (which must be a tuple) as getting passed as
147 /// its individual components at the LLVM level.
149 /// This is used for the "rust-call" ABI.
150 pub spread_arg: Option<Local>,
152 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
153 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
154 /// this conversion from happening and use short circuiting, we will cause the following code
155 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
157 /// List of places where control flow was destroyed. Used for error reporting.
158 pub control_flow_destroyed: Vec<(Span, String)>,
160 /// A span representing this MIR, for error reporting
163 /// A cache for various calculations
167 impl<'tcx> Mir<'tcx> {
169 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
170 source_scopes: IndexVec<SourceScope, SourceScopeData>,
171 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
172 promoted: IndexVec<Promoted, Mir<'tcx>>,
173 yield_ty: Option<Ty<'tcx>>,
174 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
176 upvar_decls: Vec<UpvarDecl>,
178 control_flow_destroyed: Vec<(Span, String)>,
180 // We need `arg_count` locals, and one for the return place
182 local_decls.len() >= arg_count + 1,
183 "expected at least {} locals, got {}",
189 phase: MirPhase::Build,
192 source_scope_local_data,
195 generator_drop: None,
196 generator_layout: None,
202 cache: cache::Cache::new(),
203 control_flow_destroyed,
208 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
213 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
214 self.cache.invalidate();
215 &mut self.basic_blocks
219 pub fn basic_blocks_and_local_decls_mut(
222 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
223 &mut LocalDecls<'tcx>,
225 self.cache.invalidate();
226 (&mut self.basic_blocks, &mut self.local_decls)
230 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
231 self.cache.predecessors(self)
235 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
236 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
240 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
241 let if_zero_locations = if loc.statement_index == 0 {
242 let predecessor_blocks = self.predecessors_for(loc.block);
243 let num_predecessor_blocks = predecessor_blocks.len();
245 (0..num_predecessor_blocks)
246 .map(move |i| predecessor_blocks[i])
247 .map(move |bb| self.terminator_loc(bb)),
253 let if_not_zero_locations = if loc.statement_index == 0 {
258 statement_index: loc.statement_index - 1,
265 .chain(if_not_zero_locations)
269 pub fn dominators(&self) -> Dominators<BasicBlock> {
274 pub fn local_kind(&self, local: Local) -> LocalKind {
275 let index = local.as_usize();
278 self.local_decls[local].mutability == Mutability::Mut,
279 "return place should be mutable"
282 LocalKind::ReturnPointer
283 } else if index < self.arg_count + 1 {
285 } else if self.local_decls[local].name.is_some() {
292 /// Returns an iterator over all temporaries.
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.is_some() {
305 /// Returns an iterator over all user-declared locals.
307 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
308 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
309 let local = Local::new(index);
310 if self.local_decls[local].is_user_variable.is_some() {
318 /// Returns an iterator over all user-declared mutable locals.
320 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
321 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
322 let local = Local::new(index);
323 let decl = &self.local_decls[local];
324 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
332 /// Returns an iterator over all user-declared mutable arguments and locals.
334 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
335 (1..self.local_decls.len()).filter_map(move |index| {
336 let local = Local::new(index);
337 let decl = &self.local_decls[local];
338 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
339 && decl.mutability == Mutability::Mut
348 /// Returns an iterator over all function arguments.
350 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
351 let arg_count = self.arg_count;
352 (1..=arg_count).map(Local::new)
355 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
356 /// locals that are neither arguments nor the return place).
358 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
359 let arg_count = self.arg_count;
360 let local_count = self.local_decls.len();
361 (arg_count + 1..local_count).map(Local::new)
364 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
365 /// invalidating statement indices in `Location`s.
366 pub fn make_statement_nop(&mut self, location: Location) {
367 let block = &mut self[location.block];
368 debug_assert!(location.statement_index < block.statements.len());
369 block.statements[location.statement_index].make_nop()
372 /// Returns the source info associated with `location`.
373 pub fn source_info(&self, location: Location) -> &SourceInfo {
374 let block = &self[location.block];
375 let stmts = &block.statements;
376 let idx = location.statement_index;
377 if idx < stmts.len() {
378 &stmts[idx].source_info
380 assert_eq!(idx, stmts.len());
381 &block.terminator().source_info
385 /// Check if `sub` is a sub scope of `sup`
386 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
388 match self.source_scopes[sub].parent_scope {
389 None => return false,
396 /// Return the return type, it always return first element from `local_decls` array
397 pub fn return_ty(&self) -> Ty<'tcx> {
398 self.local_decls[RETURN_PLACE].ty
401 /// Get the location of the terminator for the given block
402 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
405 statement_index: self[bb].statements.len(),
410 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
413 /// Unsafe because of a PushUnsafeBlock
415 /// Unsafe because of an unsafe fn
417 /// Unsafe because of an `unsafe` block
418 ExplicitUnsafe(ast::NodeId),
421 impl_stable_hash_for!(struct Mir<'tcx> {
425 source_scope_local_data,
434 control_flow_destroyed,
439 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
440 type Output = BasicBlockData<'tcx>;
443 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
444 &self.basic_blocks()[index]
448 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
450 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
451 &mut self.basic_blocks_mut()[index]
455 #[derive(Copy, Clone, Debug)]
456 pub enum ClearCrossCrate<T> {
461 impl<T> ClearCrossCrate<T> {
462 pub fn assert_crate_local(self) -> T {
464 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
465 ClearCrossCrate::Set(v) => v,
470 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
471 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
473 /// Grouped information about the source code origin of a MIR entity.
474 /// Intended to be inspected by diagnostics and debuginfo.
475 /// Most passes can work with it as a whole, within a single function.
476 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
477 pub struct SourceInfo {
478 /// Source span for the AST pertaining to this MIR entity.
481 /// The source scope, keeping track of which bindings can be
482 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
483 pub scope: SourceScope,
486 ///////////////////////////////////////////////////////////////////////////
487 // Mutability and borrow kinds
489 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
490 pub enum Mutability {
495 impl From<Mutability> for hir::Mutability {
496 fn from(m: Mutability) -> Self {
498 Mutability::Mut => hir::MutMutable,
499 Mutability::Not => hir::MutImmutable,
504 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
505 pub enum BorrowKind {
506 /// Data must be immutable and is aliasable.
509 /// The immediately borrowed place must be immutable, but projections from
510 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
511 /// conflict with a mutable borrow of `a.b.c`.
513 /// This is used when lowering matches: when matching on a place we want to
514 /// ensure that place have the same value from the start of the match until
515 /// an arm is selected. This prevents this code from compiling:
517 /// let mut x = &Some(0);
520 /// Some(_) if { x = &None; false } => (),
524 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
525 /// should not prevent `if let None = x { ... }`, for example, because the
526 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
527 /// We can also report errors with this kind of borrow differently.
530 /// Data must be immutable but not aliasable. This kind of borrow
531 /// cannot currently be expressed by the user and is used only in
532 /// implicit closure bindings. It is needed when the closure is
533 /// borrowing or mutating a mutable referent, e.g.:
535 /// let x: &mut isize = ...;
536 /// let y = || *x += 5;
538 /// If we were to try to translate this closure into a more explicit
539 /// form, we'd encounter an error with the code as written:
541 /// struct Env { x: & &mut isize }
542 /// let x: &mut isize = ...;
543 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
544 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
546 /// This is then illegal because you cannot mutate an `&mut` found
547 /// in an aliasable location. To solve, you'd have to translate with
548 /// an `&mut` borrow:
550 /// struct Env { x: & &mut isize }
551 /// let x: &mut isize = ...;
552 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
553 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
555 /// Now the assignment to `**env.x` is legal, but creating a
556 /// mutable pointer to `x` is not because `x` is not mutable. We
557 /// could fix this by declaring `x` as `let mut x`. This is ok in
558 /// user code, if awkward, but extra weird for closures, since the
559 /// borrow is hidden.
561 /// So we introduce a "unique imm" borrow -- the referent is
562 /// immutable, but not aliasable. This solves the problem. For
563 /// simplicity, we don't give users the way to express this
564 /// borrow, it's just used when translating closures.
567 /// Data is mutable and not aliasable.
569 /// True if this borrow arose from method-call auto-ref
570 /// (i.e., `adjustment::Adjust::Borrow`)
571 allow_two_phase_borrow: bool,
576 pub fn allows_two_phase_borrow(&self) -> bool {
578 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
579 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
584 ///////////////////////////////////////////////////////////////////////////
585 // Variables and temps
589 DEBUG_FORMAT = "_{}",
590 const RETURN_PLACE = 0,
594 /// Classifies locals into categories. See `Mir::local_kind`.
595 #[derive(PartialEq, Eq, Debug)]
597 /// User-declared variable binding
599 /// Compiler-introduced temporary
601 /// Function argument
603 /// Location of function's return value
607 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
608 pub struct VarBindingForm<'tcx> {
609 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
610 pub binding_mode: ty::BindingMode,
611 /// If an explicit type was provided for this variable binding,
612 /// this holds the source Span of that type.
614 /// NOTE: If you want to change this to a `HirId`, be wary that
615 /// doing so breaks incremental compilation (as of this writing),
616 /// while a `Span` does not cause our tests to fail.
617 pub opt_ty_info: Option<Span>,
618 /// Place of the RHS of the =, or the subject of the `match` where this
619 /// variable is initialized. None in the case of `let PATTERN;`.
620 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
621 /// (a) the right-hand side isn't evaluated as a place expression.
622 /// (b) it gives a way to separate this case from the remaining cases
624 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
625 /// Span of the pattern in which this variable was bound.
629 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
630 pub enum BindingForm<'tcx> {
631 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
632 Var(VarBindingForm<'tcx>),
633 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
634 ImplicitSelf(ImplicitSelfKind),
635 /// Reference used in a guard expression to ensure immutability.
639 /// Represents what type of implicit self a function has, if any.
640 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
641 pub enum ImplicitSelfKind {
642 /// Represents a `fn x(self);`.
644 /// Represents a `fn x(mut self);`.
646 /// Represents a `fn x(&self);`.
648 /// Represents a `fn x(&mut self);`.
650 /// Represents when a function does not have a self argument or
651 /// when a function has a `self: X` argument.
655 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
657 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
664 impl_stable_hash_for!(enum self::ImplicitSelfKind {
672 impl_stable_hash_for!(enum self::MirPhase {
679 mod binding_form_impl {
680 use ich::StableHashingContext;
681 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
683 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
684 fn hash_stable<W: StableHasherResult>(
686 hcx: &mut StableHashingContext<'a>,
687 hasher: &mut StableHasher<W>,
689 use super::BindingForm::*;
690 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
693 Var(binding) => binding.hash_stable(hcx, hasher),
694 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
701 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
702 /// created during evaluation of expressions in a block tail
703 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
705 /// It is used to improve diagnostics when such temporaries are
706 /// involved in borrow_check errors, e.g., explanations of where the
707 /// temporaries come from, when their destructors are run, and/or how
708 /// one might revise the code to satisfy the borrow checker's rules.
709 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
710 pub struct BlockTailInfo {
711 /// If `true`, then the value resulting from evaluating this tail
712 /// expression is ignored by the block's expression context.
714 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
715 /// but not e.g., `let _x = { ...; tail };`
716 pub tail_result_is_ignored: bool,
719 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
723 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
724 /// argument, or the return place.
725 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
726 pub struct LocalDecl<'tcx> {
727 /// `let mut x` vs `let x`.
729 /// Temporaries and the return place are always mutable.
730 pub mutability: Mutability,
732 /// Some(binding_mode) if this corresponds to a user-declared local variable.
734 /// This is solely used for local diagnostics when generating
735 /// warnings/errors when compiling the current crate, and
736 /// therefore it need not be visible across crates. pnkfelix
737 /// currently hypothesized we *need* to wrap this in a
738 /// `ClearCrossCrate` as long as it carries as `HirId`.
739 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
741 /// True if this is an internal local
743 /// These locals are not based on types in the source code and are only used
744 /// for a few desugarings at the moment.
746 /// The generator transformation will sanity check the locals which are live
747 /// across a suspension point against the type components of the generator
748 /// which type checking knows are live across a suspension point. We need to
749 /// flag drop flags to avoid triggering this check as they are introduced
752 /// Unsafety checking will also ignore dereferences of these locals,
753 /// so they can be used for raw pointers only used in a desugaring.
755 /// This should be sound because the drop flags are fully algebraic, and
756 /// therefore don't affect the OIBIT or outlives properties of the
760 /// If this local is a temporary and `is_block_tail` is `Some`,
761 /// then it is a temporary created for evaluation of some
762 /// subexpression of some block's tail expression (with no
763 /// intervening statement context).
764 pub is_block_tail: Option<BlockTailInfo>,
766 /// Type of this local.
769 /// If the user manually ascribed a type to this variable,
770 /// e.g., via `let x: T`, then we carry that type here. The MIR
771 /// borrow checker needs this information since it can affect
772 /// region inference.
773 pub user_ty: UserTypeProjections<'tcx>,
775 /// Name of the local, used in debuginfo and pretty-printing.
777 /// Note that function arguments can also have this set to `Some(_)`
778 /// to generate better debuginfo.
779 pub name: Option<Name>,
781 /// The *syntactic* (i.e., not visibility) source scope the local is defined
782 /// in. If the local was defined in a let-statement, this
783 /// is *within* the let-statement, rather than outside
786 /// This is needed because the visibility source scope of locals within
787 /// a let-statement is weird.
789 /// The reason is that we want the local to be *within* the let-statement
790 /// for lint purposes, but we want the local to be *after* the let-statement
791 /// for names-in-scope purposes.
793 /// That's it, if we have a let-statement like the one in this
797 /// fn foo(x: &str) {
798 /// #[allow(unused_mut)]
799 /// let mut x: u32 = { // <- one unused mut
800 /// let mut y: u32 = x.parse().unwrap();
807 /// Then, from a lint point of view, the declaration of `x: u32`
808 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
809 /// lint scopes are the same as the AST/HIR nesting.
811 /// However, from a name lookup point of view, the scopes look more like
812 /// as if the let-statements were `match` expressions:
815 /// fn foo(x: &str) {
817 /// match x.parse().unwrap() {
826 /// We care about the name-lookup scopes for debuginfo - if the
827 /// debuginfo instruction pointer is at the call to `x.parse()`, we
828 /// want `x` to refer to `x: &str`, but if it is at the call to
829 /// `drop(x)`, we want it to refer to `x: u32`.
831 /// To allow both uses to work, we need to have more than a single scope
832 /// for a local. We have the `source_info.scope` represent the
833 /// "syntactic" lint scope (with a variable being under its let
834 /// block) while the `visibility_scope` represents the "local variable"
835 /// scope (where the "rest" of a block is under all prior let-statements).
837 /// The end result looks like this:
841 /// │{ argument x: &str }
843 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
844 /// │ │ // in practice because I'm lazy.
846 /// │ │← x.source_info.scope
847 /// │ │← `x.parse().unwrap()`
849 /// │ │ │← y.source_info.scope
851 /// │ │ │{ let y: u32 }
853 /// │ │ │← y.visibility_scope
856 /// │ │{ let x: u32 }
857 /// │ │← x.visibility_scope
858 /// │ │← `drop(x)` // this accesses `x: u32`
860 pub source_info: SourceInfo,
862 /// Source scope within which the local is visible (for debuginfo)
863 /// (see `source_info` for more details).
864 pub visibility_scope: SourceScope,
867 impl<'tcx> LocalDecl<'tcx> {
868 /// Returns true only if local is a binding that can itself be
869 /// made mutable via the addition of the `mut` keyword, namely
870 /// something like the occurrences of `x` in:
871 /// - `fn foo(x: Type) { ... }`,
873 /// - or `match ... { C(x) => ... }`
874 pub fn can_be_made_mutable(&self) -> bool {
875 match self.is_user_variable {
876 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
877 binding_mode: ty::BindingMode::BindByValue(_),
883 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
890 /// Returns true if local is definitely not a `ref ident` or
891 /// `ref mut ident` binding. (Such bindings cannot be made into
892 /// mutable bindings, but the inverse does not necessarily hold).
893 pub fn is_nonref_binding(&self) -> bool {
894 match self.is_user_variable {
895 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
896 binding_mode: ty::BindingMode::BindByValue(_),
902 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
908 /// Create a new `LocalDecl` for a temporary.
910 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
911 Self::new_local(ty, Mutability::Mut, false, span)
914 /// Converts `self` into same `LocalDecl` except tagged as immutable.
916 pub fn immutable(mut self) -> Self {
917 self.mutability = Mutability::Not;
921 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
923 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
924 assert!(self.is_block_tail.is_none());
925 self.is_block_tail = Some(info);
929 /// Create a new `LocalDecl` for a internal temporary.
931 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
932 Self::new_local(ty, Mutability::Mut, true, span)
938 mutability: Mutability,
945 user_ty: UserTypeProjections::none(),
947 source_info: SourceInfo {
949 scope: OUTERMOST_SOURCE_SCOPE,
951 visibility_scope: OUTERMOST_SOURCE_SCOPE,
953 is_user_variable: None,
958 /// Builds a `LocalDecl` for the return place.
960 /// This must be inserted into the `local_decls` list as the first local.
962 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
964 mutability: Mutability::Mut,
966 user_ty: UserTypeProjections::none(),
967 source_info: SourceInfo {
969 scope: OUTERMOST_SOURCE_SCOPE,
971 visibility_scope: OUTERMOST_SOURCE_SCOPE,
974 name: None, // FIXME maybe we do want some name here?
975 is_user_variable: None,
980 /// A closure capture, with its name and mode.
981 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
982 pub struct UpvarDecl {
983 pub debug_name: Name,
985 /// `HirId` of the captured variable
986 pub var_hir_id: ClearCrossCrate<HirId>,
988 /// If true, the capture is behind a reference.
991 pub mutability: Mutability,
994 ///////////////////////////////////////////////////////////////////////////
998 pub struct BasicBlock {
999 DEBUG_FORMAT = "bb{}",
1000 const START_BLOCK = 0,
1005 pub fn start_location(self) -> Location {
1013 ///////////////////////////////////////////////////////////////////////////
1014 // BasicBlockData and Terminator
1016 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1017 pub struct BasicBlockData<'tcx> {
1018 /// List of statements in this block.
1019 pub statements: Vec<Statement<'tcx>>,
1021 /// Terminator for this block.
1023 /// NB. This should generally ONLY be `None` during construction.
1024 /// Therefore, you should generally access it via the
1025 /// `terminator()` or `terminator_mut()` methods. The only
1026 /// exception is that certain passes, such as `simplify_cfg`, swap
1027 /// out the terminator temporarily with `None` while they continue
1028 /// to recurse over the set of basic blocks.
1029 pub terminator: Option<Terminator<'tcx>>,
1031 /// If true, this block lies on an unwind path. This is used
1032 /// during codegen where distinct kinds of basic blocks may be
1033 /// generated (particularly for MSVC cleanup). Unwind blocks must
1034 /// only branch to other unwind blocks.
1035 pub is_cleanup: bool,
1038 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1039 pub struct Terminator<'tcx> {
1040 pub source_info: SourceInfo,
1041 pub kind: TerminatorKind<'tcx>,
1044 #[derive(Clone, RustcEncodable, RustcDecodable)]
1045 pub enum TerminatorKind<'tcx> {
1046 /// block should have one successor in the graph; we jump there
1047 Goto { target: BasicBlock },
1049 /// operand evaluates to an integer; jump depending on its value
1050 /// to one of the targets, and otherwise fallback to `otherwise`
1052 /// discriminant value being tested
1053 discr: Operand<'tcx>,
1055 /// type of value being tested
1056 switch_ty: Ty<'tcx>,
1058 /// Possible values. The locations to branch to in each case
1059 /// are found in the corresponding indices from the `targets` vector.
1060 values: Cow<'tcx, [u128]>,
1062 /// Possible branch sites. The last element of this vector is used
1063 /// for the otherwise branch, so targets.len() == values.len() + 1
1065 // This invariant is quite non-obvious and also could be improved.
1066 // One way to make this invariant is to have something like this instead:
1068 // branches: Vec<(ConstInt, BasicBlock)>,
1069 // otherwise: Option<BasicBlock> // exhaustive if None
1071 // However we’ve decided to keep this as-is until we figure a case
1072 // where some other approach seems to be strictly better than other.
1073 targets: Vec<BasicBlock>,
1076 /// Indicates that the landing pad is finished and unwinding should
1077 /// continue. Emitted by build::scope::diverge_cleanup.
1080 /// Indicates that the landing pad is finished and that the process
1081 /// should abort. Used to prevent unwinding for foreign items.
1084 /// Indicates a normal return. The return place should have
1085 /// been filled in by now. This should occur at most once.
1088 /// Indicates a terminator that can never be reached.
1093 location: Place<'tcx>,
1095 unwind: Option<BasicBlock>,
1098 /// Drop the Place and assign the new value over it. This ensures
1099 /// that the assignment to `P` occurs *even if* the destructor for
1100 /// place unwinds. Its semantics are best explained by the
1105 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1113 /// Drop(P, goto BB1, unwind BB2)
1116 /// // P is now uninitialized
1120 /// // P is now uninitialized -- its dtor panicked
1125 location: Place<'tcx>,
1126 value: Operand<'tcx>,
1128 unwind: Option<BasicBlock>,
1131 /// Block ends with a call of a converging function
1133 /// The function that’s being called
1134 func: Operand<'tcx>,
1135 /// Arguments the function is called with.
1136 /// These are owned by the callee, which is free to modify them.
1137 /// This allows the memory occupied by "by-value" arguments to be
1138 /// reused across function calls without duplicating the contents.
1139 args: Vec<Operand<'tcx>>,
1140 /// Destination for the return value. If some, the call is converging.
1141 destination: Option<(Place<'tcx>, BasicBlock)>,
1142 /// Cleanups to be done if the call unwinds.
1143 cleanup: Option<BasicBlock>,
1144 /// Whether this is from a call in HIR, rather than from an overloaded
1145 /// operator. True for overloaded function call.
1146 from_hir_call: bool,
1149 /// Jump to the target if the condition has the expected value,
1150 /// otherwise panic with a message and a cleanup target.
1152 cond: Operand<'tcx>,
1154 msg: AssertMessage<'tcx>,
1156 cleanup: Option<BasicBlock>,
1161 /// The value to return
1162 value: Operand<'tcx>,
1163 /// Where to resume to
1165 /// Cleanup to be done if the generator is dropped at this suspend point
1166 drop: Option<BasicBlock>,
1169 /// Indicates the end of the dropping of a generator
1172 /// A block where control flow only ever takes one real path, but borrowck
1173 /// needs to be more conservative.
1175 /// The target normal control flow will take
1176 real_target: BasicBlock,
1177 /// The list of blocks control flow could conceptually take, but won't
1179 imaginary_targets: Vec<BasicBlock>,
1181 /// A terminator for blocks that only take one path in reality, but where we
1182 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1183 /// This can arise in infinite loops with no function calls for example.
1185 /// The target normal control flow will take
1186 real_target: BasicBlock,
1187 /// The imaginary cleanup block link. This particular path will never be taken
1188 /// in practice, but in order to avoid fragility we want to always
1189 /// consider it in borrowck. We don't want to accept programs which
1190 /// pass borrowck only when panic=abort or some assertions are disabled
1191 /// due to release vs. debug mode builds. This needs to be an Option because
1192 /// of the remove_noop_landing_pads and no_landing_pads passes
1193 unwind: Option<BasicBlock>,
1197 pub type Successors<'a> =
1198 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1199 pub type SuccessorsMut<'a> =
1200 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1202 impl<'tcx> Terminator<'tcx> {
1203 pub fn successors(&self) -> Successors<'_> {
1204 self.kind.successors()
1207 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1208 self.kind.successors_mut()
1211 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1215 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1216 self.kind.unwind_mut()
1220 impl<'tcx> TerminatorKind<'tcx> {
1221 pub fn if_<'a, 'gcx>(
1222 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1223 cond: Operand<'tcx>,
1226 ) -> TerminatorKind<'tcx> {
1227 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1228 TerminatorKind::SwitchInt {
1230 switch_ty: tcx.types.bool,
1231 values: From::from(BOOL_SWITCH_FALSE),
1232 targets: vec![f, t],
1236 pub fn successors(&self) -> Successors<'_> {
1237 use self::TerminatorKind::*;
1248 } => None.into_iter().chain(&[]),
1249 Goto { target: ref t }
1252 cleanup: Some(ref t),
1256 destination: Some((_, ref t)),
1283 } => Some(t).into_iter().chain(&[]),
1285 destination: Some((_, ref t)),
1286 cleanup: Some(ref u),
1296 unwind: Some(ref u),
1301 unwind: Some(ref u),
1306 cleanup: Some(ref u),
1311 unwind: Some(ref u),
1312 } => Some(t).into_iter().chain(slice::from_ref(u)),
1313 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1316 ref imaginary_targets,
1317 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1321 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1322 use self::TerminatorKind::*;
1333 } => None.into_iter().chain(&mut []),
1334 Goto { target: ref mut t }
1337 cleanup: Some(ref mut t),
1341 destination: Some((_, ref mut t)),
1366 real_target: ref mut t,
1368 } => Some(t).into_iter().chain(&mut []),
1370 destination: Some((_, ref mut t)),
1371 cleanup: Some(ref mut u),
1376 drop: Some(ref mut u),
1381 unwind: Some(ref mut u),
1386 unwind: Some(ref mut u),
1391 cleanup: Some(ref mut u),
1395 real_target: ref mut t,
1396 unwind: Some(ref mut u),
1397 } => Some(t).into_iter().chain(slice::from_mut(u)),
1400 } => None.into_iter().chain(&mut targets[..]),
1402 ref mut real_target,
1403 ref mut imaginary_targets,
1404 } => Some(real_target)
1406 .chain(&mut imaginary_targets[..]),
1410 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1412 TerminatorKind::Goto { .. }
1413 | TerminatorKind::Resume
1414 | TerminatorKind::Abort
1415 | TerminatorKind::Return
1416 | TerminatorKind::Unreachable
1417 | TerminatorKind::GeneratorDrop
1418 | TerminatorKind::Yield { .. }
1419 | TerminatorKind::SwitchInt { .. }
1420 | TerminatorKind::FalseEdges { .. } => None,
1421 TerminatorKind::Call {
1422 cleanup: ref unwind,
1425 | TerminatorKind::Assert {
1426 cleanup: ref unwind,
1429 | TerminatorKind::DropAndReplace { ref unwind, .. }
1430 | TerminatorKind::Drop { ref unwind, .. }
1431 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1435 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1437 TerminatorKind::Goto { .. }
1438 | TerminatorKind::Resume
1439 | TerminatorKind::Abort
1440 | TerminatorKind::Return
1441 | TerminatorKind::Unreachable
1442 | TerminatorKind::GeneratorDrop
1443 | TerminatorKind::Yield { .. }
1444 | TerminatorKind::SwitchInt { .. }
1445 | TerminatorKind::FalseEdges { .. } => None,
1446 TerminatorKind::Call {
1447 cleanup: ref mut unwind,
1450 | TerminatorKind::Assert {
1451 cleanup: ref mut unwind,
1454 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1455 | TerminatorKind::Drop { ref mut unwind, .. }
1456 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1461 impl<'tcx> BasicBlockData<'tcx> {
1462 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1470 /// Accessor for terminator.
1472 /// Terminator may not be None after construction of the basic block is complete. This accessor
1473 /// provides a convenience way to reach the terminator.
1474 pub fn terminator(&self) -> &Terminator<'tcx> {
1475 self.terminator.as_ref().expect("invalid terminator state")
1478 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1479 self.terminator.as_mut().expect("invalid terminator state")
1482 pub fn retain_statements<F>(&mut self, mut f: F)
1484 F: FnMut(&mut Statement<'_>) -> bool,
1486 for s in &mut self.statements {
1493 pub fn expand_statements<F, I>(&mut self, mut f: F)
1495 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1496 I: iter::TrustedLen<Item = Statement<'tcx>>,
1498 // Gather all the iterators we'll need to splice in, and their positions.
1499 let mut splices: Vec<(usize, I)> = vec![];
1500 let mut extra_stmts = 0;
1501 for (i, s) in self.statements.iter_mut().enumerate() {
1502 if let Some(mut new_stmts) = f(s) {
1503 if let Some(first) = new_stmts.next() {
1504 // We can already store the first new statement.
1507 // Save the other statements for optimized splicing.
1508 let remaining = new_stmts.size_hint().0;
1510 splices.push((i + 1 + extra_stmts, new_stmts));
1511 extra_stmts += remaining;
1519 // Splice in the new statements, from the end of the block.
1520 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1521 // where a range of elements ("gap") is left uninitialized, with
1522 // splicing adding new elements to the end of that gap and moving
1523 // existing elements from before the gap to the end of the gap.
1524 // For now, this is safe code, emulating a gap but initializing it.
1525 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1526 self.statements.resize(
1529 source_info: SourceInfo {
1531 scope: OUTERMOST_SOURCE_SCOPE,
1533 kind: StatementKind::Nop,
1536 for (splice_start, new_stmts) in splices.into_iter().rev() {
1537 let splice_end = splice_start + new_stmts.size_hint().0;
1538 while gap.end > splice_end {
1541 self.statements.swap(gap.start, gap.end);
1543 self.statements.splice(splice_start..splice_end, new_stmts);
1544 gap.end = splice_start;
1548 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1549 if index < self.statements.len() {
1550 &self.statements[index]
1557 impl<'tcx> Debug for TerminatorKind<'tcx> {
1558 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1559 self.fmt_head(fmt)?;
1560 let successor_count = self.successors().count();
1561 let labels = self.fmt_successor_labels();
1562 assert_eq!(successor_count, labels.len());
1564 match successor_count {
1567 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1570 write!(fmt, " -> [")?;
1571 for (i, target) in self.successors().enumerate() {
1575 write!(fmt, "{}: {:?}", labels[i], target)?;
1583 impl<'tcx> TerminatorKind<'tcx> {
1584 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1585 /// successor basic block, if any. The only information not included is the list of possible
1586 /// successors, which may be rendered differently between the text and the graphviz format.
1587 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1588 use self::TerminatorKind::*;
1590 Goto { .. } => write!(fmt, "goto"),
1592 discr: ref place, ..
1593 } => write!(fmt, "switchInt({:?})", place),
1594 Return => write!(fmt, "return"),
1595 GeneratorDrop => write!(fmt, "generator_drop"),
1596 Resume => write!(fmt, "resume"),
1597 Abort => write!(fmt, "abort"),
1598 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1599 Unreachable => write!(fmt, "unreachable"),
1600 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1605 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1612 if let Some((ref destination, _)) = *destination {
1613 write!(fmt, "{:?} = ", destination)?;
1615 write!(fmt, "{:?}(", func)?;
1616 for (index, arg) in args.iter().enumerate() {
1620 write!(fmt, "{:?}", arg)?;
1630 write!(fmt, "assert(")?;
1634 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1636 FalseEdges { .. } => write!(fmt, "falseEdges"),
1637 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1641 /// Return the list of labels for the edges to the successor basic blocks.
1642 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1643 use self::TerminatorKind::*;
1645 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1646 Goto { .. } => vec!["".into()],
1652 let size = ty::tls::with(|tcx| {
1653 let param_env = ty::ParamEnv::empty();
1654 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1655 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1660 let mut s = String::new();
1662 val: ConstValue::Scalar(
1665 size: size.bytes() as u8,
1670 fmt_const_val(&mut s, &c).unwrap();
1672 }).chain(iter::once("otherwise".into()))
1676 destination: Some(_),
1679 } => vec!["return".into(), "unwind".into()],
1681 destination: Some(_),
1684 } => vec!["return".into()],
1689 } => vec!["unwind".into()],
1695 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1696 Yield { drop: None, .. } => vec!["resume".into()],
1697 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1698 vec!["return".into()]
1705 } => vec!["return".into(), "unwind".into()],
1706 Assert { cleanup: None, .. } => vec!["".into()],
1707 Assert { .. } => vec!["success".into(), "unwind".into()],
1709 ref imaginary_targets,
1712 let mut l = vec!["real".into()];
1713 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1718 } => vec!["real".into(), "cleanup".into()],
1719 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1724 ///////////////////////////////////////////////////////////////////////////
1727 #[derive(Clone, RustcEncodable, RustcDecodable)]
1728 pub struct Statement<'tcx> {
1729 pub source_info: SourceInfo,
1730 pub kind: StatementKind<'tcx>,
1733 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1734 #[cfg(target_arch = "x86_64")]
1735 static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Statement<'_>>() == 56);
1737 impl<'tcx> Statement<'tcx> {
1738 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1739 /// invalidating statement indices in `Location`s.
1740 pub fn make_nop(&mut self) {
1741 self.kind = StatementKind::Nop
1744 /// Changes a statement to a nop and returns the original statement.
1745 pub fn replace_nop(&mut self) -> Self {
1747 source_info: self.source_info,
1748 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1753 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1754 pub enum StatementKind<'tcx> {
1755 /// Write the RHS Rvalue to the LHS Place.
1756 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1758 /// This represents all the reading that a pattern match may do
1759 /// (e.g., inspecting constants and discriminant values), and the
1760 /// kind of pattern it comes from. This is in order to adapt potential
1761 /// error messages to these specific patterns.
1763 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1764 /// never accessed still get some sanity checks for e.g. `let x: ! = ..;`
1765 FakeRead(FakeReadCause, Place<'tcx>),
1767 /// Write the discriminant for a variant to the enum Place.
1770 variant_index: VariantIdx,
1773 /// Start a live range for the storage of the local.
1776 /// End the current live range for the storage of the local.
1779 /// Execute a piece of inline Assembly.
1781 asm: Box<InlineAsm>,
1782 outputs: Box<[Place<'tcx>]>,
1783 inputs: Box<[(Span, Operand<'tcx>)]>,
1786 /// Retag references in the given place, ensuring they got fresh tags. This is
1787 /// part of the Stacked Borrows model. These statements are currently only interpreted
1788 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1789 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1790 /// for more details.
1792 /// `fn_entry` indicates whether this is the initial retag that happens in the
1793 /// function prolog.
1795 /// `two_phase` indicates whether this is just the reservation action of
1796 /// a two-phase borrow.
1798 /// The place to retag
1802 /// Escape the given reference to a raw pointer, so that it can be accessed
1803 /// without precise provenance tracking. These statements are currently only interpreted
1804 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1805 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1806 /// for more details.
1807 EscapeToRaw(Operand<'tcx>),
1809 /// Encodes a user's type ascription. These need to be preserved
1810 /// intact so that NLL can respect them. For example:
1814 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1815 /// to the user-given type `T`. The effect depends on the specified variance:
1817 /// - `Covariant` -- requires that `T_y <: T`
1818 /// - `Contravariant` -- requires that `T_y :> T`
1819 /// - `Invariant` -- requires that `T_y == T`
1820 /// - `Bivariant` -- no effect
1821 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection<'tcx>>),
1823 /// No-op. Useful for deleting instructions without affecting statement indices.
1827 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1828 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1829 pub enum FakeReadCause {
1830 /// Inject a fake read of the borrowed input at the start of each arm's
1831 /// pattern testing code.
1833 /// This should ensure that you cannot change the variant for an enum
1834 /// while you are in the midst of matching on it.
1837 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1838 /// generate a read of x to check that it is initialized and safe.
1841 /// Officially, the semantics of
1843 /// `let pattern = <expr>;`
1845 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1846 /// into the pattern.
1848 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1849 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1850 /// but in some cases it can affect the borrow checker, as in #53695.
1851 /// Therefore, we insert a "fake read" here to ensure that we get
1852 /// appropriate errors.
1856 impl<'tcx> Debug for Statement<'tcx> {
1857 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1858 use self::StatementKind::*;
1860 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1861 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1862 Retag { fn_entry, two_phase, ref place } =>
1863 write!(fmt, "Retag({}{}{:?})",
1864 if fn_entry { "[fn entry] " } else { "" },
1865 if two_phase { "[2phase] " } else { "" },
1868 EscapeToRaw(ref place) => write!(fmt, "EscapeToRaw({:?})", place),
1869 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1870 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1874 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1879 } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1880 AscribeUserType(ref place, ref variance, ref c_ty) => {
1881 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1883 Nop => write!(fmt, "nop"),
1888 ///////////////////////////////////////////////////////////////////////////
1891 /// A path to a value; something that can be evaluated without
1892 /// changing or disturbing program state.
1893 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1894 pub enum Place<'tcx> {
1898 /// static or static mut variable
1899 Static(Box<Static<'tcx>>),
1901 /// Constant code promoted to an injected static
1902 Promoted(Box<(Promoted, Ty<'tcx>)>),
1904 /// projection out of a place (access a field, deref a pointer, etc)
1905 Projection(Box<PlaceProjection<'tcx>>),
1908 /// The def-id of a static, along with its normalized type (which is
1909 /// stored to avoid requiring normalization when reading MIR).
1910 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1911 pub struct Static<'tcx> {
1916 impl_stable_hash_for!(struct Static<'tcx> {
1921 /// The `Projection` data structure defines things of the form `B.x`
1922 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1923 /// shared between `Constant` and `Place`. See the aliases
1924 /// `PlaceProjection` etc below.
1925 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1926 pub struct Projection<'tcx, B, V, T> {
1928 pub elem: ProjectionElem<'tcx, V, T>,
1931 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1932 pub enum ProjectionElem<'tcx, V, T> {
1937 /// These indices are generated by slice patterns. Easiest to explain
1941 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1942 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1943 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1944 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1947 /// index or -index (in Python terms), depending on from_end
1949 /// thing being indexed must be at least this long
1951 /// counting backwards from end?
1955 /// These indices are generated by slice patterns.
1957 /// slice[from:-to] in Python terms.
1963 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1964 /// this for ADTs with more than one variant. It may be better to
1965 /// just introduce it always, or always for enums.
1966 Downcast(&'tcx AdtDef, VariantIdx),
1969 /// Alias for projections as they appear in places, where the base is a place
1970 /// and the index is a local.
1971 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1973 /// Alias for projections as they appear in places, where the base is a place
1974 /// and the index is a local.
1975 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1977 // at least on 64 bit systems, `PlaceElem` should not be larger than two pointers
1978 static_assert!(PROJECTION_ELEM_IS_2_PTRS_LARGE:
1979 mem::size_of::<PlaceElem<'_>>() <= 16
1982 /// Alias for projections as they appear in `UserTypeProjection`, where we
1983 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1984 pub type ProjectionKind<'tcx> = ProjectionElem<'tcx, (), ()>;
1988 DEBUG_FORMAT = "field[{}]"
1992 impl<'tcx> Place<'tcx> {
1993 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1994 self.elem(ProjectionElem::Field(f, ty))
1997 pub fn deref(self) -> Place<'tcx> {
1998 self.elem(ProjectionElem::Deref)
2001 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
2002 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
2005 pub fn index(self, index: Local) -> Place<'tcx> {
2006 self.elem(ProjectionElem::Index(index))
2009 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2010 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
2013 /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
2014 /// a single deref of a local.
2016 /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2017 pub fn local(&self) -> Option<Local> {
2019 Place::Local(local) |
2020 Place::Projection(box Projection {
2021 base: Place::Local(local),
2022 elem: ProjectionElem::Deref,
2028 /// Find the innermost `Local` from this `Place`.
2029 pub fn base_local(&self) -> Option<Local> {
2031 Place::Local(local) => Some(*local),
2032 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2033 Place::Promoted(..) | Place::Static(..) => None,
2038 impl<'tcx> Debug for Place<'tcx> {
2039 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2043 Local(id) => write!(fmt, "{:?}", id),
2044 Static(box self::Static { def_id, ty }) => write!(
2047 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2050 Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2051 Projection(ref data) => match data.elem {
2052 ProjectionElem::Downcast(ref adt_def, index) => {
2053 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2055 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2056 ProjectionElem::Field(field, ty) => {
2057 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2059 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2060 ProjectionElem::ConstantIndex {
2064 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2065 ProjectionElem::ConstantIndex {
2069 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2070 ProjectionElem::Subslice { from, to } if to == 0 => {
2071 write!(fmt, "{:?}[{:?}:]", data.base, from)
2073 ProjectionElem::Subslice { from, to } if from == 0 => {
2074 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2076 ProjectionElem::Subslice { from, to } => {
2077 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2084 ///////////////////////////////////////////////////////////////////////////
2088 pub struct SourceScope {
2089 DEBUG_FORMAT = "scope[{}]",
2090 const OUTERMOST_SOURCE_SCOPE = 0,
2094 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2095 pub struct SourceScopeData {
2097 pub parent_scope: Option<SourceScope>,
2100 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2101 pub struct SourceScopeLocalData {
2102 /// A NodeId with lint levels equivalent to this scope's lint levels.
2103 pub lint_root: ast::NodeId,
2104 /// The unsafe block that contains this node.
2108 ///////////////////////////////////////////////////////////////////////////
2111 /// These are values that can appear inside an rvalue. They are intentionally
2112 /// limited to prevent rvalues from being nested in one another.
2113 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
2114 pub enum Operand<'tcx> {
2115 /// Copy: The value must be available for use afterwards.
2117 /// This implies that the type of the place must be `Copy`; this is true
2118 /// by construction during build, but also checked by the MIR type checker.
2121 /// Move: The value (including old borrows of it) will not be used again.
2123 /// Safe for values of all types (modulo future developments towards `?Move`).
2124 /// Correct usage patterns are enforced by the borrow checker for safe code.
2125 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2128 /// Synthesizes a constant value.
2129 Constant(Box<Constant<'tcx>>),
2132 impl<'tcx> Debug for Operand<'tcx> {
2133 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2134 use self::Operand::*;
2136 Constant(ref a) => write!(fmt, "{:?}", a),
2137 Copy(ref place) => write!(fmt, "{:?}", place),
2138 Move(ref place) => write!(fmt, "move {:?}", place),
2143 impl<'tcx> Operand<'tcx> {
2144 /// Convenience helper to make a constant that refers to the fn
2145 /// with given def-id and substs. Since this is used to synthesize
2146 /// MIR, assumes `user_ty` is None.
2147 pub fn function_handle<'a>(
2148 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2150 substs: &'tcx Substs<'tcx>,
2153 let ty = tcx.type_of(def_id).subst(tcx, substs);
2154 Operand::Constant(box Constant {
2158 literal: ty::Const::zero_sized(tcx, ty),
2162 pub fn to_copy(&self) -> Self {
2164 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2165 Operand::Move(ref place) => Operand::Copy(place.clone()),
2170 ///////////////////////////////////////////////////////////////////////////
2173 #[derive(Clone, RustcEncodable, RustcDecodable)]
2174 pub enum Rvalue<'tcx> {
2175 /// x (either a move or copy, depending on type of x)
2179 Repeat(Operand<'tcx>, u64),
2182 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2184 /// length of a [X] or [X;n] value
2187 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2189 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2190 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2192 NullaryOp(NullOp, Ty<'tcx>),
2193 UnaryOp(UnOp, Operand<'tcx>),
2195 /// Read the discriminant of an ADT.
2197 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2198 /// be defined to return, say, a 0) if ADT is not an enum.
2199 Discriminant(Place<'tcx>),
2201 /// Create an aggregate value, like a tuple or struct. This is
2202 /// only needed because we want to distinguish `dest = Foo { x:
2203 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2204 /// that `Foo` has a destructor. These rvalues can be optimized
2205 /// away after type-checking and before lowering.
2206 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2209 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2213 /// Convert unique, zero-sized type for a fn to fn()
2216 /// Convert non capturing closure to fn()
2219 /// Convert safe fn() to unsafe fn()
2222 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2223 /// codegen must figure out the details once full monomorphization
2224 /// is known. For example, this could be used to cast from a
2225 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<dyn Trait>`
2226 /// (presuming `T: Trait`).
2230 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2231 pub enum AggregateKind<'tcx> {
2232 /// The type is of the element
2236 /// The second field is the variant index. It's equal to 0 for struct
2237 /// and union expressions. The fourth field is
2238 /// active field number and is present only for union expressions
2239 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2240 /// active field index would identity the field `c`
2245 Option<UserTypeAnnotation<'tcx>>,
2249 Closure(DefId, ClosureSubsts<'tcx>),
2250 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2253 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2255 /// The `+` operator (addition)
2257 /// The `-` operator (subtraction)
2259 /// The `*` operator (multiplication)
2261 /// The `/` operator (division)
2263 /// The `%` operator (modulus)
2265 /// The `^` operator (bitwise xor)
2267 /// The `&` operator (bitwise and)
2269 /// The `|` operator (bitwise or)
2271 /// The `<<` operator (shift left)
2273 /// The `>>` operator (shift right)
2275 /// The `==` operator (equality)
2277 /// The `<` operator (less than)
2279 /// The `<=` operator (less than or equal to)
2281 /// The `!=` operator (not equal to)
2283 /// The `>=` operator (greater than or equal to)
2285 /// The `>` operator (greater than)
2287 /// The `ptr.offset` operator
2292 pub fn is_checkable(self) -> bool {
2295 Add | Sub | Mul | Shl | Shr => true,
2301 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2303 /// Return the size of a value of that type
2305 /// Create a new uninitialized box for a value of that type
2309 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2311 /// The `!` operator for logical inversion
2313 /// The `-` operator for negation
2317 impl<'tcx> Debug for Rvalue<'tcx> {
2318 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2319 use self::Rvalue::*;
2322 Use(ref place) => write!(fmt, "{:?}", place),
2323 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2324 Len(ref a) => write!(fmt, "Len({:?})", a),
2325 Cast(ref kind, ref place, ref ty) => {
2326 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2328 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2329 CheckedBinaryOp(ref op, ref a, ref b) => {
2330 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2332 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2333 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2334 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2335 Ref(region, borrow_kind, ref place) => {
2336 let kind_str = match borrow_kind {
2337 BorrowKind::Shared => "",
2338 BorrowKind::Shallow => "shallow ",
2339 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2342 // When printing regions, add trailing space if necessary.
2343 let region = if ppaux::verbose() || ppaux::identify_regions() {
2344 let mut region = region.to_string();
2345 if region.len() > 0 {
2350 // Do not even print 'static
2353 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2356 Aggregate(ref kind, ref places) => {
2357 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2358 let mut tuple_fmt = fmt.debug_tuple("");
2359 for place in places {
2360 tuple_fmt.field(place);
2366 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2368 AggregateKind::Tuple => match places.len() {
2369 0 => write!(fmt, "()"),
2370 1 => write!(fmt, "({:?},)", places[0]),
2371 _ => fmt_tuple(fmt, places),
2374 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2375 let variant_def = &adt_def.variants[variant];
2377 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
2379 match variant_def.ctor_kind {
2380 CtorKind::Const => Ok(()),
2381 CtorKind::Fn => fmt_tuple(fmt, places),
2382 CtorKind::Fictive => {
2383 let mut struct_fmt = fmt.debug_struct("");
2384 for (field, place) in variant_def.fields.iter().zip(places) {
2385 struct_fmt.field(&field.ident.as_str(), place);
2392 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2393 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
2394 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2395 format!("[closure@{:?}]", node_id)
2397 format!("[closure@{:?}]", tcx.hir().span(node_id))
2399 let mut struct_fmt = fmt.debug_struct(&name);
2401 tcx.with_freevars(node_id, |freevars| {
2402 for (freevar, place) in freevars.iter().zip(places) {
2403 let var_name = tcx.hir().name(freevar.var_id());
2404 struct_fmt.field(&var_name.as_str(), place);
2410 write!(fmt, "[closure]")
2414 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2415 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
2416 let name = format!("[generator@{:?}]", tcx.hir().span(node_id));
2417 let mut struct_fmt = fmt.debug_struct(&name);
2419 tcx.with_freevars(node_id, |freevars| {
2420 for (freevar, place) in freevars.iter().zip(places) {
2421 let var_name = tcx.hir().name(freevar.var_id());
2422 struct_fmt.field(&var_name.as_str(), place);
2424 struct_fmt.field("$state", &places[freevars.len()]);
2425 for i in (freevars.len() + 1)..places.len() {
2427 .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2433 write!(fmt, "[generator]")
2442 ///////////////////////////////////////////////////////////////////////////
2445 /// Two constants are equal if they are the same constant. Note that
2446 /// this does not necessarily mean that they are "==" in Rust -- in
2447 /// particular one must be wary of `NaN`!
2449 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2450 pub struct Constant<'tcx> {
2454 /// Optional user-given type: for something like
2455 /// `collect::<Vec<_>>`, this would be present and would
2456 /// indicate that `Vec<_>` was explicitly specified.
2458 /// Needed for NLL to impose user-given type constraints.
2459 pub user_ty: Option<UserTypeAnnotation<'tcx>>,
2461 pub literal: &'tcx ty::Const<'tcx>,
2464 /// A user-given type annotation attached to a constant. These arise
2465 /// from constants that are named via paths, like `Foo::<A>::new` and
2467 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2468 pub enum UserTypeAnnotation<'tcx> {
2469 Ty(CanonicalTy<'tcx>),
2471 /// The canonical type is the result of `type_of(def_id)` with the
2472 /// given substitutions applied.
2473 TypeOf(DefId, CanonicalUserSubsts<'tcx>),
2476 EnumTypeFoldableImpl! {
2477 impl<'tcx> TypeFoldable<'tcx> for UserTypeAnnotation<'tcx> {
2478 (UserTypeAnnotation::Ty)(ty),
2479 (UserTypeAnnotation::TypeOf)(def, substs),
2484 impl<'a, 'tcx> Lift<'tcx> for UserTypeAnnotation<'a> {
2485 type Lifted = UserTypeAnnotation<'tcx>;
2486 (UserTypeAnnotation::Ty)(ty),
2487 (UserTypeAnnotation::TypeOf)(def, substs),
2491 /// A collection of projections into user types.
2493 /// They are projections because a binding can occur a part of a
2494 /// parent pattern that has been ascribed a type.
2496 /// Its a collection because there can be multiple type ascriptions on
2497 /// the path from the root of the pattern down to the binding itself.
2502 /// struct S<'a>((i32, &'a str), String);
2503 /// let S((_, w): (i32, &'static str), _): S = ...;
2504 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2505 /// // --------------------------------- ^ (2)
2508 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2509 /// ascribed the type `(i32, &'static str)`.
2511 /// The highlights labelled `(2)` show the whole pattern being
2512 /// ascribed the type `S`.
2514 /// In this example, when we descend to `w`, we will have built up the
2515 /// following two projected types:
2517 /// * base: `S`, projection: `(base.0).1`
2518 /// * base: `(i32, &'static str)`, projection: `base.1`
2520 /// The first will lead to the constraint `w: &'1 str` (for some
2521 /// inferred region `'1`). The second will lead to the constraint `w:
2523 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2524 pub struct UserTypeProjections<'tcx> {
2525 pub(crate) contents: Vec<(UserTypeProjection<'tcx>, Span)>,
2528 BraceStructTypeFoldableImpl! {
2529 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections<'tcx> {
2534 impl<'tcx> UserTypeProjections<'tcx> {
2535 pub fn none() -> Self {
2536 UserTypeProjections { contents: vec![] }
2539 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection<'tcx>, Span)>) -> Self {
2540 UserTypeProjections { contents: projs.collect() }
2543 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection<'tcx>, Span)> {
2544 self.contents.iter()
2547 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection<'tcx>> {
2548 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2552 /// Encodes the effect of a user-supplied type annotation on the
2553 /// subcomponents of a pattern. The effect is determined by applying the
2554 /// given list of proejctions to some underlying base type. Often,
2555 /// the projection element list `projs` is empty, in which case this
2556 /// directly encodes a type in `base`. But in the case of complex patterns with
2557 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2558 /// in which case the `projs` vector is used.
2562 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2564 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2565 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2566 /// determined by finding the type of the `.0` field from `T`.
2567 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2568 pub struct UserTypeProjection<'tcx> {
2569 pub base: UserTypeAnnotation<'tcx>,
2570 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
2573 impl<'tcx> Copy for ProjectionKind<'tcx> { }
2575 CloneTypeFoldableAndLiftImpls! { ProjectionKind<'tcx>, }
2577 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection<'tcx> {
2578 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2579 use mir::ProjectionElem::*;
2581 let base = self.base.fold_with(folder);
2582 let projs: Vec<_> = self.projs
2587 Field(f, ()) => Field(f.clone(), ()),
2588 Index(()) => Index(()),
2589 elem => elem.clone(),
2593 UserTypeProjection { base, projs }
2596 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2597 self.base.visit_with(visitor)
2598 // Note: there's nothing in `self.proj` to visit.
2603 pub struct Promoted {
2604 DEBUG_FORMAT = "promoted[{}]"
2608 impl<'tcx> Debug for Constant<'tcx> {
2609 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2610 write!(fmt, "const ")?;
2611 fmt_const_val(fmt, self.literal)
2615 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2616 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2618 let value = const_val.val;
2619 let ty = const_val.ty;
2620 // print some primitives
2621 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2623 Bool if bits == 0 => return write!(f, "false"),
2624 Bool if bits == 1 => return write!(f, "true"),
2625 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2626 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2627 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2629 let bit_width = ty::tls::with(|tcx| {
2630 let ty = tcx.lift_to_global(&ty).unwrap();
2631 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2636 let shift = 128 - bit_width;
2637 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2639 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2643 // print function definitions
2644 if let FnDef(did, _) = ty.sty {
2645 return write!(f, "{}", item_path_str(did));
2647 // print string literals
2648 if let ConstValue::ScalarPair(ptr, len) = value {
2649 if let Scalar::Ptr(ptr) = ptr {
2650 if let Scalar::Bits { bits: len, .. } = len {
2651 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2652 return ty::tls::with(|tcx| {
2653 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2654 if let Some(interpret::AllocKind::Memory(alloc)) = alloc {
2655 assert_eq!(len as usize as u128, len);
2657 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2658 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2659 write!(f, "{:?}", s)
2661 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2668 // just raw dump everything else
2669 write!(f, "{:?}:{}", value, ty)
2672 fn item_path_str(def_id: DefId) -> String {
2673 ty::tls::with(|tcx| tcx.item_path_str(def_id))
2676 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2677 type Node = BasicBlock;
2680 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2681 fn num_nodes(&self) -> usize {
2682 self.basic_blocks.len()
2686 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2687 fn start_node(&self) -> Self::Node {
2692 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2693 fn predecessors<'graph>(
2696 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2697 self.predecessors_for(node).clone().into_iter()
2701 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2702 fn successors<'graph>(
2705 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2706 self.basic_blocks[node].terminator().successors().cloned()
2710 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2711 type Item = BasicBlock;
2712 type Iter = IntoIter<BasicBlock>;
2715 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2716 type Item = BasicBlock;
2717 type Iter = iter::Cloned<Successors<'b>>;
2720 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2721 pub struct Location {
2722 /// the location is within this block
2723 pub block: BasicBlock,
2725 /// the location is the start of the statement; or, if `statement_index`
2726 /// == num-statements, then the start of the terminator.
2727 pub statement_index: usize,
2730 impl fmt::Debug for Location {
2731 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2732 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2737 pub const START: Location = Location {
2742 /// Returns the location immediately after this one within the enclosing block.
2744 /// Note that if this location represents a terminator, then the
2745 /// resulting location would be out of bounds and invalid.
2746 pub fn successor_within_block(&self) -> Location {
2749 statement_index: self.statement_index + 1,
2753 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2754 pub fn is_predecessor_of<'tcx>(&self, other: Location, mir: &Mir<'tcx>) -> bool {
2755 // If we are in the same block as the other location and are an earlier statement
2756 // then we are a predecessor of `other`.
2757 if self.block == other.block && self.statement_index < other.statement_index {
2761 // If we're in another block, then we want to check that block is a predecessor of `other`.
2762 let mut queue: Vec<BasicBlock> = mir.predecessors_for(other.block).clone();
2763 let mut visited = FxHashSet::default();
2765 while let Some(block) = queue.pop() {
2766 // If we haven't visited this block before, then make sure we visit it's predecessors.
2767 if visited.insert(block) {
2768 queue.append(&mut mir.predecessors_for(block).clone());
2773 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2774 // we found that block by looking at the predecessors of `other`).
2775 if self.block == block {
2783 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2784 if self.block == other.block {
2785 self.statement_index <= other.statement_index
2787 dominators.is_dominated_by(other.block, self.block)
2792 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2793 pub enum UnsafetyViolationKind {
2795 /// Right now function calls to `const unsafe fn` are only permitted behind a feature gate
2796 /// Also, even `const unsafe fn` need an `unsafe` block to do the allowed operations.
2798 /// Permitted in const fn and regular fns
2800 ExternStatic(ast::NodeId),
2801 BorrowPacked(ast::NodeId),
2804 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2805 pub struct UnsafetyViolation {
2806 pub source_info: SourceInfo,
2807 pub description: InternedString,
2808 pub details: InternedString,
2809 pub kind: UnsafetyViolationKind,
2812 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2813 pub struct UnsafetyCheckResult {
2814 /// Violations that are propagated *upwards* from this function
2815 pub violations: Lrc<[UnsafetyViolation]>,
2816 /// unsafe blocks in this function, along with whether they are used. This is
2817 /// used for the "unused_unsafe" lint.
2818 pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2821 /// The layout of generator state
2822 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2823 pub struct GeneratorLayout<'tcx> {
2824 pub fields: Vec<LocalDecl<'tcx>>,
2827 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2828 pub struct BorrowCheckResult<'gcx> {
2829 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2830 pub used_mut_upvars: SmallVec<[Field; 8]>,
2833 /// After we borrow check a closure, we are left with various
2834 /// requirements that we have inferred between the free regions that
2835 /// appear in the closure's signature or on its field types. These
2836 /// requirements are then verified and proved by the closure's
2837 /// creating function. This struct encodes those requirements.
2839 /// The requirements are listed as being between various
2840 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2841 /// vids refer to the free regions that appear in the closure (or
2842 /// generator's) type, in order of appearance. (This numbering is
2843 /// actually defined by the `UniversalRegions` struct in the NLL
2844 /// region checker. See for example
2845 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2846 /// regions in the closure's type "as if" they were erased, so their
2847 /// precise identity is not important, only their position.
2849 /// Example: If type check produces a closure with the closure substs:
2852 /// ClosureSubsts = [
2853 /// i8, // the "closure kind"
2854 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2855 /// &'a String, // some upvar
2859 /// here, there is one unique free region (`'a`) but it appears
2860 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2863 /// ClosureSubsts = [
2864 /// i8, // the "closure kind"
2865 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2866 /// &'2 String, // some upvar
2870 /// Now the code might impose a requirement like `'1: '2`. When an
2871 /// instance of the closure is created, the corresponding free regions
2872 /// can be extracted from its type and constrained to have the given
2873 /// outlives relationship.
2875 /// In some cases, we have to record outlives requirements between
2876 /// types and regions as well. In that case, if those types include
2877 /// any regions, those regions are recorded as `ReClosureBound`
2878 /// instances assigned one of these same indices. Those regions will
2879 /// be substituted away by the creator. We use `ReClosureBound` in
2880 /// that case because the regions must be allocated in the global
2881 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2882 /// internally within the rest of the NLL code).
2883 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2884 pub struct ClosureRegionRequirements<'gcx> {
2885 /// The number of external regions defined on the closure. In our
2886 /// example above, it would be 3 -- one for `'static`, then `'1`
2887 /// and `'2`. This is just used for a sanity check later on, to
2888 /// make sure that the number of regions we see at the callsite
2890 pub num_external_vids: usize,
2892 /// Requirements between the various free regions defined in
2894 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2897 /// Indicates an outlives constraint between a type or between two
2898 /// free-regions declared on the closure.
2899 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2900 pub struct ClosureOutlivesRequirement<'tcx> {
2901 // This region or type ...
2902 pub subject: ClosureOutlivesSubject<'tcx>,
2904 // ... must outlive this one.
2905 pub outlived_free_region: ty::RegionVid,
2907 // If not, report an error here ...
2908 pub blame_span: Span,
2910 // ... due to this reason.
2911 pub category: ConstraintCategory,
2914 /// Outlives constraints can be categorized to determine whether and why they
2915 /// are interesting (for error reporting). Order of variants indicates sort
2916 /// order of the category, thereby influencing diagnostic output.
2918 /// See also [rustc_mir::borrow_check::nll::constraints]
2919 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2920 pub enum ConstraintCategory {
2928 /// A constraint that came from checking the body of a closure.
2930 /// We try to get the category that the closure used when reporting this.
2938 /// A "boring" constraint (caused by the given location) is one that
2939 /// the user probably doesn't want to see described in diagnostics,
2940 /// because it is kind of an artifact of the type system setup.
2941 /// Example: `x = Foo { field: y }` technically creates
2942 /// intermediate regions representing the "type of `Foo { field: y
2943 /// }`", and data flows from `y` into those variables, but they
2944 /// are not very interesting. The assignment into `x` on the other
2947 // Boring and applicable everywhere.
2950 /// A constraint that doesn't correspond to anything the user sees.
2954 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2955 /// that must outlive some region.
2956 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2957 pub enum ClosureOutlivesSubject<'tcx> {
2958 /// Subject is a type, typically a type parameter, but could also
2959 /// be a projection. Indicates a requirement like `T: 'a` being
2960 /// passed to the caller, where the type here is `T`.
2962 /// The type here is guaranteed not to contain any free regions at
2966 /// Subject is a free region from the closure. Indicates a requirement
2967 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2968 Region(ty::RegionVid),
2972 * TypeFoldable implementations for MIR types
2975 CloneTypeFoldableAndLiftImpls! {
2984 SourceScopeLocalData,
2987 BraceStructTypeFoldableImpl! {
2988 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2992 source_scope_local_data,
3001 control_flow_destroyed,
3007 BraceStructTypeFoldableImpl! {
3008 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
3013 BraceStructTypeFoldableImpl! {
3014 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3027 BraceStructTypeFoldableImpl! {
3028 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3035 BraceStructTypeFoldableImpl! {
3036 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3041 EnumTypeFoldableImpl! {
3042 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3043 (StatementKind::Assign)(a, b),
3044 (StatementKind::FakeRead)(cause, place),
3045 (StatementKind::SetDiscriminant) { place, variant_index },
3046 (StatementKind::StorageLive)(a),
3047 (StatementKind::StorageDead)(a),
3048 (StatementKind::InlineAsm) { asm, outputs, inputs },
3049 (StatementKind::Retag) { fn_entry, two_phase, place },
3050 (StatementKind::EscapeToRaw)(place),
3051 (StatementKind::AscribeUserType)(a, v, b),
3052 (StatementKind::Nop),
3056 EnumTypeFoldableImpl! {
3057 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3058 (ClearCrossCrate::Clear),
3059 (ClearCrossCrate::Set)(a),
3060 } where T: TypeFoldable<'tcx>
3063 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3064 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3065 use mir::TerminatorKind::*;
3067 let kind = match self.kind {
3068 Goto { target } => Goto { target },
3075 discr: discr.fold_with(folder),
3076 switch_ty: switch_ty.fold_with(folder),
3077 values: values.clone(),
3078 targets: targets.clone(),
3085 location: location.fold_with(folder),
3094 } => DropAndReplace {
3095 location: location.fold_with(folder),
3096 value: value.fold_with(folder),
3105 value: value.fold_with(folder),
3116 let dest = destination
3118 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3121 func: func.fold_with(folder),
3122 args: args.fold_with(folder),
3135 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3136 EvalErrorKind::BoundsCheck {
3137 len: len.fold_with(folder),
3138 index: index.fold_with(folder),
3144 cond: cond.fold_with(folder),
3151 GeneratorDrop => GeneratorDrop,
3155 Unreachable => Unreachable,
3158 ref imaginary_targets,
3161 imaginary_targets: imaginary_targets.clone(),
3172 source_info: self.source_info,
3177 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3178 use mir::TerminatorKind::*;
3185 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3186 Drop { ref location, .. } => location.visit_with(visitor),
3191 } => location.visit_with(visitor) || value.visit_with(visitor),
3192 Yield { ref value, .. } => value.visit_with(visitor),
3199 let dest = if let Some((ref loc, _)) = *destination {
3200 loc.visit_with(visitor)
3204 dest || func.visit_with(visitor) || args.visit_with(visitor)
3207 ref cond, ref msg, ..
3209 if cond.visit_with(visitor) {
3210 if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3211 len.visit_with(visitor) || index.visit_with(visitor)
3226 | FalseUnwind { .. } => false,
3231 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3232 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3234 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3239 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3240 if let &Place::Projection(ref p) = self {
3241 p.visit_with(visitor)
3248 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3249 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3252 Use(ref op) => Use(op.fold_with(folder)),
3253 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3254 Ref(region, bk, ref place) => {
3255 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3257 Len(ref place) => Len(place.fold_with(folder)),
3258 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3259 BinaryOp(op, ref rhs, ref lhs) => {
3260 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3262 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3263 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3265 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3266 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3267 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3268 Aggregate(ref kind, ref fields) => {
3269 let kind = box match **kind {
3270 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3271 AggregateKind::Tuple => AggregateKind::Tuple,
3272 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3275 substs.fold_with(folder),
3276 user_ty.fold_with(folder),
3279 AggregateKind::Closure(id, substs) => {
3280 AggregateKind::Closure(id, substs.fold_with(folder))
3282 AggregateKind::Generator(id, substs, movablity) => {
3283 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3286 Aggregate(kind, fields.fold_with(folder))
3291 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3294 Use(ref op) => op.visit_with(visitor),
3295 Repeat(ref op, _) => op.visit_with(visitor),
3296 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3297 Len(ref place) => place.visit_with(visitor),
3298 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3299 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3300 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3302 UnaryOp(_, ref val) => val.visit_with(visitor),
3303 Discriminant(ref place) => place.visit_with(visitor),
3304 NullaryOp(_, ty) => ty.visit_with(visitor),
3305 Aggregate(ref kind, ref fields) => {
3307 AggregateKind::Array(ty) => ty.visit_with(visitor),
3308 AggregateKind::Tuple => false,
3309 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3310 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3312 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3313 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3314 }) || fields.visit_with(visitor)
3320 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3321 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3323 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3324 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3325 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3329 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3331 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3332 Operand::Constant(ref c) => c.visit_with(visitor),
3337 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3339 B: TypeFoldable<'tcx>,
3340 V: TypeFoldable<'tcx>,
3341 T: TypeFoldable<'tcx>,
3343 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3344 use mir::ProjectionElem::*;
3346 let base = self.base.fold_with(folder);
3347 let elem = match self.elem {
3349 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3350 Index(ref v) => Index(v.fold_with(folder)),
3351 ref elem => elem.clone(),
3354 Projection { base, elem }
3357 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3358 use mir::ProjectionElem::*;
3360 self.base.visit_with(visitor) || match self.elem {
3361 Field(_, ref ty) => ty.visit_with(visitor),
3362 Index(ref v) => v.visit_with(visitor),
3368 impl<'tcx> TypeFoldable<'tcx> for Field {
3369 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3372 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3377 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3378 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3380 span: self.span.clone(),
3381 ty: self.ty.fold_with(folder),
3382 user_ty: self.user_ty.fold_with(folder),
3383 literal: self.literal.fold_with(folder),
3386 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3387 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)