mod.rs 103.1 KB
Newer Older
1
//! MIR datatypes and passes. See the [rustc dev guide] for more info.
M
Malo Jaffré 已提交
2
//!
3
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4

5
use crate::mir::coverage::{CodeRegion, CoverageKind};
6
use crate::mir::interpret::{Allocation, ConstValue, GlobalAlloc, Scalar};
M
Mark Mansi 已提交
7
use crate::mir::visit::MirVisitable;
A
Albin Stjerna 已提交
8
use crate::ty::adjustment::PointerCast;
M
Matthew Jasper 已提交
9
use crate::ty::codec::{TyDecoder, TyEncoder};
A
Albin Stjerna 已提交
10 11 12
use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
use crate::ty::print::{FmtPrinter, Printer};
use crate::ty::subst::{Subst, SubstsRef};
D
Dylan MacKenzie 已提交
13
use crate::ty::{self, List, Ty, TyCtxt};
14
use crate::ty::{AdtDef, InstanceDef, Region, ScalarInt, UserTypeAnnotationIndex};
15
use rustc_hir::def::{CtorKind, Namespace};
16
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
17
use rustc_hir::{self, GeneratorKind};
18
use rustc_hir::{self as hir, HirId};
19
use rustc_target::abi::{Size, VariantIdx};
20

21
use polonius_engine::Atom;
U
Ujjwal Sharma 已提交
22
pub use rustc_ast::Mutability;
D
David Wood 已提交
23
use rustc_data_structures::fx::FxHashSet;
24
use rustc_data_structures::graph::dominators::{dominators, Dominators};
25
use rustc_data_structures::graph::{self, GraphSuccessors};
M
Mark Rousskov 已提交
26 27 28
use rustc_index::bit_set::BitMatrix;
use rustc_index::vec::{Idx, IndexVec};
use rustc_serialize::{Decodable, Encodable};
29
use rustc_span::symbol::Symbol;
30
use rustc_span::{Span, DUMMY_SP};
31
use rustc_target::asm::InlineAsmRegOrRegClass;
S
Santiago Pastorino 已提交
32
use std::borrow::Cow;
33
use std::convert::TryInto;
A
Albin Stjerna 已提交
34
use std::fmt::{self, Debug, Display, Formatter, Write};
35
use std::ops::{ControlFlow, Index, IndexMut};
S
Santiago Pastorino 已提交
36
use std::slice;
37
use std::{iter, mem, option};
N
Niko Matsakis 已提交
38

D
Dániel Buga 已提交
39
use self::graph_cyclic_cache::GraphIsCyclicCache;
40
use self::predecessors::{PredecessorCache, Predecessors};
41
pub use self::query::*;
42

B
Bastian Kauschke 已提交
43
pub mod abstract_const;
44
pub mod coverage;
D
Dániel Buga 已提交
45
mod graph_cyclic_cache;
46
pub mod interpret;
47
pub mod mono;
48
mod predecessors;
49
mod query;
S
Santiago Pastorino 已提交
50
pub mod tcx;
R
root 已提交
51 52
pub mod terminator;
pub use terminator::*;
S
Santiago Pastorino 已提交
53
pub mod traversal;
54
mod type_foldable;
S
Santiago Pastorino 已提交
55
pub mod visit;
56

57
/// Types for locals
58
pub type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
59

60 61
pub trait HasLocalDecls<'tcx> {
    fn local_decls(&self) -> &LocalDecls<'tcx>;
62 63
}

64
impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
65
    #[inline]
66
    fn local_decls(&self) -> &LocalDecls<'tcx> {
67 68 69 70
        self
    }
}

71
impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
72
    #[inline]
73
    fn local_decls(&self) -> &LocalDecls<'tcx> {
74 75 76 77
        &self.local_decls
    }
}

78 79
/// The various "big phases" that MIR goes through.
///
80 81 82 83
/// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
/// dialects forbid certain variants or values in certain phases.
///
/// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
84
/// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
85
///
86
/// Warning: ordering of variants is significant.
M
Matthew Jasper 已提交
87
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
88
#[derive(HashStable)]
89
pub enum MirPhase {
W
Wesley Wiser 已提交
90
    Build = 0,
91
    // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
92
    // We used to have this for pre-miri MIR based const eval.
W
Wesley Wiser 已提交
93
    Const = 1,
94 95 96 97 98 99 100 101 102 103 104 105 106 107
    /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
    /// by creating a new MIR body per promoted element. After this phase (and thus the termination
    /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
    /// query.
    ConstPromotion = 2,
    /// After this phase
    /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
    /// * `DropAndReplace` is gone for good
    /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
    ///   means that the auto-generated drop glue will be invoked.
    DropLowering = 3,
    /// After this phase, generators are explicit state machines (no more `Yield`).
    /// `AggregateKind::Generator` is gone for good.
    GeneratorLowering = 4,
O
Oliver Scherer 已提交
108
    Optimization = 5,
109 110
}

111
impl MirPhase {
112
    /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
113
    pub fn phase_index(&self) -> usize {
W
Wesley Wiser 已提交
114
        *self as usize
115 116 117
    }
}

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
/// Where a specific `mir::Body` comes from.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
pub struct MirSource<'tcx> {
    pub instance: InstanceDef<'tcx>,

    /// If `Some`, this is a promoted rvalue within the parent function.
    pub promoted: Option<Promoted>,
}

impl<'tcx> MirSource<'tcx> {
    pub fn item(def_id: DefId) -> Self {
        MirSource {
            instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
            promoted: None,
        }
    }

    pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
        MirSource { instance, promoted: None }
    }

    pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
        self.instance.with_opt_param()
    }

    #[inline]
    pub fn def_id(&self) -> DefId {
        self.instance.def_id()
    }
}

D
Dániel Buga 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
pub struct GeneratorInfo<'tcx> {
    /// The yield type of the function, if it is a generator.
    pub yield_ty: Option<Ty<'tcx>>,

    /// Generator drop glue.
    pub generator_drop: Option<Body<'tcx>>,

    /// The layout of a generator. Produced by the state transformation.
    pub generator_layout: Option<GeneratorLayout<'tcx>>,

    /// If this is a generator then record the type of source expression that caused this generator
    /// to be created.
    pub generator_kind: GeneratorKind,
}

166
/// The lowered representation of a single function.
M
Matthew Jasper 已提交
167
#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
168
pub struct Body<'tcx> {
C
Camelid 已提交
169
    /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
N
Niko Matsakis 已提交
170
    /// that indexes into this vector.
171
    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
N
Niko Matsakis 已提交
172

173 174 175 176 177 178 179
    /// Records how far through the "desugaring and optimization" process this particular
    /// MIR has traversed. This is particularly useful when inlining, since in that context
    /// we instantiate the promoted constants and add them to our promoted vector -- but those
    /// promoted items have already been optimized, whereas ours have not. This field allows
    /// us to see the difference and forego optimization on the inlined promoted items.
    pub phase: MirPhase,

180 181
    pub source: MirSource<'tcx>,

182
    /// A list of source scopes; these are referenced by statements
183
    /// and used for debuginfo. Indexed by a `SourceScope`.
184
    pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
N
Niko Matsakis 已提交
185

D
Dániel Buga 已提交
186
    pub generator: Option<Box<GeneratorInfo<'tcx>>>,
D
Squash  
David Haig 已提交
187

188 189 190 191 192
    /// Declarations of locals.
    ///
    /// The first local is the return value pointer, followed by `arg_count`
    /// locals for the function arguments, followed by any user-declared
    /// variables and temporaries.
193
    pub local_decls: LocalDecls<'tcx>,
N
Niko Matsakis 已提交
194

195
    /// User type annotations.
D
Dylan MacKenzie 已提交
196
    pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
D
David Wood 已提交
197

198
    /// The number of arguments this function takes.
199
    ///
200
    /// Starting at local 1, `arg_count` locals will be provided by the caller
201 202 203 204
    /// and can be assumed to be initialized.
    ///
    /// If this MIR was built for a constant, this will be 0.
    pub arg_count: usize,
A
Ariel Ben-Yehuda 已提交
205

206 207
    /// Mark an argument local (which must be a tuple) as getting passed as
    /// its individual components at the LLVM level.
208 209
    ///
    /// This is used for the "rust-call" ABI.
210
    pub spread_arg: Option<Local>,
211

212 213
    /// Debug information pertaining to user variables, including captures.
    pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
214

215
    /// A span representing this MIR, for error reporting.
A
Ariel Ben-Yehuda 已提交
216
    pub span: Span,
217

218 219 220
    /// Constants that are required to evaluate successfully for this MIR to be well-formed.
    /// We hold in this field all the constants we are not able to evaluate yet.
    pub required_consts: Vec<Constant<'tcx>>,
221

222 223 224 225 226 227 228 229 230 231 232
    /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
    ///
    /// Note that this does not actually mean that this body is not computable right now.
    /// The repeat count in the following example is polymorphic, but can still be evaluated
    /// without knowing anything about the type parameter `T`.
    ///
    /// ```rust
    /// fn test<T>() {
    ///     let _ = [0; std::mem::size_of::<*mut T>()];
    /// }
    /// ```
B
review  
Bastian Kauschke 已提交
233 234 235 236
    ///
    /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
    /// removed the last mention of all generic params. We do not want to rely on optimizations and
    /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
237 238
    pub is_polymorphic: bool,

239
    predecessor_cache: PredecessorCache,
D
Dániel Buga 已提交
240
    is_cyclic: GraphIsCyclicCache,
N
Niko Matsakis 已提交
241 242
}

243
impl<'tcx> Body<'tcx> {
S
Santiago Pastorino 已提交
244
    pub fn new(
245
        source: MirSource<'tcx>,
S
Santiago Pastorino 已提交
246
        basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
247
        source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
D
David Wood 已提交
248
        local_decls: LocalDecls<'tcx>,
D
Dylan MacKenzie 已提交
249
        user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
S
Santiago Pastorino 已提交
250
        arg_count: usize,
251
        var_debug_info: Vec<VarDebugInfo<'tcx>>,
S
Santiago Pastorino 已提交
252
        span: Span,
M
Mark Rousskov 已提交
253
        generator_kind: Option<GeneratorKind>,
S
Santiago Pastorino 已提交
254
    ) -> Self {
255
        // We need `arg_count` locals, and one for the return place.
S
Santiago Pastorino 已提交
256
        assert!(
257
            local_decls.len() > arg_count,
S
Santiago Pastorino 已提交
258 259 260 261
            "expected at least {} locals, got {}",
            arg_count + 1,
            local_decls.len()
        );
262

263
        let mut body = Body {
264
            phase: MirPhase::Build,
265
            source,
266
            basic_blocks,
267
            source_scopes,
D
Dániel Buga 已提交
268 269 270 271 272 273 274 275
            generator: generator_kind.map(|generator_kind| {
                Box::new(GeneratorInfo {
                    yield_ty: None,
                    generator_drop: None,
                    generator_layout: None,
                    generator_kind,
                })
            }),
276
            local_decls,
D
David Wood 已提交
277
            user_type_annotations,
278
            arg_count,
279
            spread_arg: None,
280
            var_debug_info,
281
            span,
282
            required_consts: Vec::new(),
283
            is_polymorphic: false,
284
            predecessor_cache: PredecessorCache::new(),
D
Dániel Buga 已提交
285
            is_cyclic: GraphIsCyclicCache::new(),
286 287 288
        };
        body.is_polymorphic = body.has_param_types_or_consts();
        body
N
Niko Matsakis 已提交
289 290
    }

D
Dylan MacKenzie 已提交
291 292 293 294 295 296
    /// Returns a partially initialized MIR body containing only a list of basic blocks.
    ///
    /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
    /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
    /// crate.
    pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
297
        let mut body = Body {
D
Dylan MacKenzie 已提交
298
            phase: MirPhase::Build,
299
            source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
D
Dylan MacKenzie 已提交
300 301
            basic_blocks,
            source_scopes: IndexVec::new(),
D
Dániel Buga 已提交
302
            generator: None,
D
Dylan MacKenzie 已提交
303 304 305 306 307
            local_decls: IndexVec::new(),
            user_type_annotations: IndexVec::new(),
            arg_count: 0,
            spread_arg: None,
            span: DUMMY_SP,
308
            required_consts: Vec::new(),
D
Dylan MacKenzie 已提交
309
            var_debug_info: Vec::new(),
310
            is_polymorphic: false,
311
            predecessor_cache: PredecessorCache::new(),
D
Dániel Buga 已提交
312
            is_cyclic: GraphIsCyclicCache::new(),
313 314 315
        };
        body.is_polymorphic = body.has_param_types_or_consts();
        body
D
Dylan MacKenzie 已提交
316 317
    }

318 319 320
    #[inline]
    pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
        &self.basic_blocks
N
Niko Matsakis 已提交
321 322
    }

323 324 325
    #[inline]
    pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
        // Because the user could mutate basic block terminators via this reference, we need to
D
Dániel Buga 已提交
326
        // invalidate the caches.
327 328
        //
        // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
D
Dániel Buga 已提交
329
        // invalidate the caches.
330
        self.predecessor_cache.invalidate();
D
Dániel Buga 已提交
331
        self.is_cyclic.invalidate();
332 333 334 335 336 337 338 339
        &mut self.basic_blocks
    }

    #[inline]
    pub fn basic_blocks_and_local_decls_mut(
        &mut self,
    ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
        self.predecessor_cache.invalidate();
D
Dániel Buga 已提交
340
        self.is_cyclic.invalidate();
341 342 343
        (&mut self.basic_blocks, &mut self.local_decls)
    }

