1use std::assert_matches;
2use std::cmp::Ordering;
3
4use itertools::Itertools as _;
5use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
6use rustc_index::IndexVec;
7use rustc_middle::mir;
8use rustc_middle::ty::adjustment::PointerCoercion;
9use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
10use rustc_middle::ty::{self, Instance, Mutability, Ty, TyCtxt};
11use rustc_session::config::OptLevel;
12use rustc_span::{bug, span_bug};
13use tracing::{debug, instrument};
14
15use super::FunctionCx;
16use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
17use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
18use crate::common::IntPredicate;
19use crate::traits::*;
20use crate::{MemFlags, base};
21
22impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
23 fn try_codegen_const_aggregate_as_immediate(
24 &mut self,
25 bx: &mut Bx,
26 dest: PlaceRef<'tcx, Bx::Value>,
27 kind: &mir::AggregateKind<'tcx>,
28 operands: &IndexVec<abi::FieldIdx, mir::Operand<'tcx>>,
29 ) -> bool {
30 let variant_index = match kind {
35 mir::AggregateKind::Tuple => FIRST_VARIANT,
36 mir::AggregateKind::Adt(_, variant_index, _, _, None) => *variant_index,
37 _ => return false,
38 };
39 if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.fields {
abi::FieldsShape::Arbitrary { .. } => true,
_ => false,
}matches!(dest.layout.fields, abi::FieldsShape::Arbitrary { .. }) {
40 return false;
41 }
42 if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.variants {
abi::Variants::Single { index } if index == variant_index => true,
_ => false,
}matches!(dest.layout.variants, abi::Variants::Single { index } if index == variant_index)
50 {
51 return false;
52 }
53 if true {
{
match (&operands.len(), &dest.layout.fields.count()) {
(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!(operands.len(), dest.layout.fields.count());
56
57 let size = dest.layout.size.bytes();
58 let llty = match size {
59 1 => bx.cx().type_i8(),
60 2 => bx.cx().type_i16(),
61 4 => bx.cx().type_i32(),
62 8 => bx.cx().type_i64(),
63 16 => bx.cx().type_i128(),
64 _ => return false,
65 };
66
67 let mut value = 0u128;
68 for (field_idx, operand) in operands.iter_enumerated() {
69 let field_layout = dest.layout.field(bx.cx(), field_idx.as_usize());
70 if field_layout.is_zst() {
71 continue;
72 }
73 let mir::Operand::Constant(constant) = operand else {
74 return false;
75 };
76 let Some(field_value) = self.eval_mir_constant(constant).try_to_bits(field_layout.size)
77 else {
78 return false;
79 };
80
81 let field_size = field_layout.size.bytes();
82 let field_offset = dest.layout.fields.offset(field_idx.as_usize()).bytes();
83 if true {
if !(field_offset + field_size <= size) {
::core::panicking::panic("assertion failed: field_offset + field_size <= size")
};
};debug_assert!(field_offset + field_size <= size);
84 let shift = match bx.tcx().data_layout.endian {
85 abi::Endian::Little => field_offset * 8,
86 abi::Endian::Big => (size - field_offset - field_size) * 8,
87 };
88 value |= field_value << shift;
89 }
90
91 let value = bx.cx().const_uint_big(llty, value);
92 bx.store_to_place(value, dest.val);
93 true
94 }
95
96 fn is_entirely_uninit_const(&self, operand: &mir::Operand<'tcx>) -> bool {
97 let mir::Operand::Constant(const_op) = operand else { return false };
98 self.eval_mir_constant(const_op).all_bytes_uninit(self.cx.tcx())
99 }
100
101 {}
#[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_rvalue",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(101u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dest")
}> =
::tracing::__macro_support::FieldName::new("dest");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rvalue")
}> =
::tracing::__macro_support::FieldName::new("rvalue");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
as &dyn ::tracing::field::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: () = loop {};
return __tracing_attr_fake_return;
}
{
match *rvalue {
mir::Rvalue::Use(ref operand, with_retag) => {
if self.is_entirely_uninit_const(operand) { return; }
let cg_operand = self.codegen_operand(bx, operand);
if #[allow(non_exhaustive_omitted_patterns)] match cg_operand.layout.backend_repr
{
BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } =>
true,
_ => false,
} {
if true {
if !!#[allow(non_exhaustive_omitted_patterns)] match cg_operand.val
{
OperandValue::Ref(..) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: !matches!(cg_operand.val, OperandValue::Ref(..))")
};
};
}
let flags =
if let ty::Ref(_, pointee_ty, Mutability::Not) =
cg_operand.layout.ty.kind() && with_retag.yes() &&
pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env()) {
MemFlags::CAPTURES_READ_ONLY
} else { MemFlags::empty() };
cg_operand.store_with_annotation_and_flags(bx, dest, flags);
}
mir::Rvalue::Cast(mir::CastKind::PointerCoercion(PointerCoercion::Unsize,
_), ref source, _) => {
if let BackendRepr::ScalarPair { .. } =
dest.layout.backend_repr {
let temp = self.codegen_rvalue_operand(bx, rvalue);
temp.store_with_annotation(bx, dest);
return;
}
let operand = self.codegen_operand(bx, source);
match operand.val {
OperandValue::Pair(..) | OperandValue::Immediate(_) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/rvalue.rs:167",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(167u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_rvalue: creating ugly alloca")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let scratch = PlaceRef::alloca(bx, operand.layout);
scratch.storage_live(bx);
operand.store_with_annotation(bx, scratch);
base::coerce_unsized_into(bx, scratch, dest);
scratch.storage_dead(bx);
}
OperandValue::Ref(val) => {
if val.llextra.is_some() {
::rustc_span::macros::bug_impl(None,
format_args!("unsized coercion on an unsized rvalue"),
Location::caller());
}
base::coerce_unsized_into(bx, val.with_type(operand.layout),
dest);
}
OperandValue::ZeroSized => {
::rustc_span::macros::bug_impl(None,
format_args!("unsized coercion on a ZST rvalue"),
Location::caller());
}
}
}
mir::Rvalue::Cast(mir::CastKind::Transmute |
mir::CastKind::Subtype, ref operand, _ty) => {
let src = self.codegen_operand(bx, operand);
self.codegen_transmute(bx, src, dest);
}
mir::Rvalue::Repeat(ref elem, count) => {
if dest.layout.is_zst() { return; }
if self.is_entirely_uninit_const(elem) {
let size = bx.const_usize(dest.layout.size.bytes());
bx.memset(dest.val.llval, bx.const_undef(bx.type_i8()),
size, dest.val.align, MemFlags::empty());
return;
}
let cg_elem = self.codegen_operand(bx, elem);
let try_init_all_same =
|bx: &mut Bx, v|
{
let start = dest.val.llval;
let size = bx.const_usize(dest.layout.size.bytes());
if let Some(int) = bx.cx().const_to_opt_u128(v, false) &&
let bytes =
&int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()] &&
let Ok(&byte) = bytes.iter().all_equal_value() {
let fill = bx.cx().const_u8(byte);
bx.memset(start, fill, size, dest.val.align,
MemFlags::empty());
return true;
}
let v = bx.from_immediate(v);
if bx.cx().val_ty(v) == bx.cx().type_i8() {
bx.memset(start, v, size, dest.val.align,
MemFlags::empty());
return true;
}
false
};
if let OperandValue::Immediate(v) = cg_elem.val &&
try_init_all_same(bx, v) {
return;
}
let count =
self.monomorphize(count).try_to_target_usize(bx.tcx()).expect("expected monomorphic const in codegen");
bx.write_operand_repeatedly(cg_elem, count, dest);
}
mir::Rvalue::Aggregate(ref kind, ref operands) if
!#[allow(non_exhaustive_omitted_patterns)] match **kind {
mir::AggregateKind::RawPtr(..) => true,
_ => false,
} => {
if self.try_codegen_const_aggregate_as_immediate(bx, dest,
kind, operands) {
return;
}
let (variant_index, variant_dest, active_field_index) =
match **kind {
mir::AggregateKind::Adt(_, variant_index, _, _,
active_field_index) => {
let variant_dest = dest.project_downcast(bx, variant_index);
(variant_index, variant_dest, active_field_index)
}
_ => (FIRST_VARIANT, dest, None),
};
if active_field_index.is_some() {
{
match (&operands.len(), &1) {
(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);
}
}
}
};
}
for (i, operand) in operands.iter_enumerated() {
if self.is_entirely_uninit_const(operand) { continue; }
let op = self.codegen_operand(bx, operand);
if !op.layout.is_zst() {
let field_index = active_field_index.unwrap_or(i);
let field =
if let mir::AggregateKind::Array(_) = **kind {
let llindex =
bx.cx().const_usize(field_index.as_u32().into());
variant_dest.project_index(bx, llindex)
} else {
variant_dest.project_field(bx, field_index.as_usize())
};
op.store_with_annotation(bx, field);
}
}
dest.codegen_set_discr(bx, variant_index);
}
_ => {
let temp = self.codegen_rvalue_operand(bx, rvalue);
temp.store_with_annotation(bx, dest);
}
}
}
}
}#[instrument(level = "trace", skip(self, bx))]
102 pub(crate) fn codegen_rvalue(
103 &mut self,
104 bx: &mut Bx,
105 dest: PlaceRef<'tcx, Bx::Value>,
106 rvalue: &mir::Rvalue<'tcx>,
107 ) {
108 match *rvalue {
109 mir::Rvalue::Use(ref operand, with_retag) => {
110 if self.is_entirely_uninit_const(operand) {
111 return;
112 }
113 let cg_operand = self.codegen_operand(bx, operand);
114 if matches!(
118 cg_operand.layout.backend_repr,
119 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. },
120 ) {
121 debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
122 }
123 let flags = if let ty::Ref(_, pointee_ty, Mutability::Not) =
126 cg_operand.layout.ty.kind()
127 && with_retag.yes()
128 && pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env())
129 {
130 MemFlags::CAPTURES_READ_ONLY
131 } else {
132 MemFlags::empty()
133 };
134 cg_operand.store_with_annotation_and_flags(bx, dest, flags);
137 }
138
139 mir::Rvalue::Cast(
140 mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
141 ref source,
142 _,
143 ) => {
144 if let BackendRepr::ScalarPair { .. } = dest.layout.backend_repr {
147 let temp = self.codegen_rvalue_operand(bx, rvalue);
150 temp.store_with_annotation(bx, dest);
151 return;
152 }
153
154 let operand = self.codegen_operand(bx, source);
159 match operand.val {
160 OperandValue::Pair(..) | OperandValue::Immediate(_) => {
161 debug!("codegen_rvalue: creating ugly alloca");
168 let scratch = PlaceRef::alloca(bx, operand.layout);
169 scratch.storage_live(bx);
170 operand.store_with_annotation(bx, scratch);
171 base::coerce_unsized_into(bx, scratch, dest);
172 scratch.storage_dead(bx);
173 }
174 OperandValue::Ref(val) => {
175 if val.llextra.is_some() {
176 bug!("unsized coercion on an unsized rvalue");
177 }
178 base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
179 }
180 OperandValue::ZeroSized => {
181 bug!("unsized coercion on a ZST rvalue");
182 }
183 }
184 }
185
186 mir::Rvalue::Cast(
187 mir::CastKind::Transmute | mir::CastKind::Subtype,
188 ref operand,
189 _ty,
190 ) => {
191 let src = self.codegen_operand(bx, operand);
192 self.codegen_transmute(bx, src, dest);
193 }
194
195 mir::Rvalue::Repeat(ref elem, count) => {
196 if dest.layout.is_zst() {
198 return;
199 }
200
201 if self.is_entirely_uninit_const(elem) {
204 let size = bx.const_usize(dest.layout.size.bytes());
205 bx.memset(
206 dest.val.llval,
207 bx.const_undef(bx.type_i8()),
208 size,
209 dest.val.align,
210 MemFlags::empty(),
211 );
212 return;
213 }
214
215 let cg_elem = self.codegen_operand(bx, elem);
216
217 let try_init_all_same = |bx: &mut Bx, v| {
218 let start = dest.val.llval;
219 let size = bx.const_usize(dest.layout.size.bytes());
220
221 if let Some(int) = bx.cx().const_to_opt_u128(v, false)
223 && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
224 && let Ok(&byte) = bytes.iter().all_equal_value()
225 {
226 let fill = bx.cx().const_u8(byte);
227 bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
228 return true;
229 }
230
231 let v = bx.from_immediate(v);
233 if bx.cx().val_ty(v) == bx.cx().type_i8() {
234 bx.memset(start, v, size, dest.val.align, MemFlags::empty());
235 return true;
236 }
237 false
238 };
239
240 if let OperandValue::Immediate(v) = cg_elem.val
241 && try_init_all_same(bx, v)
242 {
243 return;
244 }
245
246 let count = self
247 .monomorphize(count)
248 .try_to_target_usize(bx.tcx())
249 .expect("expected monomorphic const in codegen");
250
251 bx.write_operand_repeatedly(cg_elem, count, dest);
252 }
253
254 mir::Rvalue::Aggregate(ref kind, ref operands)
257 if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
258 {
259 if self.try_codegen_const_aggregate_as_immediate(bx, dest, kind, operands) {
260 return;
261 }
262
263 let (variant_index, variant_dest, active_field_index) = match **kind {
264 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
265 let variant_dest = dest.project_downcast(bx, variant_index);
266 (variant_index, variant_dest, active_field_index)
267 }
268 _ => (FIRST_VARIANT, dest, None),
269 };
270 if active_field_index.is_some() {
271 assert_eq!(operands.len(), 1);
272 }
273 for (i, operand) in operands.iter_enumerated() {
274 if self.is_entirely_uninit_const(operand) {
277 continue;
278 }
279 let op = self.codegen_operand(bx, operand);
280 if !op.layout.is_zst() {
282 let field_index = active_field_index.unwrap_or(i);
283 let field = if let mir::AggregateKind::Array(_) = **kind {
284 let llindex = bx.cx().const_usize(field_index.as_u32().into());
285 variant_dest.project_index(bx, llindex)
286 } else {
287 variant_dest.project_field(bx, field_index.as_usize())
288 };
289 op.store_with_annotation(bx, field);
290 }
291 }
292 dest.codegen_set_discr(bx, variant_index);
293 }
294
295 _ => {
296 let temp = self.codegen_rvalue_operand(bx, rvalue);
297 temp.store_with_annotation(bx, dest);
298 }
299 }
300 }
301
302 fn codegen_transmute(
307 &mut self,
308 bx: &mut Bx,
309 src: OperandRef<'tcx, Bx::Value>,
310 dst: PlaceRef<'tcx, Bx::Value>,
311 ) {
312 if !src.layout.is_sized() {
::core::panicking::panic("assertion failed: src.layout.is_sized()")
};assert!(src.layout.is_sized());
314 if !dst.layout.is_sized() {
::core::panicking::panic("assertion failed: dst.layout.is_sized()")
};assert!(dst.layout.is_sized());
315
316 if src.layout.size != dst.layout.size
317 || src.layout.is_uninhabited()
318 || dst.layout.is_uninhabited()
319 {
320 bx.unreachable_nonterminator();
323 } else {
324 src.store_with_annotation(bx, dst.val.with_type(src.layout));
328 }
329 }
330
331 pub(crate) fn codegen_transmute_operand(
336 &mut self,
337 bx: &mut Bx,
338 operand: OperandRef<'tcx, Bx::Value>,
339 cast: TyAndLayout<'tcx>,
340 ) -> OperandValue<Bx::Value> {
341 if let abi::BackendRepr::Memory { .. } = cast.backend_repr
342 && !cast.is_zst()
343 {
344 ::rustc_span::macros::bug_impl(Some(self.mir.span),
format_args!("Use `codegen_transmute` to transmute to {0:?}", cast),
Location::caller());span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
345 }
346
347 if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
350 return operand.val;
351 }
352
353 if operand.layout.size != cast.size
355 || operand.layout.is_uninhabited()
356 || cast.is_uninhabited()
357 {
358 bx.unreachable_nonterminator();
359
360 return OperandValue::poison(bx, cast);
363 }
364
365 #[inline]
368 fn vector_can_bitcast(x: abi::Scalar) -> bool {
369 #[allow(non_exhaustive_omitted_patterns)] match x {
abi::Scalar::Initialized {
value: abi::Primitive::Int(..) | abi::Primitive::Float(..), .. } =>
true,
_ => false,
}matches!(
370 x,
371 abi::Scalar::Initialized {
372 value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
373 ..
374 }
375 )
376 }
377
378 let cx = bx.cx();
379 match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
380 _ if cast.is_zst() => OperandValue::ZeroSized,
381 (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
382 {
match (&source_place_val.llextra, &None) {
(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!(source_place_val.llextra, None);
383 bx.load_operand(source_place_val.with_type(cast)).val
386 }
387 (
388 OperandValue::Immediate(imm),
389 abi::BackendRepr::Scalar(from_scalar),
390 abi::BackendRepr::Scalar(to_scalar),
391 ) if from_scalar.size(cx) == to_scalar.size(cx) => {
392 OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
393 }
394 (
395 OperandValue::Immediate(imm),
396 abi::BackendRepr::SimdVector { element: from_scalar, .. },
397 abi::BackendRepr::SimdVector { element: to_scalar, .. },
398 ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
399 let to_backend_ty = bx.cx().immediate_backend_type(cast);
400 OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
401 }
402 (
403 OperandValue::Immediate(imm),
404 abi::BackendRepr::SimdScalableVector { element: from_scalar, .. },
405 abi::BackendRepr::SimdScalableVector { element: to_scalar, .. },
406 ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
407 let to_backend_ty = bx.cx().immediate_backend_type(cast);
408 OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
409 }
410 (
411 OperandValue::Pair(imm_a, imm_b),
412 abi::BackendRepr::ScalarPair { a: in_a, b: in_b, b_offset: in_offset },
413 abi::BackendRepr::ScalarPair { a: out_a, b: out_b, b_offset: out_offset },
414 ) if in_a.size(cx) == out_a.size(cx)
415 && in_b.size(cx) == out_b.size(cx)
416 && in_offset == out_offset =>
417 {
418 OperandValue::Pair(
419 transmute_scalar(bx, imm_a, in_a, out_a),
420 transmute_scalar(bx, imm_b, in_b, out_b),
421 )
422 }
423 _ => {
424 let align = Ord::max(operand.layout.align, cast.align);
434 let size = Ord::max(operand.layout.size, cast.size);
435 let temp = PlaceValue::alloca(bx, size, align);
436 bx.lifetime_start(temp.llval, size);
437 operand.store_with_annotation(bx, temp.with_type(operand.layout));
438 let val = bx.load_operand(temp.with_type(cast)).val;
439 bx.lifetime_end(temp.llval, size);
440 val
441 }
442 }
443 }
444
445 fn cast_immediate(
450 &self,
451 bx: &mut Bx,
452 mut imm: Bx::Value,
453 from_scalar: abi::Scalar,
454 from_backend_ty: Bx::Type,
455 to_scalar: abi::Scalar,
456 to_backend_ty: Bx::Type,
457 ) -> Option<Bx::Value> {
458 use abi::Primitive::*;
459
460 assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
465
466 imm = match (from_scalar.primitive(), to_scalar.primitive()) {
467 (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
468 (Float(src), Float(dst)) => match dst.size().cmp(&src.size()) {
469 Ordering::Greater => bx.fpext(imm, to_backend_ty),
470 Ordering::Less => bx.fptrunc(imm, to_backend_ty),
471 Ordering::Equal => imm,
472 },
473 (Int(_, is_signed), Float(_)) => {
474 if is_signed {
475 bx.sitofp(imm, to_backend_ty)
476 } else {
477 bx.uitofp(imm, to_backend_ty)
478 }
479 }
480 (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
481 (Int(_, is_signed), Pointer(..)) => {
482 let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
483 bx.inttoptr(usize_imm, to_backend_ty)
484 }
485 (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
486 _ => return None,
487 };
488 Some(imm)
489 }
490
491 pub(crate) fn codegen_rvalue_operand(
492 &mut self,
493 bx: &mut Bx,
494 rvalue: &mir::Rvalue<'tcx>,
495 ) -> OperandRef<'tcx, Bx::Value> {
496 match *rvalue {
497 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
498 let operand = self.codegen_operand(bx, source);
499 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/rvalue.rs:499",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(499u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cast operand is {0:?}",
operand) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("cast operand is {:?}", operand);
500 let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
501
502 let val = match *kind {
503 mir::CastKind::PointerExposeProvenance => {
504 if !cast.backend_repr.is_scalar_or_simd() {
::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
505 let llptr = operand.immediate();
506 let llcast_ty = bx.cx().immediate_backend_type(cast);
507 let lladdr = bx.ptrtoint(llptr, llcast_ty);
508 OperandValue::Immediate(lladdr)
509 }
510 mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
511 match *operand.layout.ty.kind() {
512 ty::FnDef(def_id, args) => {
513 let instance = ty::Instance::resolve_for_fn_ptr(
514 bx.tcx(),
515 bx.typing_env(),
516 def_id,
517 args.no_bound_vars().unwrap(),
518 )
519 .unwrap();
520 OperandValue::Immediate(
521 bx.get_fn_addr(
522 instance,
523 bx.sess().pointer_authentication_functions(),
524 ),
525 )
526 }
527 _ => ::rustc_span::macros::bug_impl(None,
format_args!("{0} cannot be reified to a fn ptr", operand.layout.ty),
Location::caller())bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
528 }
529 }
530 mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
531 match *operand.layout.ty.kind() {
532 ty::Closure(def_id, args) => {
533 let instance = Instance::resolve_closure(
534 bx.cx().tcx(),
535 def_id,
536 args,
537 ty::ClosureKind::FnOnce,
538 );
539 OperandValue::Immediate(
540 bx.cx().get_fn_addr(
541 instance,
542 bx.sess().pointer_authentication_functions(),
543 ),
544 )
545 }
546 _ => ::rustc_span::macros::bug_impl(None,
format_args!("{0} cannot be cast to a fn ptr", operand.layout.ty),
Location::caller())bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
547 }
548 }
549 mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
550 operand.val
552 }
553 mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
554 {
match cast.backend_repr {
BackendRepr::ScalarPair { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"BackendRepr::ScalarPair { .. }",
::core::option::Option::None);
}
}
};assert_matches!(cast.backend_repr, BackendRepr::ScalarPair { .. });
555 let (lldata, llextra) = operand.val.pointer_parts();
556 let (lldata, llextra) =
557 base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
558 OperandValue::Pair(lldata, llextra)
559 }
560 mir::CastKind::PointerCoercion(
561 PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
562 _,
563 ) => {
564 ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} is for borrowck, and should never appear in codegen",
kind), Location::caller());bug!("{kind:?} is for borrowck, and should never appear in codegen");
565 }
566 mir::CastKind::PtrToPtr if let BackendRepr::ScalarPair { .. } = operand.layout.backend_repr => {
567 if let OperandValue::Pair(data_ptr, meta) = operand.val {
568 if let BackendRepr::ScalarPair { .. } = cast.layout.backend_repr {
569 OperandValue::Pair(data_ptr, meta)
570 } else {
571 OperandValue::Immediate(data_ptr)
573 }
574 } else {
575 ::rustc_span::macros::bug_impl(None,
format_args!("unexpected non-pair operand"), Location::caller());bug!("unexpected non-pair operand");
576 }
577 }
578 | mir::CastKind::IntToInt
579 | mir::CastKind::FloatToInt
580 | mir::CastKind::FloatToFloat
581 | mir::CastKind::IntToFloat
582 | mir::CastKind::PtrToPtr
583 | mir::CastKind::FnPtrToPtr
584 | mir::CastKind::PointerWithExposedProvenance => {
588 let imm = operand.immediate();
589 let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
590 else {
591 ::rustc_span::macros::bug_impl(None,
format_args!("Found non-scalar for operand {0:?}", operand),
Location::caller());bug!("Found non-scalar for operand {operand:?}");
592 };
593 let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
594
595 if !cast.backend_repr.is_scalar_or_simd() {
::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
596 let to_backend_ty = bx.cx().immediate_backend_type(cast);
597 if operand.layout.is_uninhabited() {
598 let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
599 return OperandRef { val, layout: cast, move_annotation: None };
600 }
601 let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
602 ::rustc_span::macros::bug_impl(None,
format_args!("Found non-scalar for cast {0:?}", cast),
Location::caller());bug!("Found non-scalar for cast {cast:?}");
603 };
604
605 self.cast_immediate(
606 bx,
607 imm,
608 from_scalar,
609 from_backend_ty,
610 to_scalar,
611 to_backend_ty,
612 )
613 .map(OperandValue::Immediate)
614 .unwrap_or_else(|| {
615 ::rustc_span::macros::bug_impl(None,
format_args!("Unsupported cast of {0:?} to {1:?}", operand, cast),
Location::caller());bug!("Unsupported cast of {operand:?} to {cast:?}");
616 })
617 }
618 mir::CastKind::Transmute | mir::CastKind::BoxDerefTransmute | mir::CastKind::Subtype => {
619 self.codegen_transmute_operand(bx, operand, cast)
620 }
621 };
622 OperandRef { val, layout: cast, move_annotation: None }
623 }
624
625 mir::Rvalue::Ref(_, bk, place) => {
626 let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
627 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
628 };
629 let op = self.codegen_place_to_pointer(bx, place, mk_ref);
630 if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
631 self.codegen_retag_operand(bx, op, false)
632 } else {
633 op
634 }
635 }
636
637 mir::Rvalue::Reborrow(_, _, place) => {
642 self.codegen_operand(bx, &mir::Operand::Copy(place))
643 }
644
645 mir::Rvalue::RawPtr(kind, place) => {
646 let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
647 Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
648 };
649 self.codegen_place_to_pointer(bx, place, mk_ptr)
650 }
651
652 mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
653 if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
654 {
655 let lhs = self.codegen_operand(bx, lhs);
656 let rhs = self.codegen_operand(bx, rhs);
657 let result = self.codegen_scalar_checked_binop(
658 bx,
659 op,
660 lhs.immediate(),
661 rhs.immediate(),
662 lhs.layout.ty,
663 );
664 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
665 let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
666 OperandRef {
667 val: result,
668 layout: bx.cx().layout_of(operand_ty),
669 move_annotation: None,
670 }
671 }
672
673 mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
674 let lhs = self.codegen_operand(bx, lhs);
675 let rhs = self.codegen_operand(bx, rhs);
676 let llresult = match (lhs.val, rhs.val) {
677 (
678 OperandValue::Pair(lhs_addr, lhs_extra),
679 OperandValue::Pair(rhs_addr, rhs_extra),
680 ) => self.codegen_wide_ptr_binop(
681 bx,
682 op,
683 lhs_addr,
684 lhs_extra,
685 rhs_addr,
686 rhs_extra,
687 lhs.layout.ty,
688 ),
689
690 (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
691 .codegen_scalar_binop(
692 bx,
693 op,
694 lhs_val,
695 rhs_val,
696 lhs.layout.ty,
697 rhs.layout.ty,
698 ),
699
700 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
701 };
702 OperandRef {
703 val: OperandValue::Immediate(llresult),
704 layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
705 move_annotation: None,
706 }
707 }
708
709 mir::Rvalue::UnaryOp(op, ref operand) => {
710 let operand = self.codegen_operand(bx, operand);
711 let is_float = operand.layout.ty.is_floating_point();
712 let (val, layout) = match op {
713 mir::UnOp::Not => {
714 let llval = bx.not(operand.immediate());
715 (OperandValue::Immediate(llval), operand.layout)
716 }
717 mir::UnOp::Neg => {
718 let llval = if is_float {
719 bx.fneg(operand.immediate())
720 } else {
721 bx.neg(operand.immediate())
722 };
723 (OperandValue::Immediate(llval), operand.layout)
724 }
725 mir::UnOp::PtrMetadata => {
726 if !(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()) {
::core::panicking::panic("assertion failed: operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()")
};assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
727 let (_, meta) = operand.val.pointer_parts();
728 {
match (&(operand.layout.fields.count() > 1), &meta.is_some()) {
(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!(operand.layout.fields.count() > 1, meta.is_some());
729 if let Some(meta) = meta {
730 (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
731 } else {
732 (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
733 }
734 }
735 };
736 if !val.is_expected_variant_for_type(layout) {
{
::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
val, layout));
}
};assert!(
737 val.is_expected_variant_for_type(layout),
738 "Made wrong variant {val:?} for type {layout:?}",
739 );
740 OperandRef { val, layout, move_annotation: None }
741 }
742
743 mir::Rvalue::Discriminant(ref place) => {
744 let discr_ty = rvalue.ty(self.mir, bx.tcx());
745 let discr_ty = self.monomorphize(discr_ty);
746 let operand = self.codegen_consume(bx, place.as_ref());
747 let discr = operand.codegen_get_discr(self, bx, discr_ty);
748 OperandRef {
749 val: OperandValue::Immediate(discr),
750 layout: self.cx.layout_of(discr_ty),
751 move_annotation: None,
752 }
753 }
754
755 mir::Rvalue::ThreadLocalRef(def_id) => {
756 if !bx.cx().tcx().is_static(def_id) {
::core::panicking::panic("assertion failed: bx.cx().tcx().is_static(def_id)")
};assert!(bx.cx().tcx().is_static(def_id));
757 let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
758 let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
759 {
760 let instance = ty::Instance {
761 def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
762 args: ty::GenericArgs::empty(),
763 };
764 let fn_ptr =
765 bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
766 let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
767 let fn_ty = bx.fn_decl_backend_type(fn_abi);
768 let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
769 Some(bx.tcx().codegen_instance_attrs(instance.def))
770 } else {
771 None
772 };
773 bx.call(
774 fn_ty,
775 fn_attrs.as_deref(),
776 Some(fn_abi),
777 fn_ptr,
778 ReturnSlot::Direct,
779 &[],
780 None,
781 Some(instance),
782 )
783 } else {
784 bx.get_static(def_id)
785 };
786 OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
787 }
788
789 mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
790
791 mir::Rvalue::Repeat(ref elem, len_const) => {
792 let operand = self.codegen_operand(bx, elem);
796 let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
797 let array_ty = self.monomorphize(array_ty);
798 let array_layout = bx.layout_of(array_ty);
799 if !array_layout.is_zst() {
::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
800 OperandRef {
801 val: OperandValue::ZeroSized,
802 layout: array_layout,
803 move_annotation: None,
804 }
805 }
806
807 mir::Rvalue::Aggregate(ref kind, ref fields) => {
808 let (variant_index, active_field_index) = match **kind {
809 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
810 (variant_index, active_field_index)
811 }
812 _ => (FIRST_VARIANT, None),
813 };
814
815 let ty = rvalue.ty(self.mir, self.cx.tcx());
816 let ty = self.monomorphize(ty);
817 let layout = self.cx.layout_of(ty);
818
819 let mut builder = OperandRefBuilder::new(layout);
820 for (field_idx, field) in fields.iter_enumerated() {
821 let op = self.codegen_operand(bx, field);
822 let fi = active_field_index.unwrap_or(field_idx);
823 builder.insert_field(bx, variant_index, fi, op);
824 }
825
826 let tag_result = codegen_tag_value(self.cx, variant_index, layout);
827 match tag_result {
828 Err(super::place::UninhabitedVariantError) => {
829 bx.abort_immediate();
833 let val = OperandValue::poison(bx, layout);
834 OperandRef { val, layout, move_annotation: None }
835 }
836 Ok(maybe_tag_value) => {
837 if let Some((tag_field, tag_imm)) = maybe_tag_value {
838 builder.insert_imm(tag_field, tag_imm);
839 }
840 builder.build(bx.cx())
841 }
842 }
843 }
844
845 mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
846 let operand = self.codegen_operand(bx, operand);
847 let binder_ty = self.monomorphize(binder_ty);
848 let layout = bx.cx().layout_of(binder_ty);
849 OperandRef { val: operand.val, layout, move_annotation: None }
850 }
851
852 mir::Rvalue::CopyForDeref(_) => ::rustc_span::macros::bug_impl(None,
format_args!("`CopyForDeref` in codegen"), Location::caller())bug!("`CopyForDeref` in codegen"),
853 }
854 }
855
856 fn codegen_place_to_pointer(
858 &mut self,
859 bx: &mut Bx,
860 place: mir::Place<'tcx>,
861 mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
862 ) -> OperandRef<'tcx, Bx::Value> {
863 let cg_place = self.codegen_place(bx, place.as_ref());
864 let val = cg_place.val.address();
865
866 let ty = cg_place.layout.ty;
867 if !if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
#[allow(non_exhaustive_omitted_patterns)]
match val { OperandValue::Pair(..) => true, _ => false, }
} else {
#[allow(non_exhaustive_omitted_patterns)]
match val { OperandValue::Immediate(..) => true, _ => false, }
} {
{
::core::panicking::panic_fmt(format_args!("Address of place was unexpectedly {0:?} for pointee type {1:?}",
val, ty));
}
};assert!(
868 if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
869 matches!(val, OperandValue::Pair(..))
870 } else {
871 matches!(val, OperandValue::Immediate(..))
872 },
873 "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
874 );
875
876 OperandRef {
877 val,
878 layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
879 move_annotation: None,
880 }
881 }
882
883 fn codegen_scalar_binop(
884 &mut self,
885 bx: &mut Bx,
886 op: mir::BinOp,
887 lhs: Bx::Value,
888 rhs: Bx::Value,
889 lhs_ty: Ty<'tcx>,
890 rhs_ty: Ty<'tcx>,
891 ) -> Bx::Value {
892 let is_float = lhs_ty.is_floating_point();
893 let is_signed = lhs_ty.is_signed();
894 match op {
895 mir::BinOp::Add => {
896 if is_float {
897 bx.fadd(lhs, rhs)
898 } else {
899 bx.add(lhs, rhs)
900 }
901 }
902 mir::BinOp::AddUnchecked => {
903 if is_signed {
904 bx.unchecked_sadd(lhs, rhs)
905 } else {
906 bx.unchecked_uadd(lhs, rhs)
907 }
908 }
909 mir::BinOp::Sub => {
910 if is_float {
911 bx.fsub(lhs, rhs)
912 } else {
913 bx.sub(lhs, rhs)
914 }
915 }
916 mir::BinOp::SubUnchecked => {
917 if is_signed {
918 bx.unchecked_ssub(lhs, rhs)
919 } else {
920 bx.unchecked_usub(lhs, rhs)
921 }
922 }
923 mir::BinOp::Mul => {
924 if is_float {
925 bx.fmul(lhs, rhs)
926 } else {
927 bx.mul(lhs, rhs)
928 }
929 }
930 mir::BinOp::MulUnchecked => {
931 if is_signed {
932 bx.unchecked_smul(lhs, rhs)
933 } else {
934 bx.unchecked_umul(lhs, rhs)
935 }
936 }
937 mir::BinOp::Div => {
938 if is_float {
939 bx.fdiv(lhs, rhs)
940 } else if is_signed {
941 bx.sdiv(lhs, rhs)
942 } else {
943 bx.udiv(lhs, rhs)
944 }
945 }
946 mir::BinOp::Rem => {
947 if is_float {
948 bx.frem(lhs, rhs)
949 } else if is_signed {
950 bx.srem(lhs, rhs)
951 } else {
952 bx.urem(lhs, rhs)
953 }
954 }
955 mir::BinOp::BitOr => bx.or(lhs, rhs),
956 mir::BinOp::BitAnd => bx.and(lhs, rhs),
957 mir::BinOp::BitXor => bx.xor(lhs, rhs),
958 mir::BinOp::Offset => {
959 let pointee_type = lhs_ty
960 .builtin_deref(true)
961 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("deref of non-pointer {0:?}", lhs_ty), Location::caller())bug!("deref of non-pointer {:?}", lhs_ty));
962 let pointee_layout = bx.cx().layout_of(pointee_type);
963 if pointee_layout.is_zst() {
964 lhs
967 } else {
968 if !rhs_ty.is_signed() {
969 bx.inbounds_nuw_gep(pointee_layout.size, lhs, rhs)
970 } else {
971 bx.inbounds_gep(pointee_layout.size, lhs, rhs)
972 }
973 }
974 }
975 mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
976 let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
977 bx.shl(lhs, rhs)
978 }
979 mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
980 let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
981 if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
982 }
983 mir::BinOp::Ne
984 | mir::BinOp::Lt
985 | mir::BinOp::Gt
986 | mir::BinOp::Eq
987 | mir::BinOp::Le
988 | mir::BinOp::Ge => {
989 if is_float {
990 bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
991 } else {
992 bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
993 }
994 }
995 mir::BinOp::Cmp => {
996 if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
997 bx.three_way_compare(lhs_ty, lhs, rhs)
998 }
999 mir::BinOp::AddWithOverflow
1000 | mir::BinOp::SubWithOverflow
1001 | mir::BinOp::MulWithOverflow => {
1002 ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} needs to return a pair, so call codegen_scalar_checked_binop instead",
op), Location::caller())bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1003 }
1004 }
1005 }
1006
1007 fn codegen_wide_ptr_binop(
1008 &mut self,
1009 bx: &mut Bx,
1010 op: mir::BinOp,
1011 lhs_addr: Bx::Value,
1012 lhs_extra: Bx::Value,
1013 rhs_addr: Bx::Value,
1014 rhs_extra: Bx::Value,
1015 _input_ty: Ty<'tcx>,
1016 ) -> Bx::Value {
1017 match op {
1018 mir::BinOp::Eq => {
1019 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1020 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1021 bx.and(lhs, rhs)
1022 }
1023 mir::BinOp::Ne => {
1024 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1025 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1026 bx.or(lhs, rhs)
1027 }
1028 mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1029 let (op, strict_op) = match op {
1031 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1032 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1033 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1034 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1035 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
1036 };
1037 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1038 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1039 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1040 let rhs = bx.and(and_lhs, and_rhs);
1041 bx.or(lhs, rhs)
1042 }
1043 _ => {
1044 ::rustc_span::macros::bug_impl(None,
format_args!("unexpected wide ptr binop"), Location::caller());bug!("unexpected wide ptr binop");
1045 }
1046 }
1047 }
1048
1049 fn codegen_scalar_checked_binop(
1050 &mut self,
1051 bx: &mut Bx,
1052 op: mir::BinOp,
1053 lhs: Bx::Value,
1054 rhs: Bx::Value,
1055 input_ty: Ty<'tcx>,
1056 ) -> OperandValue<Bx::Value> {
1057 let (val, of) = match op {
1058 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1060 let oop = match op {
1061 mir::BinOp::Add => OverflowOp::Add,
1062 mir::BinOp::Sub => OverflowOp::Sub,
1063 mir::BinOp::Mul => OverflowOp::Mul,
1064 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1065 };
1066 bx.checked_binop(oop, input_ty, lhs, rhs)
1067 }
1068 _ => ::rustc_span::macros::bug_impl(None,
format_args!("Operator `{0:?}` is not a checkable operator", op),
Location::caller())bug!("Operator `{:?}` is not a checkable operator", op),
1069 };
1070
1071 OperandValue::Pair(val, of)
1072 }
1073}
1074
1075pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1083 bx: &mut Bx,
1084 mut imm: Bx::Value,
1085 from_scalar: abi::Scalar,
1086 to_scalar: abi::Scalar,
1087) -> Bx::Value {
1088 {
match (&from_scalar.size(bx.cx()), &to_scalar.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!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
1089 let imm_ty = bx.cx().val_ty(imm);
1090 if !bx.cx().vector_element_type(imm_ty).is_none() {
{
::core::panicking::panic_fmt(format_args!("Vector type {0:?} not allowed in transmute_scalar {1:?} -> {2:?}",
imm_ty, from_scalar, to_scalar));
}
};assert!(
1091 bx.cx().vector_element_type(imm_ty).is_none(),
1092 "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1093 );
1094
1095 if from_scalar == to_scalar {
1099 return imm;
1100 }
1101
1102 use abi::Primitive::*;
1103 imm = bx.from_immediate(imm);
1104
1105 let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1106 if true {
{
match (&bx.cx().val_ty(imm), &from_backend_ty) {
(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!(bx.cx().val_ty(imm), from_backend_ty);
1107 let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1108
1109 assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1119
1120 imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1121 (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1122 (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1123 (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1124 (Pointer(..), Int(..)) => {
1125 bx.ptrtoint(imm, to_backend_ty)
1127 }
1128 (Float(_), Pointer(..)) => {
1129 let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1130 bx.inttoptr(int_imm, to_backend_ty)
1131 }
1132 (Pointer(..), Float(_)) => {
1133 let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1135 bx.bitcast(int_imm, to_backend_ty)
1136 }
1137 };
1138
1139 if true {
{
match (&bx.cx().val_ty(imm), &to_backend_ty) {
(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!(bx.cx().val_ty(imm), to_backend_ty);
1140
1141 assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1147
1148 imm = bx.to_immediate_scalar(imm, to_scalar);
1149 imm
1150}
1151
1152fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1157 bx: &mut Bx,
1158 imm: Bx::Value,
1159 scalar: abi::Scalar,
1160 backend_ty: Bx::Type,
1161 known: Option<&abi::Scalar>,
1162) {
1163 if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
OptLevel::No => true,
_ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1164 return;
1165 }
1166
1167 match (scalar, known) {
1168 (abi::Scalar::Union { .. }, _) => return,
1169 (_, None) => {
1170 if scalar.is_always_valid(bx.cx()) {
1171 return;
1172 }
1173 }
1174 (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1175 let known_range = known.valid_range(bx.cx());
1176 if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1177 return;
1178 }
1179 }
1180 }
1181
1182 match scalar.primitive() {
1183 abi::Primitive::Int(..) => {
1184 let range = scalar.valid_range(bx.cx());
1185 bx.assume_integer_range(imm, backend_ty, range);
1186 }
1187 abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1188 if !scalar.valid_range(bx.cx()).contains(0) =>
1189 {
1190 bx.assume_nonnull(imm);
1191 }
1192 abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1193 }
1194}