1use std::fmt;
23use itertools::Either;
4use rustc_abias abi;
5use rustc_abi::{
6Align, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, TagEncoding, VariantIdx, Variants,
7};
8use rustc_hir::LangItem;
9use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range};
10use rustc_middle::mir::{self, ConstValue};
11use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
12use rustc_middle::ty::{self, Ty};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::{AnnotateMoves, DebugInfo, OptLevel};
15use tracing::{debug, instrument};
1617use super::place::{PlaceRef, PlaceValue};
18use super::rvalue::transmute_scalar;
19use super::{FunctionCx, LocalRef};
20use crate::MemFlags;
21use crate::common::IntPredicate;
22use crate::traits::*;
2324/// The representation of a Rust value. The enum variant is in fact
25/// uniquely determined by the value's type, but is kept as a
26/// safety check.
27#[derive(#[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValue<V> { }Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValue<V> {
#[inline]
fn clone(&self) -> OperandValue<V> {
match self {
OperandValue::Ref(__self_0) =>
OperandValue::Ref(::core::clone::Clone::clone(__self_0)),
OperandValue::Immediate(__self_0) =>
OperandValue::Immediate(::core::clone::Clone::clone(__self_0)),
OperandValue::Pair(__self_0, __self_1) =>
OperandValue::Pair(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
OperandValue::ZeroSized => OperandValue::ZeroSized,
}
}
}Clone, #[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValue<V> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
OperandValue::Ref(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ref",
&__self_0),
OperandValue::Immediate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Immediate", &__self_0),
OperandValue::Pair(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
__self_0, &__self_1),
OperandValue::ZeroSized =>
::core::fmt::Formatter::write_str(f, "ZeroSized"),
}
}
}Debug)]
28pub enum OperandValue<V> {
29/// A reference to the actual operand. The data is guaranteed
30 /// to be valid for the operand's lifetime.
31 /// The second value, if any, is the extra data (vtable or length)
32 /// which indicates that it refers to an unsized rvalue.
33 ///
34 /// An `OperandValue` *must* be this variant for any type for which
35 /// [`LayoutTypeCodegenMethods::is_backend_ref`] returns `true`.
36 /// (That basically amounts to "isn't one of the other variants".)
37 ///
38 /// This holds a [`PlaceValue`] (like a [`PlaceRef`] does) with a pointer
39 /// to the location holding the value. The type behind that pointer is the
40 /// one returned by [`LayoutTypeCodegenMethods::backend_type`].
41Ref(PlaceValue<V>),
42/// A single LLVM immediate value.
43 ///
44 /// An `OperandValue` *must* be this variant for any type for which
45 /// [`LayoutTypeCodegenMethods::is_backend_immediate`] returns `true`.
46 /// The backend value in this variant must be the *immediate* backend type,
47 /// as returned by [`LayoutTypeCodegenMethods::immediate_backend_type`].
48Immediate(V),
49/// A pair of immediate LLVM values. Used by wide pointers too.
50 ///
51 /// # Invariants
52 /// - For `Pair(a, b)`, `a` is always at offset 0, but may have `FieldIdx(1..)`
53 /// - `b` is not at offset 0, because `V` is not a 1ZST type.
54 /// - `a` and `b` will have a different FieldIdx, but otherwise `b`'s may be lower
55 /// or they may not be adjacent, due to arbitrary numbers of 1ZST fields that
56 /// will not affect the shape of the data which determines if `Pair` will be used.
57 /// - An `OperandValue` *must* be this variant for any type for which
58 /// [`LayoutTypeCodegenMethods::is_backend_scalar_pair`] returns `true`.
59 /// - The backend values in this variant must be the *immediate* backend types,
60 /// as returned by [`LayoutTypeCodegenMethods::scalar_pair_element_backend_type`]
61 /// with `immediate: true`.
62Pair(V, V),
63/// A value taking no bytes, and which therefore needs no LLVM value at all.
64 ///
65 /// If you ever need a `V` to pass to something, get a fresh poison value
66 /// from [`ConstCodegenMethods::const_poison`].
67 ///
68 /// An `OperandValue` *must* be this variant for any type for which
69 /// `is_zst` on its `Layout` returns `true`. Note however that
70 /// these values can still require alignment.
71ZeroSized,
72}
7374impl<V: CodegenObject> OperandValue<V> {
75/// Return the data pointer and optional metadata as backend values
76 /// if this value can be treat as a pointer.
77pub(crate) fn try_pointer_parts(self) -> Option<(V, Option<V>)> {
78match self {
79 OperandValue::Immediate(llptr) => Some((llptr, None)),
80 OperandValue::Pair(llptr, llextra) => Some((llptr, Some(llextra))),
81 OperandValue::Ref(_) | OperandValue::ZeroSized => None,
82 }
83 }
8485/// Treat this value as a pointer and return the data pointer and
86 /// optional metadata as backend values.
87 ///
88 /// If you're making a place, use [`Self::deref`] instead.
89pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
90self.try_pointer_parts()
91 .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("OperandValue cannot be a pointer: {0:?}",
self))bug!("OperandValue cannot be a pointer: {self:?}"))
92 }
9394/// Treat this value as a pointer and return the place to which it points.
95 ///
96 /// The pointer immediate doesn't inherently know its alignment,
97 /// so you need to pass it in. If you want to get it from a type's ABI
98 /// alignment, then maybe you want [`OperandRef::deref`] instead.
99 ///
100 /// This is the inverse of [`PlaceValue::address`].
101pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
102let (llval, llextra) = self.pointer_parts();
103PlaceValue { llval, llextra, align }
104 }
105106#[must_use]
107pub(crate) fn is_expected_variant_for_type<'tcx, Cx: LayoutTypeCodegenMethods<'tcx>>(
108&self,
109 cx: &Cx,
110 ty: TyAndLayout<'tcx>,
111 ) -> bool {
112match self {
113 OperandValue::ZeroSized => ty.is_zst(),
114 OperandValue::Immediate(_) => cx.is_backend_immediate(ty),
115 OperandValue::Pair(_, _) => cx.is_backend_scalar_pair(ty),
116 OperandValue::Ref(_) => cx.is_backend_ref(ty),
117 }
118 }
119}
120121/// An `OperandRef` is an "SSA" reference to a Rust value, along with
122/// its type.
123///
124/// NOTE: unless you know a value's type exactly, you should not
125/// generate LLVM opcodes acting on it and instead act via methods,
126/// to avoid nasty edge cases. In particular, using `Builder::store`
127/// directly is sure to cause problems -- use `OperandRef::store`
128/// instead.
129#[derive(#[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
OperandRef<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
OperandRef<'tcx, V> {
#[inline]
fn clone(&self) -> OperandRef<'tcx, V> {
OperandRef {
val: ::core::clone::Clone::clone(&self.val),
layout: ::core::clone::Clone::clone(&self.layout),
move_annotation: ::core::clone::Clone::clone(&self.move_annotation),
}
}
}Clone)]
130pub struct OperandRef<'tcx, V> {
131/// The value.
132pub val: OperandValue<V>,
133134/// The layout of value, based on its Rust type.
135pub layout: TyAndLayout<'tcx>,
136137/// Annotation for profiler visibility of move/copy operations.
138 /// When set, the store operation should appear as an inlined call to this function.
139pub move_annotation: Option<ty::Instance<'tcx>>,
140}
141142impl<V: CodegenObject> fmt::Debugfor OperandRef<'_, V> {
143fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144f.write_fmt(format_args!("OperandRef({0:?} @ {1:?})", self.val, self.layout))write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)145 }
146}
147148impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
149pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
150if !layout.is_zst() {
::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
151OperandRef { val: OperandValue::ZeroSized, layout, move_annotation: None }
152 }
153154pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
155 bx: &mut Bx,
156 val: mir::ConstValue,
157 ty: Ty<'tcx>,
158 ) -> Self {
159let layout = bx.layout_of(ty);
160161let val = match val {
162 ConstValue::Scalar(x) => {
163let BackendRepr::Scalar(scalar) = layout.backend_repr else {
164::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ByVal layout: {0:#?}",
layout));bug!("from_const: invalid ByVal layout: {:#?}", layout);
165 };
166let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
167 OperandValue::Immediate(llval)
168 }
169 ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
170 ConstValue::Slice { alloc_id, meta } => {
171let BackendRepr::ScalarPair { a: a_scalar, b: _, b_offset: _ } =
172layout.backend_repr
173else {
174::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ScalarPair layout: {0:#?}",
layout));bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
175 };
176let a = Scalar::from_pointer(Pointer::new(alloc_id.into(), Size::ZERO), &bx.tcx());
177let a_llval = bx.scalar_to_backend(
178a,
179a_scalar,
180bx.scalar_pair_element_backend_type(layout, 0, true),
181 );
182let b_llval = bx.const_usize(meta);
183 OperandValue::Pair(a_llval, b_llval)
184 }
185 ConstValue::Indirect { alloc_id, offset } => {
186let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
187return Self::from_const_alloc(bx, layout, alloc, offset);
188 }
189 };
190191OperandRef { val, layout, move_annotation: None }
192 }
193194fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
195 bx: &mut Bx,
196 layout: TyAndLayout<'tcx>,
197 alloc: rustc_middle::mir::interpret::ConstAllocation<'tcx>,
198 offset: Size,
199 ) -> Self {
200let alloc_align = alloc.inner().align;
201if !(alloc_align >= layout.align.abi) {
{
::core::panicking::panic_fmt(format_args!("{1:?} < {0:?}",
layout.align.abi, alloc_align));
}
};assert!(alloc_align >= layout.align.abi, "{alloc_align:?} < {:?}", layout.align.abi);
202203let read_scalar = |start, size, s: abi::Scalar, ty| {
204match alloc.0.read_scalar(
205bx,
206alloc_range(start, size),
207/*read_provenance*/ #[allow(non_exhaustive_omitted_patterns)] match s.primitive() {
abi::Primitive::Pointer(_) => true,
_ => false,
}matches!(s.primitive(), abi::Primitive::Pointer(_)),
208 ) {
209Ok(val) => bx.scalar_to_backend(val, s, ty),
210Err(_) => bx.const_poison(ty),
211 }
212 };
213214// It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
215 // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
216 // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
217 // case where some of the bytes are initialized and others are not. So, we need an extra
218 // check that walks over the type of `mplace` to make sure it is truly correct to treat this
219 // like a `Scalar` (or `ScalarPair`).
220match layout.backend_repr {
221 BackendRepr::Scalar(s @ abi::Scalar::Initialized { .. }) => {
222let size = s.size(bx);
223{
match (&size, &layout.size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("abi::Scalar size does not match layout size")));
}
}
}
};assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
224let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
225OperandRef { val: OperandValue::Immediate(val), layout, move_annotation: None }
226 }
227 BackendRepr::ScalarPair {
228 a: a @ abi::Scalar::Initialized { .. },
229 b: b @ abi::Scalar::Initialized { .. },
230 b_offset: local_b_offset,
231 } => {
232let (a_size, b_size) = (a.size(bx), b.size(bx));
233let alloc_b_offset = offset + local_b_offset;
234if !(alloc_b_offset.bytes() > 0) {
::core::panicking::panic("assertion failed: alloc_b_offset.bytes() > 0")
};assert!(alloc_b_offset.bytes() > 0);
235let a_val = read_scalar(
236offset,
237a_size,
238a,
239bx.scalar_pair_element_backend_type(layout, 0, true),
240 );
241let b_val = read_scalar(
242alloc_b_offset,
243b_size,
244b,
245bx.scalar_pair_element_backend_type(layout, 1, true),
246 );
247OperandRef { val: OperandValue::Pair(a_val, b_val), layout, move_annotation: None }
248 }
249_ if layout.is_zst() => OperandRef::zero_sized(layout),
250_ => {
251// Neither a scalar nor scalar pair. Load from a place
252let base_addr = bx.static_addr_of(alloc, None);
253254let llval = bx.const_ptr_byte_offset(base_addr, offset);
255bx.load_operand(PlaceRef::new_sized(llval, layout))
256 }
257 }
258 }
259260/// Asserts that this operand refers to a scalar and returns
261 /// a reference to its value.
262pub fn immediate(self) -> V {
263match self.val {
264 OperandValue::Immediate(s) => s,
265_ => ::rustc_middle::util::bug::bug_fmt(format_args!("not immediate: {0:?}", self))bug!("not immediate: {:?}", self),
266 }
267 }
268269/// Asserts that this operand is a pointer (or reference) and returns
270 /// the place to which it points. (This requires no code to be emitted
271 /// as we represent places using the pointer to the place.)
272 ///
273 /// This uses [`Ty::builtin_deref`] to include the type of the place and
274 /// assumes the place is aligned to the pointee's usual ABI alignment.
275 ///
276 /// If you don't need the type, see [`OperandValue::pointer_parts`]
277 /// or [`OperandValue::deref`].
278pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
279if self.layout.ty.is_box() {
280// Derefer should have removed all Box derefs
281::rustc_middle::util::bug::bug_fmt(format_args!("dereferencing {0:?} in codegen",
self.layout.ty));bug!("dereferencing {:?} in codegen", self.layout.ty);
282 }
283284let projected_ty = self285 .layout
286 .ty
287 .builtin_deref(true)
288 .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("deref of non-pointer {0:?}",
self))bug!("deref of non-pointer {:?}", self));
289290let layout = cx.layout_of(projected_ty);
291self.val.deref(layout.align.abi).with_type(layout)
292 }
293294/// Store this operand into a place, applying move/copy annotation if present.
295 ///
296 /// This is the preferred method for storing operands, as it automatically
297 /// applies profiler annotations for tracked move/copy operations.
298pub fn store_with_annotation<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
299self,
300 bx: &mut Bx,
301 dest: PlaceRef<'tcx, V>,
302 ) {
303self.store_with_annotation_and_flags(bx, dest, MemFlags::empty())
304 }
305306/// Same as store_with_annotation(), but also specify flags for the store.
307pub fn store_with_annotation_and_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
308self,
309 bx: &mut Bx,
310 dest: PlaceRef<'tcx, V>,
311 flags: MemFlags,
312 ) {
313if let Some(instance) = self.move_annotation {
314bx.with_move_annotation(instance, |bx| self.val.store_with_flags(bx, dest, flags))
315 } else {
316self.val.store_with_flags(bx, dest, flags)
317 }
318 }
319320/// If this operand is a `Pair`, we return an aggregate with the two values.
321 /// For other cases, see `immediate`.
322 ///
323 /// Note: The use of this is discouraged outside cg_llvm, as some other backends
324 /// don't natively support packing multiple things into one like this.
325pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
326self,
327 bx: &mut Bx,
328 ) -> V {
329if let OperandValue::Pair(a, b) = self.val {
330let llty = bx.cx().immediate_backend_type(self.layout);
331{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:331",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(331u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Operand::immediate_or_packed_pair: packing {0:?} into {1:?}",
self, llty) as &dyn Value))])
});
} else { ; }
};debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
332// Reconstruct the immediate aggregate.
333let mut llpair = bx.cx().const_poison(llty);
334llpair = bx.insert_value(llpair, a, 0);
335llpair = bx.insert_value(llpair, b, 1);
336llpair337 } else {
338self.immediate()
339 }
340 }
341342/// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
343 ///
344 /// Note: The use of this is discouraged outside cg_llvm, as some other backends
345 /// don't natively support packing multiple things into one like this.
346pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
347 bx: &mut Bx,
348 llval: V,
349 layout: TyAndLayout<'tcx>,
350 ) -> Self {
351let val = if let BackendRepr::ScalarPair { .. } = layout.backend_repr {
352{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:352",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(352u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Operand::from_immediate_or_packed_pair: unpacking {0:?} @ {1:?}",
llval, layout) as &dyn Value))])
});
} else { ; }
};debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
353354// Deconstruct the immediate aggregate.
355let a_llval = bx.extract_value(llval, 0);
356let b_llval = bx.extract_value(llval, 1);
357 OperandValue::Pair(a_llval, b_llval)
358 } else {
359 OperandValue::Immediate(llval)
360 };
361OperandRef { val, layout, move_annotation: None }
362 }
363364pub(crate) fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
365&self,
366 fx: &mut FunctionCx<'a, 'tcx, Bx>,
367 bx: &mut Bx,
368 i: usize,
369 ) -> Self {
370let field = self.layout.field(bx.cx(), i);
371let offset = self.layout.fields.offset(i);
372373if !bx.is_backend_ref(self.layout) && bx.is_backend_ref(field) {
374// Part of https://github.com/rust-lang/compiler-team/issues/838
375::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
format_args!("Non-ref type {0:?} cannot project to ref field type {1:?}",
self, field));span_bug!(
376 fx.mir.span,
377"Non-ref type {self:?} cannot project to ref field type {field:?}",
378 );
379 }
380381let val = if field.is_zst() {
382 OperandValue::ZeroSized383 } else if field.size == self.layout.size {
384{
match (&offset.bytes(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(offset.bytes(), 0);
385fx.codegen_transmute_operand(bx, *self, field)
386 } else {
387let (in_scalar, imm) = match (self.val, self.layout.backend_repr) {
388// Extract a scalar component from a pair.
389(
390 OperandValue::Pair(a_llval, b_llval),
391 BackendRepr::ScalarPair { a, b, b_offset },
392 ) => {
393if offset.bytes() == 0 {
394{
match (&field.size, &a.size(bx.cx())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(field.size, a.size(bx.cx()));
395 (Some(a), a_llval)
396 } else {
397{
match (&offset, &b_offset) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(offset, b_offset);
398{
match (&field.size, &b.size(bx.cx())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(field.size, b.size(bx.cx()));
399 (Some(b), b_llval)
400 }
401 }
402403_ => {
404::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
format_args!("OperandRef::extract_field({0:?}): not applicable", self))span_bug!(fx.mir.span, "OperandRef::extract_field({:?}): not applicable", self)405 }
406 };
407 OperandValue::Immediate(match field.backend_repr {
408 BackendRepr::SimdVector { .. } => imm,
409 BackendRepr::Scalar(out_scalar) => {
410let Some(in_scalar) = in_scalarelse {
411::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
format_args!("OperandRef::extract_field({0:?}): missing input scalar for output scalar",
self))span_bug!(
412 fx.mir.span,
413"OperandRef::extract_field({:?}): missing input scalar for output scalar",
414self
415)416 };
417if in_scalar != out_scalar {
418// If the backend and backend_immediate types might differ,
419 // flip back to the backend type then to the new immediate.
420 // This avoids nop truncations, but still handles things like
421 // Bools in union fields needs to be truncated.
422let backend = bx.from_immediate(imm);
423bx.to_immediate_scalar(backend, out_scalar)
424 } else {
425imm426 }
427 }
428 BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }
429 | BackendRepr::Memory { .. }
430 | BackendRepr::SimdScalableVector { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
431 })
432 };
433434OperandRef { val, layout: field, move_annotation: None }
435 }
436437/// Obtain the actual discriminant of a value.
438#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("codegen_get_discr",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(438u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["self", "cast_to"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cast_to)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: V = loop {};
return __tracing_attr_fake_return;
}
{
let dl = &bx.tcx().data_layout;
let cast_to_layout = bx.cx().layout_of(cast_to);
let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
if self.layout.is_uninhabited() {
return bx.cx().const_poison(cast_to);
}
let (tag_scalar, tag_encoding, tag_field) =
match self.layout.variants {
Variants::Empty => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("we already handled uninhabited types")));
}
Variants::Single { index } => {
let discr_val =
if let Some(discr) =
self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
discr.val
} else {
{
match (&index, &FIRST_VARIANT) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
0
};
return bx.cx().const_uint_big(cast_to, discr_val);
}
Variants::Multiple { tag, ref tag_encoding, tag_field, .. }
=> {
(tag, tag_encoding, tag_field)
}
};
let tag_op =
match self.val {
OperandValue::ZeroSized =>
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached")),
OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
self.extract_field(fx, bx, tag_field.as_usize())
}
OperandValue::Ref(place) => {
let tag =
place.with_type(self.layout).project_field(bx,
tag_field.as_usize());
bx.load_operand(tag)
}
};
let tag_imm = tag_op.immediate();
match *tag_encoding {
TagEncoding::Direct => {
let signed =
match tag_scalar.primitive() {
Primitive::Int(_, signed) =>
!tag_scalar.is_bool() && signed,
_ => false,
};
bx.intcast(tag_imm, cast_to, signed)
}
TagEncoding::Niche {
untagged_variant, ref niche_variants, niche_start } => {
let (tag, tag_llty) =
match tag_scalar.primitive() {
Primitive::Pointer(_) => {
let t = bx.type_from_integer(dl.ptr_sized_integer());
let tag = bx.ptrtoint(tag_imm, t);
(tag, t)
}
_ =>
(tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
};
let relative_max =
niche_variants.last.as_u32() -
niche_variants.start.as_u32();
let niche_start_const =
bx.cx().const_uint_big(tag_llty, niche_start);
let (is_niche, tagged_discr, delta) =
if relative_max == 0 {
let is_niche =
bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
let tagged_discr =
bx.cx().const_uint(cast_to,
niche_variants.start.as_u32() as u64);
(is_niche, tagged_discr, 0)
} else {
if niche_variants.contains(&untagged_variant) &&
bx.cx().sess().opts.optimize != OptLevel::No {
let impossible =
niche_start.wrapping_add(u128::from(untagged_variant.as_u32())).wrapping_sub(u128::from(niche_variants.start.as_u32()));
let impossible =
bx.cx().const_uint_big(tag_llty, impossible);
let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
bx.assume(ne);
}
let tag_range = tag_scalar.valid_range(&dl);
let tag_size = tag_scalar.size(&dl);
let niche_end =
u128::from(relative_max).wrapping_add(niche_start);
let niche_end = tag_size.truncate(niche_end);
let relative_discr = bx.sub(tag, niche_start_const);
let cast_tag = bx.intcast(relative_discr, cast_to, false);
let is_niche =
if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
if niche_start == tag_range.start {
let niche_end_const =
bx.cx().const_uint_big(tag_llty, niche_end);
bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
} else {
{
match (&niche_end, &tag_range.end) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
}
} else if tag_range.no_signed_wraparound(tag_size) ==
Ok(true) {
if niche_start == tag_range.start {
let niche_end_const =
bx.cx().const_uint_big(tag_llty, niche_end);
bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
} else {
{
match (&niche_end, &tag_range.end) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
}
} else {
bx.icmp(IntPredicate::IntULE, relative_discr,
bx.cx().const_uint(tag_llty, relative_max as u64))
};
(is_niche, cast_tag, niche_variants.start.as_u32() as u128)
};
let tagged_discr =
if delta == 0 {
tagged_discr
} else {
bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
};
let untagged_variant_const =
bx.cx().const_uint(cast_to,
u64::from(untagged_variant.as_u32()));
let discr =
bx.select(is_niche, tagged_discr, untagged_variant_const);
discr
}
}
}
}
}#[instrument(level = "trace", skip(fx, bx))]439pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
440self,
441 fx: &mut FunctionCx<'a, 'tcx, Bx>,
442 bx: &mut Bx,
443 cast_to: Ty<'tcx>,
444 ) -> V {
445let dl = &bx.tcx().data_layout;
446let cast_to_layout = bx.cx().layout_of(cast_to);
447let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
448449// We check uninhabitedness separately because a type like
450 // `enum Foo { Bar(i32, !) }` is still reported as `Variants::Single`,
451 // *not* as `Variants::Empty`.
452if self.layout.is_uninhabited() {
453return bx.cx().const_poison(cast_to);
454 }
455456let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
457 Variants::Empty => unreachable!("we already handled uninhabited types"),
458 Variants::Single { index } => {
459let discr_val =
460if let Some(discr) = self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
461 discr.val
462 } else {
463// This arm is for types which are neither enums nor coroutines,
464 // and thus for which the only possible "variant" should be the first one.
465assert_eq!(index, FIRST_VARIANT);
466// There's thus no actual discriminant to return, so we return
467 // what it would have been if this was a single-variant enum.
4680
469};
470return bx.cx().const_uint_big(cast_to, discr_val);
471 }
472 Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
473 (tag, tag_encoding, tag_field)
474 }
475 };
476477// Read the tag/niche-encoded discriminant from memory.
478let tag_op = match self.val {
479 OperandValue::ZeroSized => bug!(),
480 OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
481self.extract_field(fx, bx, tag_field.as_usize())
482 }
483 OperandValue::Ref(place) => {
484let tag = place.with_type(self.layout).project_field(bx, tag_field.as_usize());
485 bx.load_operand(tag)
486 }
487 };
488let tag_imm = tag_op.immediate();
489490// Decode the discriminant (specifically if it's niche-encoded).
491match *tag_encoding {
492 TagEncoding::Direct => {
493let signed = match tag_scalar.primitive() {
494// We use `i1` for bytes that are always `0` or `1`,
495 // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
496 // let LLVM interpret the `i1` as signed, because
497 // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`.
498Primitive::Int(_, signed) => !tag_scalar.is_bool() && signed,
499_ => false,
500 };
501 bx.intcast(tag_imm, cast_to, signed)
502 }
503 TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
504// Cast to an integer so we don't have to treat a pointer as a
505 // special case.
506let (tag, tag_llty) = match tag_scalar.primitive() {
507// FIXME(erikdesjardins): handle non-default addrspace ptr sizes
508Primitive::Pointer(_) => {
509let t = bx.type_from_integer(dl.ptr_sized_integer());
510let tag = bx.ptrtoint(tag_imm, t);
511 (tag, t)
512 }
513_ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
514 };
515516// `layout_sanity_check` ensures that we only get here for cases where the discriminant
517 // value and the variant index match, since that's all `Niche` can encode.
518519let relative_max = niche_variants.last.as_u32() - niche_variants.start.as_u32();
520let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start);
521522// We have a subrange `niche_start..=niche_end` inside `range`.
523 // If the value of the tag is inside this subrange, it's a
524 // "niche value", an increment of the discriminant. Otherwise it
525 // indicates the untagged variant.
526 // A general algorithm to extract the discriminant from the tag
527 // is:
528 // relative_tag = tag - niche_start
529 // is_niche = relative_tag <= (ule) relative_max
530 // discr = if is_niche {
531 // cast(relative_tag) + niche_variants.start()
532 // } else {
533 // untagged_variant
534 // }
535 // However, we will likely be able to emit simpler code.
536let (is_niche, tagged_discr, delta) = if relative_max == 0 {
537// Best case scenario: only one tagged variant. This will
538 // likely become just a comparison and a jump.
539 // The algorithm is:
540 // is_niche = tag == niche_start
541 // discr = if is_niche {
542 // niche_start
543 // } else {
544 // untagged_variant
545 // }
546let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
547let tagged_discr =
548 bx.cx().const_uint(cast_to, niche_variants.start.as_u32() as u64);
549 (is_niche, tagged_discr, 0)
550 } else {
551// Thanks to parameter attributes and load metadata, LLVM already knows
552 // the general valid range of the tag. It's possible, though, for there
553 // to be an impossible value *in the middle*, which those ranges don't
554 // communicate, so it's worth an `assume` to let the optimizer know.
555 // Most importantly, this means when optimizing a variant test like
556 // `SELECT(is_niche, complex, CONST) == CONST` it's ok to simplify that
557 // to `!is_niche` because the `complex` part can't possibly match.
558 //
559 // This was previously asserted on `tagged_discr` below, where the
560 // impossible value is more obvious, but that caused an intermediate
561 // value to become multi-use and thus not optimize, so instead this
562 // assumes on the original input which is always multi-use. See
563 // <https://github.com/llvm/llvm-project/issues/134024#issuecomment-3131782555>
564 //
565 // FIXME: If we ever get range assume operand bundles in LLVM (so we
566 // don't need the `icmp`s in the instruction stream any more), it
567 // might be worth moving this back to being on the switch argument
568 // where it's more obviously applicable.
569if niche_variants.contains(&untagged_variant)
570 && bx.cx().sess().opts.optimize != OptLevel::No
571 {
572let impossible = niche_start
573 .wrapping_add(u128::from(untagged_variant.as_u32()))
574 .wrapping_sub(u128::from(niche_variants.start.as_u32()));
575let impossible = bx.cx().const_uint_big(tag_llty, impossible);
576let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
577 bx.assume(ne);
578 }
579580// With multiple niched variants we'll have to actually compute
581 // the variant index from the stored tag.
582 //
583 // However, there's still one small optimization we can often do for
584 // determining *whether* a tag value is a natural value or a niched
585 // variant. The general algorithm involves a subtraction that often
586 // wraps in practice, making it tricky to analyse. However, in cases
587 // where there are few enough possible values of the tag that it doesn't
588 // need to wrap around, we can instead just look for the contiguous
589 // tag values on the end of the range with a single comparison.
590 //
591 // For example, take the type `enum Demo { A, B, Untagged(bool) }`.
592 // The `bool` is {0, 1}, and the two other variants are given the
593 // tags {2, 3} respectively. That means the `tag_range` is
594 // `[0, 3]`, which doesn't wrap as unsigned (nor as signed), so
595 // we can test for the niched variants with just `>= 2`.
596 //
597 // That means we're looking either for the niche values *above*
598 // the natural values of the untagged variant:
599 //
600 // niche_start niche_end
601 // | |
602 // v v
603 // MIN -------------+---------------------------+---------- MAX
604 // ^ | is niche |
605 // | +---------------------------+
606 // | |
607 // tag_range.start tag_range.end
608 //
609 // Or *below* the natural values:
610 //
611 // niche_start niche_end
612 // | |
613 // v v
614 // MIN ----+-----------------------+---------------------- MAX
615 // | is niche | ^
616 // +-----------------------+ |
617 // | |
618 // tag_range.start tag_range.end
619 //
620 // With those two options and having the flexibility to choose
621 // between a signed or unsigned comparison on the tag, that
622 // covers most realistic scenarios. The tests have a (contrived)
623 // example of a 1-byte enum with over 128 niched variants which
624 // wraps both as signed as unsigned, though, and for something
625 // like that we're stuck with the general algorithm.
626627let tag_range = tag_scalar.valid_range(&dl);
628let tag_size = tag_scalar.size(&dl);
629let niche_end = u128::from(relative_max).wrapping_add(niche_start);
630let niche_end = tag_size.truncate(niche_end);
631632let relative_discr = bx.sub(tag, niche_start_const);
633let cast_tag = bx.intcast(relative_discr, cast_to, false);
634let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
635if niche_start == tag_range.start {
636let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
637 bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
638 } else {
639assert_eq!(niche_end, tag_range.end);
640 bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
641 }
642 } else if tag_range.no_signed_wraparound(tag_size) == Ok(true) {
643if niche_start == tag_range.start {
644let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
645 bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
646 } else {
647assert_eq!(niche_end, tag_range.end);
648 bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
649 }
650 } else {
651 bx.icmp(
652 IntPredicate::IntULE,
653 relative_discr,
654 bx.cx().const_uint(tag_llty, relative_max as u64),
655 )
656 };
657658 (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
659 };
660661let tagged_discr = if delta == 0 {
662 tagged_discr
663 } else {
664 bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
665 };
666667let untagged_variant_const =
668 bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32()));
669670let discr = bx.select(is_niche, tagged_discr, untagged_variant_const);
671672// In principle we could insert assumes on the possible range of `discr`, but
673 // currently in LLVM this isn't worth it because the original `tag` will
674 // have either a `range` parameter attribute or `!range` metadata,
675 // or come from a `transmute` that already `assume`d it.
676677discr
678 }
679 }
680 }
681}
682683/// Each of these variants starts out as `Either::Right` when it's uninitialized,
684/// then setting the field changes that to `Either::Left` with the backend value.
685#[derive(#[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValueBuilder<V> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
OperandValueBuilder::ZeroSized =>
::core::fmt::Formatter::write_str(f, "ZeroSized"),
OperandValueBuilder::Immediate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Immediate", &__self_0),
OperandValueBuilder::Pair(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
__self_0, &__self_1),
OperandValueBuilder::Vector(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Vector",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValueBuilder<V>
{
}Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValueBuilder<V>
{
#[inline]
fn clone(&self) -> OperandValueBuilder<V> {
match self {
OperandValueBuilder::ZeroSized => OperandValueBuilder::ZeroSized,
OperandValueBuilder::Immediate(__self_0) =>
OperandValueBuilder::Immediate(::core::clone::Clone::clone(__self_0)),
OperandValueBuilder::Pair(__self_0, __self_1) =>
OperandValueBuilder::Pair(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
OperandValueBuilder::Vector(__self_0) =>
OperandValueBuilder::Vector(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
686enum OperandValueBuilder<V> {
687 ZeroSized,
688 Immediate(Either<V, abi::Scalar>),
689 Pair(Either<V, abi::Scalar>, Either<V, abi::Scalar>),
690/// `repr(simd)` types need special handling because they each have a non-empty
691 /// array field (which uses [`OperandValue::Ref`]) despite the SIMD type itself
692 /// using [`OperandValue::Immediate`] which for any other kind of type would
693 /// mean that its one non-ZST field would also be [`OperandValue::Immediate`].
694Vector(Either<V, ()>),
695}
696697/// Allows building up an `OperandRef` by setting fields one at a time.
698#[derive(#[automatically_derived]
impl<'tcx, V: ::core::fmt::Debug> ::core::fmt::Debug for
OperandRefBuilder<'tcx, V> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OperandRefBuilder", "val", &self.val, "layout", &&self.layout)
}
}Debug, #[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
OperandRefBuilder<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
OperandRefBuilder<'tcx, V> {
#[inline]
fn clone(&self) -> OperandRefBuilder<'tcx, V> {
OperandRefBuilder {
val: ::core::clone::Clone::clone(&self.val),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone)]
699pub(super) struct OperandRefBuilder<'tcx, V> {
700 val: OperandValueBuilder<V>,
701 layout: TyAndLayout<'tcx>,
702}
703704impl<'a, 'tcx, V: CodegenObject> OperandRefBuilder<'tcx, V> {
705/// Creates an uninitialized builder for an instance of the `layout`.
706 ///
707 /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which should
708 /// be built up inside a [`PlaceRef`] instead as they need an allocated place
709 /// into which to write the values of the fields.
710pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
711let val = match layout.backend_repr {
712 BackendRepr::Memory { .. } if layout.is_zst() => OperandValueBuilder::ZeroSized,
713 BackendRepr::Scalar(s) => OperandValueBuilder::Immediate(Either::Right(s)),
714 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
715 OperandValueBuilder::Pair(Either::Right(a), Either::Right(b))
716 }
717 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
718 OperandValueBuilder::Vector(Either::Right(()))
719 }
720 BackendRepr::Memory { .. } => {
721::rustc_middle::util::bug::bug_fmt(format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
layout));bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
722 }
723 };
724OperandRefBuilder { val, layout }
725 }
726727/// Creates an initialized builder for updating an existing `operand`.
728 ///
729 /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which use
730 /// which use [`OperandValue::Ref`]. In this case, updates should be
731 /// performed by writing into the place
732pub(super) fn from_existing(operand: OperandRef<'tcx, V>) -> Self {
733let layout = operand.layout;
734let val = match (operand.val, layout.backend_repr) {
735 (OperandValue::ZeroSized, _) => OperandValueBuilder::ZeroSized,
736 (OperandValue::Immediate(v), BackendRepr::Scalar(_)) => {
737 OperandValueBuilder::Immediate(Either::Left(v))
738 }
739 (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => {
740 OperandValueBuilder::Vector(Either::Left(v))
741 }
742 (OperandValue::Pair(a, b), BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }) => {
743 OperandValueBuilder::Pair(Either::Left(a), Either::Left(b))
744 }
745 (_, BackendRepr::Memory { .. }) => {
746::rustc_middle::util::bug::bug_fmt(format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
layout));bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
747 }
748_ => {
749::rustc_middle::util::bug::bug_fmt(format_args!("Operand cannot be used with `from_existing`: {0:?}",
operand))bug!("Operand cannot be used with `from_existing`: {operand:?}")750 }
751 };
752OperandRefBuilder { val, layout }
753 }
754755pub(super) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
756&mut self,
757 bx: &mut Bx,
758 variant: VariantIdx,
759 field: FieldIdx,
760 field_operand: OperandRef<'tcx, V>,
761 ) {
762if let OperandValue::ZeroSized = field_operand.val {
763// A ZST never adds any state, so just ignore it.
764 // This special-casing is worth it because of things like
765 // `Result<!, !>` where `Ok(never)` is legal to write,
766 // but the type shows as FieldShape::Primitive so we can't
767 // actually look at the layout for the field being set.
768return;
769 }
770771let is_zero_offset = if let abi::FieldsShape::Primitive = self.layout.fields {
772// The other branch looking at field layouts ICEs for primitives,
773 // so we need to handle them separately.
774 // Because we handled ZSTs above (like the metadata in a thin pointer),
775 // the only possibility is that we're setting the one-and-only field.
776if !!self.layout.is_zst() {
::core::panicking::panic("assertion failed: !self.layout.is_zst()")
};assert!(!self.layout.is_zst());
777{
match (&variant, &FIRST_VARIANT) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(variant, FIRST_VARIANT);
778{
match (&field, &FieldIdx::ZERO) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(field, FieldIdx::ZERO);
779true
780} else {
781let variant_layout = self.layout.for_variant(bx.cx(), variant);
782let field_offset = variant_layout.fields.offset(field.as_usize());
783field_offset == Size::ZERO784 };
785786let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
787let to_scalar = tgt.unwrap_right();
788// We transmute here (rather than just `from_immediate`) because in
789 // `Result<usize, *const ()>` the field of the `Ok` is an integer,
790 // but the corresponding scalar in the enum is a pointer.
791let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
792*tgt = Either::Left(imm);
793 };
794795match (field_operand.val, field_operand.layout.backend_repr) {
796 (OperandValue::ZeroSized, _) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Handled above")));
}unreachable!("Handled above"),
797 (OperandValue::Immediate(v), BackendRepr::Scalar(from_scalar)) => match &mut self.val {
798 OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
799update(val, v, from_scalar);
800 }
801 OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
802update(fst, v, from_scalar);
803 }
804 OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
805update(snd, v, from_scalar);
806 }
807_ => {
808::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")809 }
810 },
811 (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => match &mut self.val {
812 OperandValueBuilder::Vector(val @ Either::Right(())) if is_zero_offset => {
813*val = Either::Left(v);
814 }
815_ => {
816::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")817 }
818 },
819 (
820 OperandValue::Pair(a, b),
821 BackendRepr::ScalarPair { a: from_sa, b: from_sb, b_offset: _ },
822 ) => match &mut self.val {
823 OperandValueBuilder::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
824update(fst, a, from_sa);
825update(snd, b, from_sb);
826 }
827_ => {
828::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")829 }
830 },
831 (OperandValue::Ref(place), BackendRepr::Memory { .. }) => match &mut self.val {
832 OperandValueBuilder::Vector(val @ Either::Right(())) => {
833let ibty = bx.cx().immediate_backend_type(self.layout);
834let simd = bx.load_from_place(ibty, place);
835*val = Either::Left(simd);
836 }
837_ => {
838::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")839 }
840 },
841_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Operand cannot be used with `insert_field`: {0:?}",
field_operand))bug!("Operand cannot be used with `insert_field`: {field_operand:?}"),
842 }
843 }
844845/// Insert the immediate value `imm` for field `f` in the *type itself*,
846 /// rather than into one of the variants.
847 ///
848 /// Most things want [`Self::insert_field`] instead, but this one is
849 /// necessary for writing things like enum tags that aren't in any variant.
850pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
851let field_offset = self.layout.fields.offset(f.as_usize());
852let is_zero_offset = field_offset == Size::ZERO;
853match &mut self.val {
854 OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
855*val = Either::Left(imm);
856 }
857 OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
858*fst = Either::Left(imm);
859 }
860 OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
861*snd = Either::Left(imm);
862 }
863_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into field {1:?} of {2:?}",
imm, f, self))bug!("Tried to insert {imm:?} into field {f:?} of {self:?}"),
864 }
865 }
866867/// Replaces the current immediate value at the offset `offset`
868 /// with the value `imm`. A value must already be present.
869 ///
870 /// This is used along with [`Self::from_existing`] to perform in-place updates
871 /// of any operand.
872pub(super) fn update_imm(&mut self, offset: Size, imm: V) {
873let is_zero_offset = offset == Size::ZERO;
874match &mut self.val {
875 OperandValueBuilder::Immediate(val @ Either::Left(_)) if is_zero_offset => {
876*val = Either::Left(imm);
877 }
878 OperandValueBuilder::Pair(fst @ Either::Left(_), _) if is_zero_offset => {
879*fst = Either::Left(imm);
880 }
881 OperandValueBuilder::Pair(_, snd @ Either::Left(_)) if !is_zero_offset => {
882*snd = Either::Left(imm);
883 }
884_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to update {0:?} at offset {1:?} of {2:?}",
imm, offset, self))bug!("Tried to update {imm:?} at offset {offset:?} of {self:?}"),
885 }
886 }
887888/// After having set all necessary fields, this converts the builder back
889 /// to the normal `OperandRef`.
890 ///
891 /// ICEs if any required fields were not set.
892pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
893let OperandRefBuilder { val, layout } = *self;
894895// For something like `Option::<u32>::None`, it's expected that the
896 // payload scalar will not actually have been set, so this converts
897 // unset scalars to corresponding `undef` values so long as the scalar
898 // from the layout allows uninit.
899let unwrap = |r: Either<V, abi::Scalar>| match r {
900 Either::Left(v) => v,
901 Either::Right(s) if s.is_uninit_valid() => {
902let bty = cx.type_from_scalar(s);
903cx.const_undef(bty)
904 }
905 Either::Right(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("OperandRef::build called while fields are missing {0:?}",
self))bug!("OperandRef::build called while fields are missing {self:?}"),
906 };
907908let val = match val {
909 OperandValueBuilder::ZeroSized => OperandValue::ZeroSized,
910 OperandValueBuilder::Immediate(v) => OperandValue::Immediate(unwrap(v)),
911 OperandValueBuilder::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
912 OperandValueBuilder::Vector(v) => match v {
913 Either::Left(v) => OperandValue::Immediate(v),
914 Either::Right(())
915if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
916 && element.is_uninit_valid() =>
917 {
918let bty = cx.immediate_backend_type(layout);
919 OperandValue::Immediate(cx.const_undef(bty))
920 }
921 Either::Right(()) => {
922::rustc_middle::util::bug::bug_fmt(format_args!("OperandRef::build called while fields are missing {0:?}",
self))bug!("OperandRef::build called while fields are missing {self:?}")923 }
924 },
925 };
926OperandRef { val, layout, move_annotation: None }
927 }
928}
929930/// Default size limit for move/copy annotations (in bytes). 64 bytes is a common size of a cache
931/// line, and the assumption is that anything this size or below is very cheap to move/copy, so only
932/// annotate copies larger than this.
933const MOVE_ANNOTATION_DEFAULT_LIMIT: u64 = 65;
934935impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
936/// Returns an `OperandValue` that's generally UB to use in any way.
937 ///
938 /// Depending on the `layout`, returns `ZeroSized` for ZSTs, an `Immediate` or
939 /// `Pair` containing poison value(s), or a `Ref` containing a poison pointer.
940 ///
941 /// Supports sized types only.
942pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
943 bx: &mut Bx,
944 layout: TyAndLayout<'tcx>,
945 ) -> OperandValue<V> {
946if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
947if layout.is_zst() {
948 OperandValue::ZeroSized949 } else if bx.cx().is_backend_immediate(layout) {
950let ibty = bx.cx().immediate_backend_type(layout);
951 OperandValue::Immediate(bx.const_poison(ibty))
952 } else if bx.cx().is_backend_scalar_pair(layout) {
953let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
954let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
955 OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
956 } else {
957let ptr = bx.cx().type_ptr();
958 OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
959 }
960 }
961962pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
963self,
964 bx: &mut Bx,
965 dest: PlaceRef<'tcx, V>,
966 ) {
967self.store_with_flags(bx, dest, MemFlags::empty());
968 }
969970pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
971self,
972 bx: &mut Bx,
973 dest: PlaceRef<'tcx, V>,
974 ) {
975self.store_with_flags(bx, dest, MemFlags::VOLATILE);
976 }
977978pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
979self,
980 bx: &mut Bx,
981 dest: PlaceRef<'tcx, V>,
982 ) {
983self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
984 }
985986pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
987self,
988 bx: &mut Bx,
989 dest: PlaceRef<'tcx, V>,
990 flags: MemFlags,
991 ) {
992{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:992",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(992u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("OperandRef::store: operand={0:?}, dest={1:?}",
self, dest) as &dyn Value))])
});
} else { ; }
};debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
993match self {
994 OperandValue::ZeroSized => {
995// Avoid generating stores of zero-sized values, because the only way to have a
996 // zero-sized value is through `undef`/`poison`, and the store itself is useless.
997}
998 OperandValue::Ref(val) => {
999if !dest.layout.is_sized() {
{
::core::panicking::panic_fmt(format_args!("cannot directly store unsized values"));
}
};assert!(dest.layout.is_sized(), "cannot directly store unsized values");
1000if val.llextra.is_some() {
1001::rustc_middle::util::bug::bug_fmt(format_args!("cannot directly store unsized values"));bug!("cannot directly store unsized values");
1002 }
1003bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
1004 }
1005 OperandValue::Immediate(s) => {
1006let val = bx.from_immediate(s);
1007bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
1008 }
1009 OperandValue::Pair(a, b) => {
1010let BackendRepr::ScalarPair { a: _, b: _, b_offset } = dest.layout.backend_repr
1011else {
1012::rustc_middle::util::bug::bug_fmt(format_args!("store_with_flags: invalid ScalarPair layout: {0:#?}",
dest.layout));bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout);
1013 };
10141015let val = bx.from_immediate(a);
1016let align = dest.val.align;
1017bx.store_with_flags(val, dest.val.llval, align, flags);
10181019let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
1020let val = bx.from_immediate(b);
1021let align = dest.val.align.restrict_for_offset(b_offset);
1022// The CAPTURES_READ_ONLY flag only applies to the first element.
1023bx.store_with_flags(val, llptr, align, flags & !MemFlags::CAPTURES_READ_ONLY);
1024 }
1025 }
1026 }
1027}
10281029impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1030fn maybe_codegen_consume_direct(
1031&mut self,
1032 bx: &mut Bx,
1033 place_ref: mir::PlaceRef<'tcx>,
1034 ) -> Option<OperandRef<'tcx, Bx::Value>> {
1035{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1035",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1035u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("maybe_codegen_consume_direct(place_ref={0:?})",
place_ref) as &dyn Value))])
});
} else { ; }
};debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
10361037match self.locals[place_ref.local] {
1038 LocalRef::Operand(mut o) => {
1039// We only need to handle the projections that
1040 // `LocalAnalyzer::process_place` let make it here.
1041for elem in place_ref.projection {
1042match *elem {
1043 mir::ProjectionElem::Field(f, _) => {
1044if !!o.layout.ty.is_any_ptr() {
{
::core::panicking::panic_fmt(format_args!("Bad PlaceRef: destructing pointers should use cast/PtrMetadata, but tried to access field {0:?} of pointer {1:?}",
f, o));
}
};assert!(
1045 !o.layout.ty.is_any_ptr(),
1046"Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
1047 but tried to access field {f:?} of pointer {o:?}",
1048 );
1049 o = o.extract_field(self, bx, f.index());
1050 }
1051 mir::PlaceElem::Downcast(_, vidx) => {
1052if true {
{
match (&o.layout.variants, &abi::Variants::Single { index: vidx }) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(
1053 o.layout.variants,
1054 abi::Variants::Single { index: vidx },
1055 );
1056let layout = o.layout.for_variant(bx.cx(), vidx);
1057 o = OperandRef { layout, ..o }
1058 }
1059_ => return None,
1060 }
1061 }
10621063Some(o)
1064 }
1065 LocalRef::PendingOperand => {
1066::rustc_middle::util::bug::bug_fmt(format_args!("use of {0:?} before def",
place_ref));bug!("use of {:?} before def", place_ref);
1067 }
1068 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
1069// watch out for locals that do not have an
1070 // alloca; they are handled somewhat differently
1071None1072 }
1073 }
1074 }
10751076pub fn codegen_consume(
1077&mut self,
1078 bx: &mut Bx,
1079 place_ref: mir::PlaceRef<'tcx>,
1080 ) -> OperandRef<'tcx, Bx::Value> {
1081{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1081",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1081u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_consume(place_ref={0:?})",
place_ref) as &dyn Value))])
});
} else { ; }
};debug!("codegen_consume(place_ref={:?})", place_ref);
10821083let ty = self.monomorphized_place_ty(place_ref);
1084let layout = bx.cx().layout_of(ty);
10851086// ZSTs don't require any actual memory access.
1087if layout.is_zst() {
1088return OperandRef::zero_sized(layout);
1089 }
10901091if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
1092return o;
1093 }
10941095// for most places, to consume them we just load them
1096 // out from their home
1097let place = self.codegen_place(bx, place_ref);
1098bx.load_operand(place)
1099 }
11001101pub fn codegen_operand(
1102&mut self,
1103 bx: &mut Bx,
1104 operand: &mir::Operand<'tcx>,
1105 ) -> OperandRef<'tcx, Bx::Value> {
1106{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1106",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1106u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_operand(operand={0:?})",
operand) as &dyn Value))])
});
} else { ; }
};debug!("codegen_operand(operand={:?})", operand);
11071108match *operand {
1109 mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
1110let kind = match operand {
1111 mir::Operand::Move(_) => LangItem::CompilerMove,
1112 mir::Operand::Copy(_) => LangItem::CompilerCopy,
1113_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1114 };
11151116// Check if we should annotate this move/copy for profiling
1117let move_annotation = self.move_copy_annotation_instance(bx, place.as_ref(), kind);
11181119OperandRef { move_annotation, ..self.codegen_consume(bx, place.as_ref()) }
1120 }
11211122 mir::Operand::RuntimeChecks(checks) => {
1123let layout = bx.layout_of(bx.tcx().types.bool);
1124let BackendRepr::Scalar(scalar) = layout.backend_repr else {
1125::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ByVal layout: {0:#?}",
layout));bug!("from_const: invalid ByVal layout: {:#?}", layout);
1126 };
1127let x = Scalar::from_bool(checks.value(bx.tcx().sess));
1128let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
1129let val = OperandValue::Immediate(llval);
1130OperandRef { val, layout, move_annotation: None }
1131 }
11321133 mir::Operand::Constant(ref constant) => {
1134let constant_ty = self.monomorphize(constant.ty());
1135// Most SIMD vector constants should be passed as immediates.
1136 // (In particular, some intrinsics really rely on this.)
1137if constant_ty.is_simd() {
1138// However, some SIMD types do not actually use the vector ABI
1139 // (in particular, packed SIMD types do not). Ensure we exclude those.
1140 //
1141 // We also have to exclude vectors of pointers because `immediate_const_vector`
1142 // does not work for those.
1143let layout = bx.layout_of(constant_ty);
1144let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1145if let BackendRepr::SimdVector { .. } = layout.backend_repr
1146 && element_ty.is_numeric()
1147 {
1148let (llval, ty) = self.immediate_const_vector(bx, constant);
1149return OperandRef {
1150 val: OperandValue::Immediate(llval),
1151 layout: bx.layout_of(ty),
1152 move_annotation: None,
1153 };
1154 }
1155 }
1156self.eval_mir_constant_to_operand(bx, constant)
1157 }
1158 }
1159 }
11601161/// Creates an `Instance` for annotating a move/copy operation at codegen time.
1162 ///
1163 /// Returns `Some(instance)` if the operation should be annotated with debug info, `None`
1164 /// otherwise. The instance represents a monomorphized `compiler_move<T, SIZE>` or
1165 /// `compiler_copy<T, SIZE>` function that can be used to create debug scopes.
1166 ///
1167 /// There are a number of conditions that must be met for an annotation to be created, but aside
1168 /// from the basics (annotation is enabled, we're generating debuginfo), the primary concern is
1169 /// moves/copies which could result in a real `memcpy`. So we check for the size limit, but also
1170 /// that the underlying representation of the type is in memory.
1171fn move_copy_annotation_instance(
1172&self,
1173 bx: &Bx,
1174 place: mir::PlaceRef<'tcx>,
1175 kind: LangItem,
1176 ) -> Option<ty::Instance<'tcx>> {
1177let tcx = bx.tcx();
1178let sess = tcx.sess;
11791180// Skip if we're not generating debuginfo
1181if sess.opts.debuginfo == DebugInfo::None {
1182return None;
1183 }
11841185// Check if annotation is enabled and get size limit (otherwise skip)
1186let size_limit = match sess.opts.unstable_opts.annotate_moves {
1187 AnnotateMoves::Disabled => return None,
1188 AnnotateMoves::Enabled(None) => MOVE_ANNOTATION_DEFAULT_LIMIT,
1189 AnnotateMoves::Enabled(Some(limit)) => limit,
1190 };
11911192let ty = self.monomorphized_place_ty(place);
1193let layout = bx.cx().layout_of(ty);
1194let ty_size = layout.size.bytes();
11951196// Only annotate if type has a memory representation and exceeds size limit (and has a
1197 // non-zero size)
1198if layout.is_zst()
1199 || ty_size < size_limit1200 || !#[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(layout.backend_repr, BackendRepr::Memory { .. })1201 {
1202return None;
1203 }
12041205// Look up the DefId for compiler_move or compiler_copy lang item
1206let def_id = tcx.lang_items().get(kind)?;
12071208// Create generic args: compiler_move<T, SIZE> or compiler_copy<T, SIZE>
1209let size_const = ty::Const::from_target_usize(tcx, ty_size);
1210let generic_args = tcx.mk_args(&[ty.into(), size_const.into()]);
12111212// Create the Instance
1213let typing_env = self.mir.typing_env(tcx);
1214let instance = ty::Instance::expect_resolve(
1215tcx,
1216typing_env,
1217def_id,
1218generic_args,
1219 rustc_span::DUMMY_SP, // span only used for error messages
1220);
12211222Some(instance)
1223 }
1224}