344 345 346 347 348 349 350 351 352
    #[inline]
    pub fn basic_blocks_local_decls_mut_and_var_debug_info(
        &mut self,
    ) -> (
        &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
        &mut LocalDecls<'tcx>,
        &mut Vec<VarDebugInfo<'tcx>>,
    ) {
        self.predecessor_cache.invalidate();
D
Dániel Buga 已提交
353
        self.is_cyclic.invalidate();
354 355 356
        (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
    }

357 358 359
    /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
    /// `START_BLOCK`.
    pub fn is_cfg_cyclic(&self) -> bool {
D
Dániel Buga 已提交
360
        self.is_cyclic.is_cyclic(self)
361 362
    }

363 364
    #[inline]
    pub fn local_kind(&self, local: Local) -> LocalKind {
365
        let index = local.as_usize();
366
        if index == 0 {
S
Santiago Pastorino 已提交
367 368 369 370
            debug_assert!(
                self.local_decls[local].mutability == Mutability::Mut,
                "return place should be mutable"
            );
371 372 373 374

            LocalKind::ReturnPointer
        } else if index < self.arg_count + 1 {
            LocalKind::Arg
375
        } else if self.local_decls[local].is_user_variable() {
376 377 378 379 380 381
            LocalKind::Var
        } else {
            LocalKind::Temp
        }
    }

382 383 384 385 386 387
    /// Returns an iterator over all user-declared mutable locals.
    #[inline]
    pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
        (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
            let local = Local::new(index);
            let decl = &self.local_decls[local];
M
Matthew Jasper 已提交
388
            if decl.is_user_variable() && decl.mutability == Mutability::Mut {
389 390 391 392 393 394 395
                Some(local)
            } else {
                None
            }
        })
    }

396
    /// Returns an iterator over all user-declared mutable arguments and locals.
397
    #[inline]
S
Santiago Pastorino 已提交
398
    pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
399
        (1..self.local_decls.len()).filter_map(move |index| {
400 401
            let local = Local::new(index);
            let decl = &self.local_decls[local];
M
Matthew Jasper 已提交
402
            if (decl.is_user_variable() || index < self.arg_count + 1)
S
Santiago Pastorino 已提交
403
                && decl.mutability == Mutability::Mut
404
            {
405 406 407 408 409 410 411
                Some(local)
            } else {
                None
            }
        })
    }

412 413
    /// Returns an iterator over all function arguments.
    #[inline]
414
    pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
415
        let arg_count = self.arg_count;
416
        (1..arg_count + 1).map(Local::new)
417 418 419
    }

    /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
O
Oliver Schneider 已提交
420
    /// locals that are neither arguments nor the return place).
421
    #[inline]
422 423 424
    pub fn vars_and_temps_iter(
        &self,
    ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
J
Jonas Schievink 已提交
425 426
        let arg_count = self.arg_count;
        let local_count = self.local_decls.len();
S
Santiago Pastorino 已提交
427
        (arg_count + 1..local_count).map(Local::new)
428 429
    }

430 431 432
    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
    /// invalidating statement indices in `Location`s.
    pub fn make_statement_nop(&mut self, location: Location) {
433
        let block = &mut self.basic_blocks[location.block];
434 435 436
        debug_assert!(location.statement_index < block.statements.len());
        block.statements[location.statement_index].make_nop()
    }
O
Oliver Schneider 已提交
437 438 439 440 441 442 443 444 445

    /// Returns the source info associated with `location`.
    pub fn source_info(&self, location: Location) -> &SourceInfo {
        let block = &self[location.block];
        let stmts = &block.statements;
        let idx = location.statement_index;
        if idx < stmts.len() {
            &stmts[idx].source_info
        } else {
L
ljedrz 已提交
446
            assert_eq!(idx, stmts.len());
O
Oliver Schneider 已提交
447 448 449 450
            &block.terminator().source_info
        }
    }

451
    /// Returns the return type; it always return first element from `local_decls` array.
D
Dylan MacKenzie 已提交
452
    #[inline]
O
Oliver Schneider 已提交
453 454 455
    pub fn return_ty(&self) -> Ty<'tcx> {
        self.local_decls[RETURN_PLACE].ty
    }
456

457
    /// Gets the location of the terminator for the given block.
D
Dylan MacKenzie 已提交
458
    #[inline]
459
    pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
A
Albin Stjerna 已提交
460
        Location { block: bb, statement_index: self[bb].statements.len() }
461
    }
462

D
Dylan MacKenzie 已提交
463
    #[inline]
464
    pub fn predecessors(&self) -> &Predecessors {
465 466 467 468 469 470 471
        self.predecessor_cache.compute(&self.basic_blocks)
    }

    #[inline]
    pub fn dominators(&self) -> Dominators<BasicBlock> {
        dominators(self)
    }
D
Dániel Buga 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

    #[inline]
    pub fn yield_ty(&self) -> Option<Ty<'tcx>> {
        self.generator.as_ref().and_then(|generator| generator.yield_ty)
    }

    #[inline]
    pub fn generator_layout(&self) -> Option<&GeneratorLayout<'tcx>> {
        self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref())
    }

    #[inline]
    pub fn generator_drop(&self) -> Option<&Body<'tcx>> {
        self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref())
    }

    #[inline]
    pub fn generator_kind(&self) -> Option<GeneratorKind> {
        self.generator.as_ref().map(|generator| generator.generator_kind)
    }
N
Niko Matsakis 已提交
492 493
}

M
Matthew Jasper 已提交
494
#[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
A
Ariel Ben-Yehuda 已提交
495 496
pub enum Safety {
    Safe,
497 498
    /// Unsafe because of compiler-generated unsafe code, like `await` desugaring
    BuiltinUnsafe,
A
Ariel Ben-Yehuda 已提交
499 500 501
    /// Unsafe because of an unsafe fn
    FnUnsafe,
    /// Unsafe because of an `unsafe` block
L
ljedrz 已提交
502
    ExplicitUnsafe(hir::HirId),
503 504
}

505
impl<'tcx> Index<BasicBlock> for Body<'tcx> {
506 507 508 509
    type Output = BasicBlockData<'tcx>;

    #[inline]
    fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
510
        &self.basic_blocks()[index]
511 512 513
    }
}

514 515 516 517 518 519 520
impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
    #[inline]
    fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
        &mut self.basic_blocks_mut()[index]
    }
}

C
Camille GILLOT 已提交
521
#[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
O
Oliver Schneider 已提交
522
pub enum ClearCrossCrate<T> {
523
    Clear,
S
Santiago Pastorino 已提交
524
    Set(T),
525 526
}

527
impl<T> ClearCrossCrate<T> {
528
    pub fn as_ref(&self) -> ClearCrossCrate<&T> {
529 530 531 532 533 534
        match self {
            ClearCrossCrate::Clear => ClearCrossCrate::Clear,
            ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
        }
    }

535 536 537 538 539 540 541 542
    pub fn assert_crate_local(self) -> T {
        match self {
            ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
            ClearCrossCrate::Set(v) => v,
        }
    }
}

543 544 545
const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;

M
Matthew Jasper 已提交
546
impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
547
    #[inline]
M
Matthew Jasper 已提交
548 549 550 551 552
    fn encode(&self, e: &mut E) -> Result<(), E::Error> {
        if E::CLEAR_CROSS_CRATE {
            return Ok(());
        }

553 554 555 556 557 558 559 560 561
        match *self {
            ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
            ClearCrossCrate::Set(ref val) => {
                TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
                val.encode(e)
            }
        }
    }
}
M
Matthew Jasper 已提交
562
impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
563
    #[inline]
M
Matthew Jasper 已提交
564 565 566 567 568
    fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
        if D::CLEAR_CROSS_CRATE {
            return Ok(ClearCrossCrate::Clear);
        }

569 570 571 572 573 574 575 576
        let discr = u8::decode(d)?;

        match discr {
            TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
            TAG_CLEAR_CROSS_CRATE_SET => {
                let val = T::decode(d)?;
                Ok(ClearCrossCrate::Set(val))
            }
M
Matthew Jasper 已提交
577
            tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
578 579 580
        }
    }
}
581

582 583 584
/// Grouped information about the source code origin of a MIR entity.
/// Intended to be inspected by diagnostics and debuginfo.
/// Most passes can work with it as a whole, within a single function.
B
Brian Wignall 已提交
585
// The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
B
bjorn3 已提交
586
// `Hash`. Please ping @bjorn3 if removing them.
M
Matthew Jasper 已提交
587
#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
588
pub struct SourceInfo {
589
    /// The source span for the AST pertaining to this MIR entity.
590 591
    pub span: Span,

592 593
    /// The source scope, keeping track of which bindings can be
    /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
S
Santiago Pastorino 已提交
594
    pub scope: SourceScope,
595 596
}

597 598 599 600 601 602 603
impl SourceInfo {
    #[inline]
    pub fn outermost(span: Span) -> Self {
        SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
    }
}

N
Niko Matsakis 已提交
604
///////////////////////////////////////////////////////////////////////////
605
// Borrow kinds
606

M
Matthew Jasper 已提交
607
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
608
#[derive(Hash, HashStable)]
N
Niko Matsakis 已提交
609 610 611 612
pub enum BorrowKind {
    /// Data must be immutable and is aliasable.
    Shared,

M
Matthew Jasper 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    /// The immediately borrowed place must be immutable, but projections from
    /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
    /// conflict with a mutable borrow of `a.b.c`.
    ///
    /// This is used when lowering matches: when matching on a place we want to
    /// ensure that place have the same value from the start of the match until
    /// an arm is selected. This prevents this code from compiling:
    ///
    ///     let mut x = &Some(0);
    ///     match *x {
    ///         None => (),
    ///         Some(_) if { x = &None; false } => (),
    ///         Some(_) => (),
    ///     }
    ///
    /// This can't be a shared borrow because mutably borrowing (*x as Some).0
M
Matthias Krüger 已提交
629
    /// should not prevent `if let None = x { ... }`, for example, because the
M
Matthew Jasper 已提交
630 631 632 633
    /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
    /// We can also report errors with this kind of borrow differently.
    Shallow,

A
Alexander Regueiro 已提交
634
    /// Data must be immutable but not aliasable. This kind of borrow
N
Niko Matsakis 已提交
635
    /// cannot currently be expressed by the user and is used only in
A
ashtneoi 已提交
636 637
    /// implicit closure bindings. It is needed when the closure is
    /// borrowing or mutating a mutable referent, e.g.:
N
Niko Matsakis 已提交
638
    ///
639 640
    ///     let x: &mut isize = ...;
    ///     let y = || *x += 5;
N
Niko Matsakis 已提交
641 642 643 644
    ///
    /// If we were to try to translate this closure into a more explicit
    /// form, we'd encounter an error with the code as written:
    ///
645 646 647 648
    ///     struct Env { x: & &mut isize }
    ///     let x: &mut isize = ...;
    ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
    ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
N
Niko Matsakis 已提交
649
    ///
A
ashtneoi 已提交
650
    /// This is then illegal because you cannot mutate an `&mut` found
N
Niko Matsakis 已提交
651 652 653
    /// in an aliasable location. To solve, you'd have to translate with
    /// an `&mut` borrow:
    ///
654
    ///     struct Env { x: &mut &mut isize }
655 656 657
    ///     let x: &mut isize = ...;
    ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
    ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
N
Niko Matsakis 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671
    ///
    /// Now the assignment to `**env.x` is legal, but creating a
    /// mutable pointer to `x` is not because `x` is not mutable. We
    /// could fix this by declaring `x` as `let mut x`. This is ok in
    /// user code, if awkward, but extra weird for closures, since the
    /// borrow is hidden.
    ///
    /// So we introduce a "unique imm" borrow -- the referent is
    /// immutable, but not aliasable. This solves the problem. For
    /// simplicity, we don't give users the way to express this
    /// borrow, it's just used when translating closures.
    Unique,

    /// Data is mutable and not aliasable.
672
    Mut {
A
Alexander Regueiro 已提交
673 674
        /// `true` if this borrow arose from method-call auto-ref
        /// (i.e., `adjustment::Adjust::Borrow`).
S
Santiago Pastorino 已提交
675 676
        allow_two_phase_borrow: bool,
    },
N
Niko Matsakis 已提交
677 678
}

679 680 681
impl BorrowKind {
    pub fn allows_two_phase_borrow(&self) -> bool {
        match *self {
M
Matthew Jasper 已提交
682
            BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
L
ljedrz 已提交
683
            BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
684 685
        }
    }
686 687 688 689 690 691 692 693 694

    pub fn describe_mutability(&self) -> String {
        match *self {
            BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => {
                "immutable".to_string()
            }
            BorrowKind::Mut { .. } => "mutable".to_string(),
        }
    }
695 696
}

N
Niko Matsakis 已提交
697 698 699
///////////////////////////////////////////////////////////////////////////
// Variables and temps

700
rustc_index::newtype_index! {
701
    pub struct Local {
702
        derive [HashStable]
O
Oliver Schneider 已提交
703 704
        DEBUG_FORMAT = "_{}",
        const RETURN_PLACE = 0,
705 706
    }
}
707

708 709 710 711 712 713
impl Atom for Local {
    fn index(self) -> usize {
        Idx::index(self)
    }
}

714
/// Classifies locals into categories. See `Body::local_kind`.
715
#[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
716
pub enum LocalKind {
717
    /// User-declared variable binding.
718
    Var,
719
    /// Compiler-introduced temporary.
720
    Temp,
721
    /// Function argument.
722
    Arg,
723
    /// Location of function's return value.
724 725 726
    ReturnPointer,
}

M
Matthew Jasper 已提交
727
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
728
pub struct VarBindingForm<'tcx> {
729 730 731 732 733
    /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
    pub binding_mode: ty::BindingMode,
    /// If an explicit type was provided for this variable binding,
    /// this holds the source Span of that type.
    ///
A
Alexander Regueiro 已提交
734
    /// NOTE: if you want to change this to a `HirId`, be wary that
735 736 737
    /// doing so breaks incremental compilation (as of this writing),
    /// while a `Span` does not cause our tests to fail.
    pub opt_ty_info: Option<Span>,
