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-nursery.github.io/rustc-guide/mir/index.html
15 use hir::def::CtorKind;
16 use hir::def_id::DefId;
17 use hir::{self, HirId, InlineAsm};
19 use mir::interpret::{ConstValue, EvalErrorKind, Scalar};
20 use mir::visit::MirVisitable;
21 use rustc_apfloat::ieee::{Double, Single};
22 use rustc_apfloat::Float;
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 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};
44 pub use mir::interpret::AssertMessage;
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56 pub trait HasLocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx>;
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx> {
66 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
67 fn local_decls(&self) -> &LocalDecls<'tcx> {
72 /// The various "big phases" that MIR goes through.
74 /// Warning: ordering of variants is significant
75 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
84 /// Gets the index of the current MirPhase within the set of all MirPhases.
85 pub fn phase_index(&self) -> usize {
90 /// Lowered representation of a single function.
91 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
92 pub struct Mir<'tcx> {
93 /// 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>>,
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.
104 /// 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>,
108 /// Crate-local information for each source scope, that can't (and
109 /// needn't) be tracked across crates.
110 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
112 /// Rvalues promoted from this function, such as borrows of constants.
113 /// Each of them is the Mir of a constant with the fn's type parameters
114 /// in scope, but a separate set of locals.
115 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
117 /// Yield type of the function, if it is a generator.
118 pub yield_ty: Option<Ty<'tcx>>,
120 /// Generator drop glue
121 pub generator_drop: Option<Box<Mir<'tcx>>>,
123 /// The layout of a generator. Produced by the state transformation.
124 pub generator_layout: Option<GeneratorLayout<'tcx>>,
126 /// Declarations of locals.
128 /// The first local is the return value pointer, followed by `arg_count`
129 /// locals for the function arguments, followed by any user-declared
130 /// variables and temporaries.
131 pub local_decls: LocalDecls<'tcx>,
133 /// Number of arguments this function takes.
135 /// Starting at local 1, `arg_count` locals will be provided by the caller
136 /// and can be assumed to be initialized.
138 /// If this MIR was built for a constant, this will be 0.
139 pub arg_count: usize,
141 /// Names and capture modes of all the closure upvars, assuming
142 /// the first argument is either the closure or a reference to it.
143 pub upvar_decls: Vec<UpvarDecl>,
145 /// Mark an argument local (which must be a tuple) as getting passed as
146 /// its individual components at the LLVM level.
148 /// This is used for the "rust-call" ABI.
149 pub spread_arg: Option<Local>,
151 /// A span representing this MIR, for error reporting
154 /// A cache for various calculations
158 impl<'tcx> Mir<'tcx> {
160 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
161 source_scopes: IndexVec<SourceScope, SourceScopeData>,
162 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
163 promoted: IndexVec<Promoted, Mir<'tcx>>,
164 yield_ty: Option<Ty<'tcx>>,
165 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
167 upvar_decls: Vec<UpvarDecl>,
170 // We need `arg_count` locals, and one for the return place
172 local_decls.len() >= arg_count + 1,
173 "expected at least {} locals, got {}",
179 phase: MirPhase::Build,
182 source_scope_local_data,
185 generator_drop: None,
186 generator_layout: None,
192 cache: cache::Cache::new(),
197 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
202 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
203 self.cache.invalidate();
204 &mut self.basic_blocks
208 pub fn basic_blocks_and_local_decls_mut(
211 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
212 &mut LocalDecls<'tcx>,
214 self.cache.invalidate();
215 (&mut self.basic_blocks, &mut self.local_decls)
219 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
220 self.cache.predecessors(self)
224 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
225 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
229 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
230 let if_zero_locations = if loc.statement_index == 0 {
231 let predecessor_blocks = self.predecessors_for(loc.block);
232 let num_predecessor_blocks = predecessor_blocks.len();
234 (0..num_predecessor_blocks)
235 .map(move |i| predecessor_blocks[i])
236 .map(move |bb| self.terminator_loc(bb)),
242 let if_not_zero_locations = if loc.statement_index == 0 {
247 statement_index: loc.statement_index - 1,
254 .chain(if_not_zero_locations)
258 pub fn dominators(&self) -> Dominators<BasicBlock> {
263 pub fn local_kind(&self, local: Local) -> LocalKind {
264 let index = local.as_usize();
267 self.local_decls[local].mutability == Mutability::Mut,
268 "return place should be mutable"
271 LocalKind::ReturnPointer
272 } else if index < self.arg_count + 1 {
274 } else if self.local_decls[local].name.is_some() {
281 /// Returns an iterator over all temporaries.
283 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
284 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
285 let local = Local::new(index);
286 if self.local_decls[local].is_user_variable.is_some() {
294 /// Returns an iterator over all user-declared locals.
296 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
297 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
298 let local = Local::new(index);
299 if self.local_decls[local].is_user_variable.is_some() {
307 /// Returns an iterator over all user-declared mutable locals.
309 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
310 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
311 let local = Local::new(index);
312 let decl = &self.local_decls[local];
313 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
321 /// Returns an iterator over all user-declared mutable arguments and locals.
323 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
324 (1..self.local_decls.len()).filter_map(move |index| {
325 let local = Local::new(index);
326 let decl = &self.local_decls[local];
327 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
328 && decl.mutability == Mutability::Mut
337 /// Returns an iterator over all function arguments.
339 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
340 let arg_count = self.arg_count;
341 (1..arg_count + 1).map(Local::new)
344 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
345 /// locals that are neither arguments nor the return place).
347 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
348 let arg_count = self.arg_count;
349 let local_count = self.local_decls.len();
350 (arg_count + 1..local_count).map(Local::new)
353 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
354 /// invalidating statement indices in `Location`s.
355 pub fn make_statement_nop(&mut self, location: Location) {
356 let block = &mut self[location.block];
357 debug_assert!(location.statement_index < block.statements.len());
358 block.statements[location.statement_index].make_nop()
361 /// Returns the source info associated with `location`.
362 pub fn source_info(&self, location: Location) -> &SourceInfo {
363 let block = &self[location.block];
364 let stmts = &block.statements;
365 let idx = location.statement_index;
366 if idx < stmts.len() {
367 &stmts[idx].source_info
369 assert_eq!(idx, stmts.len());
370 &block.terminator().source_info
374 /// Check if `sub` is a sub scope of `sup`
375 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
377 match self.source_scopes[sub].parent_scope {
378 None => return false,
385 /// Return the return type, it always return first element from `local_decls` array
386 pub fn return_ty(&self) -> Ty<'tcx> {
387 self.local_decls[RETURN_PLACE].ty
390 /// Get the location of the terminator for the given block
391 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
394 statement_index: self[bb].statements.len(),
399 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
402 /// Unsafe because of a PushUnsafeBlock
404 /// Unsafe because of an unsafe fn
406 /// Unsafe because of an `unsafe` block
407 ExplicitUnsafe(ast::NodeId),
410 impl_stable_hash_for!(struct Mir<'tcx> {
414 source_scope_local_data,
427 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
428 type Output = BasicBlockData<'tcx>;
431 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
432 &self.basic_blocks()[index]
436 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
438 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
439 &mut self.basic_blocks_mut()[index]
443 #[derive(Copy, Clone, Debug)]
444 pub enum ClearCrossCrate<T> {
449 impl<T> ClearCrossCrate<T> {
450 pub fn assert_crate_local(self) -> T {
452 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
453 ClearCrossCrate::Set(v) => v,
458 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
459 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
461 /// Grouped information about the source code origin of a MIR entity.
462 /// Intended to be inspected by diagnostics and debuginfo.
463 /// Most passes can work with it as a whole, within a single function.
464 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
465 pub struct SourceInfo {
466 /// Source span for the AST pertaining to this MIR entity.
469 /// The source scope, keeping track of which bindings can be
470 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
471 pub scope: SourceScope,
474 ///////////////////////////////////////////////////////////////////////////
475 // Mutability and borrow kinds
477 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
478 pub enum Mutability {
483 impl From<Mutability> for hir::Mutability {
484 fn from(m: Mutability) -> Self {
486 Mutability::Mut => hir::MutMutable,
487 Mutability::Not => hir::MutImmutable,
492 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
493 pub enum BorrowKind {
494 /// Data must be immutable and is aliasable.
497 /// The immediately borrowed place must be immutable, but projections from
498 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
499 /// conflict with a mutable borrow of `a.b.c`.
501 /// This is used when lowering matches: when matching on a place we want to
502 /// ensure that place have the same value from the start of the match until
503 /// an arm is selected. This prevents this code from compiling:
505 /// let mut x = &Some(0);
508 /// Some(_) if { x = &None; false } => (),
512 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
513 /// should not prevent `if let None = x { ... }`, for example, because the
514 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
515 /// We can also report errors with this kind of borrow differently.
518 /// Data must be immutable but not aliasable. This kind of borrow
519 /// cannot currently be expressed by the user and is used only in
520 /// implicit closure bindings. It is needed when the closure is
521 /// borrowing or mutating a mutable referent, e.g.:
523 /// let x: &mut isize = ...;
524 /// let y = || *x += 5;
526 /// If we were to try to translate this closure into a more explicit
527 /// form, we'd encounter an error with the code as written:
529 /// struct Env { x: & &mut isize }
530 /// let x: &mut isize = ...;
531 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
532 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
534 /// This is then illegal because you cannot mutate an `&mut` found
535 /// in an aliasable location. To solve, you'd have to translate with
536 /// an `&mut` borrow:
538 /// struct Env { x: & &mut isize }
539 /// let x: &mut isize = ...;
540 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
541 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
543 /// Now the assignment to `**env.x` is legal, but creating a
544 /// mutable pointer to `x` is not because `x` is not mutable. We
545 /// could fix this by declaring `x` as `let mut x`. This is ok in
546 /// user code, if awkward, but extra weird for closures, since the
547 /// borrow is hidden.
549 /// So we introduce a "unique imm" borrow -- the referent is
550 /// immutable, but not aliasable. This solves the problem. For
551 /// simplicity, we don't give users the way to express this
552 /// borrow, it's just used when translating closures.
555 /// Data is mutable and not aliasable.
557 /// True if this borrow arose from method-call auto-ref
558 /// (i.e. `adjustment::Adjust::Borrow`)
559 allow_two_phase_borrow: bool,
564 pub fn allows_two_phase_borrow(&self) -> bool {
566 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
567 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
572 ///////////////////////////////////////////////////////////////////////////
573 // Variables and temps
577 DEBUG_FORMAT = "_{}",
578 const RETURN_PLACE = 0,
582 /// Classifies locals into categories. See `Mir::local_kind`.
583 #[derive(PartialEq, Eq, Debug)]
585 /// User-declared variable binding
587 /// Compiler-introduced temporary
589 /// Function argument
591 /// Location of function's return value
595 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
596 pub struct VarBindingForm<'tcx> {
597 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
598 pub binding_mode: ty::BindingMode,
599 /// If an explicit type was provided for this variable binding,
600 /// this holds the source Span of that type.
602 /// NOTE: If you want to change this to a `HirId`, be wary that
603 /// doing so breaks incremental compilation (as of this writing),
604 /// while a `Span` does not cause our tests to fail.
605 pub opt_ty_info: Option<Span>,
606 /// Place of the RHS of the =, or the subject of the `match` where this
607 /// variable is initialized. None in the case of `let PATTERN;`.
608 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
609 /// (a) the right-hand side isn't evaluated as a place expression.
610 /// (b) it gives a way to separate this case from the remaining cases
612 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
613 /// Span of the pattern in which this variable was bound.
617 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
618 pub enum BindingForm<'tcx> {
619 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
620 Var(VarBindingForm<'tcx>),
621 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
622 ImplicitSelf(ImplicitSelfKind),
623 /// Reference used in a guard expression to ensure immutability.
627 /// Represents what type of implicit self a function has, if any.
628 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
629 pub enum ImplicitSelfKind {
630 /// Represents a `fn x(self);`.
632 /// Represents a `fn x(mut self);`.
634 /// Represents a `fn x(&self);`.
636 /// Represents a `fn x(&mut self);`.
638 /// Represents when a function does not have a self argument or
639 /// when a function has a `self: X` argument.
643 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
645 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
652 impl_stable_hash_for!(enum self::ImplicitSelfKind {
660 impl_stable_hash_for!(enum self::MirPhase {
667 mod binding_form_impl {
668 use ich::StableHashingContext;
669 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
671 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
672 fn hash_stable<W: StableHasherResult>(
674 hcx: &mut StableHashingContext<'a>,
675 hasher: &mut StableHasher<W>,
677 use super::BindingForm::*;
678 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
681 Var(binding) => binding.hash_stable(hcx, hasher),
682 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
689 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
690 /// created during evaluation of expressions in a block tail
691 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
693 /// It is used to improve diagnostics when such temporaries are
694 /// involved in borrow_check errors, e.g. explanations of where the
695 /// temporaries come from, when their destructors are run, and/or how
696 /// one might revise the code to satisfy the borrow checker's rules.
697 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
698 pub struct BlockTailInfo {
699 /// If `true`, then the value resulting from evaluating this tail
700 /// expression is ignored by the block's expression context.
702 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
703 /// but not e.g. `let _x = { ...; tail };`
704 pub tail_result_is_ignored: bool,
707 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
711 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
712 /// argument, or the return place.
713 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
714 pub struct LocalDecl<'tcx> {
715 /// `let mut x` vs `let x`.
717 /// Temporaries and the return place are always mutable.
718 pub mutability: Mutability,
720 /// Some(binding_mode) if this corresponds to a user-declared local variable.
722 /// This is solely used for local diagnostics when generating
723 /// warnings/errors when compiling the current crate, and
724 /// therefore it need not be visible across crates. pnkfelix
725 /// currently hypothesized we *need* to wrap this in a
726 /// `ClearCrossCrate` as long as it carries as `HirId`.
727 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
729 /// True if this is an internal local
731 /// These locals are not based on types in the source code and are only used
732 /// for a few desugarings at the moment.
734 /// The generator transformation will sanity check the locals which are live
735 /// across a suspension point against the type components of the generator
736 /// which type checking knows are live across a suspension point. We need to
737 /// flag drop flags to avoid triggering this check as they are introduced
740 /// Unsafety checking will also ignore dereferences of these locals,
741 /// so they can be used for raw pointers only used in a desugaring.
743 /// This should be sound because the drop flags are fully algebraic, and
744 /// therefore don't affect the OIBIT or outlives properties of the
748 /// If this local is a temporary and `is_block_tail` is `Some`,
749 /// then it is a temporary created for evaluation of some
750 /// subexpression of some block's tail expression (with no
751 /// intervening statement context).
752 pub is_block_tail: Option<BlockTailInfo>,
754 /// Type of this local.
757 /// If the user manually ascribed a type to this variable,
758 /// e.g. via `let x: T`, then we carry that type here. The MIR
759 /// borrow checker needs this information since it can affect
760 /// region inference.
761 pub user_ty: UserTypeProjections<'tcx>,
763 /// Name of the local, used in debuginfo and pretty-printing.
765 /// Note that function arguments can also have this set to `Some(_)`
766 /// to generate better debuginfo.
767 pub name: Option<Name>,
769 /// The *syntactic* (i.e. not visibility) source scope the local is defined
770 /// in. If the local was defined in a let-statement, this
771 /// is *within* the let-statement, rather than outside
774 /// This is needed because the visibility source scope of locals within
775 /// a let-statement is weird.
777 /// The reason is that we want the local to be *within* the let-statement
778 /// for lint purposes, but we want the local to be *after* the let-statement
779 /// for names-in-scope purposes.
781 /// That's it, if we have a let-statement like the one in this
785 /// fn foo(x: &str) {
786 /// #[allow(unused_mut)]
787 /// let mut x: u32 = { // <- one unused mut
788 /// let mut y: u32 = x.parse().unwrap();
795 /// Then, from a lint point of view, the declaration of `x: u32`
796 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
797 /// lint scopes are the same as the AST/HIR nesting.
799 /// However, from a name lookup point of view, the scopes look more like
800 /// as if the let-statements were `match` expressions:
803 /// fn foo(x: &str) {
805 /// match x.parse().unwrap() {
814 /// We care about the name-lookup scopes for debuginfo - if the
815 /// debuginfo instruction pointer is at the call to `x.parse()`, we
816 /// want `x` to refer to `x: &str`, but if it is at the call to
817 /// `drop(x)`, we want it to refer to `x: u32`.
819 /// To allow both uses to work, we need to have more than a single scope
820 /// for a local. We have the `source_info.scope` represent the
821 /// "syntactic" lint scope (with a variable being under its let
822 /// block) while the `visibility_scope` represents the "local variable"
823 /// scope (where the "rest" of a block is under all prior let-statements).
825 /// The end result looks like this:
829 /// │{ argument x: &str }
831 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
832 /// │ │ // in practice because I'm lazy.
834 /// │ │← x.source_info.scope
835 /// │ │← `x.parse().unwrap()`
837 /// │ │ │← y.source_info.scope
839 /// │ │ │{ let y: u32 }
841 /// │ │ │← y.visibility_scope
844 /// │ │{ let x: u32 }
845 /// │ │← x.visibility_scope
846 /// │ │← `drop(x)` // this accesses `x: u32`
848 pub source_info: SourceInfo,
850 /// Source scope within which the local is visible (for debuginfo)
851 /// (see `source_info` for more details).
852 pub visibility_scope: SourceScope,
855 impl<'tcx> LocalDecl<'tcx> {
856 /// Returns true only if local is a binding that can itself be
857 /// made mutable via the addition of the `mut` keyword, namely
858 /// something like the occurrences of `x` in:
859 /// - `fn foo(x: Type) { ... }`,
861 /// - or `match ... { C(x) => ... }`
862 pub fn can_be_made_mutable(&self) -> bool {
863 match self.is_user_variable {
864 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
865 binding_mode: ty::BindingMode::BindByValue(_),
871 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
878 /// Returns true if local is definitely not a `ref ident` or
879 /// `ref mut ident` binding. (Such bindings cannot be made into
880 /// mutable bindings, but the inverse does not necessarily hold).
881 pub fn is_nonref_binding(&self) -> bool {
882 match self.is_user_variable {
883 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
884 binding_mode: ty::BindingMode::BindByValue(_),
890 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
896 /// Create a new `LocalDecl` for a temporary.
898 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
899 Self::new_local(ty, Mutability::Mut, false, span)
902 /// Converts `self` into same `LocalDecl` except tagged as immutable.
904 pub fn immutable(mut self) -> Self {
905 self.mutability = Mutability::Not;
909 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
911 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
912 assert!(self.is_block_tail.is_none());
913 self.is_block_tail = Some(info);
917 /// Create a new `LocalDecl` for a internal temporary.
919 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
920 Self::new_local(ty, Mutability::Mut, true, span)
926 mutability: Mutability,
933 user_ty: UserTypeProjections::none(),
935 source_info: SourceInfo {
937 scope: OUTERMOST_SOURCE_SCOPE,
939 visibility_scope: OUTERMOST_SOURCE_SCOPE,
941 is_user_variable: None,
946 /// Builds a `LocalDecl` for the return place.
948 /// This must be inserted into the `local_decls` list as the first local.
950 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
952 mutability: Mutability::Mut,
954 user_ty: UserTypeProjections::none(),
955 source_info: SourceInfo {
957 scope: OUTERMOST_SOURCE_SCOPE,
959 visibility_scope: OUTERMOST_SOURCE_SCOPE,
962 name: None, // FIXME maybe we do want some name here?
963 is_user_variable: None,
968 /// A closure capture, with its name and mode.
969 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
970 pub struct UpvarDecl {
971 pub debug_name: Name,
973 /// `HirId` of the captured variable
974 pub var_hir_id: ClearCrossCrate<HirId>,
976 /// If true, the capture is behind a reference.
979 pub mutability: Mutability,
982 ///////////////////////////////////////////////////////////////////////////
986 pub struct BasicBlock {
987 DEBUG_FORMAT = "bb{}",
988 const START_BLOCK = 0,
993 pub fn start_location(self) -> Location {
1001 ///////////////////////////////////////////////////////////////////////////
1002 // BasicBlockData and Terminator
1004 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1005 pub struct BasicBlockData<'tcx> {
1006 /// List of statements in this block.
1007 pub statements: Vec<Statement<'tcx>>,
1009 /// Terminator for this block.
1011 /// NB. This should generally ONLY be `None` during construction.
1012 /// Therefore, you should generally access it via the
1013 /// `terminator()` or `terminator_mut()` methods. The only
1014 /// exception is that certain passes, such as `simplify_cfg`, swap
1015 /// out the terminator temporarily with `None` while they continue
1016 /// to recurse over the set of basic blocks.
1017 pub terminator: Option<Terminator<'tcx>>,
1019 /// If true, this block lies on an unwind path. This is used
1020 /// during codegen where distinct kinds of basic blocks may be
1021 /// generated (particularly for MSVC cleanup). Unwind blocks must
1022 /// only branch to other unwind blocks.
1023 pub is_cleanup: bool,
1026 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1027 pub struct Terminator<'tcx> {
1028 pub source_info: SourceInfo,
1029 pub kind: TerminatorKind<'tcx>,
1032 #[derive(Clone, RustcEncodable, RustcDecodable)]
1033 pub enum TerminatorKind<'tcx> {
1034 /// block should have one successor in the graph; we jump there
1035 Goto { target: BasicBlock },
1037 /// operand evaluates to an integer; jump depending on its value
1038 /// to one of the targets, and otherwise fallback to `otherwise`
1040 /// discriminant value being tested
1041 discr: Operand<'tcx>,
1043 /// type of value being tested
1044 switch_ty: Ty<'tcx>,
1046 /// Possible values. The locations to branch to in each case
1047 /// are found in the corresponding indices from the `targets` vector.
1048 values: Cow<'tcx, [u128]>,
1050 /// Possible branch sites. The last element of this vector is used
1051 /// for the otherwise branch, so targets.len() == values.len() + 1
1053 // This invariant is quite non-obvious and also could be improved.
1054 // One way to make this invariant is to have something like this instead:
1056 // branches: Vec<(ConstInt, BasicBlock)>,
1057 // otherwise: Option<BasicBlock> // exhaustive if None
1059 // However we’ve decided to keep this as-is until we figure a case
1060 // where some other approach seems to be strictly better than other.
1061 targets: Vec<BasicBlock>,
1064 /// Indicates that the landing pad is finished and unwinding should
1065 /// continue. Emitted by build::scope::diverge_cleanup.
1068 /// Indicates that the landing pad is finished and that the process
1069 /// should abort. Used to prevent unwinding for foreign items.
1072 /// Indicates a normal return. The return place should have
1073 /// been filled in by now. This should occur at most once.
1076 /// Indicates a terminator that can never be reached.
1081 location: Place<'tcx>,
1083 unwind: Option<BasicBlock>,
1086 /// Drop the Place and assign the new value over it. This ensures
1087 /// that the assignment to `P` occurs *even if* the destructor for
1088 /// place unwinds. Its semantics are best explained by the
1093 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1101 /// Drop(P, goto BB1, unwind BB2)
1104 /// // P is now uninitialized
1108 /// // P is now uninitialized -- its dtor panicked
1113 location: Place<'tcx>,
1114 value: Operand<'tcx>,
1116 unwind: Option<BasicBlock>,
1119 /// Block ends with a call of a converging function
1121 /// The function that’s being called
1122 func: Operand<'tcx>,
1123 /// Arguments the function is called with.
1124 /// These are owned by the callee, which is free to modify them.
1125 /// This allows the memory occupied by "by-value" arguments to be
1126 /// reused across function calls without duplicating the contents.
1127 args: Vec<Operand<'tcx>>,
1128 /// Destination for the return value. If some, the call is converging.
1129 destination: Option<(Place<'tcx>, BasicBlock)>,
1130 /// Cleanups to be done if the call unwinds.
1131 cleanup: Option<BasicBlock>,
1132 /// Whether this is from a call in HIR, rather than from an overloaded
1133 /// operator. True for overloaded function call.
1134 from_hir_call: bool,
1137 /// Jump to the target if the condition has the expected value,
1138 /// otherwise panic with a message and a cleanup target.
1140 cond: Operand<'tcx>,
1142 msg: AssertMessage<'tcx>,
1144 cleanup: Option<BasicBlock>,
1149 /// The value to return
1150 value: Operand<'tcx>,
1151 /// Where to resume to
1153 /// Cleanup to be done if the generator is dropped at this suspend point
1154 drop: Option<BasicBlock>,
1157 /// Indicates the end of the dropping of a generator
1160 /// A block where control flow only ever takes one real path, but borrowck
1161 /// needs to be more conservative.
1163 /// The target normal control flow will take
1164 real_target: BasicBlock,
1165 /// The list of blocks control flow could conceptually take, but won't
1167 imaginary_targets: Vec<BasicBlock>,
1169 /// A terminator for blocks that only take one path in reality, but where we
1170 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1171 /// This can arise in infinite loops with no function calls for example.
1173 /// The target normal control flow will take
1174 real_target: BasicBlock,
1175 /// The imaginary cleanup block link. This particular path will never be taken
1176 /// in practice, but in order to avoid fragility we want to always
1177 /// consider it in borrowck. We don't want to accept programs which
1178 /// pass borrowck only when panic=abort or some assertions are disabled
1179 /// due to release vs. debug mode builds. This needs to be an Option because
1180 /// of the remove_noop_landing_pads and no_landing_pads passes
1181 unwind: Option<BasicBlock>,
1185 pub type Successors<'a> =
1186 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1187 pub type SuccessorsMut<'a> =
1188 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1190 impl<'tcx> Terminator<'tcx> {
1191 pub fn successors(&self) -> Successors<'_> {
1192 self.kind.successors()
1195 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1196 self.kind.successors_mut()
1199 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1203 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1204 self.kind.unwind_mut()
1208 impl<'tcx> TerminatorKind<'tcx> {
1209 pub fn if_<'a, 'gcx>(
1210 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1211 cond: Operand<'tcx>,
1214 ) -> TerminatorKind<'tcx> {
1215 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1216 TerminatorKind::SwitchInt {
1218 switch_ty: tcx.types.bool,
1219 values: From::from(BOOL_SWITCH_FALSE),
1220 targets: vec![f, t],
1224 pub fn successors(&self) -> Successors<'_> {
1225 use self::TerminatorKind::*;
1236 } => None.into_iter().chain(&[]),
1237 Goto { target: ref t }
1240 cleanup: Some(ref t),
1244 destination: Some((_, ref t)),
1271 } => Some(t).into_iter().chain(&[]),
1273 destination: Some((_, ref t)),
1274 cleanup: Some(ref u),
1284 unwind: Some(ref u),
1289 unwind: Some(ref u),
1294 cleanup: Some(ref u),
1299 unwind: Some(ref u),
1300 } => Some(t).into_iter().chain(slice::from_ref(u)),
1301 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1304 ref imaginary_targets,
1305 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1309 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1310 use self::TerminatorKind::*;
1321 } => None.into_iter().chain(&mut []),
1322 Goto { target: ref mut t }
1325 cleanup: Some(ref mut t),
1329 destination: Some((_, ref mut t)),
1354 real_target: ref mut t,
1356 } => Some(t).into_iter().chain(&mut []),
1358 destination: Some((_, ref mut t)),
1359 cleanup: Some(ref mut u),
1364 drop: Some(ref mut u),
1369 unwind: Some(ref mut u),
1374 unwind: Some(ref mut u),
1379 cleanup: Some(ref mut u),
1383 real_target: ref mut t,
1384 unwind: Some(ref mut u),
1385 } => Some(t).into_iter().chain(slice::from_mut(u)),
1388 } => None.into_iter().chain(&mut targets[..]),
1390 ref mut real_target,
1391 ref mut imaginary_targets,
1392 } => Some(real_target)
1394 .chain(&mut imaginary_targets[..]),
1398 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1400 TerminatorKind::Goto { .. }
1401 | TerminatorKind::Resume
1402 | TerminatorKind::Abort
1403 | TerminatorKind::Return
1404 | TerminatorKind::Unreachable
1405 | TerminatorKind::GeneratorDrop
1406 | TerminatorKind::Yield { .. }
1407 | TerminatorKind::SwitchInt { .. }
1408 | TerminatorKind::FalseEdges { .. } => None,
1409 TerminatorKind::Call {
1410 cleanup: ref unwind,
1413 | TerminatorKind::Assert {
1414 cleanup: ref unwind,
1417 | TerminatorKind::DropAndReplace { ref unwind, .. }
1418 | TerminatorKind::Drop { ref unwind, .. }
1419 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1423 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1425 TerminatorKind::Goto { .. }
1426 | TerminatorKind::Resume
1427 | TerminatorKind::Abort
1428 | TerminatorKind::Return
1429 | TerminatorKind::Unreachable
1430 | TerminatorKind::GeneratorDrop
1431 | TerminatorKind::Yield { .. }
1432 | TerminatorKind::SwitchInt { .. }
1433 | TerminatorKind::FalseEdges { .. } => None,
1434 TerminatorKind::Call {
1435 cleanup: ref mut unwind,
1438 | TerminatorKind::Assert {
1439 cleanup: ref mut unwind,
1442 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1443 | TerminatorKind::Drop { ref mut unwind, .. }
1444 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1449 impl<'tcx> BasicBlockData<'tcx> {
1450 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1458 /// Accessor for terminator.
1460 /// Terminator may not be None after construction of the basic block is complete. This accessor
1461 /// provides a convenience way to reach the terminator.
1462 pub fn terminator(&self) -> &Terminator<'tcx> {
1463 self.terminator.as_ref().expect("invalid terminator state")
1466 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1467 self.terminator.as_mut().expect("invalid terminator state")
1470 pub fn retain_statements<F>(&mut self, mut f: F)
1472 F: FnMut(&mut Statement<'_>) -> bool,
1474 for s in &mut self.statements {
1481 pub fn expand_statements<F, I>(&mut self, mut f: F)
1483 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1484 I: iter::TrustedLen<Item = Statement<'tcx>>,
1486 // Gather all the iterators we'll need to splice in, and their positions.
1487 let mut splices: Vec<(usize, I)> = vec![];
1488 let mut extra_stmts = 0;
1489 for (i, s) in self.statements.iter_mut().enumerate() {
1490 if let Some(mut new_stmts) = f(s) {
1491 if let Some(first) = new_stmts.next() {
1492 // We can already store the first new statement.
1495 // Save the other statements for optimized splicing.
1496 let remaining = new_stmts.size_hint().0;
1498 splices.push((i + 1 + extra_stmts, new_stmts));
1499 extra_stmts += remaining;
1507 // Splice in the new statements, from the end of the block.
1508 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1509 // where a range of elements ("gap") is left uninitialized, with
1510 // splicing adding new elements to the end of that gap and moving
1511 // existing elements from before the gap to the end of the gap.
1512 // For now, this is safe code, emulating a gap but initializing it.
1513 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1514 self.statements.resize(
1517 source_info: SourceInfo {
1519 scope: OUTERMOST_SOURCE_SCOPE,
1521 kind: StatementKind::Nop,
1524 for (splice_start, new_stmts) in splices.into_iter().rev() {
1525 let splice_end = splice_start + new_stmts.size_hint().0;
1526 while gap.end > splice_end {
1529 self.statements.swap(gap.start, gap.end);
1531 self.statements.splice(splice_start..splice_end, new_stmts);
1532 gap.end = splice_start;
1536 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1537 if index < self.statements.len() {
1538 &self.statements[index]
1545 impl<'tcx> Debug for TerminatorKind<'tcx> {
1546 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1547 self.fmt_head(fmt)?;
1548 let successor_count = self.successors().count();
1549 let labels = self.fmt_successor_labels();
1550 assert_eq!(successor_count, labels.len());
1552 match successor_count {
1555 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1558 write!(fmt, " -> [")?;
1559 for (i, target) in self.successors().enumerate() {
1563 write!(fmt, "{}: {:?}", labels[i], target)?;
1571 impl<'tcx> TerminatorKind<'tcx> {
1572 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1573 /// successor basic block, if any. The only information not included is the list of possible
1574 /// successors, which may be rendered differently between the text and the graphviz format.
1575 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1576 use self::TerminatorKind::*;
1578 Goto { .. } => write!(fmt, "goto"),
1580 discr: ref place, ..
1581 } => write!(fmt, "switchInt({:?})", place),
1582 Return => write!(fmt, "return"),
1583 GeneratorDrop => write!(fmt, "generator_drop"),
1584 Resume => write!(fmt, "resume"),
1585 Abort => write!(fmt, "abort"),
1586 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1587 Unreachable => write!(fmt, "unreachable"),
1588 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1593 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1600 if let Some((ref destination, _)) = *destination {
1601 write!(fmt, "{:?} = ", destination)?;
1603 write!(fmt, "{:?}(", func)?;
1604 for (index, arg) in args.iter().enumerate() {
1608 write!(fmt, "{:?}", arg)?;
1618 write!(fmt, "assert(")?;
1622 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1624 FalseEdges { .. } => write!(fmt, "falseEdges"),
1625 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1629 /// Return the list of labels for the edges to the successor basic blocks.
1630 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1631 use self::TerminatorKind::*;
1633 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1634 Goto { .. } => vec!["".into()],
1640 let size = ty::tls::with(|tcx| {
1641 let param_env = ty::ParamEnv::empty();
1642 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1643 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1648 let mut s = String::new();
1650 val: ConstValue::Scalar(
1653 size: size.bytes() as u8,
1658 fmt_const_val(&mut s, &c).unwrap();
1660 }).chain(iter::once("otherwise".into()))
1664 destination: Some(_),
1667 } => vec!["return".into(), "unwind".into()],
1669 destination: Some(_),
1672 } => vec!["return".into()],
1677 } => vec!["unwind".into()],
1683 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1684 Yield { drop: None, .. } => vec!["resume".into()],
1685 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1686 vec!["return".into()]
1693 } => vec!["return".into(), "unwind".into()],
1694 Assert { cleanup: None, .. } => vec!["".into()],
1695 Assert { .. } => vec!["success".into(), "unwind".into()],
1697 ref imaginary_targets,
1700 let mut l = vec!["real".into()];
1701 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1706 } => vec!["real".into(), "cleanup".into()],
1707 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1712 ///////////////////////////////////////////////////////////////////////////
1715 #[derive(Clone, RustcEncodable, RustcDecodable)]
1716 pub struct Statement<'tcx> {
1717 pub source_info: SourceInfo,
1718 pub kind: StatementKind<'tcx>,
1721 impl<'tcx> Statement<'tcx> {
1722 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1723 /// invalidating statement indices in `Location`s.
1724 pub fn make_nop(&mut self) {
1725 // `Statement` contributes significantly to peak memory usage. Make
1726 // sure it doesn't get bigger.
1727 static_assert!(STATEMENT_IS_AT_MOST_56_BYTES: mem::size_of::<Statement<'_>>() <= 56);
1729 self.kind = StatementKind::Nop
1732 /// Changes a statement to a nop and returns the original statement.
1733 pub fn replace_nop(&mut self) -> Self {
1735 source_info: self.source_info,
1736 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1741 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1742 pub enum StatementKind<'tcx> {
1743 /// Write the RHS Rvalue to the LHS Place.
1744 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1746 /// This represents all the reading that a pattern match may do
1747 /// (e.g. inspecting constants and discriminant values), and the
1748 /// kind of pattern it comes from. This is in order to adapt potential
1749 /// error messages to these specific patterns.
1750 FakeRead(FakeReadCause, Place<'tcx>),
1752 /// Write the discriminant for a variant to the enum Place.
1755 variant_index: usize,
1758 /// Start a live range for the storage of the local.
1761 /// End the current live range for the storage of the local.
1764 /// Execute a piece of inline Assembly.
1766 asm: Box<InlineAsm>,
1767 outputs: Box<[Place<'tcx>]>,
1768 inputs: Box<[(Span, Operand<'tcx>)]>,
1771 /// Retag references in the given place, ensuring they got fresh tags. This is
1772 /// part of the Stacked Borrows model. These statements are currently only interpreted
1773 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1774 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1775 /// for more details.
1777 /// `fn_entry` indicates whether this is the initial retag that happens in the
1778 /// function prolog.
1783 /// Mark one terminating point of a region scope (i.e. static region).
1784 /// (The starting point(s) arise implicitly from borrows.)
1785 EndRegion(region::Scope),
1787 /// Encodes a user's type ascription. These need to be preserved
1788 /// intact so that NLL can respect them. For example:
1792 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1793 /// to the user-given type `T`. The effect depends on the specified variance:
1795 /// - `Covariant` -- requires that `T_y <: T`
1796 /// - `Contravariant` -- requires that `T_y :> T`
1797 /// - `Invariant` -- requires that `T_y == T`
1798 /// - `Bivariant` -- no effect
1799 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection<'tcx>>),
1801 /// No-op. Useful for deleting instructions without affecting statement indices.
1805 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1806 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1807 pub enum FakeReadCause {
1808 /// Inject a fake read of the borrowed input at the start of each arm's
1809 /// pattern testing code.
1811 /// This should ensure that you cannot change the variant for an enum
1812 /// while you are in the midst of matching on it.
1815 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1816 /// generate a read of x to check that it is initialized and safe.
1819 /// Officially, the semantics of
1821 /// `let pattern = <expr>;`
1823 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1824 /// into the pattern.
1826 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1827 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1828 /// but in some cases it can affect the borrow checker, as in #53695.
1829 /// Therefore, we insert a "fake read" here to ensure that we get
1830 /// appropriate errors.
1834 impl<'tcx> Debug for Statement<'tcx> {
1835 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1836 use self::StatementKind::*;
1838 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1839 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1840 // (reuse lifetime rendering policy from ppaux.)
1841 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1842 Retag { fn_entry, ref place } =>
1843 write!(fmt, "Retag({}{:?})", if fn_entry { "[fn entry] " } else { "" }, place),
1844 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1845 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1849 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1854 } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1855 AscribeUserType(ref place, ref variance, ref c_ty) => {
1856 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1858 Nop => write!(fmt, "nop"),
1863 ///////////////////////////////////////////////////////////////////////////
1866 /// A path to a value; something that can be evaluated without
1867 /// changing or disturbing program state.
1868 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1869 pub enum Place<'tcx> {
1873 /// static or static mut variable
1874 Static(Box<Static<'tcx>>),
1876 /// Constant code promoted to an injected static
1877 Promoted(Box<(Promoted, Ty<'tcx>)>),
1879 /// projection out of a place (access a field, deref a pointer, etc)
1880 Projection(Box<PlaceProjection<'tcx>>),
1883 /// The def-id of a static, along with its normalized type (which is
1884 /// stored to avoid requiring normalization when reading MIR).
1885 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1886 pub struct Static<'tcx> {
1891 impl_stable_hash_for!(struct Static<'tcx> {
1896 /// The `Projection` data structure defines things of the form `B.x`
1897 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1898 /// shared between `Constant` and `Place`. See the aliases
1899 /// `PlaceProjection` etc below.
1900 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1901 pub struct Projection<'tcx, B, V, T> {
1903 pub elem: ProjectionElem<'tcx, V, T>,
1906 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1907 pub enum ProjectionElem<'tcx, V, T> {
1912 /// These indices are generated by slice patterns. Easiest to explain
1916 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1917 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1918 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1919 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1922 /// index or -index (in Python terms), depending on from_end
1924 /// thing being indexed must be at least this long
1926 /// counting backwards from end?
1930 /// These indices are generated by slice patterns.
1932 /// slice[from:-to] in Python terms.
1938 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1939 /// this for ADTs with more than one variant. It may be better to
1940 /// just introduce it always, or always for enums.
1941 Downcast(&'tcx AdtDef, usize),
1944 /// Alias for projections as they appear in places, where the base is a place
1945 /// and the index is a local.
1946 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1948 /// Alias for projections as they appear in places, where the base is a place
1949 /// and the index is a local.
1950 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1952 /// Alias for projections as they appear in `UserTypeProjection`, where we
1953 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1954 pub type ProjectionKind<'tcx> = ProjectionElem<'tcx, (), ()>;
1958 DEBUG_FORMAT = "field[{}]"
1962 impl<'tcx> Place<'tcx> {
1963 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1964 self.elem(ProjectionElem::Field(f, ty))
1967 pub fn deref(self) -> Place<'tcx> {
1968 self.elem(ProjectionElem::Deref)
1971 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1972 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1975 pub fn index(self, index: Local) -> Place<'tcx> {
1976 self.elem(ProjectionElem::Index(index))
1979 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1980 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
1983 /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
1984 /// a single deref of a local.
1986 /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1987 pub fn local(&self) -> Option<Local> {
1989 Place::Local(local) |
1990 Place::Projection(box Projection {
1991 base: Place::Local(local),
1992 elem: ProjectionElem::Deref,
1998 /// Find the innermost `Local` from this `Place`.
1999 pub fn base_local(&self) -> Option<Local> {
2001 Place::Local(local) => Some(*local),
2002 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2003 Place::Promoted(..) | Place::Static(..) => None,
2008 impl<'tcx> Debug for Place<'tcx> {
2009 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2013 Local(id) => write!(fmt, "{:?}", id),
2014 Static(box self::Static { def_id, ty }) => write!(
2017 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2020 Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2021 Projection(ref data) => match data.elem {
2022 ProjectionElem::Downcast(ref adt_def, index) => {
2023 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2025 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2026 ProjectionElem::Field(field, ty) => {
2027 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2029 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2030 ProjectionElem::ConstantIndex {
2034 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2035 ProjectionElem::ConstantIndex {
2039 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2040 ProjectionElem::Subslice { from, to } if to == 0 => {
2041 write!(fmt, "{:?}[{:?}:]", data.base, from)
2043 ProjectionElem::Subslice { from, to } if from == 0 => {
2044 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2046 ProjectionElem::Subslice { from, to } => {
2047 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2054 ///////////////////////////////////////////////////////////////////////////
2058 pub struct SourceScope {
2059 DEBUG_FORMAT = "scope[{}]",
2060 const OUTERMOST_SOURCE_SCOPE = 0,
2064 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2065 pub struct SourceScopeData {
2067 pub parent_scope: Option<SourceScope>,
2070 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2071 pub struct SourceScopeLocalData {
2072 /// A NodeId with lint levels equivalent to this scope's lint levels.
2073 pub lint_root: ast::NodeId,
2074 /// The unsafe block that contains this node.
2078 ///////////////////////////////////////////////////////////////////////////
2081 /// These are values that can appear inside an rvalue. They are intentionally
2082 /// limited to prevent rvalues from being nested in one another.
2083 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
2084 pub enum Operand<'tcx> {
2085 /// Copy: The value must be available for use afterwards.
2087 /// This implies that the type of the place must be `Copy`; this is true
2088 /// by construction during build, but also checked by the MIR type checker.
2091 /// Move: The value (including old borrows of it) will not be used again.
2093 /// Safe for values of all types (modulo future developments towards `?Move`).
2094 /// Correct usage patterns are enforced by the borrow checker for safe code.
2095 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2098 /// Synthesizes a constant value.
2099 Constant(Box<Constant<'tcx>>),
2102 impl<'tcx> Debug for Operand<'tcx> {
2103 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2104 use self::Operand::*;
2106 Constant(ref a) => write!(fmt, "{:?}", a),
2107 Copy(ref place) => write!(fmt, "{:?}", place),
2108 Move(ref place) => write!(fmt, "move {:?}", place),
2113 impl<'tcx> Operand<'tcx> {
2114 /// Convenience helper to make a constant that refers to the fn
2115 /// with given def-id and substs. Since this is used to synthesize
2116 /// MIR, assumes `user_ty` is None.
2117 pub fn function_handle<'a>(
2118 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2120 substs: &'tcx Substs<'tcx>,
2123 let ty = tcx.type_of(def_id).subst(tcx, substs);
2124 Operand::Constant(box Constant {
2128 literal: ty::Const::zero_sized(tcx, ty),
2132 pub fn to_copy(&self) -> Self {
2134 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2135 Operand::Move(ref place) => Operand::Copy(place.clone()),
2140 ///////////////////////////////////////////////////////////////////////////
2143 #[derive(Clone, RustcEncodable, RustcDecodable)]
2144 pub enum Rvalue<'tcx> {
2145 /// x (either a move or copy, depending on type of x)
2149 Repeat(Operand<'tcx>, u64),
2152 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2154 /// length of a [X] or [X;n] value
2157 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2159 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2160 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2162 NullaryOp(NullOp, Ty<'tcx>),
2163 UnaryOp(UnOp, Operand<'tcx>),
2165 /// Read the discriminant of an ADT.
2167 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
2168 /// be defined to return, say, a 0) if ADT is not an enum.
2169 Discriminant(Place<'tcx>),
2171 /// Create an aggregate value, like a tuple or struct. This is
2172 /// only needed because we want to distinguish `dest = Foo { x:
2173 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2174 /// that `Foo` has a destructor. These rvalues can be optimized
2175 /// away after type-checking and before lowering.
2176 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2179 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2183 /// Convert unique, zero-sized type for a fn to fn()
2186 /// Convert non capturing closure to fn()
2189 /// Convert safe fn() to unsafe fn()
2192 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2193 /// codegen must figure out the details once full monomorphization
2194 /// is known. For example, this could be used to cast from a
2195 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
2196 /// (presuming `T: Trait`).
2200 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2201 pub enum AggregateKind<'tcx> {
2202 /// The type is of the element
2206 /// The second field is the variant index. It's equal to 0 for struct
2207 /// and union expressions. The fourth field is
2208 /// active field number and is present only for union expressions
2209 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
2210 /// active field index would identity the field `c`
2215 Option<UserTypeAnnotation<'tcx>>,
2219 Closure(DefId, ClosureSubsts<'tcx>),
2220 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2223 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2225 /// The `+` operator (addition)
2227 /// The `-` operator (subtraction)
2229 /// The `*` operator (multiplication)
2231 /// The `/` operator (division)
2233 /// The `%` operator (modulus)
2235 /// The `^` operator (bitwise xor)
2237 /// The `&` operator (bitwise and)
2239 /// The `|` operator (bitwise or)
2241 /// The `<<` operator (shift left)
2243 /// The `>>` operator (shift right)
2245 /// The `==` operator (equality)
2247 /// The `<` operator (less than)
2249 /// The `<=` operator (less than or equal to)
2251 /// The `!=` operator (not equal to)
2253 /// The `>=` operator (greater than or equal to)
2255 /// The `>` operator (greater than)
2257 /// The `ptr.offset` operator
2262 pub fn is_checkable(self) -> bool {
2265 Add | Sub | Mul | Shl | Shr => true,
2271 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2273 /// Return the size of a value of that type
2275 /// Create a new uninitialized box for a value of that type
2279 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2281 /// The `!` operator for logical inversion
2283 /// The `-` operator for negation
2287 impl<'tcx> Debug for Rvalue<'tcx> {
2288 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2289 use self::Rvalue::*;
2292 Use(ref place) => write!(fmt, "{:?}", place),
2293 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2294 Len(ref a) => write!(fmt, "Len({:?})", a),
2295 Cast(ref kind, ref place, ref ty) => {
2296 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2298 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2299 CheckedBinaryOp(ref op, ref a, ref b) => {
2300 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2302 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2303 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2304 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2305 Ref(region, borrow_kind, ref place) => {
2306 let kind_str = match borrow_kind {
2307 BorrowKind::Shared => "",
2308 BorrowKind::Shallow => "shallow ",
2309 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2312 // When printing regions, add trailing space if necessary.
2313 let region = if ppaux::verbose() || ppaux::identify_regions() {
2314 let mut region = region.to_string();
2315 if region.len() > 0 {
2320 // Do not even print 'static
2323 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2326 Aggregate(ref kind, ref places) => {
2327 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2328 let mut tuple_fmt = fmt.debug_tuple("");
2329 for place in places {
2330 tuple_fmt.field(place);
2336 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2338 AggregateKind::Tuple => match places.len() {
2339 0 => write!(fmt, "()"),
2340 1 => write!(fmt, "({:?},)", places[0]),
2341 _ => fmt_tuple(fmt, places),
2344 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2345 let variant_def = &adt_def.variants[variant];
2347 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
2349 match variant_def.ctor_kind {
2350 CtorKind::Const => Ok(()),
2351 CtorKind::Fn => fmt_tuple(fmt, places),
2352 CtorKind::Fictive => {
2353 let mut struct_fmt = fmt.debug_struct("");
2354 for (field, place) in variant_def.fields.iter().zip(places) {
2355 struct_fmt.field(&field.ident.as_str(), place);
2362 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2363 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2364 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2365 format!("[closure@{:?}]", node_id)
2367 format!("[closure@{:?}]", tcx.hir.span(node_id))
2369 let mut struct_fmt = fmt.debug_struct(&name);
2371 tcx.with_freevars(node_id, |freevars| {
2372 for (freevar, place) in freevars.iter().zip(places) {
2373 let var_name = tcx.hir.name(freevar.var_id());
2374 struct_fmt.field(&var_name.as_str(), place);
2380 write!(fmt, "[closure]")
2384 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2385 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2386 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
2387 let mut struct_fmt = fmt.debug_struct(&name);
2389 tcx.with_freevars(node_id, |freevars| {
2390 for (freevar, place) in freevars.iter().zip(places) {
2391 let var_name = tcx.hir.name(freevar.var_id());
2392 struct_fmt.field(&var_name.as_str(), place);
2394 struct_fmt.field("$state", &places[freevars.len()]);
2395 for i in (freevars.len() + 1)..places.len() {
2397 .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2403 write!(fmt, "[generator]")
2412 ///////////////////////////////////////////////////////////////////////////
2415 /// Two constants are equal if they are the same constant. Note that
2416 /// this does not necessarily mean that they are "==" in Rust -- in
2417 /// particular one must be wary of `NaN`!
2419 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2420 pub struct Constant<'tcx> {
2424 /// Optional user-given type: for something like
2425 /// `collect::<Vec<_>>`, this would be present and would
2426 /// indicate that `Vec<_>` was explicitly specified.
2428 /// Needed for NLL to impose user-given type constraints.
2429 pub user_ty: Option<UserTypeAnnotation<'tcx>>,
2431 pub literal: &'tcx ty::Const<'tcx>,
2434 /// A user-given type annotation attached to a constant. These arise
2435 /// from constants that are named via paths, like `Foo::<A>::new` and
2437 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2438 pub enum UserTypeAnnotation<'tcx> {
2439 Ty(CanonicalTy<'tcx>),
2441 /// The canonical type is the result of `type_of(def_id)` with the
2442 /// given substitutions applied.
2443 TypeOf(DefId, CanonicalUserSubsts<'tcx>),
2446 EnumTypeFoldableImpl! {
2447 impl<'tcx> TypeFoldable<'tcx> for UserTypeAnnotation<'tcx> {
2448 (UserTypeAnnotation::Ty)(ty),
2449 (UserTypeAnnotation::TypeOf)(def, substs),
2454 impl<'a, 'tcx> Lift<'tcx> for UserTypeAnnotation<'a> {
2455 type Lifted = UserTypeAnnotation<'tcx>;
2456 (UserTypeAnnotation::Ty)(ty),
2457 (UserTypeAnnotation::TypeOf)(def, substs),
2461 /// A collection of projections into user types.
2463 /// They are projections because a binding can occur a part of a
2464 /// parent pattern that has been ascribed a type.
2466 /// Its a collection because there can be multiple type ascriptions on
2467 /// the path from the root of the pattern down to the binding itself.
2472 /// struct S<'a>((i32, &'a str), String);
2473 /// let S((_, w): (i32, &'static str), _): S = ...;
2474 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2475 /// // --------------------------------- ^ (2)
2478 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2479 /// ascribed the type `(i32, &'static str)`.
2481 /// The highlights labelled `(2)` show the whole pattern being
2482 /// ascribed the type `S`.
2484 /// In this example, when we descend to `w`, we will have built up the
2485 /// following two projected types:
2487 /// * base: `S`, projection: `(base.0).1`
2488 /// * base: `(i32, &'static str)`, projection: `base.1`
2490 /// The first will lead to the constraint `w: &'1 str` (for some
2491 /// inferred region `'1`). The second will lead to the constraint `w:
2493 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2494 pub struct UserTypeProjections<'tcx> {
2495 pub(crate) contents: Vec<(UserTypeProjection<'tcx>, Span)>,
2498 BraceStructTypeFoldableImpl! {
2499 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections<'tcx> {
2504 impl<'tcx> UserTypeProjections<'tcx> {
2505 pub fn none() -> Self {
2506 UserTypeProjections { contents: vec![] }
2509 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection<'tcx>, Span)>) -> Self {
2510 UserTypeProjections { contents: projs.collect() }
2513 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection<'tcx>, Span)> {
2514 self.contents.iter()
2517 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection<'tcx>> {
2518 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2522 /// Encodes the effect of a user-supplied type annotation on the
2523 /// subcomponents of a pattern. The effect is determined by applying the
2524 /// given list of proejctions to some underlying base type. Often,
2525 /// the projection element list `projs` is empty, in which case this
2526 /// directly encodes a type in `base`. But in the case of complex patterns with
2527 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2528 /// in which case the `projs` vector is used.
2532 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2534 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2535 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2536 /// determined by finding the type of the `.0` field from `T`.
2537 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2538 pub struct UserTypeProjection<'tcx> {
2539 pub base: UserTypeAnnotation<'tcx>,
2540 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
2543 impl<'tcx> Copy for ProjectionKind<'tcx> { }
2545 CloneTypeFoldableAndLiftImpls! { ProjectionKind<'tcx>, }
2547 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection<'tcx> {
2548 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2549 use mir::ProjectionElem::*;
2551 let base = self.base.fold_with(folder);
2552 let projs: Vec<_> = self.projs
2557 Field(f, ()) => Field(f.clone(), ()),
2558 Index(()) => Index(()),
2559 elem => elem.clone(),
2563 UserTypeProjection { base, projs }
2566 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2567 self.base.visit_with(visitor)
2568 // Note: there's nothing in `self.proj` to visit.
2573 pub struct Promoted {
2574 DEBUG_FORMAT = "promoted[{}]"
2578 impl<'tcx> Debug for Constant<'tcx> {
2579 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2580 write!(fmt, "const ")?;
2581 fmt_const_val(fmt, self.literal)
2585 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2586 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2588 let value = const_val.val;
2589 let ty = const_val.ty;
2590 // print some primitives
2591 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2593 Bool if bits == 0 => return write!(f, "false"),
2594 Bool if bits == 1 => return write!(f, "true"),
2595 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2596 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2597 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2599 let bit_width = ty::tls::with(|tcx| {
2600 let ty = tcx.lift_to_global(&ty).unwrap();
2601 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2606 let shift = 128 - bit_width;
2607 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2609 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2613 // print function definitons
2614 if let FnDef(did, _) = ty.sty {
2615 return write!(f, "{}", item_path_str(did));
2617 // print string literals
2618 if let ConstValue::ScalarPair(ptr, len) = value {
2619 if let Scalar::Ptr(ptr) = ptr {
2620 if let Scalar::Bits { bits: len, .. } = len {
2621 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2622 return ty::tls::with(|tcx| {
2623 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2624 if let Some(interpret::AllocType::Memory(alloc)) = alloc {
2625 assert_eq!(len as usize as u128, len);
2627 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2628 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2629 write!(f, "{:?}", s)
2631 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2638 // just raw dump everything else
2639 write!(f, "{:?}:{}", value, ty)
2642 fn item_path_str(def_id: DefId) -> String {
2643 ty::tls::with(|tcx| tcx.item_path_str(def_id))
2646 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2647 type Node = BasicBlock;
2650 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2651 fn num_nodes(&self) -> usize {
2652 self.basic_blocks.len()
2656 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2657 fn start_node(&self) -> Self::Node {
2662 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2663 fn predecessors<'graph>(
2666 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2667 self.predecessors_for(node).clone().into_iter()
2671 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2672 fn successors<'graph>(
2675 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2676 self.basic_blocks[node].terminator().successors().cloned()
2680 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2681 type Item = BasicBlock;
2682 type Iter = IntoIter<BasicBlock>;
2685 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2686 type Item = BasicBlock;
2687 type Iter = iter::Cloned<Successors<'b>>;
2690 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2691 pub struct Location {
2692 /// the location is within this block
2693 pub block: BasicBlock,
2695 /// the location is the start of the statement; or, if `statement_index`
2696 /// == num-statements, then the start of the terminator.
2697 pub statement_index: usize,
2700 impl fmt::Debug for Location {
2701 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2702 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2707 pub const START: Location = Location {
2712 /// Returns the location immediately after this one within the enclosing block.
2714 /// Note that if this location represents a terminator, then the
2715 /// resulting location would be out of bounds and invalid.
2716 pub fn successor_within_block(&self) -> Location {
2719 statement_index: self.statement_index + 1,
2723 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2724 if self.block == other.block {
2725 self.statement_index <= other.statement_index
2727 dominators.is_dominated_by(other.block, self.block)
2732 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2733 pub enum UnsafetyViolationKind {
2735 /// unsafety is not allowed at all in min const fn
2737 ExternStatic(ast::NodeId),
2738 BorrowPacked(ast::NodeId),
2741 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2742 pub struct UnsafetyViolation {
2743 pub source_info: SourceInfo,
2744 pub description: InternedString,
2745 pub details: InternedString,
2746 pub kind: UnsafetyViolationKind,
2749 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2750 pub struct UnsafetyCheckResult {
2751 /// Violations that are propagated *upwards* from this function
2752 pub violations: Lrc<[UnsafetyViolation]>,
2753 /// unsafe blocks in this function, along with whether they are used. This is
2754 /// used for the "unused_unsafe" lint.
2755 pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2758 /// The layout of generator state
2759 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2760 pub struct GeneratorLayout<'tcx> {
2761 pub fields: Vec<LocalDecl<'tcx>>,
2764 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2765 pub struct BorrowCheckResult<'gcx> {
2766 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2767 pub used_mut_upvars: SmallVec<[Field; 8]>,
2770 /// After we borrow check a closure, we are left with various
2771 /// requirements that we have inferred between the free regions that
2772 /// appear in the closure's signature or on its field types. These
2773 /// requirements are then verified and proved by the closure's
2774 /// creating function. This struct encodes those requirements.
2776 /// The requirements are listed as being between various
2777 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2778 /// vids refer to the free regions that appear in the closure (or
2779 /// generator's) type, in order of appearance. (This numbering is
2780 /// actually defined by the `UniversalRegions` struct in the NLL
2781 /// region checker. See for example
2782 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2783 /// regions in the closure's type "as if" they were erased, so their
2784 /// precise identity is not important, only their position.
2786 /// Example: If type check produces a closure with the closure substs:
2789 /// ClosureSubsts = [
2790 /// i8, // the "closure kind"
2791 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2792 /// &'a String, // some upvar
2796 /// here, there is one unique free region (`'a`) but it appears
2797 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2800 /// ClosureSubsts = [
2801 /// i8, // the "closure kind"
2802 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2803 /// &'2 String, // some upvar
2807 /// Now the code might impose a requirement like `'1: '2`. When an
2808 /// instance of the closure is created, the corresponding free regions
2809 /// can be extracted from its type and constrained to have the given
2810 /// outlives relationship.
2812 /// In some cases, we have to record outlives requirements between
2813 /// types and regions as well. In that case, if those types include
2814 /// any regions, those regions are recorded as `ReClosureBound`
2815 /// instances assigned one of these same indices. Those regions will
2816 /// be substituted away by the creator. We use `ReClosureBound` in
2817 /// that case because the regions must be allocated in the global
2818 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2819 /// internally within the rest of the NLL code).
2820 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2821 pub struct ClosureRegionRequirements<'gcx> {
2822 /// The number of external regions defined on the closure. In our
2823 /// example above, it would be 3 -- one for `'static`, then `'1`
2824 /// and `'2`. This is just used for a sanity check later on, to
2825 /// make sure that the number of regions we see at the callsite
2827 pub num_external_vids: usize,
2829 /// Requirements between the various free regions defined in
2831 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2834 /// Indicates an outlives constraint between a type or between two
2835 /// free-regions declared on the closure.
2836 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2837 pub struct ClosureOutlivesRequirement<'tcx> {
2838 // This region or type ...
2839 pub subject: ClosureOutlivesSubject<'tcx>,
2841 // ... must outlive this one.
2842 pub outlived_free_region: ty::RegionVid,
2844 // If not, report an error here ...
2845 pub blame_span: Span,
2847 // ... due to this reason.
2848 pub category: ConstraintCategory,
2851 /// Outlives constraints can be categorized to determine whether and why they
2852 /// are interesting (for error reporting). Order of variants indicates sort
2853 /// order of the category, thereby influencing diagnostic output.
2855 /// See also [rustc_mir::borrow_check::nll::constraints]
2856 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2857 pub enum ConstraintCategory {
2864 /// A constraint that came from checking the body of a closure.
2866 /// We try to get the category that the closure used when reporting this.
2874 /// A "boring" constraint (caused by the given location) is one that
2875 /// the user probably doesn't want to see described in diagnostics,
2876 /// because it is kind of an artifact of the type system setup.
2877 /// Example: `x = Foo { field: y }` technically creates
2878 /// intermediate regions representing the "type of `Foo { field: y
2879 /// }`", and data flows from `y` into those variables, but they
2880 /// are not very interesting. The assignment into `x` on the other
2883 // Boring and applicable everywhere.
2886 /// A constraint that doesn't correspond to anything the user sees.
2890 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2891 /// that must outlive some region.
2892 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2893 pub enum ClosureOutlivesSubject<'tcx> {
2894 /// Subject is a type, typically a type parameter, but could also
2895 /// be a projection. Indicates a requirement like `T: 'a` being
2896 /// passed to the caller, where the type here is `T`.
2898 /// The type here is guaranteed not to contain any free regions at
2902 /// Subject is a free region from the closure. Indicates a requirement
2903 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2904 Region(ty::RegionVid),
2908 * TypeFoldable implementations for MIR types
2911 CloneTypeFoldableAndLiftImpls! {
2920 SourceScopeLocalData,
2923 BraceStructTypeFoldableImpl! {
2924 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2928 source_scope_local_data,
2942 BraceStructTypeFoldableImpl! {
2943 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2948 BraceStructTypeFoldableImpl! {
2949 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2962 BraceStructTypeFoldableImpl! {
2963 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2970 BraceStructTypeFoldableImpl! {
2971 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2976 EnumTypeFoldableImpl! {
2977 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
2978 (StatementKind::Assign)(a, b),
2979 (StatementKind::FakeRead)(cause, place),
2980 (StatementKind::SetDiscriminant) { place, variant_index },
2981 (StatementKind::StorageLive)(a),
2982 (StatementKind::StorageDead)(a),
2983 (StatementKind::InlineAsm) { asm, outputs, inputs },
2984 (StatementKind::Retag) { fn_entry, place },
2985 (StatementKind::EndRegion)(a),
2986 (StatementKind::AscribeUserType)(a, v, b),
2987 (StatementKind::Nop),
2991 EnumTypeFoldableImpl! {
2992 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
2993 (ClearCrossCrate::Clear),
2994 (ClearCrossCrate::Set)(a),
2995 } where T: TypeFoldable<'tcx>
2998 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2999 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3000 use mir::TerminatorKind::*;
3002 let kind = match self.kind {
3003 Goto { target } => Goto { target },
3010 discr: discr.fold_with(folder),
3011 switch_ty: switch_ty.fold_with(folder),
3012 values: values.clone(),
3013 targets: targets.clone(),
3020 location: location.fold_with(folder),
3029 } => DropAndReplace {
3030 location: location.fold_with(folder),
3031 value: value.fold_with(folder),
3040 value: value.fold_with(folder),
3051 let dest = destination
3053 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3056 func: func.fold_with(folder),
3057 args: args.fold_with(folder),
3070 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3071 EvalErrorKind::BoundsCheck {
3072 len: len.fold_with(folder),
3073 index: index.fold_with(folder),
3079 cond: cond.fold_with(folder),
3086 GeneratorDrop => GeneratorDrop,
3090 Unreachable => Unreachable,
3093 ref imaginary_targets,
3096 imaginary_targets: imaginary_targets.clone(),
3107 source_info: self.source_info,
3112 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3113 use mir::TerminatorKind::*;
3120 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3121 Drop { ref location, .. } => location.visit_with(visitor),
3126 } => location.visit_with(visitor) || value.visit_with(visitor),
3127 Yield { ref value, .. } => value.visit_with(visitor),
3134 let dest = if let Some((ref loc, _)) = *destination {
3135 loc.visit_with(visitor)
3139 dest || func.visit_with(visitor) || args.visit_with(visitor)
3142 ref cond, ref msg, ..
3144 if cond.visit_with(visitor) {
3145 if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3146 len.visit_with(visitor) || index.visit_with(visitor)
3161 | FalseUnwind { .. } => false,
3166 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3167 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3169 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3174 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3175 if let &Place::Projection(ref p) = self {
3176 p.visit_with(visitor)
3183 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3184 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3187 Use(ref op) => Use(op.fold_with(folder)),
3188 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3189 Ref(region, bk, ref place) => {
3190 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3192 Len(ref place) => Len(place.fold_with(folder)),
3193 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3194 BinaryOp(op, ref rhs, ref lhs) => {
3195 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3197 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3198 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3200 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3201 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3202 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3203 Aggregate(ref kind, ref fields) => {
3204 let kind = box match **kind {
3205 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3206 AggregateKind::Tuple => AggregateKind::Tuple,
3207 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3210 substs.fold_with(folder),
3211 user_ty.fold_with(folder),
3214 AggregateKind::Closure(id, substs) => {
3215 AggregateKind::Closure(id, substs.fold_with(folder))
3217 AggregateKind::Generator(id, substs, movablity) => {
3218 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3221 Aggregate(kind, fields.fold_with(folder))
3226 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3229 Use(ref op) => op.visit_with(visitor),
3230 Repeat(ref op, _) => op.visit_with(visitor),
3231 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3232 Len(ref place) => place.visit_with(visitor),
3233 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3234 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3235 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3237 UnaryOp(_, ref val) => val.visit_with(visitor),
3238 Discriminant(ref place) => place.visit_with(visitor),
3239 NullaryOp(_, ty) => ty.visit_with(visitor),
3240 Aggregate(ref kind, ref fields) => {
3242 AggregateKind::Array(ty) => ty.visit_with(visitor),
3243 AggregateKind::Tuple => false,
3244 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3245 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3247 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3248 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3249 }) || fields.visit_with(visitor)
3255 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3256 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3258 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3259 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3260 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3264 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3266 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3267 Operand::Constant(ref c) => c.visit_with(visitor),
3272 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3274 B: TypeFoldable<'tcx>,
3275 V: TypeFoldable<'tcx>,
3276 T: TypeFoldable<'tcx>,
3278 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3279 use mir::ProjectionElem::*;
3281 let base = self.base.fold_with(folder);
3282 let elem = match self.elem {
3284 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3285 Index(ref v) => Index(v.fold_with(folder)),
3286 ref elem => elem.clone(),
3289 Projection { base, elem }
3292 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3293 use mir::ProjectionElem::*;
3295 self.base.visit_with(visitor) || match self.elem {
3296 Field(_, ref ty) => ty.visit_with(visitor),
3297 Index(ref v) => v.visit_with(visitor),
3303 impl<'tcx> TypeFoldable<'tcx> for Field {
3304 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3307 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3312 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3313 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3315 span: self.span.clone(),
3316 ty: self.ty.fold_with(folder),
3317 user_ty: self.user_ty.fold_with(folder),
3318 literal: self.literal.fold_with(folder),
3321 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3322 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)