rustc_middle/mir/
syntax.rs

1//! This defines the syntax of MIR, i.e., the set of available MIR operations, and other definitions
2//! closely related to MIR semantics.
3//! This is in a dedicated file so that changes to this file can be reviewed more carefully.
4//! The intention is that this file only contains datatype declarations, no code.
5
6use rustc_abi::{FieldIdx, VariantIdx};
7use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability};
8use rustc_data_structures::packed::Pu128;
9use rustc_hir::CoroutineKind;
10use rustc_hir::def_id::DefId;
11use rustc_index::IndexVec;
12use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
13use rustc_span::def_id::LocalDefId;
14use rustc_span::source_map::Spanned;
15use rustc_span::{Span, Symbol};
16use rustc_target::asm::InlineAsmRegOrRegClass;
17use smallvec::SmallVec;
18
19use super::{BasicBlock, Const, Local, UserTypeProjection};
20use crate::mir::coverage::CoverageKind;
21use crate::ty::adjustment::PointerCoercion;
22use crate::ty::{self, GenericArgsRef, List, Region, Ty, UserTypeAnnotationIndex};
23
24/// Represents the "flavors" of MIR.
25///
26/// All flavors of MIR use the same data structure, but there are some important differences. These
27/// differences come in two forms: Dialects and phases.
28///
29/// Dialects represent a stronger distinction than phases. This is because the transitions between
30/// dialects are semantic changes, and therefore technically *lowerings* between distinct IRs. In
31/// other words, the same [`Body`](crate::mir::Body) might be well-formed for multiple dialects, but
32/// have different semantic meaning and different behavior at runtime.
33///
34/// Each dialect additionally has a number of phases. However, phase changes never involve semantic
35/// changes. If some MIR is well-formed both before and after a phase change, it is also guaranteed
36/// that it has the same semantic meaning. In this sense, phase changes can only add additional
37/// restrictions on what MIR is well-formed.
38///
39/// When adding phases, remember to update [`MirPhase::phase_index`].
40#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
41#[derive(HashStable)]
42pub enum MirPhase {
43    /// The MIR that is generated by MIR building.
44    ///
45    /// The only things that operate on this dialect are unsafeck, the various MIR lints, and const
46    /// qualifs.
47    ///
48    /// This has no distinct phases.
49    Built,
50    /// The MIR used for most analysis.
51    ///
52    /// The only semantic change between analysis and built MIR is constant promotion. In built MIR,
53    /// sequences of statements that would generally be subject to constant promotion are
54    /// semantically constants, while in analysis MIR all constants are explicit.
55    ///
56    /// The result of const promotion is available from the `mir_promoted` and `promoted_mir` queries.
57    ///
58    /// This is the version of MIR used by borrowck and friends.
59    Analysis(AnalysisPhase),
60    /// The MIR used for CTFE, optimizations, and codegen.
61    ///
62    /// The semantic changes that occur in the lowering from analysis to runtime MIR are as follows:
63    ///
64    ///  - Drops: In analysis MIR, `Drop` terminators represent *conditional* drops; roughly speaking,
65    ///    if dataflow analysis determines that the place being dropped is uninitialized, the drop will
66    ///    not be executed. The exact semantics of this aren't written down anywhere, which means they
67    ///    are essentially "what drop elaboration does." In runtime MIR, the drops are unconditional;
68    ///    when a `Drop` terminator is reached, if the type has drop glue that drop glue is always
69    ///    executed. This may be UB if the underlying place is not initialized.
70    ///  - Packed drops: Places might in general be misaligned - in most cases this is UB, the exception
71    ///    is fields of packed structs. In analysis MIR, `Drop(P)` for a `P` that might be misaligned
72    ///    for this reason implicitly moves `P` to a temporary before dropping. Runtime MIR has no such
73    ///    rules, and dropping a misaligned place is simply UB.
74    ///  - Unwinding: in analysis MIR, unwinding from a function which may not unwind aborts. In runtime
75    ///    MIR, this is UB.
76    ///  - Retags: If `-Zmir-emit-retag` is enabled, analysis MIR has "implicit" retags in the same way
77    ///    that Rust itself has them. Where exactly these are is generally subject to change, and so we
78    ///    don't document this here. Runtime MIR has most retags explicit (though implicit retags
79    ///    can still occur at `Rvalue::{Ref,AddrOf}`).
80    ///  - Coroutine bodies: In analysis MIR, locals may actually be behind a pointer that user code has
81    ///    access to. This occurs in coroutine bodies. Such locals do not behave like other locals,
82    ///    because they eg may be aliased in surprising ways. Runtime MIR has no such special locals -
83    ///    all coroutine bodies are lowered and so all places that look like locals really are locals.
84    ///
85    /// Also note that the lint pass which reports eg `200_u8 + 200_u8` as an error is run as a part
86    /// of analysis to runtime MIR lowering. To ensure lints are reported reliably, this means that
87    /// transformations which may suppress such errors should not run on analysis MIR.
88    Runtime(RuntimePhase),
89}
90
91impl MirPhase {
92    pub fn name(&self) -> &'static str {
93        match *self {
94            MirPhase::Built => "built",
95            MirPhase::Analysis(AnalysisPhase::Initial) => "analysis",
96            MirPhase::Analysis(AnalysisPhase::PostCleanup) => "analysis-post-cleanup",
97            MirPhase::Runtime(RuntimePhase::Initial) => "runtime",
98            MirPhase::Runtime(RuntimePhase::PostCleanup) => "runtime-post-cleanup",
99            MirPhase::Runtime(RuntimePhase::Optimized) => "runtime-optimized",
100        }
101    }
102}
103
104/// See [`MirPhase::Analysis`].
105#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
106#[derive(HashStable)]
107pub enum AnalysisPhase {
108    Initial = 0,
109    /// Beginning in this phase, the following variants are disallowed:
110    /// * [`TerminatorKind::FalseUnwind`]
111    /// * [`TerminatorKind::FalseEdge`]
112    /// * [`StatementKind::FakeRead`]
113    /// * [`StatementKind::AscribeUserType`]
114    /// * [`StatementKind::Coverage`] with [`CoverageKind::BlockMarker`] or [`CoverageKind::SpanMarker`]
115    /// * [`Rvalue::Ref`] with `BorrowKind::Fake`
116    /// * [`CastKind::PointerCoercion`] with any of the following:
117    ///   * [`PointerCoercion::ArrayToPointer`]
118    ///   * [`PointerCoercion::MutToConstPointer`]
119    ///
120    /// Furthermore, `Deref` projections must be the first projection within any place (if they
121    /// appear at all)
122    PostCleanup = 1,
123}
124
125/// See [`MirPhase::Runtime`].
126#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
127#[derive(HashStable)]
128pub enum RuntimePhase {
129    /// In addition to the semantic changes, beginning with this phase, the following variants are
130    /// disallowed:
131    /// * [`TerminatorKind::Yield`]
132    /// * [`TerminatorKind::CoroutineDrop`]
133    /// * [`Rvalue::Aggregate`] for any `AggregateKind` except `Array`
134    /// * [`PlaceElem::OpaqueCast`]
135    ///
136    /// And the following variants are allowed:
137    /// * [`StatementKind::Retag`]
138    /// * [`StatementKind::SetDiscriminant`]
139    /// * [`StatementKind::Deinit`]
140    ///
141    /// Furthermore, `Copy` operands are allowed for non-`Copy` types.
142    Initial = 0,
143    /// Beginning with this phase, the following variant is disallowed:
144    /// * [`ProjectionElem::Deref`] of `Box`
145    PostCleanup = 1,
146    Optimized = 2,
147}
148
149///////////////////////////////////////////////////////////////////////////
150// Borrow kinds
151
152#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
153#[derive(Hash, HashStable)]
154pub enum BorrowKind {
155    /// Data must be immutable and is aliasable.
156    Shared,
157
158    /// An immutable, aliasable borrow that is discarded after borrow-checking. Can behave either
159    /// like a normal shared borrow or like a special shallow borrow (see [`FakeBorrowKind`]).
160    ///
161    /// This is used when lowering index expressions and matches. This is used to prevent code like
162    /// the following from compiling:
163    /// ```compile_fail,E0510
164    /// let mut x: &[_] = &[[0, 1]];
165    /// let y: &[_] = &[];
166    /// let _ = x[0][{x = y; 1}];
167    /// ```
168    /// ```compile_fail,E0510
169    /// let mut x = &Some(0);
170    /// match *x {
171    ///     None => (),
172    ///     Some(_) if { x = &None; false } => (),
173    ///     Some(_) => (),
174    /// }
175    /// ```
176    /// We can also report errors with this kind of borrow differently.
177    Fake(FakeBorrowKind),
178
179    /// Data is mutable and not aliasable.
180    Mut { kind: MutBorrowKind },
181}
182
183#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
184#[derive(Hash, HashStable)]
185pub enum RawPtrKind {
186    Mut,
187    Const,
188    /// Creates a raw pointer to a place that will only be used to access its metadata,
189    /// not the data behind the pointer. Note that this limitation is *not* enforced
190    /// by the validator.
191    ///
192    /// The borrow checker allows overlap of these raw pointers with references to the
193    /// data. This is sound even if the pointer is "misused" since any such use is anyway
194    /// unsafe. In terms of the operational semantics (i.e., Miri), this is equivalent
195    /// to `RawPtrKind::Mut`, but will never incur a retag.
196    FakeForPtrMetadata,
197}
198
199impl From<Mutability> for RawPtrKind {
200    fn from(other: Mutability) -> Self {
201        match other {
202            Mutability::Mut => RawPtrKind::Mut,
203            Mutability::Not => RawPtrKind::Const,
204        }
205    }
206}
207
208impl RawPtrKind {
209    pub fn is_fake(self) -> bool {
210        match self {
211            RawPtrKind::Mut | RawPtrKind::Const => false,
212            RawPtrKind::FakeForPtrMetadata => true,
213        }
214    }
215
216    pub fn to_mutbl_lossy(self) -> Mutability {
217        match self {
218            RawPtrKind::Mut => Mutability::Mut,
219            RawPtrKind::Const => Mutability::Not,
220
221            // We have no type corresponding to a fake borrow, so use
222            // `*const` as an approximation.
223            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
224        }
225    }
226
227    pub fn ptr_str(self) -> &'static str {
228        match self {
229            RawPtrKind::Mut => "mut",
230            RawPtrKind::Const => "const",
231            RawPtrKind::FakeForPtrMetadata => "const (fake)",
232        }
233    }
234}
235
236#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
237#[derive(Hash, HashStable)]
238pub enum MutBorrowKind {
239    Default,
240    /// This borrow arose from method-call auto-ref. (i.e., `adjustment::Adjust::Borrow`)
241    TwoPhaseBorrow,
242    /// Data must be immutable but not aliasable. This kind of borrow
243    /// cannot currently be expressed by the user and is used only in
244    /// implicit closure bindings. It is needed when the closure is
245    /// borrowing or mutating a mutable referent, e.g.:
246    /// ```
247    /// let mut z = 3;
248    /// let x: &mut isize = &mut z;
249    /// let y = || *x += 5;
250    /// ```
251    /// If we were to try to translate this closure into a more explicit
252    /// form, we'd encounter an error with the code as written:
253    /// ```compile_fail,E0594
254    /// struct Env<'a> { x: &'a &'a mut isize }
255    /// let mut z = 3;
256    /// let x: &mut isize = &mut z;
257    /// let y = (&mut Env { x: &x }, fn_ptr);  // Closure is pair of env and fn
258    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
259    /// ```
260    /// This is then illegal because you cannot mutate an `&mut` found
261    /// in an aliasable location. To solve, you'd have to translate with
262    /// an `&mut` borrow:
263    /// ```compile_fail,E0596
264    /// struct Env<'a> { x: &'a mut &'a mut isize }
265    /// let mut z = 3;
266    /// let x: &mut isize = &mut z;
267    /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
268    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
269    /// ```
270    /// Now the assignment to `**env.x` is legal, but creating a
271    /// mutable pointer to `x` is not because `x` is not mutable. We
272    /// could fix this by declaring `x` as `let mut x`. This is ok in
273    /// user code, if awkward, but extra weird for closures, since the
274    /// borrow is hidden.
275    ///
276    /// So we introduce a `ClosureCapture` borrow -- user will not have to mark the variable
277    /// containing the mutable reference as `mut`, as they didn't ever
278    /// intend to mutate the mutable reference itself. We still mutable capture it in order to
279    /// mutate the pointed value through it (but not mutating the reference itself).
280    ///
281    /// This solves the problem. For simplicity, we don't give users the way to express this
282    /// borrow, it's just used when translating closures.
283    ClosureCapture,
284}
285
286#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
287#[derive(Hash, HashStable)]
288pub enum FakeBorrowKind {
289    /// A shared shallow borrow. The immediately borrowed place must be immutable, but projections
290    /// from it don't need to be. For example, a shallow borrow of `a.b` doesn't conflict with a
291    /// mutable borrow of `a.b.c`.
292    ///
293    /// This is used when lowering matches: when matching on a place we want to ensure that place
294    /// have the same value from the start of the match until an arm is selected. This prevents this
295    /// code from compiling:
296    /// ```compile_fail,E0510
297    /// let mut x = &Some(0);
298    /// match *x {
299    ///     None => (),
300    ///     Some(_) if { x = &None; false } => (),
301    ///     Some(_) => (),
302    /// }
303    /// ```
304    /// This can't be a shared borrow because mutably borrowing `(*x as Some).0` should not checking
305    /// the discriminant or accessing other variants, because the mutating `(*x as Some).0` can't
306    /// affect the discriminant of `x`. E.g. the following is allowed:
307    /// ```rust
308    /// let mut x = Some(0);
309    /// match x {
310    ///     Some(_)
311    ///         if {
312    ///             if let Some(ref mut y) = x {
313    ///                 *y += 1;
314    ///             };
315    ///             true
316    ///         } => {}
317    ///     _ => {}
318    /// }
319    /// ```
320    Shallow,
321    /// A shared (deep) borrow. Data must be immutable and is aliasable.
322    ///
323    /// This is used when lowering deref patterns, where shallow borrows wouldn't prevent something
324    /// like:
325    // ```compile_fail
326    // let mut b = Box::new(false);
327    // match b {
328    //     deref!(true) => {} // not reached because `*b == false`
329    //     _ if { *b = true; false } => {} // not reached because the guard is `false`
330    //     deref!(false) => {} // not reached because the guard changed it
331    //     // UB because we reached the unreachable.
332    // }
333    // ```
334    Deep,
335}
336
337///////////////////////////////////////////////////////////////////////////
338// Statements
339
340/// The various kinds of statements that can appear in MIR.
341///
342/// Not all of these are allowed at every [`MirPhase`]. Check the documentation there to see which
343/// ones you do not have to worry about. The MIR validator will generally enforce such restrictions,
344/// causing an ICE if they are violated.
345#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
346#[derive(TypeFoldable, TypeVisitable)]
347pub enum StatementKind<'tcx> {
348    /// Assign statements roughly correspond to an assignment in Rust proper (`x = ...`) except
349    /// without the possibility of dropping the previous value (that must be done separately, if at
350    /// all). The *exact* way this works is undecided. It probably does something like evaluating
351    /// the LHS to a place and the RHS to a value, and then storing the value to the place. Various
352    /// parts of this may do type specific things that are more complicated than simply copying
353    /// bytes.
354    ///
355    /// **Needs clarification**: The implication of the above idea would be that assignment implies
356    /// that the resulting value is initialized. I believe we could commit to this separately from
357    /// committing to whatever part of the memory model we would need to decide on to make the above
358    /// paragraph precise. Do we want to?
359    ///
360    /// Assignments in which the types of the place and rvalue differ are not well-formed.
361    ///
362    /// **Needs clarification**: Do we ever want to worry about non-free (in the body) lifetimes for
363    /// the typing requirement in post drop-elaboration MIR? I think probably not - I'm not sure we
364    /// could meaningfully require this anyway. How about free lifetimes? Is ignoring this
365    /// interesting for optimizations? Do we want to allow such optimizations?
366    ///
367    /// **Needs clarification**: We currently require that the LHS place not overlap with any place
368    /// read as part of computation of the RHS for some rvalues (generally those not producing
369    /// primitives). This requirement is under discussion in [#68364]. As a part of this discussion,
370    /// it is also unclear in what order the components are evaluated.
371    ///
372    /// [#68364]: https://github.com/rust-lang/rust/issues/68364
373    ///
374    /// See [`Rvalue`] documentation for details on each of those.
375    Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
376
377    /// This represents all the reading that a pattern match may do (e.g., inspecting constants and
378    /// discriminant values), and the kind of pattern it comes from. This is in order to adapt
379    /// potential error messages to these specific patterns.
380    ///
381    /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
382    /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
383    ///
384    /// When executed at runtime this is a nop.
385    ///
386    /// Disallowed after drop elaboration.
387    FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
388
389    /// Write the discriminant for a variant to the enum Place.
390    ///
391    /// This is permitted for both coroutines and ADTs. This does not necessarily write to the
392    /// entire place; instead, it writes to the minimum set of bytes as required by the layout for
393    /// the type.
394    SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
395
396    /// Deinitializes the place.
397    ///
398    /// This writes `uninit` bytes to the entire place.
399    Deinit(Box<Place<'tcx>>),
400
401    /// `StorageLive` and `StorageDead` statements mark the live range of a local.
402    ///
403    /// At any point during the execution of a function, each local is either allocated or
404    /// unallocated. Except as noted below, all locals except function parameters are initially
405    /// unallocated. `StorageLive` statements cause memory to be allocated for the local while
406    /// `StorageDead` statements cause the memory to be freed. In other words,
407    /// `StorageLive`/`StorageDead` act like the heap operations `allocate`/`deallocate`, but for
408    /// stack-allocated local variables. Using a local in any way (not only reading/writing from it)
409    /// while it is unallocated is UB.
410    ///
411    /// Some locals have no `StorageLive` or `StorageDead` statements within the entire MIR body.
412    /// These locals are implicitly allocated for the full duration of the function. There is a
413    /// convenience method at `rustc_mir_dataflow::storage::always_storage_live_locals` for
414    /// computing these locals.
415    ///
416    /// If the local is already allocated, calling `StorageLive` again will implicitly free the
417    /// local and then allocate fresh uninitilized memory. If a local is already deallocated,
418    /// calling `StorageDead` again is a NOP.
419    StorageLive(Local),
420
421    /// See `StorageLive` above.
422    StorageDead(Local),
423
424    /// Retag references in the given place, ensuring they got fresh tags.
425    ///
426    /// This is part of the Stacked Borrows model. These statements are currently only interpreted
427    /// by miri and only generated when `-Z mir-emit-retag` is passed. See
428    /// <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> for
429    /// more details.
430    ///
431    /// For code that is not specific to stacked borrows, you should consider retags to read and
432    /// modify the place in an opaque way.
433    ///
434    /// Only `RetagKind::Default` and `RetagKind::FnEntry` are permitted.
435    Retag(RetagKind, Box<Place<'tcx>>),
436
437    /// This statement exists to preserve a trace of a scrutinee matched against a wildcard binding.
438    /// This is especially useful for `let _ = PLACE;` bindings that desugar to a single
439    /// `PlaceMention(PLACE)`.
440    ///
441    /// When executed at runtime, this computes the given place, but then discards
442    /// it without doing a load. `let _ = *ptr;` is fine even if the pointer is dangling.
443    PlaceMention(Box<Place<'tcx>>),
444
445    /// Encodes a user's type ascription. These need to be preserved
446    /// intact so that NLL can respect them. For example:
447    /// ```ignore (illustrative)
448    /// let a: T = y;
449    /// ```
450    /// The effect of this annotation is to relate the type `T_y` of the place `y`
451    /// to the user-given type `T`. The effect depends on the specified variance:
452    ///
453    /// - `Covariant` -- requires that `T_y <: T`
454    /// - `Contravariant` -- requires that `T_y :> T`
455    /// - `Invariant` -- requires that `T_y == T`
456    /// - `Bivariant` -- no effect
457    ///
458    /// When executed at runtime this is a nop.
459    ///
460    /// Disallowed after drop elaboration.
461    AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
462
463    /// Carries control-flow-sensitive information injected by `-Cinstrument-coverage`,
464    /// such as where to generate physical coverage-counter-increments during codegen.
465    ///
466    /// Coverage statements are used in conjunction with the coverage mappings and other
467    /// information stored in the function's
468    /// [`mir::Body::function_coverage_info`](crate::mir::Body::function_coverage_info).
469    /// (For inlined MIR, take care to look up the *original function's* coverage info.)
470    ///
471    /// Interpreters and codegen backends that don't support coverage instrumentation
472    /// can usually treat this as a no-op.
473    Coverage(
474        // Coverage statements are unlikely to ever contain type information in
475        // the foreseeable future, so excluding them from TypeFoldable/TypeVisitable
476        // avoids some unhelpful derive boilerplate.
477        #[type_foldable(identity)]
478        #[type_visitable(ignore)]
479        CoverageKind,
480    ),
481
482    /// Denotes a call to an intrinsic that does not require an unwind path and always returns.
483    /// This avoids adding a new block and a terminator for simple intrinsics.
484    Intrinsic(Box<NonDivergingIntrinsic<'tcx>>),
485
486    /// Instructs the const eval interpreter to increment a counter; this counter is used to track
487    /// how many steps the interpreter has taken. It is used to prevent the user from writing const
488    /// code that runs for too long or infinitely. Other than in the const eval interpreter, this
489    /// is a no-op.
490    ConstEvalCounter,
491
492    /// No-op. Useful for deleting instructions without affecting statement indices.
493    Nop,
494
495    /// Marker statement indicating where `place` would be dropped.
496    /// This is semantically equivalent to `Nop`, so codegen and MIRI should interpret this
497    /// statement as such.
498    /// The only use case of this statement is for linting in MIR to detect temporary lifetime
499    /// changes.
500    BackwardIncompatibleDropHint {
501        /// Place to drop
502        place: Box<Place<'tcx>>,
503        /// Reason for backward incompatibility
504        reason: BackwardIncompatibleDropReason,
505    },
506}
507
508impl StatementKind<'_> {
509    /// Returns a simple string representation of a `StatementKind` variant, independent of any
510    /// values it might hold (e.g. `StatementKind::Assign` always returns `"Assign"`).
511    pub const fn name(&self) -> &'static str {
512        match self {
513            StatementKind::Assign(..) => "Assign",
514            StatementKind::FakeRead(..) => "FakeRead",
515            StatementKind::SetDiscriminant { .. } => "SetDiscriminant",
516            StatementKind::Deinit(..) => "Deinit",
517            StatementKind::StorageLive(..) => "StorageLive",
518            StatementKind::StorageDead(..) => "StorageDead",
519            StatementKind::Retag(..) => "Retag",
520            StatementKind::PlaceMention(..) => "PlaceMention",
521            StatementKind::AscribeUserType(..) => "AscribeUserType",
522            StatementKind::Coverage(..) => "Coverage",
523            StatementKind::Intrinsic(..) => "Intrinsic",
524            StatementKind::ConstEvalCounter => "ConstEvalCounter",
525            StatementKind::Nop => "Nop",
526            StatementKind::BackwardIncompatibleDropHint { .. } => "BackwardIncompatibleDropHint",
527        }
528    }
529}
530
531#[derive(
532    Clone,
533    TyEncodable,
534    TyDecodable,
535    Debug,
536    PartialEq,
537    Hash,
538    HashStable,
539    TypeFoldable,
540    TypeVisitable
541)]
542pub enum NonDivergingIntrinsic<'tcx> {
543    /// Denotes a call to the intrinsic function `assume`.
544    ///
545    /// The operand must be a boolean. Optimizers may use the value of the boolean to backtrack its
546    /// computation to infer information about other variables. So if the boolean came from a
547    /// `x < y` operation, subsequent operations on `x` and `y` could elide various bound checks.
548    /// If the argument is `false`, this operation is equivalent to `TerminatorKind::Unreachable`.
549    Assume(Operand<'tcx>),
550
551    /// Denotes a call to the intrinsic function `copy_nonoverlapping`.
552    ///
553    /// First, all three operands are evaluated. `src` and `dest` must each be a reference, pointer,
554    /// or `Box` pointing to the same type `T`. `count` must evaluate to a `usize`. Then, `src` and
555    /// `dest` are dereferenced, and `count * size_of::<T>()` bytes beginning with the first byte of
556    /// the `src` place are copied to the contiguous range of bytes beginning with the first byte
557    /// of `dest`.
558    ///
559    /// **Needs clarification**: In what order are operands computed and dereferenced? It should
560    /// probably match the order for assignment, but that is also undecided.
561    ///
562    /// **Needs clarification**: Is this typed or not, ie is there a typed load and store involved?
563    /// I vaguely remember Ralf saying somewhere that he thought it should not be.
564    CopyNonOverlapping(CopyNonOverlapping<'tcx>),
565}
566
567/// Describes what kind of retag is to be performed.
568#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
569#[rustc_pass_by_value]
570pub enum RetagKind {
571    /// The initial retag of arguments when entering a function.
572    FnEntry,
573    /// Retag preparing for a two-phase borrow.
574    TwoPhase,
575    /// Retagging raw pointers.
576    Raw,
577    /// A "normal" retag.
578    Default,
579}
580
581/// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
582#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
583pub enum FakeReadCause {
584    /// Inject a fake read of the borrowed input at the end of each guards
585    /// code.
586    ///
587    /// This should ensure that you cannot change the variant for an enum while
588    /// you are in the midst of matching on it.
589    ForMatchGuard,
590
591    /// `let x: !; match x {}` doesn't generate any read of x so we need to
592    /// generate a read of x to check that it is initialized and safe.
593    ///
594    /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
595    /// FakeRead for that Place outside the closure, in such a case this option would be
596    /// Some(closure_def_id).
597    /// Otherwise, the value of the optional LocalDefId will be None.
598    //
599    // We can use LocalDefId here since fake read statements are removed
600    // before codegen in the `CleanupNonCodegenStatements` pass.
601    ForMatchedPlace(Option<LocalDefId>),
602
603    /// A fake read of the RefWithinGuard version of a bind-by-value variable
604    /// in a match guard to ensure that its value hasn't change by the time
605    /// we create the OutsideGuard version.
606    ForGuardBinding,
607
608    /// Officially, the semantics of
609    ///
610    /// `let pattern = <expr>;`
611    ///
612    /// is that `<expr>` is evaluated into a temporary and then this temporary is
613    /// into the pattern.
614    ///
615    /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
616    /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
617    /// but in some cases it can affect the borrow checker, as in #53695.
618    /// Therefore, we insert a "fake read" here to ensure that we get
619    /// appropriate errors.
620    ///
621    /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
622    /// FakeRead for that Place outside the closure, in such a case this option would be
623    /// Some(closure_def_id).
624    /// Otherwise, the value of the optional DefId will be None.
625    ForLet(Option<LocalDefId>),
626
627    /// If we have an index expression like
628    ///
629    /// (*x)[1][{ x = y; 4}]
630    ///
631    /// then the first bounds check is invalidated when we evaluate the second
632    /// index expression. Thus we create a fake borrow of `x` across the second
633    /// indexer, which will cause a borrow check error.
634    ForIndex,
635}
636
637#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
638#[derive(TypeFoldable, TypeVisitable)]
639pub struct CopyNonOverlapping<'tcx> {
640    pub src: Operand<'tcx>,
641    pub dst: Operand<'tcx>,
642    /// Number of elements to copy from src to dest, not bytes.
643    pub count: Operand<'tcx>,
644}
645
646/// Represents how a [`TerminatorKind::Call`] was constructed.
647/// Used only for diagnostics.
648#[derive(Clone, Copy, TyEncodable, TyDecodable, Debug, PartialEq, Hash, HashStable)]
649#[derive(TypeFoldable, TypeVisitable)]
650pub enum CallSource {
651    /// This came from something such as `a > b` or `a + b`. In THIR, if `from_hir_call`
652    /// is false then this is the desugaring.
653    OverloadedOperator,
654    /// This was from comparison generated by a match, used by const-eval for better errors
655    /// when the comparison cannot be done in compile time.
656    ///
657    /// (see <https://github.com/rust-lang/rust/issues/90237>)
658    MatchCmp,
659    /// Other types of desugaring that did not come from the HIR, but we don't care about
660    /// for diagnostics (yet).
661    Misc,
662    /// Normal function call, no special source
663    Normal,
664}
665
666impl CallSource {
667    pub fn from_hir_call(self) -> bool {
668        matches!(self, CallSource::Normal)
669    }
670}
671
672#[derive(Clone, Copy, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
673#[derive(TypeFoldable, TypeVisitable)]
674/// The macro that an inline assembly block was created by
675pub enum InlineAsmMacro {
676    /// The `asm!` macro
677    Asm,
678    /// The `naked_asm!` macro
679    NakedAsm,
680}
681
682impl InlineAsmMacro {
683    pub const fn diverges(self, options: InlineAsmOptions) -> bool {
684        match self {
685            InlineAsmMacro::Asm => options.contains(InlineAsmOptions::NORETURN),
686            InlineAsmMacro::NakedAsm => true,
687        }
688    }
689}
690
691///////////////////////////////////////////////////////////////////////////
692// Terminators
693
694/// The various kinds of terminators, representing ways of exiting from a basic block.
695///
696/// A note on unwinding: Panics may occur during the execution of some terminators. Depending on the
697/// `-C panic` flag, this may either cause the program to abort or the call stack to unwind. Such
698/// terminators have a `unwind: UnwindAction` field on them. If stack unwinding occurs, then
699/// once the current function is reached, an action will be taken based on the `unwind` field.
700/// If the action is `Cleanup`, then the execution continues at the given basic block. If the
701/// action is `Continue` then no cleanup is performed, and the stack continues unwinding.
702///
703/// The basic block pointed to by a `Cleanup` unwind action must have its `cleanup` flag set.
704/// `cleanup` basic blocks have a couple restrictions:
705///  1. All `unwind` fields in them must be `UnwindAction::Terminate` or `UnwindAction::Unreachable`.
706///  2. `Return` terminators are not allowed in them. `Terminate` and `Resume` terminators are.
707///  3. All other basic blocks (in the current body) that are reachable from `cleanup` basic blocks
708///     must also be `cleanup`. This is a part of the type system and checked statically, so it is
709///     still an error to have such an edge in the CFG even if it's known that it won't be taken at
710///     runtime.
711///  4. The control flow between cleanup blocks must look like an upside down tree. Roughly
712///     speaking, this means that control flow that looks like a V is allowed, while control flow
713///     that looks like a W is not. This is necessary to ensure that landing pad information can be
714///     correctly codegened on MSVC. More precisely:
715///
716///     Begin with the standard control flow graph `G`. Modify `G` as follows: for any two cleanup
717///     vertices `u` and `v` such that `u` dominates `v`, contract `u` and `v` into a single vertex,
718///     deleting self edges and duplicate edges in the process. Now remove all vertices from `G`
719///     that are not cleanup vertices or are not reachable. The resulting graph must be an inverted
720///     tree, that is each vertex may have at most one successor and there may be no cycles.
721#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
722pub enum TerminatorKind<'tcx> {
723    /// Block has one successor; we continue execution there.
724    Goto { target: BasicBlock },
725
726    /// Switches based on the computed value.
727    ///
728    /// First, evaluates the `discr` operand. The type of the operand must be a signed or unsigned
729    /// integer, char, or bool, and must match the given type. Then, if the list of switch targets
730    /// contains the computed value, continues execution at the associated basic block. Otherwise,
731    /// continues execution at the "otherwise" basic block.
732    ///
733    /// Target values may not appear more than once.
734    SwitchInt {
735        /// The discriminant value being tested.
736        discr: Operand<'tcx>,
737        targets: SwitchTargets,
738    },
739
740    /// Indicates that the landing pad is finished and that the process should continue unwinding.
741    ///
742    /// Like a return, this marks the end of this invocation of the function.
743    ///
744    /// Only permitted in cleanup blocks. `Resume` is not permitted with `-C unwind=abort` after
745    /// deaggregation runs.
746    UnwindResume,
747
748    /// Indicates that the landing pad is finished and that the process should terminate.
749    ///
750    /// Used to prevent unwinding for foreign items or with `-C unwind=abort`. Only permitted in
751    /// cleanup blocks.
752    UnwindTerminate(UnwindTerminateReason),
753
754    /// Returns from the function.
755    ///
756    /// Like function calls, the exact semantics of returns in Rust are unclear. Returning very
757    /// likely at least assigns the value currently in the return place (`_0`) to the place
758    /// specified in the associated `Call` terminator in the calling function, as if assigned via
759    /// `dest = move _0`. It might additionally do other things, like have side-effects in the
760    /// aliasing model.
761    ///
762    /// If the body is a coroutine body, this has slightly different semantics; it instead causes a
763    /// `CoroutineState::Returned(_0)` to be created (as if by an `Aggregate` rvalue) and assigned
764    /// to the return place.
765    Return,
766
767    /// Indicates a terminator that can never be reached.
768    ///
769    /// Executing this terminator is UB.
770    Unreachable,
771
772    /// The behavior of this statement differs significantly before and after drop elaboration.
773    ///
774    /// After drop elaboration: `Drop` terminators are a complete nop for types that have no drop
775    /// glue. For other types, `Drop` terminators behave exactly like a call to
776    /// `core::mem::drop_in_place` with a pointer to the given place.
777    ///
778    /// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically,
779    /// the `Drop` will be executed if...
780    ///
781    /// **Needs clarification**: End of that sentence. This in effect should document the exact
782    /// behavior of drop elaboration. The following sounds vaguely right, but I'm not quite sure:
783    ///
784    /// > The drop glue is executed if, among all statements executed within this `Body`, an assignment to
785    /// > the place or one of its "parents" occurred more recently than a move out of it. This does not
786    /// > consider indirect assignments.
787    ///
788    /// The `replace` flag indicates whether this terminator was created as part of an assignment.
789    /// This should only be used for diagnostic purposes, and does not have any operational
790    /// meaning.
791    Drop { place: Place<'tcx>, target: BasicBlock, unwind: UnwindAction, replace: bool },
792
793    /// Roughly speaking, evaluates the `func` operand and the arguments, and starts execution of
794    /// the referred to function. The operand types must match the argument types of the function.
795    /// The return place type must match the return type. The type of the `func` operand must be
796    /// callable, meaning either a function pointer, a function type, or a closure type.
797    ///
798    /// **Needs clarification**: The exact semantics of this. Current backends rely on `move`
799    /// operands not aliasing the return place. It is unclear how this is justified in MIR, see
800    /// [#71117].
801    ///
802    /// [#71117]: https://github.com/rust-lang/rust/issues/71117
803    Call {
804        /// The function that’s being called.
805        func: Operand<'tcx>,
806        /// Arguments the function is called with.
807        /// These are owned by the callee, which is free to modify them.
808        /// This allows the memory occupied by "by-value" arguments to be
809        /// reused across function calls without duplicating the contents.
810        /// The span for each arg is also included
811        /// (e.g. `a` and `b` in `x.foo(a, b)`).
812        args: Box<[Spanned<Operand<'tcx>>]>,
813        /// Where the returned value will be written
814        destination: Place<'tcx>,
815        /// Where to go after this call returns. If none, the call necessarily diverges.
816        target: Option<BasicBlock>,
817        /// Action to be taken if the call unwinds.
818        unwind: UnwindAction,
819        /// Where this call came from in HIR/THIR.
820        call_source: CallSource,
821        /// This `Span` is the span of the function, without the dot and receiver
822        /// e.g. `foo(a, b)` in `x.foo(a, b)`
823        fn_span: Span,
824    },
825
826    /// Tail call.
827    ///
828    /// Roughly speaking this is a chimera of [`Call`] and [`Return`], with some caveats.
829    /// Semantically tail calls consists of two actions:
830    /// - pop of the current stack frame
831    /// - a call to the `func`, with the return address of the **current** caller
832    ///   - so that a `return` inside `func` returns to the caller of the caller
833    ///     of the function that is currently being executed
834    ///
835    /// Note that in difference with [`Call`] this is missing
836    /// - `destination` (because it's always the return place)
837    /// - `target` (because it's always taken from the current stack frame)
838    /// - `unwind` (because it's always taken from the current stack frame)
839    ///
840    /// [`Call`]: TerminatorKind::Call
841    /// [`Return`]: TerminatorKind::Return
842    TailCall {
843        /// The function that’s being called.
844        func: Operand<'tcx>,
845        /// Arguments the function is called with.
846        /// These are owned by the callee, which is free to modify them.
847        /// This allows the memory occupied by "by-value" arguments to be
848        /// reused across function calls without duplicating the contents.
849        args: Box<[Spanned<Operand<'tcx>>]>,
850        // FIXME(explicit_tail_calls): should we have the span for `become`? is this span accurate? do we need it?
851        /// This `Span` is the span of the function, without the dot and receiver
852        /// (e.g. `foo(a, b)` in `x.foo(a, b)`
853        fn_span: Span,
854    },
855
856    /// Evaluates the operand, which must have type `bool`. If it is not equal to `expected`,
857    /// initiates a panic. Initiating a panic corresponds to a `Call` terminator with some
858    /// unspecified constant as the function to call, all the operands stored in the `AssertMessage`
859    /// as parameters, and `None` for the destination. Keep in mind that the `cleanup` path is not
860    /// necessarily executed even in the case of a panic, for example in `-C panic=abort`. If the
861    /// assertion does not fail, execution continues at the specified basic block.
862    ///
863    /// When overflow checking is disabled and this is run-time MIR (as opposed to compile-time MIR
864    /// that is used for CTFE), the following variants of this terminator behave as `goto target`:
865    /// - `OverflowNeg(..)`,
866    /// - `Overflow(op, ..)` if op is add, sub, mul, shl, shr, but NOT div or rem.
867    Assert {
868        cond: Operand<'tcx>,
869        expected: bool,
870        msg: Box<AssertMessage<'tcx>>,
871        target: BasicBlock,
872        unwind: UnwindAction,
873    },
874
875    /// Marks a suspend point.
876    ///
877    /// Like `Return` terminators in coroutine bodies, this computes `value` and then a
878    /// `CoroutineState::Yielded(value)` as if by `Aggregate` rvalue. That value is then assigned to
879    /// the return place of the function calling this one, and execution continues in the calling
880    /// function. When next invoked with the same first argument, execution of this function
881    /// continues at the `resume` basic block, with the second argument written to the `resume_arg`
882    /// place. If the coroutine is dropped before then, the `drop` basic block is invoked.
883    ///
884    /// Note that coroutines can be (unstably) cloned under certain conditions, which means that
885    /// this terminator can **return multiple times**! MIR optimizations that reorder code into
886    /// different basic blocks needs to be aware of that.
887    /// See <https://github.com/rust-lang/rust/issues/95360>.
888    ///
889    /// Not permitted in bodies that are not coroutine bodies, or after coroutine lowering.
890    ///
891    /// **Needs clarification**: What about the evaluation order of the `resume_arg` and `value`?
892    Yield {
893        /// The value to return.
894        value: Operand<'tcx>,
895        /// Where to resume to.
896        resume: BasicBlock,
897        /// The place to store the resume argument in.
898        resume_arg: Place<'tcx>,
899        /// Cleanup to be done if the coroutine is dropped at this suspend point.
900        drop: Option<BasicBlock>,
901    },
902
903    /// Indicates the end of dropping a coroutine.
904    ///
905    /// Semantically just a `return` (from the coroutines drop glue). Only permitted in the same situations
906    /// as `yield`.
907    ///
908    /// **Needs clarification**: Is that even correct? The coroutine drop code is always confusing
909    /// to me, because it's not even really in the current body.
910    ///
911    /// **Needs clarification**: Are there type system constraints on these terminators? Should
912    /// there be a "block type" like `cleanup` blocks for them?
913    CoroutineDrop,
914
915    /// A block where control flow only ever takes one real path, but borrowck needs to be more
916    /// conservative.
917    ///
918    /// At runtime this is semantically just a goto.
919    ///
920    /// Disallowed after drop elaboration.
921    FalseEdge {
922        /// The target normal control flow will take.
923        real_target: BasicBlock,
924        /// A block control flow could conceptually jump to, but won't in
925        /// practice.
926        imaginary_target: BasicBlock,
927    },
928
929    /// A terminator for blocks that only take one path in reality, but where we reserve the right
930    /// to unwind in borrowck, even if it won't happen in practice. This can arise in infinite loops
931    /// with no function calls for example.
932    ///
933    /// At runtime this is semantically just a goto.
934    ///
935    /// Disallowed after drop elaboration.
936    FalseUnwind {
937        /// The target normal control flow will take.
938        real_target: BasicBlock,
939        /// The imaginary cleanup block link. This particular path will never be taken
940        /// in practice, but in order to avoid fragility we want to always
941        /// consider it in borrowck. We don't want to accept programs which
942        /// pass borrowck only when `panic=abort` or some assertions are disabled
943        /// due to release vs. debug mode builds.
944        unwind: UnwindAction,
945    },
946
947    /// Block ends with an inline assembly block. This is a terminator since
948    /// inline assembly is allowed to diverge.
949    InlineAsm {
950        /// Macro used to create this inline asm: one of `asm!` or `naked_asm!`
951        asm_macro: InlineAsmMacro,
952
953        /// The template for the inline assembly, with placeholders.
954        template: &'tcx [InlineAsmTemplatePiece],
955
956        /// The operands for the inline assembly, as `Operand`s or `Place`s.
957        operands: Box<[InlineAsmOperand<'tcx>]>,
958
959        /// Miscellaneous options for the inline assembly.
960        options: InlineAsmOptions,
961
962        /// Source spans for each line of the inline assembly code. These are
963        /// used to map assembler errors back to the line in the source code.
964        line_spans: &'tcx [Span],
965
966        /// Valid targets for the inline assembly.
967        /// The first element is the fallthrough destination, unless
968        /// asm_macro == InlineAsmMacro::NakedAsm or InlineAsmOptions::NORETURN is set.
969        targets: Box<[BasicBlock]>,
970
971        /// Action to be taken if the inline assembly unwinds. This is present
972        /// if and only if InlineAsmOptions::MAY_UNWIND is set.
973        unwind: UnwindAction,
974    },
975}
976
977#[derive(
978    Clone,
979    Debug,
980    TyEncodable,
981    TyDecodable,
982    Hash,
983    HashStable,
984    PartialEq,
985    TypeFoldable,
986    TypeVisitable
987)]
988pub enum BackwardIncompatibleDropReason {
989    Edition2024,
990}
991
992impl TerminatorKind<'_> {
993    /// Returns a simple string representation of a `TerminatorKind` variant, independent of any
994    /// values it might hold (e.g. `TerminatorKind::Call` always returns `"Call"`).
995    pub const fn name(&self) -> &'static str {
996        match self {
997            TerminatorKind::Goto { .. } => "Goto",
998            TerminatorKind::SwitchInt { .. } => "SwitchInt",
999            TerminatorKind::UnwindResume => "UnwindResume",
1000            TerminatorKind::UnwindTerminate(_) => "UnwindTerminate",
1001            TerminatorKind::Return => "Return",
1002            TerminatorKind::Unreachable => "Unreachable",
1003            TerminatorKind::Drop { .. } => "Drop",
1004            TerminatorKind::Call { .. } => "Call",
1005            TerminatorKind::TailCall { .. } => "TailCall",
1006            TerminatorKind::Assert { .. } => "Assert",
1007            TerminatorKind::Yield { .. } => "Yield",
1008            TerminatorKind::CoroutineDrop => "CoroutineDrop",
1009            TerminatorKind::FalseEdge { .. } => "FalseEdge",
1010            TerminatorKind::FalseUnwind { .. } => "FalseUnwind",
1011            TerminatorKind::InlineAsm { .. } => "InlineAsm",
1012        }
1013    }
1014}
1015
1016#[derive(Debug, Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
1017pub struct SwitchTargets {
1018    /// Possible values. The locations to branch to in each case
1019    /// are found in the corresponding indices from the `targets` vector.
1020    pub(super) values: SmallVec<[Pu128; 1]>,
1021
1022    /// Possible branch sites. The last element of this vector is used
1023    /// for the otherwise branch, so targets.len() == values.len() + 1
1024    /// should hold.
1025    //
1026    // This invariant is quite non-obvious and also could be improved.
1027    // One way to make this invariant is to have something like this instead:
1028    //
1029    // branches: Vec<(ConstInt, BasicBlock)>,
1030    // otherwise: Option<BasicBlock> // exhaustive if None
1031    //
1032    // However we’ve decided to keep this as-is until we figure a case
1033    // where some other approach seems to be strictly better than other.
1034    pub(super) targets: SmallVec<[BasicBlock; 2]>,
1035}
1036
1037/// Action to be taken when a stack unwind happens.
1038#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1039#[derive(TypeFoldable, TypeVisitable)]
1040pub enum UnwindAction {
1041    /// No action is to be taken. Continue unwinding.
1042    ///
1043    /// This is similar to `Cleanup(bb)` where `bb` does nothing but `Resume`, but they are not
1044    /// equivalent, as presence of `Cleanup(_)` will make a frame non-POF.
1045    Continue,
1046    /// Triggers undefined behavior if unwind happens.
1047    Unreachable,
1048    /// Terminates the execution if unwind happens.
1049    ///
1050    /// Depending on the platform and situation this may cause a non-unwindable panic or abort.
1051    Terminate(UnwindTerminateReason),
1052    /// Cleanups to be done.
1053    Cleanup(BasicBlock),
1054}
1055
1056/// The reason we are terminating the process during unwinding.
1057#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1058#[derive(TypeFoldable, TypeVisitable)]
1059pub enum UnwindTerminateReason {
1060    /// Unwinding is just not possible given the ABI of this function.
1061    Abi,
1062    /// We were already cleaning up for an ongoing unwind, and a *second*, *nested* unwind was
1063    /// triggered by the drop glue.
1064    InCleanup,
1065}
1066
1067/// Information about an assertion failure.
1068#[derive(Clone, Hash, HashStable, PartialEq, Debug)]
1069#[derive(TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
1070pub enum AssertKind<O> {
1071    BoundsCheck { len: O, index: O },
1072    Overflow(BinOp, O, O),
1073    OverflowNeg(O),
1074    DivisionByZero(O),
1075    RemainderByZero(O),
1076    ResumedAfterReturn(CoroutineKind),
1077    ResumedAfterPanic(CoroutineKind),
1078    MisalignedPointerDereference { required: O, found: O },
1079    NullPointerDereference,
1080}
1081
1082#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
1083#[derive(TypeFoldable, TypeVisitable)]
1084pub enum InlineAsmOperand<'tcx> {
1085    In {
1086        reg: InlineAsmRegOrRegClass,
1087        value: Operand<'tcx>,
1088    },
1089    Out {
1090        reg: InlineAsmRegOrRegClass,
1091        late: bool,
1092        place: Option<Place<'tcx>>,
1093    },
1094    InOut {
1095        reg: InlineAsmRegOrRegClass,
1096        late: bool,
1097        in_value: Operand<'tcx>,
1098        out_place: Option<Place<'tcx>>,
1099    },
1100    Const {
1101        value: Box<ConstOperand<'tcx>>,
1102    },
1103    SymFn {
1104        value: Box<ConstOperand<'tcx>>,
1105    },
1106    SymStatic {
1107        def_id: DefId,
1108    },
1109    Label {
1110        /// This represents the index into the `targets` array in `TerminatorKind::InlineAsm`.
1111        target_index: usize,
1112    },
1113}
1114
1115/// Type for MIR `Assert` terminator error messages.
1116pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1117
1118///////////////////////////////////////////////////////////////////////////
1119// Places
1120
1121/// Places roughly correspond to a "location in memory." Places in MIR are the same mathematical
1122/// object as places in Rust. This of course means that what exactly they are is undecided and part
1123/// of the Rust memory model. However, they will likely contain at least the following pieces of
1124/// information in some form:
1125///
1126///  1. The address in memory that the place refers to.
1127///  2. The provenance with which the place is being accessed.
1128///  3. The type of the place and an optional variant index. See [`PlaceTy`][super::tcx::PlaceTy].
1129///  4. Optionally, some metadata. This exists if and only if the type of the place is not `Sized`.
1130///
1131/// We'll give a description below of how all pieces of the place except for the provenance are
1132/// calculated. We cannot give a description of the provenance, because that is part of the
1133/// undecided aliasing model - we only include it here at all to acknowledge its existence.
1134///
1135/// Each local naturally corresponds to the place `Place { local, projection: [] }`. This place has
1136/// the address of the local's allocation and the type of the local.
1137///
1138/// **Needs clarification:** Unsized locals seem to present a bit of an issue. Their allocation
1139/// can't actually be created on `StorageLive`, because it's unclear how big to make the allocation.
1140/// Furthermore, MIR produces assignments to unsized locals, although that is not permitted under
1141/// `#![feature(unsized_locals)]` in Rust. Besides just putting "unsized locals are special and
1142/// different" in a bunch of places, I (JakobDegen) don't know how to incorporate this behavior into
1143/// the current MIR semantics in a clean way - possibly this needs some design work first.
1144///
1145/// For places that are not locals, ie they have a non-empty list of projections, we define the
1146/// values as a function of the parent place, that is the place with its last [`ProjectionElem`]
1147/// stripped. The way this is computed of course depends on the kind of that last projection
1148/// element:
1149///
1150///  - [`Downcast`](ProjectionElem::Downcast): This projection sets the place's variant index to the
1151///    given one, and makes no other changes. A `Downcast` projection must always be followed
1152///    immediately by a `Field` projection.
1153///  - [`Field`](ProjectionElem::Field): `Field` projections take their parent place and create a
1154///    place referring to one of the fields of the type. The resulting address is the parent
1155///    address, plus the offset of the field. The type becomes the type of the field. If the parent
1156///    was unsized and so had metadata associated with it, then the metadata is retained if the
1157///    field is unsized and thrown out if it is sized.
1158///
1159///    These projections are only legal for tuples, ADTs, closures, and coroutines. If the ADT or
1160///    coroutine has more than one variant, the parent place's variant index must be set, indicating
1161///    which variant is being used. If it has just one variant, the variant index may or may not be
1162///    included - the single possible variant is inferred if it is not included.
1163///  - [`OpaqueCast`](ProjectionElem::OpaqueCast): This projection changes the place's type to the
1164///    given one, and makes no other changes. A `OpaqueCast` projection on any type other than an
1165///    opaque type from the current crate is not well-formed.
1166///  - [`ConstantIndex`](ProjectionElem::ConstantIndex): Computes an offset in units of `T` into the
1167///    place as described in the documentation for the `ProjectionElem`. The resulting address is
1168///    the parent's address plus that offset, and the type is `T`. This is only legal if the parent
1169///    place has type `[T;  N]` or `[T]` (*not* `&[T]`). Since such a `T` is always sized, any
1170///    resulting metadata is thrown out.
1171///  - [`Subslice`](ProjectionElem::Subslice): This projection calculates an offset and a new
1172///    address in a similar manner as `ConstantIndex`. It is also only legal on `[T; N]` and `[T]`.
1173///    However, this yields a `Place` of type `[T]`, and additionally sets the metadata to be the
1174///    length of the subslice.
1175///  - [`Index`](ProjectionElem::Index): Like `ConstantIndex`, only legal on `[T; N]` or `[T]`.
1176///    However, `Index` additionally takes a local from which the value of the index is computed at
1177///    runtime. Computing the value of the index involves interpreting the `Local` as a
1178///    `Place { local, projection: [] }`, and then computing its value as if done via
1179///    [`Operand::Copy`]. The array/slice is then indexed with the resulting value. The local must
1180///    have type `usize`.
1181///  - [`Deref`](ProjectionElem::Deref): Derefs are the last type of projection, and the most
1182///    complicated. They are only legal on parent places that are references, pointers, or `Box`. A
1183///    `Deref` projection begins by loading a value from the parent place, as if by
1184///    [`Operand::Copy`]. It then dereferences the resulting pointer, creating a place of the
1185///    pointee's type. The resulting address is the address that was stored in the pointer. If the
1186///    pointee type is unsized, the pointer additionally stored the value of the metadata.
1187///
1188/// The "validity invariant" of places is the same as that of raw pointers, meaning that e.g.
1189/// `*ptr` on a dangling or unaligned pointer is never UB. (Later doing a load/store on that place
1190/// or turning it into a reference can be UB though!) The only ways for a place computation can
1191/// cause UB are:
1192/// - On a `Deref` projection, we do an actual load of the inner place, with all the usual
1193///   consequences (the inner place must be based on an aligned pointer, it must point to allocated
1194///   memory, the aliasig model must allow reads, this must not be a data race).
1195/// - For the projections that perform pointer arithmetic, the offset must in-bounds of an
1196///   allocation (i.e., the preconditions of `ptr::offset` must be met).
1197#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable, TypeFoldable, TypeVisitable)]
1198pub struct Place<'tcx> {
1199    pub local: Local,
1200
1201    /// projection out of a place (access a field, deref a pointer, etc)
1202    pub projection: &'tcx List<PlaceElem<'tcx>>,
1203}
1204
1205#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1206#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1207pub enum ProjectionElem<V, T> {
1208    Deref,
1209
1210    /// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
1211    /// rustc can identify that a field projection refers to either two different regions of memory
1212    /// or the same one between the base and the 'projection element'.
1213    /// Read more about projections in the [rustc-dev-guide][mir-datatypes]
1214    ///
1215    /// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
1216    Field(FieldIdx, T),
1217
1218    /// Index into a slice/array.
1219    ///
1220    /// Note that this does not also dereference, and so it does not exactly correspond to slice
1221    /// indexing in Rust. In other words, in the below Rust code:
1222    ///
1223    /// ```rust
1224    /// let x = &[1, 2, 3, 4];
1225    /// let i = 2;
1226    /// x[i];
1227    /// ```
1228    ///
1229    /// The `x[i]` is turned into a `Deref` followed by an `Index`, not just an `Index`. The same
1230    /// thing is true of the `ConstantIndex` and `Subslice` projections below.
1231    Index(V),
1232
1233    /// These indices are generated by slice patterns. Easiest to explain
1234    /// by example:
1235    ///
1236    /// ```ignore (illustrative)
1237    /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1238    /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1239    /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1240    /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1241    /// ```
1242    ConstantIndex {
1243        /// index or -index (in Python terms), depending on from_end
1244        offset: u64,
1245        /// The thing being indexed must be at least this long -- otherwise, the
1246        /// projection is UB.
1247        ///
1248        /// For arrays this is always the exact length.
1249        min_length: u64,
1250        /// Counting backwards from end? This is always false when indexing an
1251        /// array.
1252        from_end: bool,
1253    },
1254
1255    /// These indices are generated by slice patterns.
1256    ///
1257    /// If `from_end` is true `slice[from..slice.len() - to]`.
1258    /// Otherwise `array[from..to]`.
1259    Subslice {
1260        from: u64,
1261        to: u64,
1262        /// Whether `to` counts from the start or end of the array/slice.
1263        /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1264        /// For `ProjectionKind`, this can also be `true` for arrays.
1265        from_end: bool,
1266    },
1267
1268    /// "Downcast" to a variant of an enum or a coroutine.
1269    ///
1270    /// The included Symbol is the name of the variant, used for printing MIR.
1271    ///
1272    /// This operation itself is never UB, all it does is change the type of the place.
1273    Downcast(Option<Symbol>, VariantIdx),
1274
1275    /// Like an explicit cast from an opaque type to a concrete type, but without
1276    /// requiring an intermediate variable.
1277    OpaqueCast(T),
1278
1279    /// A transmute from an unsafe binder to the type that it wraps. This is a projection
1280    /// of a place, so it doesn't necessarily constitute a move out of the binder.
1281    UnwrapUnsafeBinder(T),
1282
1283    /// A `Subtype(T)` projection is applied to any `StatementKind::Assign` where
1284    /// type of lvalue doesn't match the type of rvalue, the primary goal is making subtyping
1285    /// explicit during optimizations and codegen.
1286    ///
1287    /// This projection doesn't impact the runtime behavior of the program except for potentially changing
1288    /// some type metadata of the interpreter or codegen backend.
1289    ///
1290    /// This goal is achieved with mir_transform pass `Subtyper`, which runs right after
1291    /// borrowchecker, as we only care about subtyping that can affect trait selection and
1292    /// `TypeId`.
1293    Subtype(T),
1294}
1295
1296/// Alias for projections as they appear in places, where the base is a place
1297/// and the index is a local.
1298pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1299
1300///////////////////////////////////////////////////////////////////////////
1301// Operands
1302
1303/// An operand in MIR represents a "value" in Rust, the definition of which is undecided and part of
1304/// the memory model. One proposal for a definition of values can be found [on UCG][value-def].
1305///
1306/// [value-def]: https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/value-domain.md
1307///
1308/// The most common way to create values is via loading a place. Loading a place is an operation
1309/// which reads the memory of the place and converts it to a value. This is a fundamentally *typed*
1310/// operation. The nature of the value produced depends on the type of the conversion. Furthermore,
1311/// there may be other effects: if the type has a validity constraint loading the place might be UB
1312/// if the validity constraint is not met.
1313///
1314/// **Needs clarification:** Is loading a place that has its variant index set well-formed? Miri
1315/// currently implements it, but it seems like this may be something to check against in the
1316/// validator.
1317#[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)]
1318pub enum Operand<'tcx> {
1319    /// Creates a value by loading the given place.
1320    ///
1321    /// Before drop elaboration, the type of the place must be `Copy`. After drop elaboration there
1322    /// is no such requirement.
1323    Copy(Place<'tcx>),
1324
1325    /// Creates a value by performing loading the place, just like the `Copy` operand.
1326    ///
1327    /// This *may* additionally overwrite the place with `uninit` bytes, depending on how we decide
1328    /// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this
1329    /// place without first re-initializing it.
1330    ///
1331    /// **Needs clarification:** The operational impact of `Move` is unclear. Currently (both in
1332    /// Miri and codegen) it has no effect at all unless it appears in an argument to `Call`; for
1333    /// `Call` it allows the argument to be passed to the callee "in-place", i.e. the callee might
1334    /// just get a reference to this place instead of a full copy. Miri implements this with a
1335    /// combination of aliasing model "protectors" and putting `uninit` into the place. Ralf
1336    /// proposes that we don't want these semantics for `Move` in regular assignments, because
1337    /// loading a place should not have side-effects, and the aliasing model "protectors" are
1338    /// inherently tied to a function call. Are these the semantics we want for MIR? Is this
1339    /// something we can even decide without knowing more about Rust's memory model?
1340    ///
1341    /// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188
1342    Move(Place<'tcx>),
1343
1344    /// Constants are already semantically values, and remain unchanged.
1345    Constant(Box<ConstOperand<'tcx>>),
1346}
1347
1348#[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
1349#[derive(TypeFoldable, TypeVisitable)]
1350pub struct ConstOperand<'tcx> {
1351    pub span: Span,
1352
1353    /// Optional user-given type: for something like
1354    /// `collect::<Vec<_>>`, this would be present and would
1355    /// indicate that `Vec<_>` was explicitly specified.
1356    ///
1357    /// Needed for NLL to impose user-given type constraints.
1358    pub user_ty: Option<UserTypeAnnotationIndex>,
1359
1360    pub const_: Const<'tcx>,
1361}
1362
1363///////////////////////////////////////////////////////////////////////////
1364// Rvalues
1365
1366/// The various kinds of rvalues that can appear in MIR.
1367///
1368/// Not all of these are allowed at every [`MirPhase`] - when this is the case, it's stated below.
1369///
1370/// Computing any rvalue begins by evaluating the places and operands in some order (**Needs
1371/// clarification**: Which order?). These are then used to produce a "value" - the same kind of
1372/// value that an [`Operand`] produces.
1373#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
1374pub enum Rvalue<'tcx> {
1375    /// Yields the operand unchanged
1376    Use(Operand<'tcx>),
1377
1378    /// Creates an array where each element is the value of the operand.
1379    ///
1380    /// This is the cause of a bug in the case where the repetition count is zero because the value
1381    /// is not dropped, see [#74836].
1382    ///
1383    /// Corresponds to source code like `[x; 32]`.
1384    ///
1385    /// [#74836]: https://github.com/rust-lang/rust/issues/74836
1386    Repeat(Operand<'tcx>, ty::Const<'tcx>),
1387
1388    /// Creates a reference of the indicated kind to the place.
1389    ///
1390    /// There is not much to document here, because besides the obvious parts the semantics of this
1391    /// are essentially entirely a part of the aliasing model. There are many UCG issues discussing
1392    /// exactly what the behavior of this operation should be.
1393    ///
1394    /// `Shallow` borrows are disallowed after drop lowering.
1395    Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1396
1397    /// Creates a pointer/reference to the given thread local.
1398    ///
1399    /// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a
1400    /// `*const T`, and if neither of those apply a `&T`.
1401    ///
1402    /// **Note:** This is a runtime operation that actually executes code and is in this sense more
1403    /// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to
1404    /// SIGILL for some reason that I (JakobDegen) never got a chance to look into.
1405    ///
1406    /// **Needs clarification**: Are there weird additional semantics here related to the runtime
1407    /// nature of this operation?
1408    ThreadLocalRef(DefId),
1409
1410    /// Creates a raw pointer with the indicated mutability to the place.
1411    ///
1412    /// This is generated by pointer casts like `&v as *const _` or raw borrow expressions like
1413    /// `&raw const v`.
1414    ///
1415    /// Like with references, the semantics of this operation are heavily dependent on the aliasing
1416    /// model.
1417    RawPtr(RawPtrKind, Place<'tcx>),
1418
1419    /// Yields the length of the place, as a `usize`.
1420    ///
1421    /// If the type of the place is an array, this is the array length. For slices (`[T]`, not
1422    /// `&[T]`) this accesses the place's metadata to determine the length. This rvalue is
1423    /// ill-formed for places of other types.
1424    ///
1425    /// This cannot be a `UnOp(PtrMetadata, _)` because that expects a value, and we only
1426    /// have a place, and `UnOp(PtrMetadata, RawPtr(place))` is not a thing.
1427    Len(Place<'tcx>),
1428
1429    /// Performs essentially all of the casts that can be performed via `as`.
1430    ///
1431    /// This allows for casts from/to a variety of types.
1432    ///
1433    /// **FIXME**: Document exactly which `CastKind`s allow which types of casts.
1434    Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1435
1436    /// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second
1437    ///   parameter may be a `usize` as well.
1438    /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats,
1439    ///   raw pointers, or function pointers and return a `bool`. The types of the operands must be
1440    ///   matching, up to the usual caveat of the lifetimes in function pointers.
1441    /// * Left and right shift operations accept signed or unsigned integers not necessarily of the
1442    ///   same type and return a value of the same type as their LHS. Like in Rust, the RHS is
1443    ///   truncated as needed.
1444    /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching
1445    ///   types and return a value of that type.
1446    /// * The `FooWithOverflow` are like the `Foo`, but returning `(T, bool)` instead of just `T`,
1447    ///   where the `bool` is true if the result is not equal to the infinite-precision result.
1448    /// * The remaining operations accept signed integers, unsigned integers, or floats with
1449    ///   matching types and return a value of that type.
1450    BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
1451
1452    /// Computes a value as described by the operation.
1453    NullaryOp(NullOp<'tcx>, Ty<'tcx>),
1454
1455    /// Exactly like `BinaryOp`, but less operands.
1456    ///
1457    /// Also does two's-complement arithmetic. Negation requires a signed integer or a float;
1458    /// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds
1459    /// return a value with the same type as their operand.
1460    UnaryOp(UnOp, Operand<'tcx>),
1461
1462    /// Computes the discriminant of the place, returning it as an integer of type
1463    /// [`discriminant_ty`]. Returns zero for types without discriminant.
1464    ///
1465    /// The validity requirements for the underlying value are undecided for this rvalue, see
1466    /// [#91095]. Note too that the value of the discriminant is not the same thing as the
1467    /// variant index; use [`discriminant_for_variant`] to convert.
1468    ///
1469    /// [`discriminant_ty`]: crate::ty::Ty::discriminant_ty
1470    /// [#91095]: https://github.com/rust-lang/rust/issues/91095
1471    /// [`discriminant_for_variant`]: crate::ty::Ty::discriminant_for_variant
1472    Discriminant(Place<'tcx>),
1473
1474    /// Creates an aggregate value, like a tuple or struct.
1475    ///
1476    /// This is needed because dataflow analysis needs to distinguish
1477    /// `dest = Foo { x: ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case that `Foo`
1478    /// has a destructor.
1479    ///
1480    /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Coroutine`. After
1481    /// coroutine lowering, `Coroutine` aggregate kinds are disallowed too.
1482    Aggregate(Box<AggregateKind<'tcx>>, IndexVec<FieldIdx, Operand<'tcx>>),
1483
1484    /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
1485    ///
1486    /// This is different from a normal transmute because dataflow analysis will treat the box as
1487    /// initialized but its content as uninitialized. Like other pointer casts, this in general
1488    /// affects alias analysis.
1489    ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
1490
1491    /// A CopyForDeref is equivalent to a read from a place at the
1492    /// codegen level, but is treated specially by drop elaboration. When such a read happens, it
1493    /// is guaranteed (via nature of the mir_opt `Derefer` in rustc_mir_transform/src/deref_separator)
1494    /// that the only use of the returned value is a deref operation, immediately
1495    /// followed by one or more projections. Drop elaboration treats this rvalue as if the
1496    /// read never happened and just projects further. This allows simplifying various MIR
1497    /// optimizations and codegen backends that previously had to handle deref operations anywhere
1498    /// in a place.
1499    CopyForDeref(Place<'tcx>),
1500
1501    /// Wraps a value in an unsafe binder.
1502    WrapUnsafeBinder(Operand<'tcx>, Ty<'tcx>),
1503}
1504
1505#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1506pub enum CastKind {
1507    /// An exposing pointer to address cast. A cast between a pointer and an integer type, or
1508    /// between a function pointer and an integer type.
1509    /// See the docs on `expose_provenance` for more details.
1510    PointerExposeProvenance,
1511    /// An address-to-pointer cast that picks up an exposed provenance.
1512    /// See the docs on `with_exposed_provenance` for more details.
1513    PointerWithExposedProvenance,
1514    /// Pointer related casts that are done by coercions. Note that reference-to-raw-ptr casts are
1515    /// translated into `&raw mut/const *r`, i.e., they are not actually casts.
1516    ///
1517    /// The following are allowed in [`AnalysisPhase::Initial`] as they're needed for borrowck,
1518    /// but after that are forbidden (including in all phases of runtime MIR):
1519    /// * [`PointerCoercion::ArrayToPointer`]
1520    /// * [`PointerCoercion::MutToConstPointer`]
1521    ///
1522    /// Both are runtime nops, so should be [`CastKind::PtrToPtr`] instead in runtime MIR.
1523    PointerCoercion(PointerCoercion, CoercionSource),
1524    IntToInt,
1525    FloatToInt,
1526    FloatToFloat,
1527    IntToFloat,
1528    PtrToPtr,
1529    FnPtrToPtr,
1530    /// Reinterpret the bits of the input as a different type.
1531    ///
1532    /// MIR is well-formed if the input and output types have different sizes,
1533    /// but running a transmute between differently-sized types is UB.
1534    ///
1535    /// Allowed only in [`MirPhase::Runtime`]; Earlier it's a [`TerminatorKind::Call`].
1536    Transmute,
1537}
1538
1539/// Represents how a [`CastKind::PointerCoercion`] was constructed.
1540/// Used only for diagnostics.
1541#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1542pub enum CoercionSource {
1543    /// The coercion was manually written by the user with an `as` cast.
1544    AsCast,
1545    /// The coercion was automatically inserted by the compiler.
1546    Implicit,
1547}
1548
1549#[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1550#[derive(TypeFoldable, TypeVisitable)]
1551pub enum AggregateKind<'tcx> {
1552    /// The type is of the element
1553    Array(Ty<'tcx>),
1554    Tuple,
1555
1556    /// The second field is the variant index. It's equal to 0 for struct
1557    /// and union expressions. The last field is the
1558    /// active field number and is present only for union expressions
1559    /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1560    /// active field index would identity the field `c`
1561    Adt(DefId, VariantIdx, GenericArgsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>),
1562
1563    Closure(DefId, GenericArgsRef<'tcx>),
1564    Coroutine(DefId, GenericArgsRef<'tcx>),
1565    CoroutineClosure(DefId, GenericArgsRef<'tcx>),
1566
1567    /// Construct a raw pointer from the data pointer and metadata.
1568    ///
1569    /// The `Ty` here is the type of the *pointee*, not the pointer itself.
1570    /// The `Mutability` indicates whether this produces a `*const` or `*mut`.
1571    ///
1572    /// The [`Rvalue::Aggregate`] operands for thus must be
1573    ///
1574    /// 0. A raw pointer of matching mutability with any [`core::ptr::Thin`] pointee
1575    /// 1. A value of the appropriate [`core::ptr::Pointee::Metadata`] type
1576    ///
1577    /// *Both* operands must always be included, even the unit value if this is
1578    /// creating a thin pointer. If you're just converting between thin pointers,
1579    /// you may want an [`Rvalue::Cast`] with [`CastKind::PtrToPtr`] instead.
1580    RawPtr(Ty<'tcx>, Mutability),
1581}
1582
1583#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1584pub enum NullOp<'tcx> {
1585    /// Returns the size of a value of that type
1586    SizeOf,
1587    /// Returns the minimum alignment of a type
1588    AlignOf,
1589    /// Returns the offset of a field
1590    OffsetOf(&'tcx List<(VariantIdx, FieldIdx)>),
1591    /// Returns whether we should perform some UB-checking at runtime.
1592    /// See the `ub_checks` intrinsic docs for details.
1593    UbChecks,
1594    /// Returns whether we should perform contract-checking at runtime.
1595    /// See the `contract_checks` intrinsic docs for details.
1596    ContractChecks,
1597}
1598
1599#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1600#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
1601pub enum UnOp {
1602    /// The `!` operator for logical inversion
1603    Not,
1604    /// The `-` operator for negation
1605    Neg,
1606    /// Gets the metadata `M` from a `*const`/`*mut`/`&`/`&mut` to
1607    /// `impl Pointee<Metadata = M>`.
1608    ///
1609    /// For example, this will give a `()` from `*const i32`, a `usize` from
1610    /// `&mut [u8]`, or a `ptr::DynMetadata<dyn Foo>` (internally a pointer)
1611    /// from a `*mut dyn Foo`.
1612    ///
1613    /// Allowed only in [`MirPhase::Runtime`]; earlier it's an intrinsic.
1614    PtrMetadata,
1615}
1616
1617#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1618#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1619pub enum BinOp {
1620    /// The `+` operator (addition)
1621    Add,
1622    /// Like `Add`, but with UB on overflow.  (Integers only.)
1623    AddUnchecked,
1624    /// Like `Add`, but returns `(T, bool)` of both the wrapped result
1625    /// and a bool indicating whether it overflowed.
1626    AddWithOverflow,
1627    /// The `-` operator (subtraction)
1628    Sub,
1629    /// Like `Sub`, but with UB on overflow.  (Integers only.)
1630    SubUnchecked,
1631    /// Like `Sub`, but returns `(T, bool)` of both the wrapped result
1632    /// and a bool indicating whether it overflowed.
1633    SubWithOverflow,
1634    /// The `*` operator (multiplication)
1635    Mul,
1636    /// Like `Mul`, but with UB on overflow.  (Integers only.)
1637    MulUnchecked,
1638    /// Like `Mul`, but returns `(T, bool)` of both the wrapped result
1639    /// and a bool indicating whether it overflowed.
1640    MulWithOverflow,
1641    /// The `/` operator (division)
1642    ///
1643    /// For integer types, division by zero is UB, as is `MIN / -1` for signed.
1644    /// The compiler should have inserted checks prior to this.
1645    ///
1646    /// Floating-point division by zero is safe, and does not need guards.
1647    Div,
1648    /// The `%` operator (modulus)
1649    ///
1650    /// For integer types, using zero as the modulus (second operand) is UB,
1651    /// as is `MIN % -1` for signed.
1652    /// The compiler should have inserted checks prior to this.
1653    ///
1654    /// Floating-point remainder by zero is safe, and does not need guards.
1655    Rem,
1656    /// The `^` operator (bitwise xor)
1657    BitXor,
1658    /// The `&` operator (bitwise and)
1659    BitAnd,
1660    /// The `|` operator (bitwise or)
1661    BitOr,
1662    /// The `<<` operator (shift left)
1663    ///
1664    /// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
1665    /// In other words, it is (uniquely) determined as follows:
1666    /// - it is "equal modulo LHS::BITS" to the RHS
1667    /// - it is in the range `0..LHS::BITS`
1668    Shl,
1669    /// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
1670    ShlUnchecked,
1671    /// The `>>` operator (shift right)
1672    ///
1673    /// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
1674    /// In other words, it is (uniquely) determined as follows:
1675    /// - it is "equal modulo LHS::BITS" to the RHS
1676    /// - it is in the range `0..LHS::BITS`
1677    ///
1678    /// This is an arithmetic shift if the LHS is signed
1679    /// and a logical shift if the LHS is unsigned.
1680    Shr,
1681    /// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
1682    ShrUnchecked,
1683    /// The `==` operator (equality)
1684    Eq,
1685    /// The `<` operator (less than)
1686    Lt,
1687    /// The `<=` operator (less than or equal to)
1688    Le,
1689    /// The `!=` operator (not equal to)
1690    Ne,
1691    /// The `>=` operator (greater than or equal to)
1692    Ge,
1693    /// The `>` operator (greater than)
1694    Gt,
1695    /// The `<=>` operator (three-way comparison, like `Ord::cmp`)
1696    ///
1697    /// This is supported only on the integer types and `char`, always returning
1698    /// [`rustc_hir::LangItem::OrderingEnum`] (aka [`std::cmp::Ordering`]).
1699    ///
1700    /// [`Rvalue::BinaryOp`]`(BinOp::Cmp, A, B)` returns
1701    /// - `Ordering::Less` (`-1_i8`, as a Scalar) if `A < B`
1702    /// - `Ordering::Equal` (`0_i8`, as a Scalar) if `A == B`
1703    /// - `Ordering::Greater` (`+1_i8`, as a Scalar) if `A > B`
1704    Cmp,
1705    /// The `ptr.offset` operator
1706    Offset,
1707}
1708
1709// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1710#[cfg(target_pointer_width = "64")]
1711mod size_asserts {
1712    use rustc_data_structures::static_assert_size;
1713
1714    use super::*;
1715    // tidy-alphabetical-start
1716    static_assert_size!(AggregateKind<'_>, 32);
1717    static_assert_size!(Operand<'_>, 24);
1718    static_assert_size!(Place<'_>, 16);
1719    static_assert_size!(PlaceElem<'_>, 24);
1720    static_assert_size!(Rvalue<'_>, 40);
1721    static_assert_size!(StatementKind<'_>, 16);
1722    static_assert_size!(TerminatorKind<'_>, 80);
1723    // tidy-alphabetical-end
1724}