738 739 740 741 742 743 744
    /// Place of the RHS of the =, or the subject of the `match` where this
    /// variable is initialized. None in the case of `let PATTERN;`.
    /// Some((None, ..)) in the case of and `let [mut] x = ...` because
    /// (a) the right-hand side isn't evaluated as a place expression.
    /// (b) it gives a way to separate this case from the remaining cases
    ///     for diagnostics.
    pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
745
    /// The span of the pattern in which this variable was bound.
746
    pub pat_span: Span,
747 748
}

M
Matthew Jasper 已提交
749
#[derive(Clone, Debug, TyEncodable, TyDecodable)]
750
pub enum BindingForm<'tcx> {
751
    /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
752
    Var(VarBindingForm<'tcx>),
753
    /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
754
    ImplicitSelf(ImplicitSelfKind),
755 756
    /// Reference used in a guard expression to ensure immutability.
    RefForGuard,
757 758
}

759
/// Represents what type of implicit self a function has, if any.
M
Matthew Jasper 已提交
760
#[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
761 762 763 764 765 766 767 768 769 770 771
pub enum ImplicitSelfKind {
    /// Represents a `fn x(self);`.
    Imm,
    /// Represents a `fn x(mut self);`.
    Mut,
    /// Represents a `fn x(&self);`.
    ImmRef,
    /// Represents a `fn x(&mut self);`.
    MutRef,
    /// Represents when a function does not have a self argument or
    /// when a function has a `self: X` argument.
A
Albin Stjerna 已提交
772
    None,
773 774
}

L
words  
lcnr 已提交
775
TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
776

777
mod binding_form_impl {
M
Mark Mansi 已提交
778
    use crate::ich::StableHashingContext;
779
    use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
780

781
    impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
782
        fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
783
            use super::BindingForm::*;
E
est31 已提交
784
            std::mem::discriminant(self).hash_stable(hcx, hasher);
785 786 787

            match self {
                Var(binding) => binding.hash_stable(hcx, hasher),
788
                ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
789
                RefForGuard => (),
790 791 792 793
            }
        }
    }
}
794

795 796 797 798 799
/// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
/// created during evaluation of expressions in a block tail
/// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
///
/// It is used to improve diagnostics when such temporaries are
800
/// involved in borrow_check errors, e.g., explanations of where the
801 802
/// temporaries come from, when their destructors are run, and/or how
/// one might revise the code to satisfy the borrow checker's rules.
M
Matthew Jasper 已提交
803
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
804 805 806 807 808
pub struct BlockTailInfo {
    /// If `true`, then the value resulting from evaluating this tail
    /// expression is ignored by the block's expression context.
    ///
    /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
809
    /// but not e.g., `let _x = { ...; tail };`
810
    pub tail_result_is_ignored: bool,
811 812 813

    /// `Span` of the tail expression.
    pub span: Span,
814 815
}

816 817 818
/// A MIR local.
///
/// This can be a binding declared by the user, a temporary inserted by the compiler, a function
O
Oliver Schneider 已提交
819
/// argument, or the return place.
M
Matthew Jasper 已提交
820
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
821
pub struct LocalDecl<'tcx> {
822
    /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
823
    ///
O
Oliver Schneider 已提交
824
    /// Temporaries and the return place are always mutable.
N
Niko Matsakis 已提交
825
    pub mutability: Mutability,
826

M
Matthew Jasper 已提交
827
    // FIXME(matthewjasper) Don't store in this in `Body`
828
    pub local_info: Option<Box<LocalInfo<'tcx>>>,
829

A
Alexander Regueiro 已提交
830
    /// `true` if this is an internal local.
831
    ///
J
John Kåre Alsaker 已提交
832
    /// These locals are not based on types in the source code and are only used
A
Ariel Ben-Yehuda 已提交
833
    /// for a few desugarings at the moment.
834 835 836 837 838
    ///
    /// The generator transformation will sanity check the locals which are live
    /// across a suspension point against the type components of the generator
    /// which type checking knows are live across a suspension point. We need to
    /// flag drop flags to avoid triggering this check as they are introduced
J
John Kåre Alsaker 已提交
839
    /// after typeck.
840 841
    ///
    /// This should be sound because the drop flags are fully algebraic, and
842
    /// therefore don't affect the auto-trait or outlives properties of the
843
    /// generator.
844 845
    pub internal: bool,

846 847 848 849
    /// If this local is a temporary and `is_block_tail` is `Some`,
    /// then it is a temporary created for evaluation of some
    /// subexpression of some block's tail expression (with no
    /// intervening statement context).
M
Matthew Jasper 已提交
850
    // FIXME(matthewjasper) Don't store in this in `Body`
851 852
    pub is_block_tail: Option<BlockTailInfo>,

853
    /// The type of this local.
854
    pub ty: Ty<'tcx>,
855

856
    /// If the user manually ascribed a type to this variable,
857
    /// e.g., via `let x: T`, then we carry that type here. The MIR
858 859
    /// borrow checker needs this information since it can affect
    /// region inference.
M
Matthew Jasper 已提交
860
    // FIXME(matthewjasper) Don't store in this in `Body`
861
    pub user_ty: Option<Box<UserTypeProjections>>,
862

863
    /// The *syntactic* (i.e., not visibility) source scope the local is defined
864 865
    /// in. If the local was defined in a let-statement, this
    /// is *within* the let-statement, rather than outside
A
Ariel Ben-Yehuda 已提交
866
    /// of it.
867
    ///
868 869
    /// This is needed because the visibility source scope of locals within
    /// a let-statement is weird.
870 871 872 873 874 875 876
    ///
    /// The reason is that we want the local to be *within* the let-statement
    /// for lint purposes, but we want the local to be *after* the let-statement
    /// for names-in-scope purposes.
    ///
    /// That's it, if we have a let-statement like the one in this
    /// function:
877
    ///
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    /// ```
    /// fn foo(x: &str) {
    ///     #[allow(unused_mut)]
    ///     let mut x: u32 = { // <- one unused mut
    ///         let mut y: u32 = x.parse().unwrap();
    ///         y + 2
    ///     };
    ///     drop(x);
    /// }
    /// ```
    ///
    /// Then, from a lint point of view, the declaration of `x: u32`
    /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
    /// lint scopes are the same as the AST/HIR nesting.
    ///
    /// However, from a name lookup point of view, the scopes look more like
    /// as if the let-statements were `match` expressions:
    ///
    /// ```
    /// fn foo(x: &str) {
    ///     match {
    ///         match x.parse().unwrap() {
    ///             y => y + 2
    ///         }
    ///     } {
    ///         x => drop(x)
    ///     };
    /// }
    /// ```
    ///
    /// We care about the name-lookup scopes for debuginfo - if the
    /// debuginfo instruction pointer is at the call to `x.parse()`, we
    /// want `x` to refer to `x: &str`, but if it is at the call to
    /// `drop(x)`, we want it to refer to `x: u32`.
    ///
    /// To allow both uses to work, we need to have more than a single scope
914 915 916
    /// for a local. We have the `source_info.scope` represent the "syntactic"
    /// lint scope (with a variable being under its let block) while the
    /// `var_debug_info.source_info.scope` represents the "local variable"
917 918 919 920
    /// scope (where the "rest" of a block is under all prior let-statements).
    ///
    /// The end result looks like this:
    ///
921
    /// ```text
922 923 924
    /// ROOT SCOPE
    ///  │{ argument x: &str }
    ///  │
925 926
    ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
    ///  │ │                         // in practice because I'm lazy.
927
    ///  │ │
928
    ///  │ │← x.source_info.scope
929 930
    ///  │ │← `x.parse().unwrap()`
    ///  │ │
931
    ///  │ │ │← y.source_info.scope
932 933 934
    ///  │ │
    ///  │ │ │{ let y: u32 }
    ///  │ │ │
935
    ///  │ │ │← y.var_debug_info.source_info.scope
936 937 938
    ///  │ │ │← `y + 2`
    ///  │
    ///  │ │{ let x: u32 }
939
    ///  │ │← x.var_debug_info.source_info.scope
940
    ///  │ │← `drop(x)` // This accesses `x: u32`.
941
    /// ```
942
    pub source_info: SourceInfo,
N
Niko Matsakis 已提交
943 944
}

945
// `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
946
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
947
static_assert_size!(LocalDecl<'_>, 56);
948

R
Ralf Jung 已提交
949 950 951 952 953 954
/// Extra information about a some locals that's used for diagnostics and for
/// classifying variables into local variables, statics, etc, which is needed e.g.
/// for unsafety checking.
///
/// Not used for non-StaticRef temporaries, the return place, or anonymous
/// function parameters.
M
Matthew Jasper 已提交
955
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
M
Matthew Jasper 已提交
956 957
pub enum LocalInfo<'tcx> {
    /// A user-defined local variable or function parameter
M
Matthew Jasper 已提交
958 959 960 961
    ///
    /// The `BindingForm` is solely used for local diagnostics when generating
    /// warnings/errors when compiling the current crate, and therefore it need
    /// not be visible across crates.
M
Matthew Jasper 已提交
962 963 964
    User(ClearCrossCrate<BindingForm<'tcx>>),
    /// A temporary created that references the static with the given `DefId`.
    StaticRef { def_id: DefId, is_thread_local: bool },
A
Aaron Hill 已提交
965 966
    /// A temporary created that references the const with the given `DefId`
    ConstRef { def_id: DefId },
M
Matthew Jasper 已提交
967 968
}

969
impl<'tcx> LocalDecl<'tcx> {
A
Alexander Regueiro 已提交
970
    /// Returns `true` only if local is a binding that can itself be
971 972 973 974 975
    /// made mutable via the addition of the `mut` keyword, namely
    /// something like the occurrences of `x` in:
    /// - `fn foo(x: Type) { ... }`,
    /// - `let x = ...`,
    /// - or `match ... { C(x) => ... }`
S
Santiago Pastorino 已提交
976
    pub fn can_be_made_mutable(&self) -> bool {
977 978 979 980 981 982 983 984
        matches!(
            self.local_info,
            Some(box LocalInfo::User(ClearCrossCrate::Set(
                BindingForm::Var(VarBindingForm {
                    binding_mode: ty::BindingMode::BindByValue(_),
                    opt_ty_info: _,
                    opt_match_place: _,
                    pat_span: _,
M
Mark Rousskov 已提交
985
                }) | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
986 987
            )))
        )
988 989
    }

A
Alexander Regueiro 已提交
990
    /// Returns `true` if local is definitely not a `ref ident` or
991 992
    /// `ref mut ident` binding. (Such bindings cannot be made into
    /// mutable bindings, but the inverse does not necessarily hold).
S
Santiago Pastorino 已提交
993
    pub fn is_nonref_binding(&self) -> bool {
994 995 996 997 998 999 1000 1001
        matches!(
            self.local_info,
            Some(box LocalInfo::User(ClearCrossCrate::Set(
                BindingForm::Var(VarBindingForm {
                    binding_mode: ty::BindingMode::BindByValue(_),
                    opt_ty_info: _,
                    opt_match_place: _,
                    pat_span: _,
M
Mark Rousskov 已提交
1002
                }) | BindingForm::ImplicitSelf(_),
1003 1004
            )))
        )
1005 1006
    }

M
Matthew Jasper 已提交
1007 1008 1009 1010
    /// Returns `true` if this variable is a named variable or function
    /// parameter declared by the user.
    #[inline]
    pub fn is_user_variable(&self) -> bool {
1011
        matches!(self.local_info, Some(box LocalInfo::User(_)))
1012 1013
    }

M
Matthew Jasper 已提交
1014 1015 1016 1017
    /// Returns `true` if this is a reference to a variable bound in a `match`
    /// expression that is used to access said variable for the guard of the
    /// match arm.
    pub fn is_ref_for_guard(&self) -> bool {
1018 1019 1020 1021
        matches!(
            self.local_info,
            Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
        )
M
Matthew Jasper 已提交
1022 1023 1024
    }

    /// Returns `Some` if this is a reference to a static item that is used to
R
Ralf Jung 已提交
1025
    /// access that static.
M
Matthew Jasper 已提交
1026
    pub fn is_ref_to_static(&self) -> bool {
1027
        matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
M
Matthew Jasper 已提交
1028 1029
    }

R
Ralf Jung 已提交
1030 1031
    /// Returns `Some` if this is a reference to a thread-local static item that is used to
    /// access that static.
M
Matthew Jasper 已提交
1032 1033
    pub fn is_ref_to_thread_local(&self) -> bool {
        match self.local_info {
1034
            Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
M
Matthew Jasper 已提交
1035 1036 1037 1038
            _ => false,
        }
    }

1039 1040 1041 1042
    /// Returns `true` is the local is from a compiler desugaring, e.g.,
    /// `__next` from a `for` loop.
    #[inline]
    pub fn from_compiler_desugaring(&self) -> bool {
1043
        self.source_info.span.desugaring_kind().is_some()
1044 1045
    }

1046
    /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1047
    #[inline]
1048 1049 1050 1051 1052 1053 1054 1055 1056
    pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
        Self::with_source_info(ty, SourceInfo::outermost(span))
    }

    /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
    #[inline]
    pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
        LocalDecl {
            mutability: Mutability::Mut,
1057
            local_info: None,
1058 1059 1060
            internal: false,
            is_block_tail: None,
            ty,
1061
            user_ty: None,
1062 1063 1064 1065 1066 1067 1068 1069 1070
            source_info,
        }
    }

    /// Converts `self` into same `LocalDecl` except tagged as internal.
    #[inline]
    pub fn internal(mut self) -> Self {
        self.internal = true;
        self
1071 1072
    }

1073
    /// Converts `self` into same `LocalDecl` except tagged as immutable.
