]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/syntax.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / compiler / rustc_middle / src / 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
6 use super::{BasicBlock, Constant, Field, Local, SwitchTargets, UserTypeProjection};
7
8 use crate::mir::coverage::{CodeRegion, CoverageKind};
9 use crate::ty::adjustment::PointerCast;
10 use crate::ty::subst::SubstsRef;
11 use crate::ty::{self, List, Ty};
12 use crate::ty::{Region, UserTypeAnnotationIndex};
13
14 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::{self as hir};
17 use rustc_hir::{self, GeneratorKind};
18 use rustc_target::abi::VariantIdx;
19
20 use rustc_ast::Mutability;
21 use rustc_span::def_id::LocalDefId;
22 use rustc_span::symbol::Symbol;
23 use rustc_span::Span;
24 use rustc_target::asm::InlineAsmRegOrRegClass;
25
26 /// Represents the "flavors" of MIR.
27 ///
28 /// All flavors of MIR use the same data structure, but there are some important differences. These
29 /// differences come in two forms: Dialects and phases.
30 ///
31 /// Dialects represent a stronger distinction than phases. This is because the transitions between
32 /// dialects are semantic changes, and therefore technically *lowerings* between distinct IRs. In
33 /// other words, the same [`Body`](crate::mir::Body) might be well-formed for multiple dialects, but
34 /// have different semantic meaning and different behavior at runtime.
35 ///
36 /// Each dialect additionally has a number of phases. However, phase changes never involve semantic
37 /// changes. If some MIR is well-formed both before and after a phase change, it is also guaranteed
38 /// that it has the same semantic meaning. In this sense, phase changes can only add additional
39 /// restrictions on what MIR is well-formed.
40 ///
41 /// When adding phases, remember to update [`MirPhase::phase_index`].
42 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
43 #[derive(HashStable)]
44 pub enum MirPhase {
45     /// The MIR that is generated by MIR building.
46     ///
47     /// The only things that operate on this dialect are unsafeck, the various MIR lints, and const
48     /// qualifs.
49     ///
50     /// This has no distinct phases.
51     Built,
52     /// The MIR used for most analysis.
53     ///
54     /// The only semantic change between analysis and built MIR is constant promotion. In built MIR,
55     /// sequences of statements that would generally be subject to constant promotion are
56     /// semantically constants, while in analysis MIR all constants are explicit.
57     ///
58     /// The result of const promotion is available from the `mir_promoted` and `promoted_mir` queries.
59     ///
60     /// This is the version of MIR used by borrowck and friends.
61     Analysis(AnalysisPhase),
62     /// The MIR used for CTFE, optimizations, and codegen.
63     ///
64     /// The semantic changes that occur in the lowering from analysis to runtime MIR are as follows:
65     ///
66     ///  - Drops: In analysis MIR, `Drop` terminators represent *conditional* drops; roughly speaking,
67     ///    if dataflow analysis determines that the place being dropped is uninitialized, the drop will
68     ///    not be executed. The exact semantics of this aren't written down anywhere, which means they
69     ///    are essentially "what drop elaboration does." In runtime MIR, the drops are unconditional;
70     ///    when a `Drop` terminator is reached, if the type has drop glue that drop glue is always
71     ///    executed. This may be UB if the underlying place is not initialized.
72     ///  - Packed drops: Places might in general be misaligned - in most cases this is UB, the exception
73     ///    is fields of packed structs. In analysis MIR, `Drop(P)` for a `P` that might be misaligned
74     ///    for this reason implicitly moves `P` to a temporary before dropping. Runtime MIR has no such
75     ///    rules, and dropping a misaligned place is simply UB.
76     ///  - Unwinding: in analysis MIR, unwinding from a function which may not unwind aborts. In runtime
77     ///    MIR, this is UB.
78     ///  - Retags: If `-Zmir-emit-retag` is enabled, analysis MIR has "implicit" retags in the same way
79     ///    that Rust itself has them. Where exactly these are is generally subject to change, and so we
80     ///    don't document this here. Runtime MIR has all retags explicit.
81     ///  - Generator bodies: In analysis MIR, locals may actually be behind a pointer that user code has
82     ///    access to. This occurs in generator bodies. Such locals do not behave like other locals,
83     ///    because they eg may be aliased in surprising ways. Runtime MIR has no such special locals -
84     ///    all generator bodies are lowered and so all places that look like locals really are locals.
85     ///
86     /// Also note that the lint pass which reports eg `200_u8 + 200_u8` as an error is run as a part
87     /// of analysis to runtime MIR lowering. To ensure lints are reported reliably, this means that
88     /// transformations which may suppress such errors should not run on analysis MIR.
89     Runtime(RuntimePhase),
90 }
91
92 /// See [`MirPhase::Analysis`].
93 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
94 #[derive(HashStable)]
95 pub enum AnalysisPhase {
96     Initial = 0,
97     /// Beginning in this phase, the following variants are disallowed:
98     /// * [`TerminatorKind::FalseUnwind`]
99     /// * [`TerminatorKind::FalseEdge`]
100     /// * [`StatementKind::FakeRead`]
101     /// * [`StatementKind::AscribeUserType`]
102     /// * [`Rvalue::Ref`] with `BorrowKind::Shallow`
103     ///
104     /// Furthermore, `Deref` projections must be the first projection within any place (if they
105     /// appear at all)
106     PostCleanup = 1,
107 }
108
109 /// See [`MirPhase::Runtime`].
110 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
111 #[derive(HashStable)]
112 pub enum RuntimePhase {
113     /// In addition to the semantic changes, beginning with this phase, the following variants are
114     /// disallowed:
115     /// * [`TerminatorKind::DropAndReplace`]
116     /// * [`TerminatorKind::Yield`]
117     /// * [`TerminatorKind::GeneratorDrop`]
118     /// * [`Rvalue::Aggregate`] for any `AggregateKind` except `Array`
119     ///
120     /// And the following variants are allowed:
121     /// * [`StatementKind::Retag`]
122     /// * [`StatementKind::SetDiscriminant`]
123     /// * [`StatementKind::Deinit`]
124     ///
125     /// Furthermore, `Copy` operands are allowed for non-`Copy` types.
126     Initial = 0,
127     /// Beginning with this phase, the following variant is disallowed:
128     /// * [`ProjectionElem::Deref`] of `Box`
129     PostCleanup = 1,
130     Optimized = 2,
131 }
132
133 ///////////////////////////////////////////////////////////////////////////
134 // Borrow kinds
135
136 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
137 #[derive(Hash, HashStable)]
138 pub enum BorrowKind {
139     /// Data must be immutable and is aliasable.
140     Shared,
141
142     /// The immediately borrowed place must be immutable, but projections from
143     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
144     /// conflict with a mutable borrow of `a.b.c`.
145     ///
146     /// This is used when lowering matches: when matching on a place we want to
147     /// ensure that place have the same value from the start of the match until
148     /// an arm is selected. This prevents this code from compiling:
149     /// ```compile_fail,E0510
150     /// let mut x = &Some(0);
151     /// match *x {
152     ///     None => (),
153     ///     Some(_) if { x = &None; false } => (),
154     ///     Some(_) => (),
155     /// }
156     /// ```
157     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
158     /// should not prevent `if let None = x { ... }`, for example, because the
159     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
160     /// We can also report errors with this kind of borrow differently.
161     Shallow,
162
163     /// Data must be immutable but not aliasable. This kind of borrow
164     /// cannot currently be expressed by the user and is used only in
165     /// implicit closure bindings. It is needed when the closure is
166     /// borrowing or mutating a mutable referent, e.g.:
167     /// ```
168     /// let mut z = 3;
169     /// let x: &mut isize = &mut z;
170     /// let y = || *x += 5;
171     /// ```
172     /// If we were to try to translate this closure into a more explicit
173     /// form, we'd encounter an error with the code as written:
174     /// ```compile_fail,E0594
175     /// struct Env<'a> { x: &'a &'a mut isize }
176     /// let mut z = 3;
177     /// let x: &mut isize = &mut z;
178     /// let y = (&mut Env { x: &x }, fn_ptr);  // Closure is pair of env and fn
179     /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
180     /// ```
181     /// This is then illegal because you cannot mutate an `&mut` found
182     /// in an aliasable location. To solve, you'd have to translate with
183     /// an `&mut` borrow:
184     /// ```compile_fail,E0596
185     /// struct Env<'a> { x: &'a mut &'a mut isize }
186     /// let mut z = 3;
187     /// let x: &mut isize = &mut z;
188     /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
189     /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
190     /// ```
191     /// Now the assignment to `**env.x` is legal, but creating a
192     /// mutable pointer to `x` is not because `x` is not mutable. We
193     /// could fix this by declaring `x` as `let mut x`. This is ok in
194     /// user code, if awkward, but extra weird for closures, since the
195     /// borrow is hidden.
196     ///
197     /// So we introduce a "unique imm" borrow -- the referent is
198     /// immutable, but not aliasable. This solves the problem. For
199     /// simplicity, we don't give users the way to express this
200     /// borrow, it's just used when translating closures.
201     Unique,
202
203     /// Data is mutable and not aliasable.
204     Mut {
205         /// `true` if this borrow arose from method-call auto-ref
206         /// (i.e., `adjustment::Adjust::Borrow`).
207         allow_two_phase_borrow: bool,
208     },
209 }
210
211 ///////////////////////////////////////////////////////////////////////////
212 // Statements
213
214 /// The various kinds of statements that can appear in MIR.
215 ///
216 /// Not all of these are allowed at every [`MirPhase`]. Check the documentation there to see which
217 /// ones you do not have to worry about. The MIR validator will generally enforce such restrictions,
218 /// causing an ICE if they are violated.
219 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
220 #[derive(TypeFoldable, TypeVisitable)]
221 pub enum StatementKind<'tcx> {
222     /// Assign statements roughly correspond to an assignment in Rust proper (`x = ...`) except
223     /// without the possibility of dropping the previous value (that must be done separately, if at
224     /// all). The *exact* way this works is undecided. It probably does something like evaluating
225     /// the LHS to a place and the RHS to a value, and then storing the value to the place. Various
226     /// parts of this may do type specific things that are more complicated than simply copying
227     /// bytes.
228     ///
229     /// **Needs clarification**: The implication of the above idea would be that assignment implies
230     /// that the resulting value is initialized. I believe we could commit to this separately from
231     /// committing to whatever part of the memory model we would need to decide on to make the above
232     /// paragragh precise. Do we want to?
233     ///
234     /// Assignments in which the types of the place and rvalue differ are not well-formed.
235     ///
236     /// **Needs clarification**: Do we ever want to worry about non-free (in the body) lifetimes for
237     /// the typing requirement in post drop-elaboration MIR? I think probably not - I'm not sure we
238     /// could meaningfully require this anyway. How about free lifetimes? Is ignoring this
239     /// interesting for optimizations? Do we want to allow such optimizations?
240     ///
241     /// **Needs clarification**: We currently require that the LHS place not overlap with any place
242     /// read as part of computation of the RHS for some rvalues (generally those not producing
243     /// primitives). This requirement is under discussion in [#68364]. As a part of this discussion,
244     /// it is also unclear in what order the components are evaluated.
245     ///
246     /// [#68364]: https://github.com/rust-lang/rust/issues/68364
247     ///
248     /// See [`Rvalue`] documentation for details on each of those.
249     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
250
251     /// This represents all the reading that a pattern match may do (e.g., inspecting constants and
252     /// discriminant values), and the kind of pattern it comes from. This is in order to adapt
253     /// potential error messages to these specific patterns.
254     ///
255     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
256     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
257     ///
258     /// When executed at runtime this is a nop.
259     ///
260     /// Disallowed after drop elaboration.
261     FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
262
263     /// Write the discriminant for a variant to the enum Place.
264     ///
265     /// This is permitted for both generators and ADTs. This does not necessarily write to the
266     /// entire place; instead, it writes to the minimum set of bytes as required by the layout for
267     /// the type.
268     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
269
270     /// Deinitializes the place.
271     ///
272     /// This writes `uninit` bytes to the entire place.
273     Deinit(Box<Place<'tcx>>),
274
275     /// `StorageLive` and `StorageDead` statements mark the live range of a local.
276     ///
277     /// At any point during the execution of a function, each local is either allocated or
278     /// unallocated. Except as noted below, all locals except function parameters are initially
279     /// unallocated. `StorageLive` statements cause memory to be allocated for the local while
280     /// `StorageDead` statements cause the memory to be freed. Using a local in any way (not only
281     /// reading/writing from it) while it is unallocated is UB.
282     ///
283     /// Some locals have no `StorageLive` or `StorageDead` statements within the entire MIR body.
284     /// These locals are implicitly allocated for the full duration of the function. There is a
285     /// convenience method at `rustc_mir_dataflow::storage::always_storage_live_locals` for
286     /// computing these locals.
287     ///
288     /// If the local is already allocated, calling `StorageLive` again is UB. However, for an
289     /// unallocated local an additional `StorageDead` all is simply a nop.
290     StorageLive(Local),
291
292     /// See `StorageLive` above.
293     StorageDead(Local),
294
295     /// Retag references in the given place, ensuring they got fresh tags.
296     ///
297     /// This is part of the Stacked Borrows model. These statements are currently only interpreted
298     /// by miri and only generated when `-Z mir-emit-retag` is passed. See
299     /// <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> for
300     /// more details.
301     ///
302     /// For code that is not specific to stacked borrows, you should consider retags to read
303     /// and modify the place in an opaque way.
304     Retag(RetagKind, Box<Place<'tcx>>),
305
306     /// Encodes a user's type ascription. These need to be preserved
307     /// intact so that NLL can respect them. For example:
308     /// ```ignore (illustrative)
309     /// let a: T = y;
310     /// ```
311     /// The effect of this annotation is to relate the type `T_y` of the place `y`
312     /// to the user-given type `T`. The effect depends on the specified variance:
313     ///
314     /// - `Covariant` -- requires that `T_y <: T`
315     /// - `Contravariant` -- requires that `T_y :> T`
316     /// - `Invariant` -- requires that `T_y == T`
317     /// - `Bivariant` -- no effect
318     ///
319     /// When executed at runtime this is a nop.
320     ///
321     /// Disallowed after drop elaboration.
322     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
323
324     /// Marks the start of a "coverage region", injected with '-Cinstrument-coverage'. A
325     /// `Coverage` statement carries metadata about the coverage region, used to inject a coverage
326     /// map into the binary. If `Coverage::kind` is a `Counter`, the statement also generates
327     /// executable code, to increment a counter variable at runtime, each time the code region is
328     /// executed.
329     Coverage(Box<Coverage>),
330
331     /// Denotes a call to an intrinsic that does not require an unwind path and always returns.
332     /// This avoids adding a new block and a terminator for simple intrinsics.
333     Intrinsic(Box<NonDivergingIntrinsic<'tcx>>),
334
335     /// No-op. Useful for deleting instructions without affecting statement indices.
336     Nop,
337 }
338
339 #[derive(
340     Clone,
341     TyEncodable,
342     TyDecodable,
343     Debug,
344     PartialEq,
345     Hash,
346     HashStable,
347     TypeFoldable,
348     TypeVisitable
349 )]
350 pub enum NonDivergingIntrinsic<'tcx> {
351     /// Denotes a call to the intrinsic function `assume`.
352     ///
353     /// The operand must be a boolean. Optimizers may use the value of the boolean to backtrack its
354     /// computation to infer information about other variables. So if the boolean came from a
355     /// `x < y` operation, subsequent operations on `x` and `y` could elide various bound checks.
356     /// If the argument is `false`, this operation is equivalent to `TerminatorKind::Unreachable`.
357     Assume(Operand<'tcx>),
358
359     /// Denotes a call to the intrinsic function `copy_nonoverlapping`.
360     ///
361     /// First, all three operands are evaluated. `src` and `dest` must each be a reference, pointer,
362     /// or `Box` pointing to the same type `T`. `count` must evaluate to a `usize`. Then, `src` and
363     /// `dest` are dereferenced, and `count * size_of::<T>()` bytes beginning with the first byte of
364     /// the `src` place are copied to the contiguous range of bytes beginning with the first byte
365     /// of `dest`.
366     ///
367     /// **Needs clarification**: In what order are operands computed and dereferenced? It should
368     /// probably match the order for assignment, but that is also undecided.
369     ///
370     /// **Needs clarification**: Is this typed or not, ie is there a typed load and store involved?
371     /// I vaguely remember Ralf saying somewhere that he thought it should not be.
372     CopyNonOverlapping(CopyNonOverlapping<'tcx>),
373 }
374
375 impl std::fmt::Display for NonDivergingIntrinsic<'_> {
376     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377         match self {
378             Self::Assume(op) => write!(f, "assume({op:?})"),
379             Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
380                 write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
381             }
382         }
383     }
384 }
385
386 /// Describes what kind of retag is to be performed.
387 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
388 #[rustc_pass_by_value]
389 pub enum RetagKind {
390     /// The initial retag when entering a function.
391     FnEntry,
392     /// Retag preparing for a two-phase borrow.
393     TwoPhase,
394     /// Retagging raw pointers.
395     Raw,
396     /// A "normal" retag.
397     Default,
398 }
399
400 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
401 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
402 pub enum FakeReadCause {
403     /// Inject a fake read of the borrowed input at the end of each guards
404     /// code.
405     ///
406     /// This should ensure that you cannot change the variant for an enum while
407     /// you are in the midst of matching on it.
408     ForMatchGuard,
409
410     /// `let x: !; match x {}` doesn't generate any read of x so we need to
411     /// generate a read of x to check that it is initialized and safe.
412     ///
413     /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
414     /// FakeRead for that Place outside the closure, in such a case this option would be
415     /// Some(closure_def_id).
416     /// Otherwise, the value of the optional LocalDefId will be None.
417     //
418     // We can use LocalDefId here since fake read statements are removed
419     // before codegen in the `CleanupNonCodegenStatements` pass.
420     ForMatchedPlace(Option<LocalDefId>),
421
422     /// A fake read of the RefWithinGuard version of a bind-by-value variable
423     /// in a match guard to ensure that its value hasn't change by the time
424     /// we create the OutsideGuard version.
425     ForGuardBinding,
426
427     /// Officially, the semantics of
428     ///
429     /// `let pattern = <expr>;`
430     ///
431     /// is that `<expr>` is evaluated into a temporary and then this temporary is
432     /// into the pattern.
433     ///
434     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
435     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
436     /// but in some cases it can affect the borrow checker, as in #53695.
437     /// Therefore, we insert a "fake read" here to ensure that we get
438     /// appropriate errors.
439     ///
440     /// If a closure pattern matches a Place starting with an Upvar, then we introduce a
441     /// FakeRead for that Place outside the closure, in such a case this option would be
442     /// Some(closure_def_id).
443     /// Otherwise, the value of the optional DefId will be None.
444     ForLet(Option<LocalDefId>),
445
446     /// If we have an index expression like
447     ///
448     /// (*x)[1][{ x = y; 4}]
449     ///
450     /// then the first bounds check is invalidated when we evaluate the second
451     /// index expression. Thus we create a fake borrow of `x` across the second
452     /// indexer, which will cause a borrow check error.
453     ForIndex,
454 }
455
456 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
457 #[derive(TypeFoldable, TypeVisitable)]
458 pub struct Coverage {
459     pub kind: CoverageKind,
460     pub code_region: Option<CodeRegion>,
461 }
462
463 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
464 #[derive(TypeFoldable, TypeVisitable)]
465 pub struct CopyNonOverlapping<'tcx> {
466     pub src: Operand<'tcx>,
467     pub dst: Operand<'tcx>,
468     /// Number of elements to copy from src to dest, not bytes.
469     pub count: Operand<'tcx>,
470 }
471
472 ///////////////////////////////////////////////////////////////////////////
473 // Terminators
474
475 /// The various kinds of terminators, representing ways of exiting from a basic block.
476 ///
477 /// A note on unwinding: Panics may occur during the execution of some terminators. Depending on the
478 /// `-C panic` flag, this may either cause the program to abort or the call stack to unwind. Such
479 /// terminators have a `cleanup: Option<BasicBlock>` field on them. If stack unwinding occurs, then
480 /// once the current function is reached, execution continues at the given basic block, if any. If
481 /// `cleanup` is `None` then no cleanup is performed, and the stack continues unwinding. This is
482 /// equivalent to the execution of a `Resume` terminator.
483 ///
484 /// The basic block pointed to by a `cleanup` field must have its `cleanup` flag set. `cleanup`
485 /// basic blocks have a couple restrictions:
486 ///  1. All `cleanup` fields in them must be `None`.
487 ///  2. `Return` terminators are not allowed in them. `Abort` and `Unwind` terminators are.
488 ///  3. All other basic blocks (in the current body) that are reachable from `cleanup` basic blocks
489 ///     must also be `cleanup`. This is a part of the type system and checked statically, so it is
490 ///     still an error to have such an edge in the CFG even if it's known that it won't be taken at
491 ///     runtime.
492 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
493 pub enum TerminatorKind<'tcx> {
494     /// Block has one successor; we continue execution there.
495     Goto { target: BasicBlock },
496
497     /// Switches based on the computed value.
498     ///
499     /// First, evaluates the `discr` operand. The type of the operand must be a signed or unsigned
500     /// integer, char, or bool, and must match the given type. Then, if the list of switch targets
501     /// contains the computed value, continues execution at the associated basic block. Otherwise,
502     /// continues execution at the "otherwise" basic block.
503     ///
504     /// Target values may not appear more than once.
505     SwitchInt {
506         /// The discriminant value being tested.
507         discr: Operand<'tcx>,
508
509         /// The type of value being tested.
510         /// This is always the same as the type of `discr`.
511         /// FIXME: remove this redundant information. Currently, it is relied on by pretty-printing.
512         switch_ty: Ty<'tcx>,
513
514         targets: SwitchTargets,
515     },
516
517     /// Indicates that the landing pad is finished and that the process should continue unwinding.
518     ///
519     /// Like a return, this marks the end of this invocation of the function.
520     ///
521     /// Only permitted in cleanup blocks. `Resume` is not permitted with `-C unwind=abort` after
522     /// deaggregation runs.
523     Resume,
524
525     /// Indicates that the landing pad is finished and that the process should abort.
526     ///
527     /// Used to prevent unwinding for foreign items or with `-C unwind=abort`. Only permitted in
528     /// cleanup blocks.
529     Abort,
530
531     /// Returns from the function.
532     ///
533     /// Like function calls, the exact semantics of returns in Rust are unclear. Returning very
534     /// likely at least assigns the value currently in the return place (`_0`) to the place
535     /// specified in the associated `Call` terminator in the calling function, as if assigned via
536     /// `dest = move _0`. It might additionally do other things, like have side-effects in the
537     /// aliasing model.
538     ///
539     /// If the body is a generator body, this has slightly different semantics; it instead causes a
540     /// `GeneratorState::Returned(_0)` to be created (as if by an `Aggregate` rvalue) and assigned
541     /// to the return place.
542     Return,
543
544     /// Indicates a terminator that can never be reached.
545     ///
546     /// Executing this terminator is UB.
547     Unreachable,
548
549     /// The behavior of this statement differs significantly before and after drop elaboration.
550     /// After drop elaboration, `Drop` executes the drop glue for the specified place, after which
551     /// it continues execution/unwinds at the given basic blocks. It is possible that executing drop
552     /// glue is special - this would be part of Rust's memory model. (**FIXME**: due we have an
553     /// issue tracking if drop glue has any interesting semantics in addition to those of a function
554     /// call?)
555     ///
556     /// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically, the
557     /// `Drop` will be executed if...
558     ///
559     /// **Needs clarification**: End of that sentence. This in effect should document the exact
560     /// behavior of drop elaboration. The following sounds vaguely right, but I'm not quite sure:
561     ///
562     /// > The drop glue is executed if, among all statements executed within this `Body`, an assignment to
563     /// > the place or one of its "parents" occurred more recently than a move out of it. This does not
564     /// > consider indirect assignments.
565     Drop { place: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
566
567     /// Drops the place and assigns a new value to it.
568     ///
569     /// This first performs the exact same operation as the pre drop-elaboration `Drop` terminator;
570     /// it then additionally assigns the `value` to the `place` as if by an assignment statement.
571     /// This assignment occurs both in the unwind and the regular code paths. The semantics are best
572     /// explained by the elaboration:
573     ///
574     /// ```ignore (MIR)
575     /// BB0 {
576     ///   DropAndReplace(P <- V, goto BB1, unwind BB2)
577     /// }
578     /// ```
579     ///
580     /// becomes
581     ///
582     /// ```ignore (MIR)
583     /// BB0 {
584     ///   Drop(P, goto BB1, unwind BB2)
585     /// }
586     /// BB1 {
587     ///   // P is now uninitialized
588     ///   P <- V
589     /// }
590     /// BB2 {
591     ///   // P is now uninitialized -- its dtor panicked
592     ///   P <- V
593     /// }
594     /// ```
595     ///
596     /// Disallowed after drop elaboration.
597     DropAndReplace {
598         place: Place<'tcx>,
599         value: Operand<'tcx>,
600         target: BasicBlock,
601         unwind: Option<BasicBlock>,
602     },
603
604     /// Roughly speaking, evaluates the `func` operand and the arguments, and starts execution of
605     /// the referred to function. The operand types must match the argument types of the function.
606     /// The return place type must match the return type. The type of the `func` operand must be
607     /// callable, meaning either a function pointer, a function type, or a closure type.
608     ///
609     /// **Needs clarification**: The exact semantics of this. Current backends rely on `move`
610     /// operands not aliasing the return place. It is unclear how this is justified in MIR, see
611     /// [#71117].
612     ///
613     /// [#71117]: https://github.com/rust-lang/rust/issues/71117
614     Call {
615         /// The function that’s being called.
616         func: Operand<'tcx>,
617         /// Arguments the function is called with.
618         /// These are owned by the callee, which is free to modify them.
619         /// This allows the memory occupied by "by-value" arguments to be
620         /// reused across function calls without duplicating the contents.
621         args: Vec<Operand<'tcx>>,
622         /// Where the returned value will be written
623         destination: Place<'tcx>,
624         /// Where to go after this call returns. If none, the call necessarily diverges.
625         target: Option<BasicBlock>,
626         /// Cleanups to be done if the call unwinds.
627         cleanup: Option<BasicBlock>,
628         /// `true` if this is from a call in HIR rather than from an overloaded
629         /// operator. True for overloaded function call.
630         from_hir_call: bool,
631         /// This `Span` is the span of the function, without the dot and receiver
632         /// (e.g. `foo(a, b)` in `x.foo(a, b)`
633         fn_span: Span,
634     },
635
636     /// Evaluates the operand, which must have type `bool`. If it is not equal to `expected`,
637     /// initiates a panic. Initiating a panic corresponds to a `Call` terminator with some
638     /// unspecified constant as the function to call, all the operands stored in the `AssertMessage`
639     /// as parameters, and `None` for the destination. Keep in mind that the `cleanup` path is not
640     /// necessarily executed even in the case of a panic, for example in `-C panic=abort`. If the
641     /// assertion does not fail, execution continues at the specified basic block.
642     Assert {
643         cond: Operand<'tcx>,
644         expected: bool,
645         msg: AssertMessage<'tcx>,
646         target: BasicBlock,
647         cleanup: Option<BasicBlock>,
648     },
649
650     /// Marks a suspend point.
651     ///
652     /// Like `Return` terminators in generator bodies, this computes `value` and then a
653     /// `GeneratorState::Yielded(value)` as if by `Aggregate` rvalue. That value is then assigned to
654     /// the return place of the function calling this one, and execution continues in the calling
655     /// function. When next invoked with the same first argument, execution of this function
656     /// continues at the `resume` basic block, with the second argument written to the `resume_arg`
657     /// place. If the generator is dropped before then, the `drop` basic block is invoked.
658     ///
659     /// Not permitted in bodies that are not generator bodies, or after generator lowering.
660     ///
661     /// **Needs clarification**: What about the evaluation order of the `resume_arg` and `value`?
662     Yield {
663         /// The value to return.
664         value: Operand<'tcx>,
665         /// Where to resume to.
666         resume: BasicBlock,
667         /// The place to store the resume argument in.
668         resume_arg: Place<'tcx>,
669         /// Cleanup to be done if the generator is dropped at this suspend point.
670         drop: Option<BasicBlock>,
671     },
672
673     /// Indicates the end of dropping a generator.
674     ///
675     /// Semantically just a `return` (from the generators drop glue). Only permitted in the same situations
676     /// as `yield`.
677     ///
678     /// **Needs clarification**: Is that even correct? The generator drop code is always confusing
679     /// to me, because it's not even really in the current body.
680     ///
681     /// **Needs clarification**: Are there type system constraints on these terminators? Should
682     /// there be a "block type" like `cleanup` blocks for them?
683     GeneratorDrop,
684
685     /// A block where control flow only ever takes one real path, but borrowck needs to be more
686     /// conservative.
687     ///
688     /// At runtime this is semantically just a goto.
689     ///
690     /// Disallowed after drop elaboration.
691     FalseEdge {
692         /// The target normal control flow will take.
693         real_target: BasicBlock,
694         /// A block control flow could conceptually jump to, but won't in
695         /// practice.
696         imaginary_target: BasicBlock,
697     },
698
699     /// A terminator for blocks that only take one path in reality, but where we reserve the right
700     /// to unwind in borrowck, even if it won't happen in practice. This can arise in infinite loops
701     /// with no function calls for example.
702     ///
703     /// At runtime this is semantically just a goto.
704     ///
705     /// Disallowed after drop elaboration.
706     FalseUnwind {
707         /// The target normal control flow will take.
708         real_target: BasicBlock,
709         /// The imaginary cleanup block link. This particular path will never be taken
710         /// in practice, but in order to avoid fragility we want to always
711         /// consider it in borrowck. We don't want to accept programs which
712         /// pass borrowck only when `panic=abort` or some assertions are disabled
713         /// due to release vs. debug mode builds. This needs to be an `Option` because
714         /// of the `remove_noop_landing_pads` and `abort_unwinding_calls` passes.
715         unwind: Option<BasicBlock>,
716     },
717
718     /// Block ends with an inline assembly block. This is a terminator since
719     /// inline assembly is allowed to diverge.
720     InlineAsm {
721         /// The template for the inline assembly, with placeholders.
722         template: &'tcx [InlineAsmTemplatePiece],
723
724         /// The operands for the inline assembly, as `Operand`s or `Place`s.
725         operands: Vec<InlineAsmOperand<'tcx>>,
726
727         /// Miscellaneous options for the inline assembly.
728         options: InlineAsmOptions,
729
730         /// Source spans for each line of the inline assembly code. These are
731         /// used to map assembler errors back to the line in the source code.
732         line_spans: &'tcx [Span],
733
734         /// Destination block after the inline assembly returns, unless it is
735         /// diverging (InlineAsmOptions::NORETURN).
736         destination: Option<BasicBlock>,
737
738         /// Cleanup to be done if the inline assembly unwinds. This is present
739         /// if and only if InlineAsmOptions::MAY_UNWIND is set.
740         cleanup: Option<BasicBlock>,
741     },
742 }
743
744 /// Information about an assertion failure.
745 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
746 pub enum AssertKind<O> {
747     BoundsCheck { len: O, index: O },
748     Overflow(BinOp, O, O),
749     OverflowNeg(O),
750     DivisionByZero(O),
751     RemainderByZero(O),
752     ResumedAfterReturn(GeneratorKind),
753     ResumedAfterPanic(GeneratorKind),
754 }
755
756 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
757 #[derive(TypeFoldable, TypeVisitable)]
758 pub enum InlineAsmOperand<'tcx> {
759     In {
760         reg: InlineAsmRegOrRegClass,
761         value: Operand<'tcx>,
762     },
763     Out {
764         reg: InlineAsmRegOrRegClass,
765         late: bool,
766         place: Option<Place<'tcx>>,
767     },
768     InOut {
769         reg: InlineAsmRegOrRegClass,
770         late: bool,
771         in_value: Operand<'tcx>,
772         out_place: Option<Place<'tcx>>,
773     },
774     Const {
775         value: Box<Constant<'tcx>>,
776     },
777     SymFn {
778         value: Box<Constant<'tcx>>,
779     },
780     SymStatic {
781         def_id: DefId,
782     },
783 }
784
785 /// Type for MIR `Assert` terminator error messages.
786 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
787
788 ///////////////////////////////////////////////////////////////////////////
789 // Places
790
791 /// Places roughly correspond to a "location in memory." Places in MIR are the same mathematical
792 /// object as places in Rust. This of course means that what exactly they are is undecided and part
793 /// of the Rust memory model. However, they will likely contain at least the following pieces of
794 /// information in some form:
795 ///
796 ///  1. The address in memory that the place refers to.
797 ///  2. The provenance with which the place is being accessed.
798 ///  3. The type of the place and an optional variant index. See [`PlaceTy`][super::tcx::PlaceTy].
799 ///  4. Optionally, some metadata. This exists if and only if the type of the place is not `Sized`.
800 ///
801 /// We'll give a description below of how all pieces of the place except for the provenance are
802 /// calculated. We cannot give a description of the provenance, because that is part of the
803 /// undecided aliasing model - we only include it here at all to acknowledge its existence.
804 ///
805 /// Each local naturally corresponds to the place `Place { local, projection: [] }`. This place has
806 /// the address of the local's allocation and the type of the local.
807 ///
808 /// **Needs clarification:** Unsized locals seem to present a bit of an issue. Their allocation
809 /// can't actually be created on `StorageLive`, because it's unclear how big to make the allocation.
810 /// Furthermore, MIR produces assignments to unsized locals, although that is not permitted under
811 /// `#![feature(unsized_locals)]` in Rust. Besides just putting "unsized locals are special and
812 /// different" in a bunch of places, I (JakobDegen) don't know how to incorporate this behavior into
813 /// the current MIR semantics in a clean way - possibly this needs some design work first.
814 ///
815 /// For places that are not locals, ie they have a non-empty list of projections, we define the
816 /// values as a function of the parent place, that is the place with its last [`ProjectionElem`]
817 /// stripped. The way this is computed of course depends on the kind of that last projection
818 /// element:
819 ///
820 ///  - [`Downcast`](ProjectionElem::Downcast): This projection sets the place's variant index to the
821 ///    given one, and makes no other changes. A `Downcast` projection on a place with its variant
822 ///    index already set is not well-formed.
823 ///  - [`Field`](ProjectionElem::Field): `Field` projections take their parent place and create a
824 ///    place referring to one of the fields of the type. The resulting address is the parent
825 ///    address, plus the offset of the field. The type becomes the type of the field. If the parent
826 ///    was unsized and so had metadata associated with it, then the metadata is retained if the
827 ///    field is unsized and thrown out if it is sized.
828 ///
829 ///    These projections are only legal for tuples, ADTs, closures, and generators. If the ADT or
830 ///    generator has more than one variant, the parent place's variant index must be set, indicating
831 ///    which variant is being used. If it has just one variant, the variant index may or may not be
832 ///    included - the single possible variant is inferred if it is not included.
833 ///  - [`OpaqueCast`](ProjectionElem::OpaqueCast): This projection changes the place's type to the
834 ///    given one, and makes no other changes. A `OpaqueCast` projection on any type other than an
835 ///    opaque type from the current crate is not well-formed.
836 ///  - [`ConstantIndex`](ProjectionElem::ConstantIndex): Computes an offset in units of `T` into the
837 ///    place as described in the documentation for the `ProjectionElem`. The resulting address is
838 ///    the parent's address plus that offset, and the type is `T`. This is only legal if the parent
839 ///    place has type `[T;  N]` or `[T]` (*not* `&[T]`). Since such a `T` is always sized, any
840 ///    resulting metadata is thrown out.
841 ///  - [`Subslice`](ProjectionElem::Subslice): This projection calculates an offset and a new
842 ///    address in a similar manner as `ConstantIndex`. It is also only legal on `[T; N]` and `[T]`.
843 ///    However, this yields a `Place` of type `[T]`, and additionally sets the metadata to be the
844 ///    length of the subslice.
845 ///  - [`Index`](ProjectionElem::Index): Like `ConstantIndex`, only legal on `[T; N]` or `[T]`.
846 ///    However, `Index` additionally takes a local from which the value of the index is computed at
847 ///    runtime. Computing the value of the index involves interpreting the `Local` as a
848 ///    `Place { local, projection: [] }`, and then computing its value as if done via
849 ///    [`Operand::Copy`]. The array/slice is then indexed with the resulting value. The local must
850 ///    have type `usize`.
851 ///  - [`Deref`](ProjectionElem::Deref): Derefs are the last type of projection, and the most
852 ///    complicated. They are only legal on parent places that are references, pointers, or `Box`. A
853 ///    `Deref` projection begins by loading a value from the parent place, as if by
854 ///    [`Operand::Copy`]. It then dereferences the resulting pointer, creating a place of the
855 ///    pointee's type. The resulting address is the address that was stored in the pointer. If the
856 ///    pointee type is unsized, the pointer additionally stored the value of the metadata.
857 ///
858 /// Computing a place may cause UB. One possibility is that the pointer used for a `Deref` may not
859 /// be suitably aligned. Another possibility is that the place is not in bounds, meaning it does not
860 /// point to an actual allocation.
861 ///
862 /// However, if this is actually UB and when the UB kicks in is undecided. This is being discussed
863 /// in [UCG#319]. The options include that every place must obey those rules, that only some places
864 /// must obey them, or that places impose no rules of their own.
865 ///
866 /// [UCG#319]: https://github.com/rust-lang/unsafe-code-guidelines/issues/319
867 ///
868 /// Rust currently requires that every place obey those two rules. This is checked by MIRI and taken
869 /// advantage of by codegen (via `gep inbounds`). That is possibly subject to change.
870 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable, TypeFoldable, TypeVisitable)]
871 pub struct Place<'tcx> {
872     pub local: Local,
873
874     /// projection out of a place (access a field, deref a pointer, etc)
875     pub projection: &'tcx List<PlaceElem<'tcx>>,
876 }
877
878 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
879 #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
880 pub enum ProjectionElem<V, T> {
881     Deref,
882     Field(Field, T),
883     /// Index into a slice/array.
884     ///
885     /// Note that this does not also dereference, and so it does not exactly correspond to slice
886     /// indexing in Rust. In other words, in the below Rust code:
887     ///
888     /// ```rust
889     /// let x = &[1, 2, 3, 4];
890     /// let i = 2;
891     /// x[i];
892     /// ```
893     ///
894     /// The `x[i]` is turned into a `Deref` followed by an `Index`, not just an `Index`. The same
895     /// thing is true of the `ConstantIndex` and `Subslice` projections below.
896     Index(V),
897
898     /// These indices are generated by slice patterns. Easiest to explain
899     /// by example:
900     ///
901     /// ```ignore (illustrative)
902     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
903     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
904     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
905     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
906     /// ```
907     ConstantIndex {
908         /// index or -index (in Python terms), depending on from_end
909         offset: u64,
910         /// The thing being indexed must be at least this long. For arrays this
911         /// is always the exact length.
912         min_length: u64,
913         /// Counting backwards from end? This is always false when indexing an
914         /// array.
915         from_end: bool,
916     },
917
918     /// These indices are generated by slice patterns.
919     ///
920     /// If `from_end` is true `slice[from..slice.len() - to]`.
921     /// Otherwise `array[from..to]`.
922     Subslice {
923         from: u64,
924         to: u64,
925         /// Whether `to` counts from the start or end of the array/slice.
926         /// For `PlaceElem`s this is `true` if and only if the base is a slice.
927         /// For `ProjectionKind`, this can also be `true` for arrays.
928         from_end: bool,
929     },
930
931     /// "Downcast" to a variant of an enum or a generator.
932     ///
933     /// The included Symbol is the name of the variant, used for printing MIR.
934     Downcast(Option<Symbol>, VariantIdx),
935
936     /// Like an explicit cast from an opaque type to a concrete type, but without
937     /// requiring an intermediate variable.
938     OpaqueCast(T),
939 }
940
941 /// Alias for projections as they appear in places, where the base is a place
942 /// and the index is a local.
943 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
944
945 ///////////////////////////////////////////////////////////////////////////
946 // Operands
947
948 /// An operand in MIR represents a "value" in Rust, the definition of which is undecided and part of
949 /// the memory model. One proposal for a definition of values can be found [on UCG][value-def].
950 ///
951 /// [value-def]: https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/value-domain.md
952 ///
953 /// The most common way to create values is via loading a place. Loading a place is an operation
954 /// which reads the memory of the place and converts it to a value. This is a fundamentally *typed*
955 /// operation. The nature of the value produced depends on the type of the conversion. Furthermore,
956 /// there may be other effects: if the type has a validity constraint loading the place might be UB
957 /// if the validity constraint is not met.
958 ///
959 /// **Needs clarification:** Ralf proposes that loading a place not have side-effects.
960 /// This is what is implemented in miri today. Are these the semantics we want for MIR? Is this
961 /// something we can even decide without knowing more about Rust's memory model?
962 ///
963 /// **Needs clarifiation:** Is loading a place that has its variant index set well-formed? Miri
964 /// currently implements it, but it seems like this may be something to check against in the
965 /// validator.
966 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)]
967 pub enum Operand<'tcx> {
968     /// Creates a value by loading the given place.
969     ///
970     /// Before drop elaboration, the type of the place must be `Copy`. After drop elaboration there
971     /// is no such requirement.
972     Copy(Place<'tcx>),
973
974     /// Creates a value by performing loading the place, just like the `Copy` operand.
975     ///
976     /// This *may* additionally overwrite the place with `uninit` bytes, depending on how we decide
977     /// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this
978     /// place without first re-initializing it.
979     ///
980     /// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188
981     Move(Place<'tcx>),
982
983     /// Constants are already semantically values, and remain unchanged.
984     Constant(Box<Constant<'tcx>>),
985 }
986
987 ///////////////////////////////////////////////////////////////////////////
988 // Rvalues
989
990 /// The various kinds of rvalues that can appear in MIR.
991 ///
992 /// Not all of these are allowed at every [`MirPhase`] - when this is the case, it's stated below.
993 ///
994 /// Computing any rvalue begins by evaluating the places and operands in some order (**Needs
995 /// clarification**: Which order?). These are then used to produce a "value" - the same kind of
996 /// value that an [`Operand`] produces.
997 #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
998 pub enum Rvalue<'tcx> {
999     /// Yields the operand unchanged
1000     Use(Operand<'tcx>),
1001
1002     /// Creates an array where each element is the value of the operand.
1003     ///
1004     /// This is the cause of a bug in the case where the repetition count is zero because the value
1005     /// is not dropped, see [#74836].
1006     ///
1007     /// Corresponds to source code like `[x; 32]`.
1008     ///
1009     /// [#74836]: https://github.com/rust-lang/rust/issues/74836
1010     Repeat(Operand<'tcx>, ty::Const<'tcx>),
1011
1012     /// Creates a reference of the indicated kind to the place.
1013     ///
1014     /// There is not much to document here, because besides the obvious parts the semantics of this
1015     /// are essentially entirely a part of the aliasing model. There are many UCG issues discussing
1016     /// exactly what the behavior of this operation should be.
1017     ///
1018     /// `Shallow` borrows are disallowed after drop lowering.
1019     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1020
1021     /// Creates a pointer/reference to the given thread local.
1022     ///
1023     /// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a
1024     /// `*const T`, and if neither of those apply a `&T`.
1025     ///
1026     /// **Note:** This is a runtime operation that actually executes code and is in this sense more
1027     /// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to
1028     /// SIGILL for some reason that I (JakobDegen) never got a chance to look into.
1029     ///
1030     /// **Needs clarification**: Are there weird additional semantics here related to the runtime
1031     /// nature of this operation?
1032     ThreadLocalRef(DefId),
1033
1034     /// Creates a pointer with the indicated mutability to the place.
1035     ///
1036     /// This is generated by pointer casts like `&v as *const _` or raw address of expressions like
1037     /// `&raw v` or `addr_of!(v)`.
1038     ///
1039     /// Like with references, the semantics of this operation are heavily dependent on the aliasing
1040     /// model.
1041     AddressOf(Mutability, Place<'tcx>),
1042
1043     /// Yields the length of the place, as a `usize`.
1044     ///
1045     /// If the type of the place is an array, this is the array length. For slices (`[T]`, not
1046     /// `&[T]`) this accesses the place's metadata to determine the length. This rvalue is
1047     /// ill-formed for places of other types.
1048     Len(Place<'tcx>),
1049
1050     /// Performs essentially all of the casts that can be performed via `as`.
1051     ///
1052     /// This allows for casts from/to a variety of types.
1053     ///
1054     /// **FIXME**: Document exactly which `CastKind`s allow which types of casts. Figure out why
1055     /// `ArrayToPointer` and `MutToConstPointer` are special.
1056     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1057
1058     /// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second
1059     ///   parameter may be a `usize` as well.
1060     /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats,
1061     ///   raw pointers, or function pointers and return a `bool`. The types of the operands must be
1062     ///   matching, up to the usual caveat of the lifetimes in function pointers.
1063     /// * Left and right shift operations accept signed or unsigned integers not necessarily of the
1064     ///   same type and return a value of the same type as their LHS. Like in Rust, the RHS is
1065     ///   truncated as needed.
1066     /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching
1067     ///   types and return a value of that type.
1068     /// * The remaining operations accept signed integers, unsigned integers, or floats with
1069     ///   matching types and return a value of that type.
1070     BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
1071
1072     /// Same as `BinaryOp`, but yields `(T, bool)` with a `bool` indicating an error condition.
1073     ///
1074     /// When overflow checking is disabled and we are generating run-time code, the error condition
1075     /// is false. Otherwise, and always during CTFE, the error condition is determined as described
1076     /// below.
1077     ///
1078     /// For addition, subtraction, and multiplication on integers the error condition is set when
1079     /// the infinite precision result would be unequal to the actual result.
1080     ///
1081     /// For shift operations on integers the error condition is set when the value of right-hand
1082     /// side is greater than or equal to the number of bits in the type of the left-hand side, or
1083     /// when the value of right-hand side is negative.
1084     ///
1085     /// Other combinations of types and operators are unsupported.
1086     CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
1087
1088     /// Computes a value as described by the operation.
1089     NullaryOp(NullOp, Ty<'tcx>),
1090
1091     /// Exactly like `BinaryOp`, but less operands.
1092     ///
1093     /// Also does two's-complement arithmetic. Negation requires a signed integer or a float;
1094     /// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds
1095     /// return a value with the same type as their operand.
1096     UnaryOp(UnOp, Operand<'tcx>),
1097
1098     /// Computes the discriminant of the place, returning it as an integer of type
1099     /// [`discriminant_ty`]. Returns zero for types without discriminant.
1100     ///
1101     /// The validity requirements for the underlying value are undecided for this rvalue, see
1102     /// [#91095]. Note too that the value of the discriminant is not the same thing as the
1103     /// variant index; use [`discriminant_for_variant`] to convert.
1104     ///
1105     /// [`discriminant_ty`]: crate::ty::Ty::discriminant_ty
1106     /// [#91095]: https://github.com/rust-lang/rust/issues/91095
1107     /// [`discriminant_for_variant`]: crate::ty::Ty::discriminant_for_variant
1108     Discriminant(Place<'tcx>),
1109
1110     /// Creates an aggregate value, like a tuple or struct.
1111     ///
1112     /// This is needed because dataflow analysis needs to distinguish
1113     /// `dest = Foo { x: ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case that `Foo`
1114     /// has a destructor.
1115     ///
1116     /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Generator`. After
1117     /// generator lowering, `Generator` aggregate kinds are disallowed too.
1118     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1119
1120     /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
1121     ///
1122     /// This is different from a normal transmute because dataflow analysis will treat the box as
1123     /// initialized but its content as uninitialized. Like other pointer casts, this in general
1124     /// affects alias analysis.
1125     ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
1126
1127     /// A CopyForDeref is equivalent to a read from a place at the
1128     /// codegen level, but is treated specially by drop elaboration. When such a read happens, it
1129     /// is guaranteed (via nature of the mir_opt `Derefer` in rustc_mir_transform/src/deref_separator)
1130     /// that the only use of the returned value is a deref operation, immediately
1131     /// followed by one or more projections. Drop elaboration treats this rvalue as if the
1132     /// read never happened and just projects further. This allows simplifying various MIR
1133     /// optimizations and codegen backends that previously had to handle deref operations anywhere
1134     /// in a place.
1135     CopyForDeref(Place<'tcx>),
1136 }
1137
1138 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1139 pub enum CastKind {
1140     /// An exposing pointer to address cast. A cast between a pointer and an integer type, or
1141     /// between a function pointer and an integer type.
1142     /// See the docs on `expose_addr` for more details.
1143     PointerExposeAddress,
1144     /// An address-to-pointer cast that picks up an exposed provenance.
1145     /// See the docs on `from_exposed_addr` for more details.
1146     PointerFromExposedAddress,
1147     /// All sorts of pointer-to-pointer casts. Note that reference-to-raw-ptr casts are
1148     /// translated into `&raw mut/const *r`, i.e., they are not actually casts.
1149     Pointer(PointerCast),
1150     /// Cast into a dyn* object.
1151     DynStar,
1152     IntToInt,
1153     FloatToInt,
1154     FloatToFloat,
1155     IntToFloat,
1156     PtrToPtr,
1157     FnPtrToPtr,
1158 }
1159
1160 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1161 #[derive(TypeFoldable, TypeVisitable)]
1162 pub enum AggregateKind<'tcx> {
1163     /// The type is of the element
1164     Array(Ty<'tcx>),
1165     Tuple,
1166
1167     /// The second field is the variant index. It's equal to 0 for struct
1168     /// and union expressions. The fourth field is
1169     /// active field number and is present only for union expressions
1170     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
1171     /// active field index would identity the field `c`
1172     Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
1173
1174     // Note: We can use LocalDefId since closures and generators a deaggregated
1175     // before codegen.
1176     Closure(LocalDefId, SubstsRef<'tcx>),
1177     Generator(LocalDefId, SubstsRef<'tcx>, hir::Movability),
1178 }
1179
1180 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
1181 pub enum NullOp {
1182     /// Returns the size of a value of that type
1183     SizeOf,
1184     /// Returns the minimum alignment of a type
1185     AlignOf,
1186 }
1187
1188 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1189 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
1190 pub enum UnOp {
1191     /// The `!` operator for logical inversion
1192     Not,
1193     /// The `-` operator for negation
1194     Neg,
1195 }
1196
1197 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Hash)]
1198 #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
1199 pub enum BinOp {
1200     /// The `+` operator (addition)
1201     Add,
1202     /// The `-` operator (subtraction)
1203     Sub,
1204     /// The `*` operator (multiplication)
1205     Mul,
1206     /// The `/` operator (division)
1207     ///
1208     /// Division by zero is UB, because the compiler should have inserted checks
1209     /// prior to this.
1210     Div,
1211     /// The `%` operator (modulus)
1212     ///
1213     /// Using zero as the modulus (second operand) is UB, because the compiler
1214     /// should have inserted checks prior to this.
1215     Rem,
1216     /// The `^` operator (bitwise xor)
1217     BitXor,
1218     /// The `&` operator (bitwise and)
1219     BitAnd,
1220     /// The `|` operator (bitwise or)
1221     BitOr,
1222     /// The `<<` operator (shift left)
1223     ///
1224     /// The offset is truncated to the size of the first operand before shifting.
1225     Shl,
1226     /// The `>>` operator (shift right)
1227     ///
1228     /// The offset is truncated to the size of the first operand before shifting.
1229     Shr,
1230     /// The `==` operator (equality)
1231     Eq,
1232     /// The `<` operator (less than)
1233     Lt,
1234     /// The `<=` operator (less than or equal to)
1235     Le,
1236     /// The `!=` operator (not equal to)
1237     Ne,
1238     /// The `>=` operator (greater than or equal to)
1239     Ge,
1240     /// The `>` operator (greater than)
1241     Gt,
1242     /// The `ptr.offset` operator
1243     Offset,
1244 }
1245
1246 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1247 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1248 mod size_asserts {
1249     use super::*;
1250     // tidy-alphabetical-start
1251     static_assert_size!(AggregateKind<'_>, 40);
1252     static_assert_size!(Operand<'_>, 24);
1253     static_assert_size!(Place<'_>, 16);
1254     static_assert_size!(PlaceElem<'_>, 24);
1255     static_assert_size!(Rvalue<'_>, 40);
1256     // tidy-alphabetical-end
1257 }