1074
    #[inline]
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    pub fn immutable(mut self) -> Self {
        self.mutability = Mutability::Not;
        self
    }

    /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
    #[inline]
    pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
        assert!(self.is_block_tail.is_none());
        self.is_block_tail = Some(info);
        self
1086
    }
1087 1088
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
#[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
pub enum VarDebugInfoContents<'tcx> {
    /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
    /// based on a `Local`, not a `Static`, and contains no indexing.
    Place(Place<'tcx>),
    Const(Constant<'tcx>),
}

impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        match self {
            VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
            VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
        }
    }
}

1106
/// Debug information pertaining to a user variable.
M
Matthew Jasper 已提交
1107
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1108
pub struct VarDebugInfo<'tcx> {
1109
    pub name: Symbol,
1110

1111 1112 1113 1114 1115 1116
    /// Source info of the user variable, including the scope
    /// within which the variable is visible (to debuginfo)
    /// (see `LocalDecl`'s `source_info` field for more details).
    pub source_info: SourceInfo,

    /// Where the data for this user variable is to be found.
1117
    pub value: VarDebugInfoContents<'tcx>,
N
Niko Matsakis 已提交
1118 1119 1120 1121 1122
}

///////////////////////////////////////////////////////////////////////////
// BasicBlock

1123
rustc_index::newtype_index! {
C
Camelid 已提交
1124
    /// A node in the MIR [control-flow graph][CFG].
C
Camelid 已提交
1125
    ///
C
Camelid 已提交
1126
    /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
C
Camelid 已提交
1127 1128 1129
    /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
    /// as an edge in a graph between basic blocks.
    ///
C
Camelid 已提交
1130
    /// Basic blocks consist of a series of [statements][Statement], ending with a
C
Camelid 已提交
1131 1132 1133 1134
    /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
    /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
    /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
    /// needed because some analyses require that there are no critical edges in the CFG.
C
Camelid 已提交
1135
    ///
C
Camelid 已提交
1136 1137 1138
    /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
    /// the actual data that a basic block holds is in [`BasicBlockData`].
    ///
C
Camelid 已提交
1139 1140 1141 1142 1143
    /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
    ///
    /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
    /// [data-flow analyses]:
    ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
C
Camelid 已提交
1144
    /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
C
Camelid 已提交
1145
    /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1146
    pub struct BasicBlock {
1147
        derive [HashStable]
1148 1149
        DEBUG_FORMAT = "bb{}",
        const START_BLOCK = 0,
1150 1151
    }
}
O
Oliver Schneider 已提交
1152 1153 1154

impl BasicBlock {
    pub fn start_location(self) -> Location {
A
Albin Stjerna 已提交
1155
        Location { block: self, statement_index: 0 }
O
Oliver Schneider 已提交
1156 1157
    }
}
N
Niko Matsakis 已提交
1158 1159

///////////////////////////////////////////////////////////////////////////
S
Simonas Kazlauskas 已提交
1160
// BasicBlockData and Terminator
N
Niko Matsakis 已提交
1161

C
Camelid 已提交
1162
/// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
M
Matthew Jasper 已提交
1163
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1164
pub struct BasicBlockData<'tcx> {
N
Niko Matsakis 已提交
1165
    /// List of statements in this block.
1166
    pub statements: Vec<Statement<'tcx>>,
N
Niko Matsakis 已提交
1167 1168 1169

    /// Terminator for this block.
    ///
A
Alexander Regueiro 已提交
1170
    /// N.B., this should generally ONLY be `None` during construction.
N
Niko Matsakis 已提交
1171 1172 1173 1174 1175
    /// Therefore, you should generally access it via the
    /// `terminator()` or `terminator_mut()` methods. The only
    /// exception is that certain passes, such as `simplify_cfg`, swap
    /// out the terminator temporarily with `None` while they continue
    /// to recurse over the set of basic blocks.
S
Simonas Kazlauskas 已提交
1176
    pub terminator: Option<Terminator<'tcx>>,
N
Niko Matsakis 已提交
1177 1178

    /// If true, this block lies on an unwind path. This is used
I
Irina Popa 已提交
1179
    /// during codegen where distinct kinds of basic blocks may be
N
Niko Matsakis 已提交
1180 1181
    /// generated (particularly for MSVC cleanup). Unwind blocks must
    /// only branch to other unwind blocks.
1182
    pub is_cleanup: bool,
N
Niko Matsakis 已提交
1183 1184
}

R
Ralf Jung 已提交
1185
/// Information about an assertion failure.
1186
#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)]
R
Ralf Jung 已提交
1187
pub enum AssertKind<O> {
R
Ralf Jung 已提交
1188
    BoundsCheck { len: O, index: O },
1189 1190 1191 1192
    Overflow(BinOp, O, O),
    OverflowNeg(O),
    DivisionByZero(O),
    RemainderByZero(O),
R
Ralf Jung 已提交
1193 1194 1195 1196
    ResumedAfterReturn(GeneratorKind),
    ResumedAfterPanic(GeneratorKind),
}

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
#[derive(
    Clone,
    Debug,
    PartialEq,
    PartialOrd,
    TyEncodable,
    TyDecodable,
    Hash,
    HashStable,
    TypeFoldable
)]
A
Amanieu d'Antras 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
pub enum InlineAsmOperand<'tcx> {
    In {
        reg: InlineAsmRegOrRegClass,
        value: Operand<'tcx>,
    },
    Out {
        reg: InlineAsmRegOrRegClass,
        late: bool,
        place: Option<Place<'tcx>>,
    },
    InOut {
        reg: InlineAsmRegOrRegClass,
        late: bool,
        in_value: Operand<'tcx>,
        out_place: Option<Place<'tcx>>,
    },
    Const {
1225
        value: Box<Constant<'tcx>>,
A
Amanieu d'Antras 已提交
1226 1227 1228 1229 1230
    },
    SymFn {
        value: Box<Constant<'tcx>>,
    },
    SymStatic {
1231
        def_id: DefId,
A
Amanieu d'Antras 已提交
1232 1233 1234
    },
}

R
Ralf Jung 已提交
1235
/// Type for MIR `Assert` terminator error messages.
R
Ralf Jung 已提交
1236
pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
R
Ralf Jung 已提交
1237

1238 1239 1240 1241 1242
pub type Successors<'a> =
    iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
pub type SuccessorsMut<'a> =
    iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;

1243
impl<'tcx> BasicBlockData<'tcx> {
S
Simonas Kazlauskas 已提交
1244
    pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
A
Albin Stjerna 已提交
1245
        BasicBlockData { statements: vec![], terminator, is_cleanup: false }
N
Niko Matsakis 已提交
1246
    }
S
Simonas Kazlauskas 已提交
1247 1248 1249 1250 1251

    /// Accessor for terminator.
    ///
    /// Terminator may not be None after construction of the basic block is complete. This accessor
    /// provides a convenience way to reach the terminator.
1252
    #[inline]
S
Simonas Kazlauskas 已提交
1253 1254 1255 1256
    pub fn terminator(&self) -> &Terminator<'tcx> {
        self.terminator.as_ref().expect("invalid terminator state")
    }

1257
    #[inline]
1258
    pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
S
Simonas Kazlauskas 已提交
1259 1260
        self.terminator.as_mut().expect("invalid terminator state")
    }
J
John Kåre Alsaker 已提交
1261

S
Santiago Pastorino 已提交
1262 1263
    pub fn retain_statements<F>(&mut self, mut f: F)
    where
1264
        F: FnMut(&mut Statement<'_>) -> bool,
S
Santiago Pastorino 已提交
1265
    {
J
John Kåre Alsaker 已提交
1266 1267
        for s in &mut self.statements {
            if !f(s) {
1268
                s.make_nop();
J
John Kåre Alsaker 已提交
1269 1270 1271
            }
        }
    }
1272

1273
    pub fn expand_statements<F, I>(&mut self, mut f: F)
S
Santiago Pastorino 已提交
1274 1275 1276
    where
        F: FnMut(&mut Statement<'tcx>) -> Option<I>,
        I: iter::TrustedLen<Item = Statement<'tcx>>,
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    {
        // Gather all the iterators we'll need to splice in, and their positions.
        let mut splices: Vec<(usize, I)> = vec![];
        let mut extra_stmts = 0;
        for (i, s) in self.statements.iter_mut().enumerate() {
            if let Some(mut new_stmts) = f(s) {
                if let Some(first) = new_stmts.next() {
                    // We can already store the first new statement.
                    *s = first;

                    // Save the other statements for optimized splicing.
                    let remaining = new_stmts.size_hint().0;
                    if remaining > 0 {
                        splices.push((i + 1 + extra_stmts, new_stmts));
                        extra_stmts += remaining;
                    }
                } else {
                    s.make_nop();
                }
            }
        }

        // Splice in the new statements, from the end of the block.
        // FIXME(eddyb) This could be more efficient with a "gap buffer"
        // where a range of elements ("gap") is left uninitialized, with
        // splicing adding new elements to the end of that gap and moving
        // existing elements from before the gap to the end of the gap.
        // For now, this is safe code, emulating a gap but initializing it.
S
Santiago Pastorino 已提交
1305 1306 1307
        let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
        self.statements.resize(
            gap.end,
1308
            Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
S
Santiago Pastorino 已提交
1309
        );
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        for (splice_start, new_stmts) in splices.into_iter().rev() {
            let splice_end = splice_start + new_stmts.size_hint().0;
            while gap.end > splice_end {
                gap.start -= 1;
                gap.end -= 1;
                self.statements.swap(gap.start, gap.end);
            }
            self.statements.splice(splice_start..splice_end, new_stmts);
            gap.end = splice_start;
        }
    }

1322
    pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
M
Mark Rousskov 已提交
1323
        if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1324
    }
N
Niko Matsakis 已提交
1325 1326
}

R
Ralf Jung 已提交
1327
impl<O> AssertKind<O> {
R
Ralf Jung 已提交
1328 1329 1330 1331
    /// Getting a description does not require `O` to be printable, and does not
    /// require allocation.
    /// The caller is expected to handle `BoundsCheck` separately.
    pub fn description(&self) -> &'static str {
R
Ralf Jung 已提交
1332
        use AssertKind::*;
R
Ralf Jung 已提交
1333
        match self {
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
            Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
            Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
            Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
            Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
            Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
            OverflowNeg(_) => "attempt to negate with overflow",
            Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
            Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
            Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
            DivisionByZero(_) => "attempt to divide by zero",
            RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
R
Ralf Jung 已提交
1345 1346 1347 1348
            ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
            ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
            ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
            ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
R
Ralf Jung 已提交
1349
            BoundsCheck { .. } => bug!("Unexpected AssertKind"),
R
Ralf Jung 已提交
1350 1351
        }
    }
1352 1353

    /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1354
    pub fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1355 1356 1357
    where
        O: Debug,
    {
1358
        use AssertKind::*;
1359
        match self {
1360
            BoundsCheck { ref len, ref index } => write!(
1361
                f,
1362
                "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1363 1364
                len, index
            ),
1365 1366

            OverflowNeg(op) => {
1367
                write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1368
            }
1369
            DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1370 1371
            RemainderByZero(op) => write!(
                f,
1372
                "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1373 1374 1375 1376
                op
            ),
            Overflow(BinOp::Add, l, r) => write!(
                f,
1377
                "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1378 1379 1380 1381
                l, r
            ),
            Overflow(BinOp::Sub, l, r) => write!(
                f,
1382
                "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1383 1384 1385 1386
                l, r
            ),
            Overflow(BinOp::Mul, l, r) => write!(
                f,
1387
                "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1388 1389 1390 1391
                l, r
            ),
            Overflow(BinOp::Div, l, r) => write!(
                f,
1392
                "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1393 1394 1395 1396
                l, r
            ),
            Overflow(BinOp::Rem, l, r) => write!(
                f,
1397
                "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1398 1399 1400
                l, r
            ),
            Overflow(BinOp::Shr, _, r) => {
1401
                write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1402 1403
            }
            Overflow(BinOp::Shl, _, r) => {
1404
                write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1405
            }
1406 1407 1408
            _ => write!(f, "\"{}\"", self.description()),
        }
    }
R
Ralf Jung 已提交
1409 1410
}

R
Ralf Jung 已提交
1411
impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
R
Ralf Jung 已提交
1412
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
R
Ralf Jung 已提交
1413
        use AssertKind::*;
R
Ralf Jung 已提交
1414
        match self {
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
            BoundsCheck { ref len, ref index } => write!(
                f,
                "index out of bounds: the length is {:?} but the index is {:?}",
                len, index
            ),
            OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
            DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
            RemainderByZero(op) => write!(
                f,
                "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
                op
            ),
1427
            Overflow(BinOp::Add, l, r) => {
1428
                write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1429 1430
            }
            Overflow(BinOp::Sub, l, r) => {
1431
                write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1432 1433
            }
            Overflow(BinOp::Mul, l, r) => {
1434
                write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1435 1436
            }
            Overflow(BinOp::Div, l, r) => {
1437
                write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1438 1439 1440
            }
            Overflow(BinOp::Rem, l, r) => write!(
                f,
1441
                "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1442 1443 1444
                l, r
            ),
            Overflow(BinOp::Shr, _, r) => {
1445
                write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1446 1447
            }
            Overflow(BinOp::Shl, _, r) => {
1448
                write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1449
            }
R
Ralf Jung 已提交
1450 1451 1452 1453 1454
            _ => write!(f, "{}", self.description()),
        }
    }
}

N
Niko Matsakis 已提交
1455 1456 1457
///////////////////////////////////////////////////////////////////////////
// Statements

M
Matthew Jasper 已提交
1458
#[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1459
pub struct Statement<'tcx> {
1460
    pub source_info: SourceInfo,
1461
    pub kind: StatementKind<'tcx>,
N
Niko Matsakis 已提交
1462 1463
}

1464
// `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1465
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
R
Roxane 已提交
1466
static_assert_size!(Statement<'_>, 32);
1467

1468
impl Statement<'_> {
1469 1470 1471 1472 1473
    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
    /// invalidating statement indices in `Location`s.
    pub fn make_nop(&mut self) {
        self.kind = StatementKind::Nop
    }
1474 1475 1476 1477 1478

    /// Changes a statement to a nop and returns the original statement.
    pub fn replace_nop(&mut self) -> Self {
        Statement {
            source_info: self.source_info,
S
Santiago Pastorino 已提交
1479
            kind: mem::replace(&mut self.kind, StatementKind::Nop),
1480 1481
        }
    }
1482 1483
}

1484
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1485
pub enum StatementKind<'tcx> {
O
Oliver Schneider 已提交
1486
    /// Write the RHS Rvalue to the LHS Place.
1487
    Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1488

1489
    /// This represents all the reading that a pattern match may do
1490
    /// (e.g., inspecting constants and discriminant values), and the
1491 1492
    /// kind of pattern it comes from. This is in order to adapt potential
    /// error messages to these specific patterns.
1493
    ///
1494
    /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
A
Alexander Regueiro 已提交
1495
    /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
R
Roxane 已提交
1496
    FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
1497

O
Oliver Schneider 已提交
1498
    /// Write the discriminant for a variant to the enum Place.
1499
    SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1500 1501

    /// Start a live range for the storage of the local.
1502
    StorageLive(Local),
1503 1504

    /// End the current live range for the storage of the local.
1505
    StorageDead(Local),
1506

N
Nicholas Nethercote 已提交
1507 1508
    /// Executes a piece of inline Assembly. Stored in a Box to keep the size
    /// of `StatementKind` low.
A
Amanieu d'Antras 已提交
1509
    LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1510

A
Alexander Regueiro 已提交
1511
    /// Retag references in the given place, ensuring they got fresh tags. This is
R
Ralf Jung 已提交
1512 1513
    /// part of the Stacked Borrows model. These statements are currently only interpreted
    /// by miri and only generated when "-Z mir-emit-retag" is passed.
1514 1515
    /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
    /// for more details.
1516
    Retag(RetagKind, Box<Place<'tcx>>),
1517

1518 1519
    /// Encodes a user's type ascription. These need to be preserved
    /// intact so that NLL can respect them. For example:
D
David Wood 已提交
1520
    ///
1521
    ///     let a: T = y;
D
David Wood 已提交
1522
    ///
1523 1524 1525 1526 1527 1528 1529
    /// The effect of this annotation is to relate the type `T_y` of the place `y`
    /// to the user-given type `T`. The effect depends on the specified variance:
    ///
    /// - `Covariant` -- requires that `T_y <: T`
    /// - `Contravariant` -- requires that `T_y :> T`
    /// - `Invariant` -- requires that `T_y == T`
    /// - `Bivariant` -- no effect
1530
    AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
D
David Wood 已提交
1531

1532
    /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1533 1534
    /// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
    /// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
K
klensy 已提交
1535
    /// executable code, to increment a counter variable at runtime, each time the code region is
1536
    /// executed.
1537 1538
    Coverage(Box<Coverage>),

K
kadmin 已提交
1539 1540 1541 1542 1543
    /// Denotes a call to the intrinsic function copy_overlapping, where `src_dst` denotes the
    /// memory being read from and written to(one field to save memory), and size
    /// indicates how many bytes are being copied over.
    CopyNonOverlapping(Box<CopyNonOverlapping<'tcx>>),

1544 1545
    /// No-op. Useful for deleting instructions without affecting statement indices.
    Nop,
N
Niko Matsakis 已提交
1546 1547
}

1548
impl<'tcx> StatementKind<'tcx> {
1549 1550 1551 1552 1553 1554 1555 1556
    pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
        match self {
            StatementKind::Assign(x) => Some(x),
            _ => None,
        }
    }

    pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
1557 1558 1559 1560 1561 1562 1563
        match self {
            StatementKind::Assign(x) => Some(x),
            _ => None,
        }
    }
}

1564
/// Describes what kind of retag is to be performed.
1565
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
1566
pub enum RetagKind {
1567
    /// The initial retag when entering a function.
1568
    FnEntry,
1569
    /// Retag preparing for a two-phase borrow.
1570
    TwoPhase,
1571
    /// Retagging raw pointers.
1572
    Raw,
1573
    /// A "normal" retag.
1574 1575 1576
    Default,
}

1577
/// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1578
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
1579
pub enum FakeReadCause {
1580 1581
    /// Inject a fake read of the borrowed input at the end of each guards
    /// code.
1582
    ///
1583 1584
    /// This should ensure that you cannot change the variant for an enum while
    /// you are in the midst of matching on it.
1585 1586 1587 1588
    ForMatchGuard,

    /// `let x: !; match x {}` doesn't generate any read of x so we need to
    /// generate a read of x to check that it is initialized and safe.
1589 1590 1591 1592 1593 1594
    ///
    /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
    /// FakeRead for that Place outside the closure, in such a case this option would be
    /// Some(closure_def_id).
    /// Otherwise, the value of the optional DefId will be None.
    ForMatchedPlace(Option<DefId>),
1595

1596 1597 1598 1599 1600
    /// A fake read of the RefWithinGuard version of a bind-by-value variable
    /// in a match guard to ensure that it's value hasn't change by the time
    /// we create the OutsideGuard version.
    ForGuardBinding,

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
    /// Officially, the semantics of
    ///
    /// `let pattern = <expr>;`
    ///
    /// is that `<expr>` is evaluated into a temporary and then this temporary is
    /// into the pattern.
    ///
    /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
    /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
    /// but in some cases it can affect the borrow checker, as in #53695.
    /// Therefore, we insert a "fake read" here to ensure that we get
    /// appropriate errors.
1613 1614 1615 1616 1617 1618
    ///
    /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
    /// FakeRead for that Place outside the closure, in such a case this option would be
    /// Some(closure_def_id).
    /// Otherwise, the value of the optional DefId will be None.
    ForLet(Option<DefId>),
1619 1620 1621 1622 1623 1624 1625 1626 1627

    /// If we have an index expression like
    ///
    /// (*x)[1][{ x = y; 4}]
    ///
    /// then the first bounds check is invalidated when we evaluate the second
    /// index expression. Thus we create a fake borrow of `x` across the second
    /// indexer, which will cause a borrow check error.
    ForIndex,
1628 1629
}

1630
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
A
Amanieu d'Antras 已提交
1631 1632
pub struct LlvmInlineAsm<'tcx> {
    pub asm: hir::LlvmInlineAsmInner,
N
Nicholas Nethercote 已提交
1633 1634 1635 1636
    pub outputs: Box<[Place<'tcx>]>,
    pub inputs: Box<[(Span, Operand<'tcx>)]>,
}

1637
impl Debug for Statement<'_> {
1638
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
N
Niko Matsakis 已提交
1639 1640
        use self::StatementKind::*;
        match self.kind {
M
Mark Rousskov 已提交
1641
            Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
R
Roxane 已提交
1642 1643 1644
            FakeRead(box (ref cause, ref place)) => {
                write!(fmt, "FakeRead({:?}, {:?})", cause, place)
            }
A
Albin Stjerna 已提交
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
            Retag(ref kind, ref place) => write!(
                fmt,
                "Retag({}{:?})",
                match kind {
                    RetagKind::FnEntry => "[fn entry] ",
                    RetagKind::TwoPhase => "[2phase] ",
                    RetagKind::Raw => "[raw] ",
                    RetagKind::Default => "",
                },
                place,
            ),
O
Oliver Schneider 已提交
1656 1657
            StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
            StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
A
Albin Stjerna 已提交
1658 1659 1660
            SetDiscriminant { ref place, variant_index } => {
                write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
            }
A
Amanieu d'Antras 已提交
1661 1662
            LlvmInlineAsm(ref asm) => {
                write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
A
Albin Stjerna 已提交
1663
            }
M
Mark Rousskov 已提交
1664
            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1665
                write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
S
Santiago Pastorino 已提交
1666
            }
L
Léo Lanteri Thauvin 已提交
1667 1668
            Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
                write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
1669
            }
L
Léo Lanteri Thauvin 已提交
1670
            Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
K
kadmin 已提交
1671 1672 1673
            CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
                ref src,
                ref dst,
K
kadmin 已提交
1674 1675 1676 1677
                ref count,
            }) => {
                write!(fmt, "copy_nonoverlapping(src={:?}, dst={:?}, count={:?})", src, dst, count)
            }
1678
            Nop => write!(fmt, "nop"),
N
Niko Matsakis 已提交
1679 1680 1681
        }
    }
}
1682

1683
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
1684 1685
pub struct Coverage {
    pub kind: CoverageKind,
1686
    pub code_region: Option<CodeRegion>,
1687 1688
}

1689
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)]
K
kadmin 已提交
1690
pub struct CopyNonOverlapping<'tcx> {
K
kadmin 已提交
1691 1692
    pub src: Operand<'tcx>,
    pub dst: Operand<'tcx>,
K
kadmin 已提交
1693 1694
    /// Number of elements to copy from src to dest, not bytes.
    pub count: Operand<'tcx>,
K
kadmin 已提交
1695 1696
}

N
Niko Matsakis 已提交
1697
///////////////////////////////////////////////////////////////////////////
O
Oliver Schneider 已提交
1698
// Places
N
Niko Matsakis 已提交
1699 1700 1701

/// A path to a value; something that can be evaluated without
/// changing or disturbing program state.
M
Matthew Jasper 已提交
1702
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1703
pub struct Place<'tcx> {
1704
    pub local: Local,
1705 1706

    /// projection out of a place (access a field, deref a pointer, etc)
S
Santiago Pastorino 已提交
1707
    pub projection: &'tcx List<PlaceElem<'tcx>>,
1708 1709
}

1710 1711 1712
#[cfg(target_arch = "x86_64")]
static_assert_size!(Place<'_>, 16);

1713
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
M
Matthew Jasper 已提交
1714
#[derive(TyEncodable, TyDecodable, HashStable)]
1715
pub enum ProjectionElem<V, T> {
N
Niko Matsakis 已提交
1716
    Deref,
1717
    Field(Field, T),
N
Niko Matsakis 已提交
1718 1719
    Index(V),

1720 1721 1722 1723 1724 1725 1726 1727 1728
    /// These indices are generated by slice patterns. Easiest to explain
    /// by example:
    ///
    /// ```
    /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
    /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
    /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
    /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
    /// ```
N
Niko Matsakis 已提交
1729
    ConstantIndex {
1730
        /// index or -index (in Python terms), depending on from_end
D
DPC 已提交
1731
        offset: u64,
1732 1733
        /// The thing being indexed must be at least this long. For arrays this
        /// is always the exact length.
D
DPC 已提交
1734
        min_length: u64,
1735 1736
        /// Counting backwards from end? This is always false when indexing an
        /// array.
1737
        from_end: bool,
N
Niko Matsakis 已提交
1738 1739
    },

1740 1741
    /// These indices are generated by slice patterns.
    ///
1742 1743
    /// If `from_end` is true `slice[from..slice.len() - to]`.
    /// Otherwise `array[from..to]`.
1744
    Subslice {
D
DPC 已提交
1745 1746
        from: u64,
        to: u64,
1747 1748 1749 1750
        /// Whether `to` counts from the start or end of the array/slice.
        /// For `PlaceElem`s this is `true` if and only if the base is a slice.
        /// For `ProjectionKind`, this can also be `true` for arrays.
        from_end: bool,
1751 1752
    },

1753 1754 1755
    /// "Downcast" to a variant of an ADT. Currently, we only introduce
    /// this for ADTs with more than one variant. It may be better to
    /// just introduce it always, or always for enums.
1756 1757 1758
    ///
    /// The included Symbol is the name of the variant, used for printing MIR.
    Downcast(Option<Symbol>, VariantIdx),
N
Niko Matsakis 已提交
1759 1760
}

D
Dylan MacKenzie 已提交
1761 1762 1763 1764 1765 1766 1767
impl<V, T> ProjectionElem<V, T> {
    /// Returns `true` if the target of this projection may refer to a different region of memory
    /// than the base.
    fn is_indirect(&self) -> bool {
        match self {
            Self::Deref => true,

M
Mark Rousskov 已提交
1768
            Self::Field(_, _)
D
Dylan MacKenzie 已提交
1769 1770 1771
            | Self::Index(_)
            | Self::ConstantIndex { .. }
            | Self::Subslice { .. }
M
Mark Rousskov 已提交
1772
            | Self::Downcast(_, _) => false,
D
Dylan MacKenzie 已提交
1773 1774 1775 1776
        }
    }
}

O
Oliver Schneider 已提交
1777
/// Alias for projections as they appear in places, where the base is a place
1778
/// and the index is a local.
1779
pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
N
Niko Matsakis 已提交
1780

1781
// At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1782
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
D
DPC 已提交
1783
static_assert_size!(PlaceElem<'_>, 24);
O
Oliver Scherer 已提交
1784

1785 1786
/// Alias for projections as they appear in `UserTypeProjection`, where we
/// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1787
pub type ProjectionKind = ProjectionElem<(), ()>;
1788

1789
rustc_index::newtype_index! {
1790
    pub struct Field {
1791
        derive [HashStable]
1792 1793 1794
        DEBUG_FORMAT = "field[{}]"
    }
}
N
Niko Matsakis 已提交
1795

1796
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1797
pub struct PlaceRef<'tcx> {
1798
    pub local: Local,
1799
    pub projection: &'tcx [PlaceElem<'tcx>],
1800 1801
}

O
Oliver Schneider 已提交
1802
impl<'tcx> Place<'tcx> {
S
Santiago Pastorino 已提交
1803
    // FIXME change this to a const fn by also making List::empty a const fn.
1804
    pub fn return_place() -> Place<'tcx> {
1805
        Place { local: RETURN_PLACE, projection: List::empty() }
N
Niko Matsakis 已提交
1806
    }
1807

D
Dylan MacKenzie 已提交
1808 1809 1810 1811 1812
    /// Returns `true` if this `Place` contains a `Deref` projection.
    ///
    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
    /// same region of memory as its base.
    pub fn is_indirect(&self) -> bool {
1813
        self.projection.iter().any(|elem| elem.is_indirect())
D
Dylan MacKenzie 已提交
1814 1815
    }

A
Alexander Regueiro 已提交
1816
    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1817
    /// a single deref of a local.
1818
    #[inline(always)]
1819
    pub fn local_or_deref_local(&self) -> Option<Local> {
1820
        self.as_ref().local_or_deref_local()
1821
    }
1822

1823 1824
    /// If this place represents a local variable like `_X` with no
    /// projections, return `Some(_X)`.
1825
    #[inline(always)]
1826
    pub fn as_local(&self) -> Option<Local> {
1827
        self.as_ref().as_local()
1828 1829
    }

1830
    #[inline]
1831
    pub fn as_ref(&self) -> PlaceRef<'tcx> {
1832
        PlaceRef { local: self.local, projection: &self.projection }
1833
    }
1834 1835 1836

    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
    /// its projection and then subsequently more projections are added.
R
Ralf Jung 已提交
1837 1838 1839
    /// As a concrete example, given the place a.b.c, this would yield:
    /// - (a, .b)
    /// - (a.b, .c)
1840
    ///
R
Ralf Jung 已提交
1841
    /// Given a place without projections, the iterator is empty.
1842
    #[inline]
R
Ralf Jung 已提交
1843 1844 1845
    pub fn iter_projections(
        self,
    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1846 1847 1848 1849 1850
        self.projection.iter().enumerate().map(move |(i, proj)| {
            let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
            (base, proj)
        })
    }
1851 1852
}

1853 1854
impl From<Local> for Place<'_> {
    fn from(local: Local) -> Self {
1855
        Place { local, projection: List::empty() }
1856 1857 1858
    }
}

1859
impl<'tcx> PlaceRef<'tcx> {
1860 1861 1862
    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
    /// a single deref of a local.
    pub fn local_or_deref_local(&self) -> Option<Local> {
1863
        match *self {
1864
            PlaceRef { local, projection: [] }
1865
            | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1866 1867 1868
            _ => None,
        }
    }
1869 1870 1871

    /// If this place represents a local variable like `_X` with no
    /// projections, return `Some(_X)`.
1872
    #[inline]
1873
    pub fn as_local(&self) -> Option<Local> {
1874 1875
        match *self {
            PlaceRef { local, projection: [] } => Some(local),
1876 1877 1878
            _ => None,
        }
    }
1879

1880
    #[inline]
1881 1882 1883 1884 1885 1886 1887
    pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
        if let &[ref proj_base @ .., elem] = self.projection {
            Some((PlaceRef { local: self.local, projection: proj_base }, elem))
        } else {
            None
        }
    }
1888 1889
}

1890
impl Debug for Place<'_> {
1891
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1892 1893 1894 1895 1896 1897 1898
        for elem in self.projection.iter().rev() {
            match elem {
                ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
                    write!(fmt, "(").unwrap();
                }
                ProjectionElem::Deref => {
                    write!(fmt, "(*").unwrap();
S
Santiago Pastorino 已提交
1899
                }
1900 1901 1902
                ProjectionElem::Index(_)
                | ProjectionElem::ConstantIndex { .. }
                | ProjectionElem::Subslice { .. } => {}
1903
            }
1904
        }
1905

1906
        write!(fmt, "{:?}", self.local)?;
1907

1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
        for elem in self.projection.iter() {
            match elem {
                ProjectionElem::Downcast(Some(name), _index) => {
                    write!(fmt, " as {})", name)?;
                }
                ProjectionElem::Downcast(None, index) => {
                    write!(fmt, " as variant#{:?})", index)?;
                }
                ProjectionElem::Deref => {
                    write!(fmt, ")")?;
                }
                ProjectionElem::Field(field, ty) => {
                    write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
                }
                ProjectionElem::Index(ref index) => {
                    write!(fmt, "[{:?}]", index)?;
                }
                ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
                    write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
                }
                ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
                    write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
                }
B
Bastian Kauschke 已提交
1931
                ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1932 1933
                    write!(fmt, "[{:?}:]", from)?;
                }
B
Bastian Kauschke 已提交
1934
                ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1935 1936
                    write!(fmt, "[:-{:?}]", to)?;
                }
1937
                ProjectionElem::Subslice { from, to, from_end: true } => {
1938
                    write!(fmt, "[{:?}:-{:?}]", from, to)?;
S
Santiago Pastorino 已提交
1939
                }
1940 1941 1942
                ProjectionElem::Subslice { from, to, from_end: false } => {
                    write!(fmt, "[{:?}..{:?}]", from, to)?;
                }
1943
            }
1944
        }
1945

1946
        Ok(())
N
Niko Matsakis 已提交
1947 1948 1949
    }
}

N
Niko Matsakis 已提交
1950 1951 1952
///////////////////////////////////////////////////////////////////////////
// Scopes

1953
rustc_index::newtype_index! {
1954
    pub struct SourceScope {
1955
        derive [HashStable]
O
Oliver Schneider 已提交
1956
        DEBUG_FORMAT = "scope[{}]",
1957
        const OUTERMOST_SOURCE_SCOPE = 0,
1958 1959
    }
}
N
Niko Matsakis 已提交
1960

1961 1962 1963 1964
impl SourceScope {
    /// Finds the original HirId this MIR item came from.
    /// This is necessary after MIR optimizations, as otherwise we get a HirId
    /// from the function that was inlined instead of the function call site.
O
Tidy  
Oli Scherer 已提交
1965 1966 1967 1968
    pub fn lint_root(
        self,
        source_scopes: &IndexVec<SourceScope, SourceScopeData<'tcx>>,
    ) -> Option<HirId> {
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
        let mut data = &source_scopes[self];
        // FIXME(oli-obk): we should be able to just walk the `inlined_parent_scope`, but it
        // does not work as I thought it would. Needs more investigation and documentation.
        while data.inlined.is_some() {
            trace!(?data);
            data = &source_scopes[data.parent_scope.unwrap()];
        }
        trace!(?data);
        match &data.local_data {
            ClearCrossCrate::Set(data) => Some(data.lint_root),
            ClearCrossCrate::Clear => None,
        }
    }
}

1984 1985
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
pub struct SourceScopeData<'tcx> {
1986
    pub span: Span,
1987
    pub parent_scope: Option<SourceScope>,
1988

1989 1990 1991 1992 1993
    /// Whether this scope is the root of a scope tree of another body,
    /// inlined into this body by the MIR inliner.
    /// `ty::Instance` is the callee, and the `Span` is the call site.
    pub inlined: Option<(ty::Instance<'tcx>, Span)>,

1994 1995 1996 1997 1998
    /// Nearest (transitive) parent scope (if any) which is inlined.
    /// This is an optimization over walking up `parent_scope`
    /// until a scope with `inlined: Some(...)` is found.
    pub inlined_parent_scope: Option<SourceScope>,

1999 2000 2001
    /// Crate-local information for this source scope, that can't (and
    /// needn't) be tracked across crates.
    pub local_data: ClearCrossCrate<SourceScopeLocalData>,
N
Niko Matsakis 已提交
2002 2003
}

M
Matthew Jasper 已提交
2004
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
2005
pub struct SourceScopeLocalData {
2006
    /// An `HirId` with lint levels equivalent to this scope's lint levels.
L
ljedrz 已提交
2007
    pub lint_root: hir::HirId,
2008 2009 2010 2011
    /// The unsafe block that contains this node.
    pub safety: Safety,
}

N
Niko Matsakis 已提交
2012 2013
///////////////////////////////////////////////////////////////////////////
// Operands
N
Niko Matsakis 已提交
2014

R
Ralf Jung 已提交
2015 2016
/// These are values that can appear inside an rvalue. They are intentionally
/// limited to prevent rvalues from being nested in one another.
2017
#[derive(Clone, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
2018
pub enum Operand<'tcx> {
O
Oliver Schneider 已提交
2019 2020 2021 2022 2023
    /// Copy: The value must be available for use afterwards.
    ///
    /// This implies that the type of the place must be `Copy`; this is true
    /// by construction during build, but also checked by the MIR type checker.
    Copy(Place<'tcx>),
2024

O
Oliver Schneider 已提交
2025 2026 2027 2028 2029 2030
    /// Move: The value (including old borrows of it) will not be used again.
    ///
    /// Safe for values of all types (modulo future developments towards `?Move`).
    /// Correct usage patterns are enforced by the borrow checker for safe code.
    /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
    Move(Place<'tcx>),
2031 2032

    /// Synthesizes a constant value.
A
Ariel Ben-Yehuda 已提交
2033
    Constant(Box<Constant<'tcx>>),
N
Niko Matsakis 已提交
2034 2035
}

2036 2037 2038
#[cfg(target_arch = "x86_64")]
static_assert_size!(Operand<'_>, 24);

2039
impl<'tcx> Debug for Operand<'tcx> {
2040
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
N
Niko Matsakis 已提交
2041 2042 2043
        use self::Operand::*;
        match *self {
            Constant(ref a) => write!(fmt, "{:?}", a),
O
Oliver Schneider 已提交
2044 2045
            Copy(ref place) => write!(fmt, "{:?}", place),
            Move(ref place) => write!(fmt, "move {:?}", place),
N
Niko Matsakis 已提交
2046 2047 2048 2049
        }
    }
}

A
Ariel Ben-Yehuda 已提交
2050
impl<'tcx> Operand<'tcx> {
2051
    /// Convenience helper to make a constant that refers to the fn
A
Alexander Regueiro 已提交
2052
    /// with given `DefId` and substs. Since this is used to synthesize
2053
    /// MIR, assumes `user_ty` is None.
2054
    pub fn function_handle(
2055
        tcx: TyCtxt<'tcx>,
2056
        def_id: DefId,
C
csmoe 已提交
2057
        substs: SubstsRef<'tcx>,
2058 2059
        span: Span,
    ) -> Self {
2060
        let ty = tcx.type_of(def_id).subst(tcx, substs);
E
est31 已提交
2061
        Operand::Constant(Box::new(Constant {
2062
            span,
2063
            user_ty: None,
O
Oli Scherer 已提交
2064
            literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)),
E
est31 已提交
2065
        }))
A
Ariel Ben-Yehuda 已提交
2066 2067
    }

2068 2069 2070 2071
    pub fn is_move(&self) -> bool {
        matches!(self, Operand::Move(..))
    }

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    /// Convenience helper to make a literal-like constant from a given scalar value.
    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
    pub fn const_from_scalar(
        tcx: TyCtxt<'tcx>,
        ty: Ty<'tcx>,
        val: Scalar,
        span: Span,
    ) -> Operand<'tcx> {
        debug_assert!({
            let param_env_and_ty = ty::ParamEnv::empty().and(ty);
            let type_size = tcx
                .layout_of(param_env_and_ty)
                .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
                .size;
2086
            let scalar_size = match val {
O
oli 已提交
2087
                Scalar::Int(int) => int.size(),
2088
                _ => panic!("Invalid scalar type {:?}", val),
2089
            };
2090 2091
            scalar_size == type_size
        });
E
est31 已提交
2092
        Operand::Constant(Box::new(Constant {
2093 2094
            span,
            user_ty: None,
2095
            literal: ConstantKind::Val(ConstValue::Scalar(val), ty),
E
est31 已提交
2096
        }))
2097 2098
    }

2099 2100 2101
    pub fn to_copy(&self) -> Self {
        match *self {
            Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2102
            Operand::Move(place) => Operand::Copy(place),
2103 2104
        }
    }
2105 2106 2107

    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
    /// constant.
2108
    pub fn place(&self) -> Option<Place<'tcx>> {
2109
        match self {
2110
            Operand::Copy(place) | Operand::Move(place) => Some(*place),
2111 2112 2113
            Operand::Constant(_) => None,
        }
    }
2114 2115 2116 2117 2118 2119 2120 2121 2122

    /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
    /// place.
    pub fn constant(&self) -> Option<&Constant<'tcx>> {
        match self {
            Operand::Constant(x) => Some(&**x),
            Operand::Copy(_) | Operand::Move(_) => None,
        }
    }
A
Ariel Ben-Yehuda 已提交
2123 2124
}

N
Niko Matsakis 已提交
2125
///////////////////////////////////////////////////////////////////////////
2126
/// Rvalues
N
Niko Matsakis 已提交
2127

2128
#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2129
pub enum Rvalue<'tcx> {
2130
    /// x (either a move or copy, depending on type of x)
2131
    Use(Operand<'tcx>),
N
Niko Matsakis 已提交
2132

2133
    /// [x; 32]
2134
    Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
N
Niko Matsakis 已提交
2135

2136
    /// &x or &mut x
O
Oliver Schneider 已提交
2137
    Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
N
Niko Matsakis 已提交
2138

2139 2140 2141 2142 2143
    /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
    /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
    /// static.
    ThreadLocalRef(DefId),

M
Matthew Jasper 已提交
2144 2145 2146 2147 2148
    /// Create a raw pointer to the given place
    /// Can be generated by raw address of expressions (`&raw const x`),
    /// or when casting a reference to a raw pointer.
    AddressOf(Mutability, Place<'tcx>),

T
Tshepang Lekhonkhobe 已提交
2149
    /// length of a `[X]` or `[X;n]` value
O
Oliver Schneider 已提交
2150
    Len(Place<'tcx>),
N
Niko Matsakis 已提交
2151

2152
    Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
N
Niko Matsakis 已提交
2153

2154 2155
    BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
    CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
N
Niko Matsakis 已提交
2156

2157
    NullaryOp(NullOp, Ty<'tcx>),
2158
    UnaryOp(UnOp, Operand<'tcx>),
N
Niko Matsakis 已提交
2159

2160 2161
    /// Read the discriminant of an ADT.
    ///
2162
    /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2163
    /// be defined to return, say, a 0) if ADT is not an enum.
O
Oliver Schneider 已提交
2164
    Discriminant(Place<'tcx>),
2165

A
Alexander Regueiro 已提交
2166
    /// Creates an aggregate value, like a tuple or struct. This is
2167 2168 2169 2170
    /// only needed because we want to distinguish `dest = Foo { x:
    /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
    /// that `Foo` has a destructor. These rvalues can be optimized
    /// away after type-checking and before lowering.
A
Ariel Ben-Yehuda 已提交
2171
    Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
N
Niko Matsakis 已提交
2172 2173
}

2174
#[cfg(target_arch = "x86_64")]
2175
static_assert_size!(Rvalue<'_>, 40);
2176

2177
#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
N
Niko Matsakis 已提交
2178 2179
pub enum CastKind {
    Misc,
2180
    Pointer(PointerCast),
N
Niko Matsakis 已提交
2181 2182
}

2183
#[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2184
pub enum AggregateKind<'tcx> {
S
Simonas Kazlauskas 已提交
2185 2186
    /// The type is of the element
    Array(Ty<'tcx>),
N
Niko Matsakis 已提交
2187
    Tuple,
O
Oliver Schneider 已提交
2188

2189 2190
    /// The second field is the variant index. It's equal to 0 for struct
    /// and union expressions. The fourth field is
O
Oliver Schneider 已提交
2191
    /// active field number and is present only for union expressions
2192
    /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
O
Oliver Schneider 已提交
2193
    /// active field index would identity the field `c`
A
Albin Stjerna 已提交
2194
    Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
O
Oliver Schneider 已提交
2195

C
csmoe 已提交
2196
    Closure(DefId, SubstsRef<'tcx>),
2197
    Generator(DefId, SubstsRef<'tcx>, hir::Movability),
N
Niko Matsakis 已提交
2198 2199
}

2200 2201 2202
#[cfg(target_arch = "x86_64")]
static_assert_size!(AggregateKind<'_>, 48);

2203
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
N
Niko Matsakis 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
pub enum BinOp {
    /// The `+` operator (addition)
    Add,
    /// The `-` operator (subtraction)
    Sub,
    /// The `*` operator (multiplication)
    Mul,
    /// The `/` operator (division)
    Div,
    /// The `%` operator (modulus)
    Rem,
    /// The `^` operator (bitwise xor)
    BitXor,
    /// The `&` operator (bitwise and)
    BitAnd,
    /// The `|` operator (bitwise or)
    BitOr,
    /// The `<<` operator (shift left)
    Shl,
    /// The `>>` operator (shift right)
    Shr,
    /// The `==` operator (equality)
    Eq,
    /// The `<` operator (less than)
    Lt,
    /// The `<=` operator (less than or equal to)
    Le,
    /// The `!=` operator (not equal to)
    Ne,
    /// The `>=` operator (greater than or equal to)
    Ge,
    /// The `>` operator (greater than)
    Gt,
2237 2238
    /// The `ptr.offset` operator
    Offset,
N
Niko Matsakis 已提交
2239 2240
}

J
James Miller 已提交
2241 2242 2243
impl BinOp {
    pub fn is_checkable(self) -> bool {
        use self::BinOp::*;
2244
        matches!(self, Add | Sub | Mul | Shl | Shr)
J
James Miller 已提交
2245 2246 2247
    }
}

2248
#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
2249
pub enum NullOp {
A
Alexander Regueiro 已提交
2250
    /// Returns the size of a value of that type
2251
    SizeOf,
A
Alexander Regueiro 已提交
2252
    /// Creates a new uninitialized box for a value of that type
2253 2254 2255
    Box,
}

2256
#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
N
Niko Matsakis 已提交
2257 2258 2259 2260
pub enum UnOp {
    /// The `!` operator for logical inversion
    Not,
    /// The `-` operator for negation
2261
    Neg,
N
Niko Matsakis 已提交
2262 2263
}

2264
impl<'tcx> Debug for Rvalue<'tcx> {
2265
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
N
Niko Matsakis 已提交
2266 2267 2268
        use self::Rvalue::*;

        match *self {
O
Oliver Schneider 已提交
2269
            Use(ref place) => write!(fmt, "{:?}", place),
2270 2271 2272 2273 2274
            Repeat(ref a, ref b) => {
                write!(fmt, "[{:?}; ", a)?;
                pretty_print_const(b, fmt, false)?;
                write!(fmt, "]")
            }
2275
            Len(ref a) => write!(fmt, "Len({:?})", a),
O
Oliver Schneider 已提交
2276 2277 2278
            Cast(ref kind, ref place, ref ty) => {
                write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
            }
2279 2280
            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
            CheckedBinaryOp(ref op, box (ref a, ref b)) => {
J
James Miller 已提交
2281 2282
                write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
            }
N
Niko Matsakis 已提交
2283
            UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
O
Oliver Schneider 已提交
2284
            Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2285
            NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2286 2287 2288 2289
            ThreadLocalRef(did) => ty::tls::with(|tcx| {
                let muta = tcx.static_mutability(did).unwrap().prefix_str();
                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
            }),
O
Oliver Schneider 已提交
2290
            Ref(region, borrow_kind, ref place) => {
2291 2292
                let kind_str = match borrow_kind {
                    BorrowKind::Shared => "",
M
Matthew Jasper 已提交
2293
                    BorrowKind::Shallow => "shallow ",
2294
                    BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2295
                };
2296

R
Ralf Jung 已提交
2297
                // When printing regions, add trailing space if necessary.
2298 2299 2300 2301 2302
                let print_region = ty::tls::with(|tcx| {
                    tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
                });
                let region = if print_region {
                    let mut region = region.to_string();
2303
                    if !region.is_empty() {
2304 2305 2306 2307 2308 2309 2310 2311
                        region.push(' ');
                    }
                    region
                } else {
                    // Do not even print 'static
                    String::new()
                };
                write!(fmt, "&{}{}{:?}", region, kind_str, place)
2312 2313
            }

M
Matthew Jasper 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322
            AddressOf(mutability, ref place) => {
                let kind_str = match mutability {
                    Mutability::Mut => "mut",
                    Mutability::Not => "const",
                };

                write!(fmt, "&raw {} {:?}", kind_str, place)
            }

O
Oliver Schneider 已提交
2323
            Aggregate(ref kind, ref places) => {
2324 2325
                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
                    let mut tuple_fmt = fmt.debug_tuple(name);
O
Oliver Schneider 已提交
2326 2327
                    for place in places {
                        tuple_fmt.field(place);
2328 2329
                    }
                    tuple_fmt.finish()
2330
                };
2331

A
Ariel Ben-Yehuda 已提交
2332
                match **kind {
O
Oliver Schneider 已提交
2333
                    AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2334

2335 2336 2337 2338 2339 2340 2341
                    AggregateKind::Tuple => {
                        if places.is_empty() {
                            write!(fmt, "()")
                        } else {
                            fmt_tuple(fmt, "")
                        }
                    }
2342

N
Niko Matsakis 已提交
2343
                    AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2344
                        let variant_def = &adt_def.variants[variant];
2345

2346 2347
                        let name = ty::tls::with(|tcx| {
                            let mut name = String::new();
B
Bastian Kauschke 已提交
2348
                            let substs = tcx.lift(substs).expect("could not lift for printing");
2349
                            FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2350
                                .print_def_path(variant_def.def_id, substs)?;
2351
                            Ok(name)
2352
                        })?;
2353

2354
                        match variant_def.ctor_kind {
2355 2356
                            CtorKind::Const => fmt.write_str(&name),
                            CtorKind::Fn => fmt_tuple(fmt, &name),
2357
                            CtorKind::Fictive => {
2358
                                let mut struct_fmt = fmt.debug_struct(&name);
J
Josh Stone 已提交
2359
                                for (field, place) in iter::zip(&variant_def.fields, places) {
V
Vadim Petrochenkov 已提交
2360
                                    struct_fmt.field(&field.ident.as_str(), place);
2361 2362 2363 2364 2365 2366
                                }
                                struct_fmt.finish()
                            }
                        }
                    }

2367
                    AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
M
marmeladema 已提交
2368
                        if let Some(def_id) = def_id.as_local() {
2369
                            let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
F
Felix S. Klock II 已提交
2370
                            let name = if tcx.sess.opts.debugging_opts.span_free_formats {
B
Bastian Kauschke 已提交
2371
                                let substs = tcx.lift(substs).unwrap();
2372 2373
                                format!(
                                    "[closure@{}]",
M
marmeladema 已提交
2374
                                    tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2375
                                )
F
Felix S. Klock II 已提交
2376
                            } else {
2377
                                let span = tcx.hir().span(hir_id);
2378 2379 2380 2381
                                format!(
                                    "[closure@{}]",
                                    tcx.sess.source_map().span_to_diagnostic_string(span)
                                )
F
Felix S. Klock II 已提交
2382
                            };
2383 2384
                            let mut struct_fmt = fmt.debug_struct(&name);

2385
                            // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2386
                            if let Some(upvars) = tcx.upvars_mentioned(def_id) {
J
Josh Stone 已提交
2387
                                for (&var_id, place) in iter::zip(upvars.keys(), places) {
2388
                                    let var_name = tcx.hir().name(var_id);
O
Oliver Schneider 已提交
2389
                                    struct_fmt.field(&var_name.as_str(), place);
2390
                                }
2391
                            }
2392 2393 2394 2395 2396 2397

                            struct_fmt.finish()
                        } else {
                            write!(fmt, "[closure]")
                        }
                    }),
J
John Kåre Alsaker 已提交
2398

2399
                    AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
M
marmeladema 已提交
2400
                        if let Some(def_id) = def_id.as_local() {
2401
                            let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
A
Albin Stjerna 已提交
2402
                            let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
J
John Kåre Alsaker 已提交
2403 2404
                            let mut struct_fmt = fmt.debug_struct(&name);

2405
                            // FIXME(project-rfc-2229#48): This should be a list of capture names/places
2406
                            if let Some(upvars) = tcx.upvars_mentioned(def_id) {
J
Josh Stone 已提交
2407
                                for (&var_id, place) in iter::zip(upvars.keys(), places) {
2408
                                    let var_name = tcx.hir().name(var_id);
O
Oliver Schneider 已提交
2409
                                    struct_fmt.field(&var_name.as_str(), place);
J
John Kåre Alsaker 已提交
2410
                                }
2411
                            }
J
John Kåre Alsaker 已提交
2412 2413 2414 2415 2416 2417

                            struct_fmt.finish()
                        } else {
                            write!(fmt, "[generator]")
                        }
                    }),
2418 2419
                }
            }
N
Niko Matsakis 已提交
2420 2421 2422 2423 2424
        }
    }
}

///////////////////////////////////////////////////////////////////////////
2425 2426 2427
/// Constants
///
/// Two constants are equal if they are the same constant. Note that
I
Ivan Tham 已提交
2428
/// this does not necessarily mean that they are `==` in Rust. In
2429
/// particular, one must be wary of `NaN`!
N
Niko Matsakis 已提交
2430

2431
#[derive(Clone, Copy, PartialEq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable)]
2432 2433
pub struct Constant<'tcx> {
    pub span: Span,
2434 2435 2436 2437 2438 2439

    /// Optional user-given type: for something like
    /// `collect::<Vec<_>>`, this would be present and would
    /// indicate that `Vec<_>` was explicitly specified.
    ///
    /// Needed for NLL to impose user-given type constraints.
D
David Wood 已提交
2440
    pub user_ty: Option<UserTypeAnnotationIndex>,
2441

O
Oli Scherer 已提交
2442
    pub literal: ConstantKind<'tcx>,
2443 2444
}

2445 2446
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, TyEncodable, TyDecodable, Hash, HashStable, Debug)]
#[derive(Lift)]
O
Oli Scherer 已提交
2447
pub enum ConstantKind<'tcx> {
2448 2449 2450 2451 2452
    /// This constant came from the type system
    Ty(&'tcx ty::Const<'tcx>),
    /// This constant cannot go back into the type system, as it represents
    /// something the type system cannot handle (e.g. pointers).
    Val(interpret::ConstValue<'tcx>, Ty<'tcx>),
N
Niko Matsakis 已提交
2453 2454
}

2455 2456
impl Constant<'tcx> {
    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2457
        match self.literal.const_for_ty()?.val.try_to_scalar() {
2458
            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) {
2459 2460 2461 2462
                GlobalAlloc::Static(def_id) => {
                    assert!(!tcx.is_thread_local_static(def_id));
                    Some(def_id)
                }
2463
                _ => None,
2464 2465 2466 2467
            },
            _ => None,
        }
    }
2468
    #[inline]
2469
    pub fn ty(&self) -> Ty<'tcx> {
2470 2471 2472 2473
        self.literal.ty()
    }
}

O
Oli Scherer 已提交
2474
impl From<&'tcx ty::Const<'tcx>> for ConstantKind<'tcx> {
2475
    #[inline]
2476 2477 2478 2479 2480
    fn from(ct: &'tcx ty::Const<'tcx>) -> Self {
        Self::Ty(ct)
    }
}

O
Oli Scherer 已提交
2481
impl ConstantKind<'tcx> {
2482 2483 2484
    /// Returns `None` if the constant is not trivially safe for use in the type system.
    pub fn const_for_ty(&self) -> Option<&'tcx ty::Const<'tcx>> {
        match self {
O
Oli Scherer 已提交
2485 2486
            ConstantKind::Ty(c) => Some(c),
            ConstantKind::Val(..) => None,
2487 2488 2489 2490 2491
        }
    }

    pub fn ty(&self) -> Ty<'tcx> {
        match self {
O
Oli Scherer 已提交
2492 2493
            ConstantKind::Ty(c) => c.ty,
            ConstantKind::Val(_, ty) => ty,
2494 2495 2496 2497 2498 2499
        }
    }

    #[inline]
    pub fn try_to_value(self) -> Option<interpret::ConstValue<'tcx>> {
        match self {
O
Oli Scherer 已提交
2500 2501
            ConstantKind::Ty(c) => c.val.try_to_value(),
            ConstantKind::Val(val, _) => Some(val),
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
        }
    }

    #[inline]
    pub fn try_to_scalar(self) -> Option<Scalar> {
        self.try_to_value()?.try_to_scalar()
    }

    #[inline]
    pub fn try_to_scalar_int(self) -> Option<ScalarInt> {
2512
        Some(self.try_to_value()?.try_to_scalar()?.assert_int())
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
    }

    #[inline]
    pub fn try_to_bits(self, size: Size) -> Option<u128> {
        self.try_to_scalar_int()?.to_bits(size).ok()
    }

    #[inline]
    pub fn try_to_bool(self) -> Option<bool> {
        self.try_to_scalar_int()?.try_into().ok()
    }

    #[inline]
    pub fn try_eval_bits(
        &self,
        tcx: TyCtxt<'tcx>,
        param_env: ty::ParamEnv<'tcx>,
        ty: Ty<'tcx>,
    ) -> Option<u128> {
        match self {
            Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty),
            Self::Val(val, t) => {
                assert_eq!(*t, ty);
                let size =
                    tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
                val.try_to_bits(size)
            }
        }
    }

    #[inline]
    pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<bool> {
        match self {
            Self::Ty(ct) => ct.try_eval_bool(tcx, param_env),
            Self::Val(val, _) => val.try_to_bool(),
        }
    }

    #[inline]
    pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option<u64> {
        match self {
            Self::Ty(ct) => ct.try_eval_usize(tcx, param_env),
            Self::Val(val, _) => val.try_to_machine_usize(tcx),
        }
2557
    }
2558 2559
}

2560 2561 2562 2563 2564 2565 2566
/// A collection of projections into user types.
///
/// They are projections because a binding can occur a part of a
/// parent pattern that has been ascribed a type.
///
/// Its a collection because there can be multiple type ascriptions on
/// the path from the root of the pattern down to the binding itself.
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
///
/// An example:
///
/// ```rust
/// struct S<'a>((i32, &'a str), String);
/// let S((_, w): (i32, &'static str), _): S = ...;
/// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
/// //  ---------------------------------  ^ (2)
/// ```
///
/// The highlights labelled `(1)` show the subpattern `(_, w)` being
/// ascribed the type `(i32, &'static str)`.
///
/// The highlights labelled `(2)` show the whole pattern being
/// ascribed the type `S`.
///
/// In this example, when we descend to `w`, we will have built up the
/// following two projected types:
///
///   * base: `S`,                   projection: `(base.0).1`
///   * base: `(i32, &'static str)`, projection: `base.1`
///
/// The first will lead to the constraint `w: &'1 str` (for some
/// inferred region `'1`). The second will lead to the constraint `w:
/// &'static str`.
M
Matthew Jasper 已提交
2592
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2593
pub struct UserTypeProjections {
2594
    pub contents: Vec<(UserTypeProjection, Span)>,
2595 2596
}

2597
impl<'tcx> UserTypeProjections {
2598 2599 2600 2601
    pub fn none() -> Self {
        UserTypeProjections { contents: vec![] }
    }

2602 2603 2604 2605
    pub fn is_empty(&self) -> bool {
        self.contents.is_empty()
    }

M
Mark Rousskov 已提交
2606 2607 2608
    pub fn projections_and_spans(
        &self,
    ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2609 2610 2611
        self.contents.iter()
    }

M
Mark Rousskov 已提交
2612
    pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2613 2614
        self.contents.iter().map(|&(ref user_type, _span)| user_type)
    }
2615

A
Albin Stjerna 已提交
2616
    pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2617 2618 2619 2620 2621 2622
        self.contents.push((user_ty.clone(), span));
        self
    }

    fn map_projections(
        mut self,
A
Albin Stjerna 已提交
2623
        mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2624 2625 2626 2627 2628 2629 2630 2631 2632
    ) -> Self {
        self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
        self
    }

    pub fn index(self) -> Self {
        self.map_projections(|pat_ty_proj| pat_ty_proj.index())
    }

D
DPC 已提交
2633
    pub fn subslice(self, from: u64, to: u64) -> Self {
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
        self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
    }

    pub fn deref(self) -> Self {
        self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
    }

    pub fn leaf(self, field: Field) -> Self {
        self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
    }

A
Albin Stjerna 已提交
2645
    pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2646 2647
        self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
    }
2648 2649
}

2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
/// Encodes the effect of a user-supplied type annotation on the
/// subcomponents of a pattern. The effect is determined by applying the
/// given list of proejctions to some underlying base type. Often,
/// the projection element list `projs` is empty, in which case this
/// directly encodes a type in `base`. But in the case of complex patterns with
/// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
/// in which case the `projs` vector is used.
///
/// Examples:
///
/// * `let x: T = ...` -- here, the `projs` vector is empty.
///
/// * `let (x, _): T = ...` -- here, the `projs` vector would contain
///   `field[0]` (aka `.0`), indicating that the type of `s` is
///   determined by finding the type of the `.0` field from `T`.
2665
#[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
2666
pub struct UserTypeProjection {
D
David Wood 已提交
2667
    pub base: UserTypeAnnotationIndex,
E
Edd Barrett 已提交
2668
    pub projs: Vec<ProjectionKind>,
2669 2670
}

A
Albin Stjerna 已提交
2671
impl Copy for ProjectionKind {}
2672

2673
impl UserTypeProjection {
2674 2675 2676 2677 2678
    pub(crate) fn index(mut self) -> Self {
        self.projs.push(ProjectionElem::Index(()));
        self
    }

D
DPC 已提交
2679
    pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2680
        self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
        self
    }

    pub(crate) fn deref(mut self) -> Self {
        self.projs.push(ProjectionElem::Deref);
        self
    }

    pub(crate) fn leaf(mut self, field: Field) -> Self {
        self.projs.push(ProjectionElem::Field(field, ()));
        self
    }

    pub(crate) fn variant(
        mut self,
2696
        adt_def: &AdtDef,
2697 2698 2699
        variant_index: VariantIdx,
        field: Field,
    ) -> Self {
2700 2701
        self.projs.push(ProjectionElem::Downcast(
            Some(adt_def.variants[variant_index].ident.name),
A
Albin Stjerna 已提交
2702 2703
            variant_index,
        ));
2704 2705 2706 2707 2708
        self.projs.push(ProjectionElem::Field(field, ()));
        self
    }
}

L
words  
lcnr 已提交
2709
TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2710

2711
impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
B
Bastian Kauschke 已提交
2712
    fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
L
words  
lcnr 已提交
2713 2714 2715 2716
        UserTypeProjection {
            base: self.base.fold_with(folder),
            projs: self.projs.fold_with(folder),
        }
2717 2718
    }

L
LeSeulArtichaut 已提交
2719 2720 2721 2722
    fn super_visit_with<Vs: TypeVisitor<'tcx>>(
        &self,
        visitor: &mut Vs,
    ) -> ControlFlow<Vs::BreakTy> {
2723 2724
        self.base.visit_with(visitor)
        // Note: there's nothing in `self.proj` to visit.
2725 2726 2727
    }
}

2728
rustc_index::newtype_index! {
2729
    pub struct Promoted {
2730
        derive [HashStable]
2731 2732 2733
        DEBUG_FORMAT = "promoted[{}]"
    }
}
O
Oliver Schneider 已提交
2734

2735
impl<'tcx> Debug for Constant<'tcx> {
2736
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2737
        write!(fmt, "{}", self)
2738 2739
    }
}
2740

2741 2742
impl<'tcx> Display for Constant<'tcx> {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2743
        match self.ty().kind() {
2744 2745 2746
            ty::FnDef(..) => {}
            _ => write!(fmt, "const ")?,
        }
2747 2748 2749 2750 2751 2752 2753
        Display::fmt(&self.literal, fmt)
    }
}

impl<'tcx> Display for ConstantKind<'tcx> {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        match *self {
O
Oli Scherer 已提交
2754 2755
            ConstantKind::Ty(c) => pretty_print_const(c, fmt, true),
            ConstantKind::Val(val, ty) => pretty_print_const_value(val, ty, fmt, true),
2756
        }
2757
    }
2758
}
2759

2760 2761 2762 2763 2764 2765 2766
fn pretty_print_const(
    c: &ty::Const<'tcx>,
    fmt: &mut Formatter<'_>,
    print_types: bool,
) -> fmt::Result {
    use crate::ty::print::PrettyPrinter;
    ty::tls::with(|tcx| {
B
Bastian Kauschke 已提交
2767
        let literal = tcx.lift(c).unwrap();
2768 2769 2770 2771 2772 2773 2774
        let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
        cx.print_alloc_ids = true;
        cx.pretty_print_const(literal, print_types)?;
        Ok(())
    })
}

2775 2776 2777 2778 2779 2780 2781 2782
fn pretty_print_const_value(
    val: interpret::ConstValue<'tcx>,
    ty: Ty<'tcx>,
    fmt: &mut Formatter<'_>,
    print_types: bool,
) -> fmt::Result {
    use crate::ty::print::PrettyPrinter;
    ty::tls::with(|tcx| {
2783
        let val = tcx.lift(val).unwrap();
2784 2785 2786 2787 2788 2789 2790 2791
        let ty = tcx.lift(ty).unwrap();
        let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
        cx.print_alloc_ids = true;
        cx.pretty_print_const_value(val, ty, print_types)?;
        Ok(())
    })
}

2792
impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2793
    type Node = BasicBlock;
2794
}
2795

2796
impl<'tcx> graph::WithNumNodes for Body<'tcx> {
D
Dylan MacKenzie 已提交
2797
    #[inline]
S
Santiago Pastorino 已提交
2798 2799 2800
    fn num_nodes(&self) -> usize {
        self.basic_blocks.len()
    }
2801
}
2802

2803
impl<'tcx> graph::WithStartNode for Body<'tcx> {
D
Dylan MacKenzie 已提交
2804
    #[inline]
S
Santiago Pastorino 已提交
2805 2806 2807
    fn start_node(&self) -> Self::Node {
        START_BLOCK
    }
2808
}
2809

2810
impl<'tcx> graph::WithSuccessors for Body<'tcx> {
D
Dylan MacKenzie 已提交
2811
    #[inline]
M
Mark Rousskov 已提交
2812
    fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2813
        self.basic_blocks[node].terminator().successors().cloned()
2814 2815 2816
    }
}

2817
impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2818
    type Item = BasicBlock;
2819
    type Iter = iter::Cloned<Successors<'b>>;
2820
}
2821

2822 2823
impl graph::GraphPredecessors<'graph> for Body<'tcx> {
    type Item = BasicBlock;
2824
    type Iter = std::iter::Copied<std::slice::Iter<'graph, BasicBlock>>;
2825 2826 2827
}

impl graph::WithPredecessors for Body<'tcx> {
D
Dylan MacKenzie 已提交
2828
    #[inline]
2829
    fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2830
        self.predecessors()[node].iter().copied()
2831 2832 2833
    }
}

J
JOE1994 已提交
2834 2835 2836
/// `Location` represents the position of the start of the statement; or, if
/// `statement_index` equals the number of statements, then the start of the
/// terminator.
2837
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2838
pub struct Location {
2839
    /// The block that the location is within.
2840 2841 2842 2843 2844
    pub block: BasicBlock,

    pub statement_index: usize,
}

2845
impl fmt::Debug for Location {
2846
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2847 2848 2849
        write!(fmt, "{:?}[{}]", self.block, self.statement_index)
    }
}
2850 2851

impl Location {
A
Albin Stjerna 已提交
2852
    pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
N
Niko Matsakis 已提交
2853

O
Oliver Schneider 已提交
2854 2855 2856 2857 2858
    /// Returns the location immediately after this one within the enclosing block.
    ///
    /// Note that if this location represents a terminator, then the
    /// resulting location would be out of bounds and invalid.
    pub fn successor_within_block(&self) -> Location {
A
Albin Stjerna 已提交
2859
        Location { block: self.block, statement_index: self.statement_index + 1 }
O
Oliver Schneider 已提交
2860 2861
    }

D
David Wood 已提交
2862
    /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2863
    pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
D
David Wood 已提交
2864 2865 2866 2867 2868 2869
        // If we are in the same block as the other location and are an earlier statement
        // then we are a predecessor of `other`.
        if self.block == other.block && self.statement_index < other.statement_index {
            return true;
        }

2870 2871
        let predecessors = body.predecessors();

D
David Wood 已提交
2872
        // If we're in another block, then we want to check that block is a predecessor of `other`.
2873
        let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
D
David Wood 已提交
2874 2875 2876 2877 2878
        let mut visited = FxHashSet::default();

        while let Some(block) = queue.pop() {
            // If we haven't visited this block before, then make sure we visit it's predecessors.
            if visited.insert(block) {
2879
                queue.extend(predecessors[block].iter().cloned());
D
David Wood 已提交
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
            } else {
                continue;
            }

            // If we found the block that `self` is in, then we are a predecessor of `other` (since
            // we found that block by looking at the predecessors of `other`).
            if self.block == block {
                return true;
            }
        }

        false
    }

2894
    pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2895 2896 2897 2898 2899 2900 2901
        if self.block == other.block {
            self.statement_index <= other.statement_index
        } else {
            dominators.is_dominated_by(other.block, self.block)
        }
    }
}