Skip to main content

rustc_codegen_llvm/
intrinsic.rs

1use std::cmp::Ordering;
2use std::ffi::c_uint;
3use std::{assert_matches, iter, ptr};
4
5use rustc_abi::{
6    AddressSpace, Align, BackendRepr, CVariadicStatus, Float, HasDataLayout, NumScalableVectors,
7    Primitive, Size, WrappingRange,
8};
9use rustc_attr_ir::find_attr;
10use rustc_codegen_ssa::RetagInfo;
11use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
12use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
13use rustc_codegen_ssa::diagnostics::{ExpectedPointerMutability, InvalidMonomorphization};
14use rustc_codegen_ssa::mir::IntrinsicResult;
15use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
16use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
17use rustc_codegen_ssa::traits::*;
18use rustc_hir as hir;
19use rustc_hir::def_id::LOCAL_CRATE;
20use rustc_lint_defs::builtin::DEPRECATED_LLVM_INTRINSIC;
21use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAlloc, alloc_range};
22use rustc_middle::mir::{self, BinOp};
23use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
24use rustc_middle::ty::offload_meta::OffloadMetadata;
25use rustc_middle::ty::{self, GenericArgsRef, Instance, SimdAlign, Ty, TyCtxt};
26use rustc_session::diagnostics::feature_err;
27use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym};
28use rustc_structures::CrateType;
29use rustc_symbol_mangling::{
30    mangle_internal_symbol, mangle_offload_export, symbol_name_for_instance_in_crate,
31};
32use rustc_target::callconv::PassMode;
33use rustc_target::spec::Arch;
34use tracing::debug;
35
36use crate::abi::FnAbiLlvmExt;
37use crate::builder::Builder;
38use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
39use crate::builder::gpu_offload::{self, OffloadKernelDims, declare_omp_get_num_devices};
40use crate::context::CodegenCx;
41use crate::declare::declare_raw_fn;
42use crate::diagnostics::{
43    AutoDiffWithoutEnable, AutoDiffWithoutLto, IntrinsicSignatureMismatch, IntrinsicWrongArch,
44    OffloadWithoutEnable, OffloadWithoutFatLTO, UnknownIntrinsic,
45};
46use crate::intrinsic::ty::typetree::fnc_typetrees;
47use crate::llvm::{self, Attribute, AttributePlace, Metadata, Type, Value};
48use crate::type_of::LayoutLlvmExt;
49use crate::va_arg::emit_va_arg;
50
51fn call_simple_intrinsic<'ll, 'tcx>(
52    bx: &mut Builder<'_, 'll, 'tcx>,
53    name: Symbol,
54    args: &[OperandRef<'tcx, &'ll Value>],
55) -> Option<&'ll Value> {
56    let llvm_version = crate::llvm_util::get_version();
57    // minimum/maximum were broken for f64/f128 before
58    // <https://github.com/llvm/llvm-project/commit/56385af687c3a7a1f67716fb3f819336789a8cab>.
59    // We use the fallback body there.
60    let fixed_minmax = llvm_version >= (23, 0, 0);
61
62    let (base_name, type_params): (&'static str, &[&'ll Type]) = match name {
63        sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
64        sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
65        sym::minimumf64 if fixed_minmax => ("llvm.minimum", &[bx.type_f64()]),
66        sym::minimumf128 if fixed_minmax => ("llvm.minimum", &[bx.type_f128()]),
67
68        sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
69        sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
70        sym::maximumf64 if fixed_minmax => ("llvm.maximum", &[bx.type_f64()]),
71        sym::maximumf128 if fixed_minmax => ("llvm.maximum", &[bx.type_f128()]),
72
73        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
74        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
75        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
76        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
77
78        _ => return None,
79    };
80    Some(bx.call_intrinsic(
81        base_name,
82        type_params,
83        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
84    ))
85}
86
87impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> {
88    fn black_box(&mut self, result: PlaceRef<'tcx, &'ll Value>, span: Span) {
89        let result_val_span = [result.val.llval];
90        // We need to "use" the argument in some way LLVM can't introspect, and on
91        // targets that support it we can typically leverage inline assembly to do
92        // this. LLVM's interpretation of inline assembly is that it's, well, a black
93        // box. This isn't the greatest implementation since it probably deoptimizes
94        // more than we want, but it's so far good enough.
95        //
96        // For zero-sized types, the location pointed to by the result may be
97        // uninitialized. Do not "use" the result in this case; instead just clobber
98        // the memory.
99        let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
100            ("~{memory}", &[])
101        } else {
102            ("r,~{memory}", &result_val_span)
103        };
104        crate::asm::inline_asm_call(
105            self,
106            "",
107            constraint,
108            inputs,
109            self.type_void(),
110            &[],
111            true,
112            false,
113            llvm::AsmDialect::Att,
114            &[span],
115            false,
116            None,
117            None,
118        )
119        .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("failed to generate inline asm call for `black_box`"),
    Location::caller())bug!("failed to generate inline asm call for `black_box`"));
120    }
121}
122
123impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
124    fn codegen_intrinsic_call(
125        &mut self,
126        instance: ty::Instance<'tcx>,
127        args: &[OperandRef<'tcx, &'ll Value>],
128        result_layout: ty::layout::TyAndLayout<'tcx>,
129        result_place: Option<PlaceValue<&'ll Value>>,
130        span: Span,
131    ) -> IntrinsicResult<'tcx, &'ll Value> {
132        let tcx = self.tcx;
133        let llvm_version = crate::llvm_util::get_version();
134
135        let name = tcx.item_name(instance.def_id());
136        let fn_args = instance.args;
137
138        let simple = call_simple_intrinsic(self, name, args);
139        let llval = match name {
140            _ if simple.is_some() => simple.unwrap(),
141            sym::minimum_number_nsz_f16
142            | sym::minimum_number_nsz_f32
143            | sym::minimum_number_nsz_f64
144            | sym::minimum_number_nsz_f128
145            | sym::maximum_number_nsz_f16
146            | sym::maximum_number_nsz_f32
147            | sym::maximum_number_nsz_f64
148            | sym::maximum_number_nsz_f128 => {
149                let intrinsic_name = if name.as_str().starts_with("min") {
150                    "llvm.minimumnum"
151                } else {
152                    "llvm.maximumnum"
153                };
154                let call = self.call_intrinsic(
155                    intrinsic_name,
156                    &[args[0].layout.immediate_llvm_type(self.cx)],
157                    &[args[0].immediate(), args[1].immediate()],
158                );
159                // `nsz` on minimumnum/maximumnum is special: its only effect is to make
160                // signed-zero ordering non-deterministic.
161                unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
162                call
163            }
164            sym::ptr_mask => {
165                let ptr = args[0].immediate();
166                self.call_intrinsic(
167                    "llvm.ptrmask",
168                    &[self.val_ty(ptr), self.type_isize()],
169                    &[ptr, args[1].immediate()],
170                )
171            }
172            sym::autodiff => {
173                return codegen_autodiff(self, instance, args, result_layout, result_place);
174            }
175            sym::offload => {
176                if tcx.sess.opts.unstable_opts.offload.is_empty() {
177                    let _ = tcx.dcx().emit_err(OffloadWithoutEnable);
178                }
179
180                if tcx.sess.lto() != rustc_session::config::Lto::Fat {
181                    let _ = tcx.dcx().emit_err(OffloadWithoutFatLTO);
182                }
183
184                codegen_offload(self, tcx, instance, args);
185                // offload *has* a return type, but somehow works without mentioning the place
186                return IntrinsicResult::WroteIntoPlace;
187            }
188            sym::offload_get_num_devices => {
189                let (fn_decl, fn_ty) = declare_omp_get_num_devices(self.cx);
190
191                let llval =
192                    self.call(fn_ty, None, None, fn_decl, ReturnSlot::Direct, &[], None, None);
193
194                return IntrinsicResult::Operand(OperandValue::Immediate(llval));
195            }
196            sym::is_val_statically_known => {
197                if let OperandValue::Immediate(imm) = args[0].val {
198                    self.call_intrinsic(
199                        "llvm.is.constant",
200                        &[args[0].layout.immediate_llvm_type(self.cx)],
201                        &[imm],
202                    )
203                } else {
204                    self.const_bool(false)
205                }
206            }
207            sym::select_unpredictable => {
208                let cond = args[0].immediate();
209                {
    match (&args[1].layout, &args[2].layout) {
        (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!(args[1].layout, args[2].layout);
210                let select = |bx: &mut Self, true_val, false_val| {
211                    let result = bx.select(cond, true_val, false_val);
212                    bx.set_unpredictable(&result);
213                    result
214                };
215                match (args[1].val, args[2].val) {
216                    (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => {
217                        if !true_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: true_val.llextra.is_none()")
};assert!(true_val.llextra.is_none());
218                        if !false_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: false_val.llextra.is_none()")
};assert!(false_val.llextra.is_none());
219                        {
    match (&true_val.align, &false_val.align) {
        (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!(true_val.align, false_val.align);
220                        let ptr = select(self, true_val.llval, false_val.llval);
221                        let selected =
222                            OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align));
223                        let result = PlaceRef { val: result_place.unwrap(), layout: result_layout };
224                        selected.store(self, result);
225                        return IntrinsicResult::WroteIntoPlace;
226                    }
227                    (OperandValue::Immediate(_), OperandValue::Immediate(_))
228                    | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => {
229                        let true_val = args[1].immediate_or_packed_pair(self);
230                        let false_val = args[2].immediate_or_packed_pair(self);
231                        select(self, true_val, false_val)
232                    }
233                    (OperandValue::ZeroSized, OperandValue::ZeroSized) => {
234                        return IntrinsicResult::Operand(OperandValue::ZeroSized);
235                    }
236                    _ => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("Incompatible OperandValue for select_unpredictable"),
    Location::caller())span_bug!(span, "Incompatible OperandValue for select_unpredictable"),
237                }
238            }
239            sym::catch_unwind => catch_unwind_intrinsic(
240                self,
241                args[0].immediate(),
242                args[1].immediate(),
243                args[2].immediate(),
244            ),
245            sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[], &[]),
246            sym::va_arg => {
247                let target = &self.cx.tcx.sess.target;
248                let stability = target.supports_c_variadic_definitions();
249                if let CVariadicStatus::Unstable { feature } = stability
250                    && !self.tcx.features().enabled(feature)
251                {
252                    let msg =
253                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C-variadic function definitions on this target are unstable"))
    })format!("C-variadic function definitions on this target are unstable");
254                    feature_err(&*self.sess(), feature, span, msg).emit();
255                }
256
257                let BackendRepr::Scalar(scalar) = result_layout.backend_repr else {
258                    ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support non-scalar types"),
    Location::caller())bug!("the va_arg intrinsic does not support non-scalar types")
259                };
260
261                // We reject types that would never be passed as varargs in C because
262                // they get promoted to a larger type, specifically integers smaller than
263                // c_int and float type smaller than c_double.
264                match scalar.primitive() {
265                    Primitive::Pointer(_) => {
266                        // Pointers are always OK.
267                    }
268                    Primitive::Int(..) => {
269                        let int_width = self.cx().size_of(result_layout.ty).bits();
270                        let target_c_int_width = self.cx().sess().target.options.c_int_width;
271                        if int_width < u64::from(target_c_int_width) {
272                            // Smaller integer types are automatically promototed and `va_arg`
273                            // should not be called on them.
274                            ::rustc_span::macros::bug_impl(None,
    format_args!("va_arg got i{0} but needs at least c_int (an i{1})",
        int_width, target_c_int_width), Location::caller());bug!(
275                                "va_arg got i{} but needs at least c_int (an i{})",
276                                int_width,
277                                target_c_int_width
278                            );
279                        }
280                    }
281                    Primitive::Float(Float::F16) => {
282                        ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f16`"),
    Location::caller())bug!("the va_arg intrinsic does not support `f16`")
283                    }
284                    Primitive::Float(Float::F16B) => {
285                        ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f16b`"),
    Location::caller())bug!("the va_arg intrinsic does not support `f16b`")
286                    }
287                    Primitive::Float(Float::F32) => {
288                        // c_double is actually f32 on avr.
289                        if self.cx().sess().target.arch != Arch::Avr {
290                            ::rustc_span::macros::bug_impl(None,
    format_args!("the va_arg intrinsic does not support `f32` on this target"),
    Location::caller())bug!("the va_arg intrinsic does not support `f32` on this target")
291                        }
292                    }
293                    Primitive::Float(Float::F64) => {
294                        // 64-bit floats are always OK.
295                    }
296                    Primitive::Float(Float::F128) => {
297                        // Supported on some targets, especially where long double is IEEE f128.
298                    }
299                    Primitive::Float(Float::PpcF128) => {
300                        // Supported on powerpc and powerpc64 targets.
301                    }
302                }
303
304                emit_va_arg(self, args[0], result_layout)
305            }
306
307            sym::volatile_load | sym::unaligned_volatile_load => {
308                // Note that we cannot just load the `llvm_type` because we should never load non-scalars.
309                // Trying to do so blows up horribly in some cases -- for example loading a
310                // `MaybeUninint<&dyn Trait>` would load as `{ [i64x2] }` which gives assertions later
311                // (if we're lucky) from things not being pointers that ought to be.
312                let ptr = args[0].immediate();
313                let abi_align = result_layout.align.abi;
314                let ptr_align = if name == sym::volatile_load { abi_align } else { Align::ONE };
315                let need_black_box = llvm_version < (23, 0, 0);
316                if result_layout.is_zst() {
317                    return IntrinsicResult::Operand(OperandValue::ZeroSized);
318                } else if let BackendRepr::Scalar(scalar) = result_layout.backend_repr
319                    && !need_black_box
320                {
321                    let load = self.volatile_load(self.type_from_scalar(scalar), ptr, ptr_align);
322                    self.to_immediate_scalar(load, scalar)
323                } else {
324                    // One day Rust will probably want to define how we split up a volatile load
325                    // of something that's *not* just an ordinary scalar, but for now we can just
326                    // use an LLVM integer type of the correct width and let it split it however.
327                    let llty = self.type_ix(result_layout.size.bits());
328                    let temp = if let Some(result_place) = result_place {
329                        PlaceRef { val: result_place, layout: result_layout }
330                    } else {
331                        PlaceRef::alloca(self, result_layout)
332                    };
333                    let llval = self.volatile_load(llty, ptr, ptr_align);
334                    self.store(llval, temp.val.llval, abi_align);
335                    if need_black_box {
336                        // LLVM up until v22 considers volatile reads `willreturn` and hence can
337                        // move UB from further down up across this read. To prevent that, insert an
338                        // inline asm block that, as far as LLVM is concerned, might not terminate,
339                        // and hence should prevent such reordering.
340                        self.black_box(temp, span);
341                    }
342                    return if result_place.is_none() {
343                        IntrinsicResult::Operand(self.load_operand(temp).val)
344                    } else {
345                        IntrinsicResult::WroteIntoPlace
346                    };
347                }
348            }
349            sym::prefetch_read_data
350            | sym::prefetch_write_data
351            | sym::prefetch_read_instruction
352            | sym::prefetch_write_instruction => {
353                let (rw, cache_type) = match name {
354                    sym::prefetch_read_data => (0, 1),
355                    sym::prefetch_write_data => (1, 1),
356                    sym::prefetch_read_instruction => (0, 0),
357                    sym::prefetch_write_instruction => (1, 0),
358                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
359                };
360                let ptr = args[0].immediate();
361                let locality = fn_args.const_at(1).to_leaf().to_i32();
362                self.call_intrinsic(
363                    "llvm.prefetch.p0",
364                    &[self.val_ty(ptr)],
365                    &[
366                        ptr,
367                        self.const_i32(rw),
368                        self.const_i32(locality),
369                        self.const_i32(cache_type),
370                    ],
371                );
372                return IntrinsicResult::Operand(OperandValue::ZeroSized);
373            }
374            sym::carrying_mul_add => {
375                let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx);
376
377                let wide_llty = self.type_ix(size.bits() * 2);
378                let args = args.as_array().unwrap();
379                let [a, b, c, d] = args.map(|a| self.intcast(a.immediate(), wide_llty, signed));
380
381                let wide = if signed {
382                    let prod = self.unchecked_smul(a, b);
383                    let acc = self.unchecked_sadd(prod, c);
384                    self.unchecked_sadd(acc, d)
385                } else {
386                    let prod = self.unchecked_umul(a, b);
387                    let acc = self.unchecked_uadd(prod, c);
388                    self.unchecked_uadd(acc, d)
389                };
390
391                let narrow_llty = self.type_ix(size.bits());
392                let low = self.trunc(wide, narrow_llty);
393                let bits_const = self.const_uint(wide_llty, size.bits());
394                // No need for ashr when signed; LLVM changes it to lshr anyway.
395                let high = self.lshr(wide, bits_const);
396                // FIXME: could be `trunc nuw`, even for signed.
397                let high = self.trunc(high, narrow_llty);
398
399                let pair_llty = self.type_struct(&[narrow_llty, narrow_llty], false);
400                let pair = self.const_poison(pair_llty);
401                let pair = self.insert_value(pair, low, 0);
402                let pair = self.insert_value(pair, high, 1);
403                pair
404            }
405
406            sym::ctlz
407            | sym::ctlz_nonzero
408            | sym::cttz
409            | sym::cttz_nonzero
410            | sym::ctpop
411            | sym::bswap
412            | sym::bitreverse
413            | sym::carryless_mul
414            | sym::integer_max
415            | sym::integer_min
416            | sym::saturating_add
417            | sym::saturating_sub
418            | sym::unchecked_funnel_shl
419            | sym::unchecked_funnel_shr => {
420                let ty = args[0].layout.ty;
421                if !ty.is_integral() {
422                    let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
423                        span,
424                        name,
425                        ty,
426                    });
427                    return IntrinsicResult::Err(err);
428                }
429                let (size, signed) = ty.int_size_and_signed(self.tcx);
430                let width = size.bits();
431                let llty = self.type_ix(width);
432                match name {
433                    sym::ctlz | sym::ctlz_nonzero | sym::cttz | sym::cttz_nonzero => {
434                        let y =
435                            self.const_bool(name == sym::ctlz_nonzero || name == sym::cttz_nonzero);
436                        let llvm_name = if name == sym::ctlz || name == sym::ctlz_nonzero {
437                            "llvm.ctlz"
438                        } else {
439                            "llvm.cttz"
440                        };
441                        let ret =
442                            self.call_intrinsic(llvm_name, &[llty], &[args[0].immediate(), y]);
443                        self.intcast(ret, result_layout.llvm_type(self), false)
444                    }
445                    sym::ctpop => self.ctpop(args[0].immediate()),
446                    sym::bswap => {
447                        if width == 8 {
448                            args[0].immediate() // byte swap a u8/i8 is just a no-op
449                        } else {
450                            self.call_intrinsic("llvm.bswap", &[llty], &[args[0].immediate()])
451                        }
452                    }
453                    sym::bitreverse => {
454                        self.call_intrinsic("llvm.bitreverse", &[llty], &[args[0].immediate()])
455                    }
456                    sym::carryless_mul => {
457                        let lhs = args[0].immediate();
458                        let rhs = args[1].immediate();
459                        self.call_intrinsic("llvm.clmul", &[llty], &[lhs, rhs])
460                    }
461                    sym::integer_min | sym::integer_max => {
462                        let lhs = args[0].immediate();
463                        let rhs = args[1].immediate();
464                        let llvm_name = match (name, signed) {
465                            (sym::integer_max, false) => "llvm.umax",
466                            (sym::integer_max, true) => "llvm.smax",
467                            (sym::integer_min, false) => "llvm.umin",
468                            (sym::integer_min, true) => "llvm.smin",
469                            _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
470                        };
471                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
472                    }
473                    sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
474                        let is_left = name == sym::unchecked_funnel_shl;
475                        let lhs = args[0].immediate();
476                        let rhs = args[1].immediate();
477                        let raw_shift = args[2].immediate();
478                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.fsh{0}",
                if is_left { 'l' } else { 'r' }))
    })format!("llvm.fsh{}", if is_left { 'l' } else { 'r' });
479
480                        // llvm expects shift to be the same type as the values, but rust
481                        // always uses `u32`.
482                        let raw_shift = self.intcast(raw_shift, self.val_ty(lhs), false);
483
484                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs, raw_shift])
485                    }
486                    sym::saturating_add | sym::saturating_sub => {
487                        let is_add = name == sym::saturating_add;
488                        let lhs = args[0].immediate();
489                        let rhs = args[1].immediate();
490                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
491                            "llvm.{}{}.sat",
492                            if signed { 's' } else { 'u' },
493                            if is_add { "add" } else { "sub" },
494                        );
495                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
496                    }
497                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
498                }
499            }
500
501            sym::fabs
502            | sym::sqrt
503            | sym::powf
504            | sym::fma
505            | sym::fmuladd
506            | sym::floor
507            | sym::ceil
508            | sym::trunc
509            | sym::round
510            | sym::round_ties_even
511            | sym::exp
512            | sym::exp2
513            | sym::log
514            | sym::log10
515            | sym::log2
516            | sym::sin
517            | sym::cos
518            | sym::powi => {
519                let ty = args[0].layout.ty;
520                let ty::Float(f) = ty.kind() else {
521                    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("the `{0}` intrinsic requires a floating-point argument, got {1:?}",
        name, ty), Location::caller());span_bug!(
522                        span,
523                        "the `{}` intrinsic requires a floating-point argument, got {:?}",
524                        name,
525                        ty
526                    );
527                };
528                let llty = self.type_float_from_ty(*f);
529                let llvm_name = match name {
530                    sym::fabs => "llvm.fabs",
531                    sym::sqrt => "llvm.sqrt",
532                    sym::powf => "llvm.pow",
533                    sym::fma => "llvm.fma",
534                    sym::fmuladd => "llvm.fmuladd",
535                    sym::floor => "llvm.floor",
536                    sym::ceil => "llvm.ceil",
537                    sym::trunc => "llvm.trunc",
538                    sym::round => "llvm.round",
539                    // We could use any of `rint`, `nearbyint`, or `roundeven`
540                    // for this -- they are all identical in semantics when
541                    // assuming the default FP environment.
542                    // `rint` is what we used for $forever.
543                    sym::round_ties_even => "llvm.rint",
544                    sym::exp => "llvm.exp",
545                    sym::exp2 => "llvm.exp2",
546                    sym::log => "llvm.log",
547                    sym::log10 => "llvm.log10",
548                    sym::log2 => "llvm.log2",
549                    sym::sin => "llvm.sin",
550                    sym::cos => "llvm.cos",
551                    sym::powi => "llvm.powi",
552
553                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
554                };
555
556                let params: &[&'ll Type] = match name {
557                    sym::powi => &[llty, self.type_i32()],
558                    _ => &[llty],
559                };
560
561                self.call_intrinsic(
562                    llvm_name,
563                    params,
564                    &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
565                )
566            }
567
568            sym::raw_eq => {
569                use BackendRepr::*;
570                let tp_ty = fn_args.type_at(0);
571                let layout = self.layout_of(tp_ty).layout;
572                let use_integer_compare = match layout.backend_repr() {
573                    Scalar(_) | ScalarPair { a: _, b: _, b_offset: _ } => true,
574                    SimdVector { .. } => false,
575                    SimdScalableVector { .. } => {
576                        let err = tcx.dcx().emit_err(InvalidMonomorphization::NonScalableType {
577                            span,
578                            name: sym::raw_eq,
579                            ty: tp_ty,
580                        });
581                        return IntrinsicResult::Err(err);
582                    }
583                    Memory { .. } => {
584                        // For rusty ABIs, small aggregates are actually passed
585                        // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
586                        // so we re-use that same threshold here.
587                        layout.size() <= self.data_layout().pointer_size() * 2
588                    }
589                };
590
591                let a = args[0].immediate();
592                let b = args[1].immediate();
593                if layout.size().bytes() == 0 {
594                    self.const_bool(true)
595                } else if use_integer_compare {
596                    let integer_ty = self.type_ix(layout.size().bits());
597                    let a_val = self.load(integer_ty, a, layout.align().abi);
598                    let b_val = self.load(integer_ty, b, layout.align().abi);
599                    self.icmp(IntPredicate::IntEQ, a_val, b_val)
600                } else {
601                    let n = self.const_usize(layout.size().bytes());
602                    let cmp = self.call_intrinsic("memcmp", &[], &[a, b, n]);
603                    self.icmp(IntPredicate::IntEQ, cmp, self.const_int(self.type_int(), 0))
604                }
605            }
606
607            sym::compare_bytes => {
608                // Here we assume that the `memcmp` provided by the target is a NOP for size 0.
609                let cmp = self.call_intrinsic(
610                    "memcmp",
611                    &[],
612                    &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
613                );
614                // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
615                self.sext(cmp, self.type_ix(32))
616            }
617
618            sym::black_box => {
619                // This `unwrap` is justified by `intrinsic_call_expects_place_always` declaring
620                // this intrinsic as always needing a return place.
621                let result = PlaceRef { val: result_place.unwrap(), layout: result_layout };
622                args[0].val.store(self, result);
623                self.black_box(result, span);
624
625                // We have copied the value to `result` already.
626                return IntrinsicResult::WroteIntoPlace;
627            }
628
629            sym::gpu_launch_sized_workgroup_mem => {
630                // Generate an anonymous global per call, with these properties:
631                // 1. The global is in the address space for workgroup memory
632                // 2. It is an `external` global
633                // 3. It is correctly aligned for the pointee `T`
634                // All instances of extern addrspace(gpu_workgroup) globals are merged in the LLVM backend.
635                // The name is irrelevant.
636                // See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
637                let name = if llvm_version < (23, 0, 0) && tcx.sess.target.arch == Arch::Nvptx64 {
638                    // The auto-assigned name for extern shared globals in the nvptx backend does
639                    // not compile in ptxas. Workaround this issue by assigning a name.
640                    // Fixed in LLVM 23.
641                    "gpu_launch_sized_workgroup_mem"
642                } else {
643                    ""
644                };
645                let global = self.declare_global_in_addrspace(
646                    name,
647                    self.type_array(self.type_i8(), 0),
648                    AddressSpace::GPU_WORKGROUP,
649                );
650                let ty::RawPtr(inner_ty, _) = result_layout.ty.kind() else { ::core::panicking::unreachable_default_msg()unreachable!() };
651                // The alignment of the global is used to specify the *minimum* alignment that
652                // must be obeyed by the GPU runtime.
653                // When multiple of these global variables are used by a kernel, the maximum alignment is taken.
654                // See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
655                let alignment = self.align_of(*inner_ty).bytes() as u32;
656                unsafe {
657                    // FIXME Workaround the above issue by taking maximum alignment if the global existed
658                    if tcx.sess.target.arch == Arch::Nvptx64 {
659                        if alignment > llvm::LLVMGetAlignment(global) {
660                            llvm::LLVMSetAlignment(global, alignment);
661                        }
662                    } else {
663                        llvm::LLVMSetAlignment(global, alignment);
664                    }
665                }
666                self.cx().const_pointercast(global, self.type_ptr())
667            }
668
669            sym::amdgpu_dispatch_ptr => {
670                let val = self.call_intrinsic("llvm.amdgcn.dispatch.ptr", &[], &[]);
671                // Relying on `LLVMBuildPointerCast` to produce an addrspacecast
672                self.pointercast(val, self.type_ptr())
673            }
674
675            sym::sve_tuple_create2 => {
676                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
677                    self.layout_of(fn_args.type_at(0)).backend_repr,
678                    BackendRepr::SimdScalableVector {
679                        number_of_vectors: NumScalableVectors(1),
680                        ..
681                    }
682                );
683                let tuple_ty = self.layout_of(fn_args.type_at(1));
684                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
685                    tuple_ty.backend_repr,
686                    BackendRepr::SimdScalableVector {
687                        number_of_vectors: NumScalableVectors(2),
688                        ..
689                    }
690                );
691                let ret = self.const_poison(self.backend_type(tuple_ty));
692                let ret = self.insert_value(ret, args[0].immediate(), 0);
693                self.insert_value(ret, args[1].immediate(), 1)
694            }
695
696            sym::sve_tuple_create3 => {
697                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
698                    self.layout_of(fn_args.type_at(0)).backend_repr,
699                    BackendRepr::SimdScalableVector {
700                        number_of_vectors: NumScalableVectors(1),
701                        ..
702                    }
703                );
704                let tuple_ty = self.layout_of(fn_args.type_at(1));
705                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(3), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(3), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
706                    tuple_ty.backend_repr,
707                    BackendRepr::SimdScalableVector {
708                        number_of_vectors: NumScalableVectors(3),
709                        ..
710                    }
711                );
712                let ret = self.const_poison(self.backend_type(tuple_ty));
713                let ret = self.insert_value(ret, args[0].immediate(), 0);
714                let ret = self.insert_value(ret, args[1].immediate(), 1);
715                self.insert_value(ret, args[2].immediate(), 2)
716            }
717
718            sym::sve_tuple_create4 => {
719                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
720                    self.layout_of(fn_args.type_at(0)).backend_repr,
721                    BackendRepr::SimdScalableVector {
722                        number_of_vectors: NumScalableVectors(1),
723                        ..
724                    }
725                );
726                let tuple_ty = self.layout_of(fn_args.type_at(1));
727                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(4), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(4), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
728                    tuple_ty.backend_repr,
729                    BackendRepr::SimdScalableVector {
730                        number_of_vectors: NumScalableVectors(4),
731                        ..
732                    }
733                );
734                let ret = self.const_poison(self.backend_type(tuple_ty));
735                let ret = self.insert_value(ret, args[0].immediate(), 0);
736                let ret = self.insert_value(ret, args[1].immediate(), 1);
737                let ret = self.insert_value(ret, args[2].immediate(), 2);
738                self.insert_value(ret, args[3].immediate(), 3)
739            }
740
741            sym::sve_tuple_get => {
742                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
            .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
743                    self.layout_of(fn_args.type_at(0)).backend_repr,
744                    BackendRepr::SimdScalableVector {
745                        number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
746                        ..
747                    }
748                );
749                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
750                    self.layout_of(fn_args.type_at(1)).backend_repr,
751                    BackendRepr::SimdScalableVector {
752                        number_of_vectors: NumScalableVectors(1),
753                        ..
754                    }
755                );
756                self.extract_value(
757                    args[0].immediate(),
758                    fn_args.const_at(2).to_leaf().to_i32() as u64,
759                )
760            }
761
762            sym::sve_tuple_set => {
763                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
            .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
764                    self.layout_of(fn_args.type_at(0)).backend_repr,
765                    BackendRepr::SimdScalableVector {
766                        number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
767                        ..
768                    }
769                );
770                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
771                    self.layout_of(fn_args.type_at(1)).backend_repr,
772                    BackendRepr::SimdScalableVector {
773                        number_of_vectors: NumScalableVectors(1),
774                        ..
775                    }
776                );
777                self.insert_value(
778                    args[0].immediate(),
779                    args[1].immediate(),
780                    fn_args.const_at(2).to_leaf().to_i32() as u64,
781                )
782            }
783
784            _ if name.as_str().starts_with("simd_") => {
785                // Unpack non-power-of-2 #[repr(packed, simd)] arguments.
786                // This gives them the expected layout of a regular #[repr(simd)] vector.
787                let mut loaded_args = Vec::new();
788                for arg in args {
789                    loaded_args.push(
790                        // #[repr(packed, simd)] vectors are passed like arrays (as references,
791                        // with reduced alignment and no padding) rather than as immediates.
792                        // We can use a vector load to fix the layout and turn the argument
793                        // into an immediate.
794                        if arg.layout.ty.is_simd()
795                            && let OperandValue::Ref(place) = arg.val
796                        {
797                            let (size, elem_ty) = arg.layout.ty.simd_size_and_type(self.tcx());
798                            let elem_ll_ty = match elem_ty.kind() {
799                                ty::Float(f) => self.type_float_from_ty(*f),
800                                ty::Int(i) => self.type_int_from_ty(*i),
801                                ty::Uint(u) => self.type_uint_from_ty(*u),
802                                ty::RawPtr(_, _) => self.type_ptr(),
803                                _ => ::core::panicking::unreachable_default_msg()unreachable!(),
804                            };
805                            let loaded =
806                                self.load_from_place(self.type_vector(elem_ll_ty, size), place);
807                            OperandRef::from_immediate_or_packed_pair(self, loaded, arg.layout)
808                        } else {
809                            *arg
810                        },
811                    );
812                }
813
814                let llret_ty = if result_layout.ty.is_simd()
815                    && let BackendRepr::Memory { .. } = result_layout.backend_repr
816                {
817                    let (size, elem_ty) = result_layout.ty.simd_size_and_type(self.tcx());
818                    let elem_ll_ty = match elem_ty.kind() {
819                        ty::Float(f) => self.type_float_from_ty(*f),
820                        ty::Int(i) => self.type_int_from_ty(*i),
821                        ty::Uint(u) => self.type_uint_from_ty(*u),
822                        ty::RawPtr(_, _) => self.type_ptr(),
823                        _ => ::core::panicking::unreachable_default_msg()unreachable!(),
824                    };
825                    self.type_vector(elem_ll_ty, size)
826                } else {
827                    result_layout.llvm_type(self)
828                };
829
830                match generic_simd_intrinsic(
831                    self,
832                    name,
833                    fn_args,
834                    &loaded_args,
835                    result_layout.ty,
836                    llret_ty,
837                    span,
838                ) {
839                    Ok(llval) => llval,
840                    // If there was an error, just skip this invocation... we'll abort compilation
841                    // anyway, but we can keep codegen'ing to find more errors.
842                    Err(err) => return IntrinsicResult::Err(err),
843                }
844            }
845
846            sym::return_address => {
847                match self.sess().target.arch {
848                    // Expand this list as needed
849                    Arch::Wasm32 | Arch::Wasm64 => {
850                        let ty = self.type_ptr();
851                        self.const_null(ty)
852                    }
853                    _ => {
854                        let ty = self.type_ix(32);
855                        let val = self.const_int(ty, 0);
856
857                        let type_params: &[&'ll Type] =
858                            if llvm_version < (23, 0, 0) { &[] } else { &[self.type_ptr()] };
859
860                        self.call_intrinsic("llvm.returnaddress", type_params, &[val])
861                    }
862                }
863            }
864
865            sym::codeview_annotation => {
866                if self.sess().target.uses_pdb_debuginfo() {
867                    codegen_codeview_annotation(self, instance, span);
868                }
869                return IntrinsicResult::Operand(OperandValue::ZeroSized);
870            }
871
872            _ => {
873                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/12433c307b5a497388ffe2f4e49dbf1ab8c71fa0/compiler/rustc_codegen_llvm/src/intrinsic.rs:873",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/12433c307b5a497388ffe2f4e49dbf1ab8c71fa0/compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(873u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::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!("unknown intrinsic \'{0}\' -- falling back to default body",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("unknown intrinsic '{}' -- falling back to default body", name);
874                // Call the fallback body instead of generating the intrinsic code
875                let fallback = ty::Instance::new_raw(instance.def_id(), instance.args);
876                return IntrinsicResult::Fallback(fallback);
877            }
878        };
879
880        if let BackendRepr::Memory { .. } = result_layout.backend_repr {
881            // We have an llvm immediate, but that's not what cg_ssa expects,
882            // so write it into the place (that always exists for memory)
883            if !result_layout.is_zst() {
884                self.store_to_place(llval, result_place.unwrap());
885            }
886            IntrinsicResult::WroteIntoPlace
887        } else {
888            IntrinsicResult::Operand(
889                OperandRef::from_immediate_or_packed_pair(self, llval, result_layout).val,
890            )
891        }
892    }
893
894    fn codegen_llvm_intrinsic_call(
895        &mut self,
896        instance: ty::Instance<'tcx>,
897        args: &[OperandRef<'tcx, Self::Value>],
898        _is_cleanup: bool,
899    ) -> Self::Value {
900        let tcx = self.tcx();
901
902        let fn_ty = instance.ty(tcx, self.typing_env());
903        let fn_sig = match *fn_ty.kind() {
904            ty::FnDef(def_id, args) => tcx.instantiate_bound_regions_with_erased(
905                tcx.fn_sig(def_id).instantiate(tcx, args.no_bound_vars().unwrap()).skip_norm_wip(),
906            ),
907            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
908        };
909        if !!fn_sig.c_variadic() {
    ::core::panicking::panic("assertion failed: !fn_sig.c_variadic()")
};assert!(!fn_sig.c_variadic());
910
911        let ret_layout = self.layout_of(fn_sig.output());
912        let llreturn_ty = if ret_layout.is_zst() {
913            self.type_void()
914        } else {
915            ret_layout.immediate_llvm_type(self)
916        };
917
918        let mut llargument_tys = Vec::with_capacity(fn_sig.inputs().len());
919        for &arg in fn_sig.inputs() {
920            let arg_layout = self.layout_of(arg);
921            if arg_layout.is_zst() {
922                continue;
923            }
924            llargument_tys.push(arg_layout.immediate_llvm_type(self));
925        }
926
927        let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) {
928            llfn
929        } else {
930            let sym = tcx.symbol_name(instance).name;
931
932            let llfn = if let Some(llfn) = self.get_declared_value(sym) {
933                llfn
934            } else {
935                intrinsic_fn(self, sym, llreturn_ty, llargument_tys, instance)
936            };
937
938            self.intrinsic_instances.borrow_mut().insert(instance, llfn);
939
940            llfn
941        };
942        let fn_ty = self.get_type_of_global(fn_ptr);
943
944        let mut llargs = ::alloc::vec::Vec::new()vec![];
945
946        for arg in args {
947            match arg.val {
948                OperandValue::ZeroSized => {}
949                OperandValue::Immediate(a) => llargs.push(a),
950                OperandValue::Pair(a, b) => {
951                    llargs.push(a);
952                    llargs.push(b);
953                }
954                OperandValue::Ref(op_place_val) => {
955                    let mut llval = op_place_val.llval;
956                    // We can't use `PlaceRef::load` here because the argument
957                    // may have a type we don't treat as immediate, but the ABI
958                    // used for this call is passing it by-value. In that case,
959                    // the load would just produce `OperandValue::Ref` instead
960                    // of the `OperandValue::Immediate` we need for the call.
961                    llval = self.load(self.backend_type(arg.layout), llval, op_place_val.align);
962                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
963                        if scalar.is_bool() {
964                            self.range_metadata(llval, WrappingRange { start: 0, end: 1 });
965                        }
966                        // We store bools as `i8` so we need to truncate to `i1`.
967                        llval = self.to_immediate_scalar(llval, scalar);
968                    }
969                    llargs.push(llval);
970                }
971            }
972        }
973
974        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/12433c307b5a497388ffe2f4e49dbf1ab8c71fa0/compiler/rustc_codegen_llvm/src/intrinsic.rs:974",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/12433c307b5a497388ffe2f4e49dbf1ab8c71fa0/compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(974u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::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!("call intrinsic {0:?} with args ({1:?})",
                                                    instance, llargs) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call intrinsic {:?} with args ({:?})", instance, llargs);
975
976        for (dest_ty, arg) in iter::zip(self.func_params_types(fn_ty), &mut llargs) {
977            let src_ty = self.val_ty(arg);
978            if !can_autocast(self, src_ty, dest_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with {1:?} (found) in `{2:?}",
                dest_ty, src_ty, fn_ptr));
    }
};assert!(
979                can_autocast(self, src_ty, dest_ty),
980                "Cannot match `{dest_ty:?}` (expected) with {src_ty:?} (found) in `{fn_ptr:?}"
981            );
982
983            *arg = autocast(self, arg, src_ty, dest_ty);
984        }
985
986        let llret = unsafe {
987            llvm::LLVMBuildCallWithOperandBundles(
988                self.llbuilder,
989                fn_ty,
990                fn_ptr,
991                llargs.as_ptr(),
992                llargs.len() as c_uint,
993                ptr::dangling(),
994                0,
995                c"".as_ptr(),
996            )
997        };
998
999        let src_ty = self.val_ty(llret);
1000        let dest_ty = llreturn_ty;
1001        if !can_autocast(self, dest_ty, src_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with `{1:?}` (found) in `{2:?}`",
                src_ty, dest_ty, fn_ptr));
    }
};assert!(
1002            can_autocast(self, dest_ty, src_ty),
1003            "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`"
1004        );
1005
1006        autocast(self, llret, src_ty, dest_ty)
1007    }
1008
1009    fn abort_immediate(&mut self) {
1010        self.call_intrinsic("llvm.trap", &[], &[]);
1011    }
1012
1013    fn assume(&mut self, val: Self::Value) {
1014        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
1015            self.call_intrinsic("llvm.assume", &[], &[val]);
1016        }
1017    }
1018
1019    fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
1020        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
1021            self.call_intrinsic(
1022                "llvm.expect",
1023                &[self.type_i1()],
1024                &[cond, self.const_bool(expected)],
1025            )
1026        } else {
1027            cond
1028        }
1029    }
1030
1031    fn ctpop(&mut self, val: Self::Value) -> Self::Value {
1032        let ret = self.call_intrinsic("llvm.ctpop", &[self.val_ty(val)], &[val]);
1033        self.intcast(ret, self.type_i32(), false)
1034    }
1035
1036    fn type_checked_load(
1037        &mut self,
1038        llvtable: &'ll Value,
1039        vtable_byte_offset: u64,
1040        typeid: &[u8],
1041    ) -> Self::Value {
1042        let typeid = self.create_metadata(typeid);
1043        let typeid = self.get_metadata_value(typeid);
1044        let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
1045        let type_checked_load = self.call_intrinsic(
1046            "llvm.type.checked.load",
1047            &[],
1048            &[llvtable, vtable_byte_offset, typeid],
1049        );
1050        self.extract_value(type_checked_load, 0)
1051    }
1052
1053    fn va_start(&mut self, va_list: &'ll Value) {
1054        self.call_intrinsic("llvm.va_start", &[self.val_ty(va_list)], &[va_list]);
1055    }
1056
1057    fn retag_reg(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) -> Self::Value {
1058        codegen_retag_inner(self, "__rust_retag_reg", ptr, info)
1059    }
1060
1061    fn retag_mem(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) {
1062        codegen_retag_inner(self, "__rust_retag_mem", ptr, info);
1063    }
1064}
1065
1066fn llvm_arch_for(rust_arch: &Arch) -> Option<&'static str> {
1067    Some(match rust_arch {
1068        Arch::AArch64 | Arch::Arm64EC => "aarch64",
1069        Arch::AmdGpu => "amdgcn",
1070        Arch::Arm => "arm",
1071        Arch::Bpf => "bpf",
1072        Arch::Hexagon => "hexagon",
1073        Arch::LoongArch32 | Arch::LoongArch64 => "loongarch",
1074        Arch::Mips | Arch::Mips32r6 | Arch::Mips64 | Arch::Mips64r6 => "mips",
1075        Arch::Nvptx64 => "nvvm",
1076        Arch::PowerPC | Arch::PowerPC64 => "ppc",
1077        Arch::RiscV32 | Arch::RiscV64 => "riscv",
1078        Arch::S390x => "s390",
1079        Arch::SpirV => "spv",
1080        Arch::Wasm32 | Arch::Wasm64 => "wasm",
1081        Arch::X86 | Arch::X86_64 => "x86",
1082        _ => return None, // fallback for unknown archs
1083    })
1084}
1085
1086fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: &'ll Type, llvm_ty: &'ll Type) -> bool {
1087    if rust_ty == llvm_ty {
1088        return true;
1089    }
1090
1091    match cx.type_kind(llvm_ty) {
1092        // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust
1093        // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM
1094        // as, well, packed structs, so they won't match with those either)
1095        TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => {
1096            let rust_element_tys = cx.struct_element_types(rust_ty);
1097            let llvm_element_tys = cx.struct_element_types(llvm_ty);
1098
1099            if rust_element_tys.len() != llvm_element_tys.len() {
1100                return false;
1101            }
1102
1103            iter::zip(rust_element_tys, llvm_element_tys).all(
1104                |(rust_element_ty, llvm_element_ty)| {
1105                    can_autocast(cx, rust_element_ty, llvm_element_ty)
1106                },
1107            )
1108        }
1109        TypeKind::Vector => {
1110            let llvm_element_ty = cx.element_type(llvm_ty);
1111            let element_count = cx.vector_length(llvm_ty) as u64;
1112
1113            if llvm_element_ty == cx.type_bf16() {
1114                rust_ty == cx.type_vector(cx.type_i16(), element_count)
1115            } else if llvm_element_ty == cx.type_i1() {
1116                let int_width = element_count.next_power_of_two().max(8);
1117                rust_ty == cx.type_ix(int_width)
1118            } else {
1119                false
1120            }
1121        }
1122        TypeKind::BFloat => rust_ty == cx.type_i16(),
1123        TypeKind::X86_AMX if cx.type_kind(rust_ty) == TypeKind::Vector => {
1124            let element_ty = cx.element_type(rust_ty);
1125            let element_count = cx.vector_length(rust_ty) as u64;
1126
1127            let element_size_bits = match cx.type_kind(element_ty) {
1128                TypeKind::Half => 16,
1129                TypeKind::Float => 32,
1130                TypeKind::Double => 64,
1131                TypeKind::FP128 => 128,
1132                TypeKind::Integer => cx.int_width(element_ty),
1133                TypeKind::Pointer => cx.int_width(cx.isize_ty),
1134                _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Vector element type `{0:?}` not one of integer, float or pointer",
        element_ty), Location::caller())bug!(
1135                    "Vector element type `{element_ty:?}` not one of integer, float or pointer"
1136                ),
1137            };
1138
1139            element_size_bits * element_count == 8192
1140        }
1141        _ => false,
1142    }
1143}
1144
1145fn autocast<'ll>(
1146    bx: &mut Builder<'_, 'll, '_>,
1147    val: &'ll Value,
1148    src_ty: &'ll Type,
1149    dest_ty: &'ll Type,
1150) -> &'ll Value {
1151    if src_ty == dest_ty {
1152        return val;
1153    }
1154    match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) {
1155        // re-pack structs
1156        (TypeKind::Struct, TypeKind::Struct) => {
1157            let mut ret = bx.const_poison(dest_ty);
1158            for (idx, (src_element_ty, dest_element_ty)) in
1159                iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty))
1160                    .enumerate()
1161            {
1162                let elt = bx.extract_value(val, idx as u64);
1163                let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty);
1164                ret = bx.insert_value(ret, casted_elt, idx as u64);
1165            }
1166            ret
1167        }
1168        // cast from the i1xN vector type to the primitive type
1169        (TypeKind::Vector, TypeKind::Integer) if bx.element_type(src_ty) == bx.type_i1() => {
1170            let vector_length = bx.vector_length(src_ty) as u64;
1171            let int_width = vector_length.next_power_of_two().max(8);
1172
1173            let val = if vector_length == int_width {
1174                val
1175            } else {
1176                // zero-extends vector
1177                let shuffle_indices = match vector_length {
1178                    0 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("zero length vectors are not allowed")));
}unreachable!("zero length vectors are not allowed"),
1179                    1 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 1, 1, 1, 1, 1, 1]))vec![0, 1, 1, 1, 1, 1, 1, 1],
1180                    2 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 2, 2, 2, 2, 2]))vec![0, 1, 2, 2, 2, 2, 2, 2],
1181                    3 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 3, 3, 3, 3, 3]))vec![0, 1, 2, 3, 3, 3, 3, 3],
1182                    4.. => (0..int_width as i32).collect(),
1183                };
1184                let shuffle_mask =
1185                    shuffle_indices.into_iter().map(|i| bx.const_i32(i)).collect::<Vec<_>>();
1186                bx.shuffle_vector(val, bx.const_null(src_ty), bx.const_vector(&shuffle_mask))
1187            };
1188            bx.bitcast(val, dest_ty)
1189        }
1190        // cast from the primitive type to the i1xN vector type
1191        (TypeKind::Integer, TypeKind::Vector) if bx.element_type(dest_ty) == bx.type_i1() => {
1192            let vector_length = bx.vector_length(dest_ty) as u64;
1193            let int_width = vector_length.next_power_of_two().max(8);
1194
1195            let intermediate_ty = bx.type_vector(bx.type_i1(), int_width);
1196            let intermediate = bx.bitcast(val, intermediate_ty);
1197
1198            if vector_length == int_width {
1199                intermediate
1200            } else {
1201                let shuffle_mask: Vec<_> =
1202                    (0..vector_length).map(|i| bx.const_i32(i as i32)).collect();
1203                bx.shuffle_vector(
1204                    intermediate,
1205                    bx.const_poison(intermediate_ty),
1206                    bx.const_vector(&shuffle_mask),
1207                )
1208            }
1209        }
1210        (TypeKind::Vector, TypeKind::X86_AMX) => {
1211            bx.call_intrinsic("llvm.x86.cast.vector.to.tile", &[src_ty], &[val])
1212        }
1213        (TypeKind::X86_AMX, TypeKind::Vector) => {
1214            bx.call_intrinsic("llvm.x86.cast.tile.to.vector", &[dest_ty], &[val])
1215        }
1216        _ => bx.bitcast(val, dest_ty), // for `bf16(xN)` <-> `u16(xN)`
1217    }
1218}
1219
1220fn intrinsic_fn<'ll, 'tcx>(
1221    bx: &Builder<'_, 'll, 'tcx>,
1222    name: &str,
1223    rust_return_ty: &'ll Type,
1224    rust_argument_tys: Vec<&'ll Type>,
1225    instance: ty::Instance<'tcx>,
1226) -> &'ll Value {
1227    let tcx = bx.tcx;
1228
1229    let rust_fn_ty = bx.type_func(&rust_argument_tys, rust_return_ty);
1230
1231    let intrinsic = llvm::Intrinsic::lookup(name.as_bytes());
1232
1233    if let Some(intrinsic) = intrinsic
1234        && intrinsic.is_target_specific()
1235    {
1236        let (llvm_arch, _) = name[5..].split_once('.').unwrap();
1237        let rust_arch = &tcx.sess.target.arch;
1238
1239        if let Some(correct_llvm_arch) = llvm_arch_for(rust_arch)
1240            && llvm_arch != correct_llvm_arch
1241        {
1242            tcx.dcx().emit_fatal(IntrinsicWrongArch {
1243                name,
1244                target_arch: rust_arch.desc(),
1245                span: tcx.def_span(instance.def_id()),
1246            });
1247        }
1248    }
1249
1250    if let Some(intrinsic) = intrinsic
1251        && !intrinsic.is_overloaded()
1252    {
1253        // FIXME: also do this for overloaded intrinsics
1254        let llfn = intrinsic.get_declaration(bx.llmod, &[]);
1255        let llvm_fn_ty = bx.get_type_of_global(llfn);
1256
1257        let llvm_return_ty = bx.get_return_type(llvm_fn_ty);
1258        let llvm_argument_tys = bx.func_params_types(llvm_fn_ty);
1259        let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty);
1260
1261        let is_correct_signature = !llvm_is_variadic
1262            && rust_argument_tys.len() == llvm_argument_tys.len()
1263            && iter::once((rust_return_ty, llvm_return_ty))
1264                .chain(iter::zip(rust_argument_tys, llvm_argument_tys))
1265                .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty));
1266
1267        if !is_correct_signature {
1268            tcx.dcx().emit_fatal(IntrinsicSignatureMismatch {
1269                name,
1270                llvm_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", llvm_fn_ty))
    })format!("{llvm_fn_ty:?}"),
1271                rust_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", rust_fn_ty))
    })format!("{rust_fn_ty:?}"),
1272                span: tcx.def_span(instance.def_id()),
1273            });
1274        }
1275
1276        return llfn;
1277    }
1278
1279    // Function addresses in Rust are never significant, allowing functions to be merged.
1280    let llfn = declare_raw_fn(
1281        bx,
1282        name,
1283        llvm::CCallConv,
1284        llvm::UnnamedAddr::Global,
1285        llvm::Visibility::Default,
1286        rust_fn_ty,
1287    );
1288
1289    if intrinsic.is_none() {
1290        let mut new_llfn = None;
1291        let can_upgrade = unsafe { llvm::LLVMRustUpgradeIntrinsicFunction(llfn, &mut new_llfn) };
1292
1293        if !can_upgrade {
1294            // This is either plain wrong, or this can be caused by incompatible LLVM versions
1295            tcx.dcx().emit_fatal(UnknownIntrinsic { name, span: tcx.def_span(instance.def_id()) });
1296        } else if let Some(def_id) = instance.def_id().as_local() {
1297            // we can emit diagnostics only for local crates
1298            let hir_id = tcx.local_def_id_to_hir_id(def_id);
1299
1300            // not all intrinsics are upgraded to some other intrinsics, most are upgraded to instruction sequences
1301            let msg = if let Some(new_llfn) = new_llfn {
1302                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{1}`, `{0}` can be used instead",
                str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap(),
                name))
    })format!(
1303                    "using deprecated intrinsic `{name}`, `{}` can be used instead",
1304                    str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap()
1305                )
1306            } else {
1307                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{0}`",
                name))
    })format!("using deprecated intrinsic `{name}`")
1308            };
1309
1310            tcx.emit_node_lint(
1311                DEPRECATED_LLVM_INTRINSIC,
1312                hir_id,
1313                rustc_errors::DiagDecorator(|d| {
1314                    d.primary_message(msg).span(tcx.hir_span(hir_id));
1315                }),
1316            );
1317        }
1318    }
1319
1320    llfn
1321}
1322
1323fn catch_unwind_intrinsic<'ll, 'tcx>(
1324    bx: &mut Builder<'_, 'll, 'tcx>,
1325    try_func: &'ll Value,
1326    data: &'ll Value,
1327    catch_func: &'ll Value,
1328) -> &'ll Value {
1329    if !bx.sess().panic_strategy().unwinds() {
1330        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1331        bx.call(try_func_ty, None, None, try_func, ReturnSlot::Direct, &[data], None, None);
1332        // Return 0 unconditionally from the intrinsic call;
1333        // we can never unwind.
1334        bx.const_bool(false)
1335    } else if wants_msvc_seh(&bx.sess().target) {
1336        codegen_msvc_try(bx, try_func, data, catch_func)
1337    } else if wants_wasm_eh(&bx.sess().target) {
1338        codegen_wasm_try(bx, try_func, data, catch_func)
1339    } else {
1340        codegen_gnu_try(bx, try_func, data, catch_func)
1341    }
1342}
1343
1344// MSVC's definition of the `rust_try` function.
1345//
1346// This implementation uses the new exception handling instructions in LLVM
1347// which have support in LLVM for SEH on MSVC targets. Although these
1348// instructions are meant to work for all targets, as of the time of this
1349// writing, however, LLVM does not recommend the usage of these new instructions
1350// as the old ones are still more optimized.
1351fn codegen_msvc_try<'ll, 'tcx>(
1352    bx: &mut Builder<'_, 'll, 'tcx>,
1353    try_func: &'ll Value,
1354    data: &'ll Value,
1355    catch_func: &'ll Value,
1356) -> &'ll Value {
1357    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1358        bx.set_personality_fn(bx.eh_personality());
1359
1360        let normal = bx.append_sibling_block("normal");
1361        let catchswitch = bx.append_sibling_block("catchswitch");
1362        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
1363        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
1364        let caught = bx.append_sibling_block("caught");
1365
1366        let try_func = llvm::get_param(bx.llfn(), 0);
1367        let data = llvm::get_param(bx.llfn(), 1);
1368        let catch_func = llvm::get_param(bx.llfn(), 2);
1369
1370        // We're generating an IR snippet that looks like:
1371        //
1372        //   declare bool @rust_try(%try_func, %data, %catch_func) {
1373        //      %slot = alloca i8*
1374        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1375        //
1376        //   normal:
1377        //      ret i1 false
1378        //
1379        //   catchswitch:
1380        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
1381        //
1382        //   catchpad_rust:
1383        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
1384        //      %ptr = load %slot
1385        //      call %catch_func(%data, %ptr)
1386        //      catchret from %tok to label %caught
1387        //
1388        //   catchpad_foreign:
1389        //      %tok = catchpad within %cs [null, 64, null]
1390        //      call %catch_func(%data, null)
1391        //      catchret from %tok to label %caught
1392        //
1393        //   caught:
1394        //      ret i1 true
1395        //   }
1396        //
1397        // This structure follows the basic usage of throw/try/catch in LLVM.
1398        // For example, compile this C++ snippet to see what LLVM generates:
1399        //
1400        //      struct rust_panic {
1401        //          rust_panic(const rust_panic&);
1402        //          ~rust_panic();
1403        //
1404        //          void* x[2];
1405        //      };
1406        //
1407        //      int __rust_try(
1408        //          void (*try_func)(void*),
1409        //          void *data,
1410        //          void (*catch_func)(void*, void*) noexcept
1411        //      ) {
1412        //          try {
1413        //              try_func(data);
1414        //              return 0;
1415        //          } catch(rust_panic& a) {
1416        //              catch_func(data, &a);
1417        //              return 1;
1418        //          } catch(...) {
1419        //              catch_func(data, NULL);
1420        //              return 1;
1421        //          }
1422        //      }
1423        //
1424        // More information can be found in libstd's seh.rs implementation.
1425        let ptr_size = bx.tcx().data_layout.pointer_size();
1426        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1427        let slot = bx.alloca(ptr_size, ptr_align);
1428        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1429        bx.invoke(
1430            try_func_ty,
1431            None,
1432            None,
1433            try_func,
1434            ReturnSlot::Direct,
1435            &[data],
1436            normal,
1437            catchswitch,
1438            None,
1439            None,
1440        );
1441
1442        bx.switch_to_block(normal);
1443        bx.ret(bx.const_bool(false));
1444
1445        bx.switch_to_block(catchswitch);
1446        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
1447
1448        // We can't use the TypeDescriptor defined in libpanic_unwind because it
1449        // might be in another DLL and the SEH encoding only supports specifying
1450        // a TypeDescriptor from the current module.
1451        //
1452        // However this isn't an issue since the MSVC runtime uses string
1453        // comparison on the type name to match TypeDescriptors rather than
1454        // pointer equality.
1455        //
1456        // So instead we generate a new TypeDescriptor in each module that uses
1457        // `try` and let the linker merge duplicate definitions in the same
1458        // module.
1459        //
1460        // When modifying, make sure that the type_name string exactly matches
1461        // the one used in library/panic_unwind/src/seh.rs.
1462        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
1463        let type_name = bx.const_bytes(b"rust_panic\0");
1464        let type_info =
1465            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
1466        let tydesc = bx.declare_global(
1467            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
1468            bx.val_ty(type_info),
1469        );
1470
1471        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1472        if bx.cx.tcx.sess.target.supports_comdat() {
1473            llvm::SetUniqueComdat(bx.llmod, tydesc);
1474        }
1475        llvm::set_initializer(tydesc, type_info);
1476
1477        // The flag value of 8 indicates that we are catching the exception by
1478        // reference instead of by value. We can't use catch by value because
1479        // that requires copying the exception object, which we don't support
1480        // since our exception object effectively contains a Box.
1481        //
1482        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1483        bx.switch_to_block(catchpad_rust);
1484        let flags = bx.const_i32(8);
1485        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
1486        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
1487        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1488        bx.call(
1489            catch_ty,
1490            None,
1491            None,
1492            catch_func,
1493            ReturnSlot::Direct,
1494            &[data, ptr],
1495            Some(&funclet),
1496            None,
1497        );
1498        bx.catch_ret(&funclet, caught);
1499
1500        // The flag value of 64 indicates a "catch-all".
1501        bx.switch_to_block(catchpad_foreign);
1502        let flags = bx.const_i32(64);
1503        let null = bx.const_null(bx.type_ptr());
1504        let funclet = bx.catch_pad(cs, &[null, flags, null]);
1505        bx.call(
1506            catch_ty,
1507            None,
1508            None,
1509            catch_func,
1510            ReturnSlot::Direct,
1511            &[data, null],
1512            Some(&funclet),
1513            None,
1514        );
1515        bx.catch_ret(&funclet, caught);
1516
1517        bx.switch_to_block(caught);
1518        bx.ret(bx.const_bool(true));
1519    });
1520
1521    // Note that no invoke is used here because by definition this function
1522    // can't panic (that's what it's catching).
1523    let ret = bx.call(
1524        llty,
1525        None,
1526        None,
1527        llfn,
1528        ReturnSlot::Direct,
1529        &[try_func, data, catch_func],
1530        None,
1531        None,
1532    );
1533    ret
1534}
1535
1536// WASM's definition of the `rust_try` function.
1537fn codegen_wasm_try<'ll, 'tcx>(
1538    bx: &mut Builder<'_, 'll, 'tcx>,
1539    try_func: &'ll Value,
1540    data: &'ll Value,
1541    catch_func: &'ll Value,
1542) -> &'ll Value {
1543    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1544        bx.set_personality_fn(bx.eh_personality());
1545
1546        let normal = bx.append_sibling_block("normal");
1547        let catchswitch = bx.append_sibling_block("catchswitch");
1548        let catchpad = bx.append_sibling_block("catchpad");
1549        let caught = bx.append_sibling_block("caught");
1550
1551        let try_func = llvm::get_param(bx.llfn(), 0);
1552        let data = llvm::get_param(bx.llfn(), 1);
1553        let catch_func = llvm::get_param(bx.llfn(), 2);
1554
1555        // We're generating an IR snippet that looks like:
1556        //
1557        //   declare i1 @rust_try(%try_func, %data, %catch_func) {
1558        //      %slot = alloca i8*
1559        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1560        //
1561        //   normal:
1562        //      ret i1 false
1563        //
1564        //   catchswitch:
1565        //      %cs = catchswitch within none [%catchpad] unwind to caller
1566        //
1567        //   catchpad:
1568        //      %tok = catchpad within %cs [null]
1569        //      %ptr = call @llvm.wasm.get.exception(token %tok)
1570        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
1571        //      call %catch_func(%data, %ptr)
1572        //      catchret from %tok to label %caught
1573        //
1574        //   caught:
1575        //      ret i1 true
1576        //   }
1577        //
1578        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1579        bx.invoke(
1580            try_func_ty,
1581            None,
1582            None,
1583            try_func,
1584            ReturnSlot::Direct,
1585            &[data],
1586            normal,
1587            catchswitch,
1588            None,
1589            None,
1590        );
1591
1592        bx.switch_to_block(normal);
1593        bx.ret(bx.const_bool(false));
1594
1595        bx.switch_to_block(catchswitch);
1596        let cs = bx.catch_switch(None, None, &[catchpad]);
1597
1598        bx.switch_to_block(catchpad);
1599        let null = bx.const_null(bx.type_ptr());
1600        let funclet = bx.catch_pad(cs, &[null]);
1601
1602        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
1603        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
1604
1605        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1606        bx.call(
1607            catch_ty,
1608            None,
1609            None,
1610            catch_func,
1611            ReturnSlot::Direct,
1612            &[data, ptr],
1613            Some(&funclet),
1614            None,
1615        );
1616        bx.catch_ret(&funclet, caught);
1617
1618        bx.switch_to_block(caught);
1619        bx.ret(bx.const_bool(true));
1620    });
1621
1622    // Note that no invoke is used here because by definition this function
1623    // can't panic (that's what it's catching).
1624    let ret = bx.call(
1625        llty,
1626        None,
1627        None,
1628        llfn,
1629        ReturnSlot::Direct,
1630        &[try_func, data, catch_func],
1631        None,
1632        None,
1633    );
1634    ret
1635}
1636
1637// Definition of the standard `try` function for Rust using the GNU-like model
1638// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1639// instructions).
1640//
1641// This codegen is a little surprising because we always call a shim
1642// function instead of inlining the call to `invoke` manually here. This is done
1643// because in LLVM we're only allowed to have one personality per function
1644// definition. The call to the `try` intrinsic is being inlined into the
1645// function calling it, and that function may already have other personality
1646// functions in play. By calling a shim we're guaranteed that our shim will have
1647// the right personality function.
1648fn codegen_gnu_try<'ll, 'tcx>(
1649    bx: &mut Builder<'_, 'll, 'tcx>,
1650    try_func: &'ll Value,
1651    data: &'ll Value,
1652    catch_func: &'ll Value,
1653) -> &'ll Value {
1654    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1655        // Codegens the shims described above:
1656        //
1657        //   bx:
1658        //      invoke %try_func(%data) normal %normal unwind %catch
1659        //
1660        //   normal:
1661        //      ret 0
1662        //
1663        //   catch:
1664        //      (%ptr, _) = landingpad
1665        //      call %catch_func(%data, %ptr)
1666        //      ret 1
1667        let then = bx.append_sibling_block("then");
1668        let catch = bx.append_sibling_block("catch");
1669
1670        let try_func = llvm::get_param(bx.llfn(), 0);
1671        let data = llvm::get_param(bx.llfn(), 1);
1672        let catch_func = llvm::get_param(bx.llfn(), 2);
1673        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1674        bx.invoke(
1675            try_func_ty,
1676            None,
1677            None,
1678            try_func,
1679            ReturnSlot::Direct,
1680            &[data],
1681            then,
1682            catch,
1683            None,
1684            None,
1685        );
1686
1687        bx.switch_to_block(then);
1688        bx.ret(bx.const_bool(false));
1689
1690        // Type indicator for the exception being thrown.
1691        //
1692        // The first value in this tuple is a pointer to the exception object
1693        // being thrown. The second value is a "selector" indicating which of
1694        // the landing pad clauses the exception's type had been matched to.
1695        // rust_try ignores the selector.
1696        bx.switch_to_block(catch);
1697        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1698        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
1699        let tydesc = bx.const_null(bx.type_ptr());
1700        bx.add_clause(vals, tydesc);
1701        let ptr = bx.extract_value(vals, 0);
1702        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1703        bx.call(catch_ty, None, None, catch_func, ReturnSlot::Direct, &[data, ptr], None, None);
1704        bx.ret(bx.const_bool(true));
1705    });
1706
1707    // Note that no invoke is used here because by definition this function
1708    // can't panic (that's what it's catching).
1709    let ret = bx.call(
1710        llty,
1711        None,
1712        None,
1713        llfn,
1714        ReturnSlot::Direct,
1715        &[try_func, data, catch_func],
1716        None,
1717        None,
1718    );
1719    ret
1720}
1721
1722// Helper function to give a Block to a closure to codegen a shim function.
1723// This is currently primarily used for the `try` intrinsic functions above.
1724fn gen_fn<'a, 'll, 'tcx>(
1725    cx: &'a CodegenCx<'ll, 'tcx>,
1726    name: &str,
1727    rust_fn_sig: ty::PolyFnSig<'tcx>,
1728    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1729) -> (&'ll Type, &'ll Value) {
1730    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1731    let llty = fn_abi.llvm_type(cx);
1732    let llfn = cx.declare_fn(name, fn_abi, None);
1733    cx.set_frame_pointer_type(llfn);
1734    cx.apply_target_cpu_attr(llfn);
1735    // FIXME(eddyb) find a nicer way to do this.
1736    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1737    let llbb = Builder::append_block(cx, llfn, "entry-block");
1738    let bx = Builder::build(cx, llbb);
1739    codegen(bx);
1740    (llty, llfn)
1741}
1742
1743// Helper function used to get a handle to the `__rust_try` function used to
1744// catch exceptions.
1745//
1746// This function is only generated once and is then cached.
1747fn get_rust_try_fn<'a, 'll, 'tcx>(
1748    cx: &'a CodegenCx<'ll, 'tcx>,
1749    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1750) -> (&'ll Type, &'ll Value) {
1751    if let Some(llfn) = cx.rust_try_fn.get() {
1752        return llfn;
1753    }
1754
1755    // Define the type up front for the signature of the rust_try function.
1756    let tcx = cx.tcx;
1757    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1758    // `unsafe fn(*mut Data) -> ()`
1759    let try_fn_ty = Ty::new_fn_ptr(
1760        tcx,
1761        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p], tcx.types.unit, hir::Safety::Unsafe)),
1762    );
1763    // `unsafe fn(*mut Data, *mut i8) -> ()`
1764    let catch_fn_ty = Ty::new_fn_ptr(
1765        tcx,
1766        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p, i8p], tcx.types.unit, hir::Safety::Unsafe)),
1767    );
1768    // `unsafe fn(unsafe fn(*mut Data) -> (), *mut Data, unsafe fn(*mut Data, *mut i8) -> ()) -> bool`
1769    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig_rust_abi(
1770        [try_fn_ty, i8p, catch_fn_ty],
1771        tcx.types.bool,
1772        hir::Safety::Unsafe,
1773    ));
1774    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1775
1776    if cx.sess().pointer_authentication() {
1777        let cfg = cx.sess().pointer_auth_config.as_ref().unwrap();
1778        let attrs: Vec<&Attribute> =
1779            cfg.fn_attrs().into_iter().map(|name| llvm::CreateAttrString(cx.llcx, name)).collect();
1780
1781        let (_ty, rust_try_fn) = rust_try;
1782        crate::attributes::apply_to_llfn(rust_try_fn, AttributePlace::Function, &attrs);
1783    }
1784
1785    cx.rust_try_fn.set(Some(rust_try));
1786    rust_try
1787}
1788
1789fn codegen_retag_inner<'ll, 'tcx>(
1790    bx: &mut Builder<'_, 'll, 'tcx>,
1791    name: &'static str,
1792    ptr: &'ll Value,
1793    info: &RetagInfo<&'ll Value>,
1794) -> &'ll Value {
1795    let size = bx.const_usize(info.size.bytes());
1796    let perms = bx.const_u8(info.flags.bits());
1797
1798    bx.call_intrinsic(
1799        name,
1800        // Retag intrinsics have special handling within `CodegenCx::declare_intrinsic`
1801        // to ensure that each form has the correct return type.
1802        &[bx.type_ptr(), bx.val_ty(size), bx.type_i8(), bx.type_ptr(), bx.type_ptr()],
1803        &[ptr, size, perms, info.im_layout, info.pin_layout],
1804    )
1805}
1806
1807fn codegen_autodiff<'ll, 'tcx>(
1808    bx: &mut Builder<'_, 'll, 'tcx>,
1809    instance: ty::Instance<'tcx>,
1810    args: &[OperandRef<'tcx, &'ll Value>],
1811    result_layout: ty::layout::TyAndLayout<'tcx>,
1812    result_place: Option<PlaceValue<&'ll Value>>,
1813) -> IntrinsicResult<'tcx, &'ll Value> {
1814    let tcx = bx.tcx;
1815    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1816        let _ = tcx.dcx().emit_err(AutoDiffWithoutEnable);
1817    }
1818
1819    let ct = tcx.crate_types();
1820    let lto = tcx.sess.lto();
1821    if ct.len() == 1 && ct.contains(&CrateType::Executable) {
1822        if lto != rustc_session::config::Lto::Fat {
1823            let _ = tcx.dcx().emit_err(AutoDiffWithoutLto);
1824        }
1825    } else {
1826        if lto != rustc_session::config::Lto::Fat && !tcx.sess.opts.cg.linker_plugin_lto.enabled() {
1827            let _ = tcx.dcx().emit_err(AutoDiffWithoutLto);
1828        }
1829    }
1830
1831    let fn_args = instance.args;
1832    let callee_ty = instance.ty(tcx, bx.typing_env());
1833
1834    let sig = callee_ty.fn_sig(tcx).skip_binder();
1835
1836    let ret_ty = sig.output();
1837    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1838
1839    let source_fn_ptr_ty = fn_args.into_type_list(tcx)[0];
1840    let fn_to_diff = args[0].immediate();
1841
1842    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1843        ty::FnDef(def_id, diff_args) => (def_id, diff_args.no_bound_vars().unwrap()),
1844        _ => ::rustc_span::macros::bug_impl(None, format_args!("invalid args"),
    Location::caller())bug!("invalid args"),
1845    };
1846
1847    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1848        Ok(Some(instance)) => instance,
1849        Ok(None) => ::rustc_span::macros::bug_impl(None,
    format_args!("could not resolve ({0:?}, {1:?}) to a specific autodiff instance",
        diff_id, diff_args), Location::caller())bug!(
1850            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1851            diff_id,
1852            diff_args
1853        ),
1854        Err(err) => {
1855            // An error has already been emitted
1856            return IntrinsicResult::Err(err);
1857        }
1858    };
1859
1860    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1861    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE);
1862
1863    let Some(Some(mut diff_attrs)) =
1864        {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(fn_diff.def_id(), &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcAutodiff(attr)) => {
                        break 'done Some(attr.clone());
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, fn_diff.def_id(), RustcAutodiff(attr) => attr.clone())
1865    else {
1866        ::rustc_span::macros::bug_impl(None,
    format_args!("could not find autodiff attrs"), Location::caller())bug!("could not find autodiff attrs")
1867    };
1868
1869    adjust_activity_to_abi(
1870        tcx,
1871        source_fn_ptr_ty,
1872        bx.cx.typing_env(),
1873        &mut diff_attrs.input_activity,
1874    );
1875
1876    let fnc_tree = fnc_typetrees(tcx, source_fn_ptr_ty);
1877
1878    // Build body
1879    generate_enzyme_call(
1880        bx,
1881        fn_to_diff,
1882        &diff_symbol,
1883        llret_ty,
1884        &val_arr,
1885        &diff_attrs,
1886        result_layout,
1887        result_place,
1888        fnc_tree,
1889    )
1890}
1891
1892// Generates the LLVM code to offload a Rust function to a target device (e.g., GPU).
1893// For each kernel call, it generates the necessary globals (including metadata such as
1894// size and pass mode), manages memory mapping to and from the device, handles all
1895// data transfers, and launches the kernel on the target device.
1896fn codegen_offload<'ll, 'tcx>(
1897    bx: &mut Builder<'_, 'll, 'tcx>,
1898    tcx: TyCtxt<'tcx>,
1899    instance: ty::Instance<'tcx>,
1900    args: &[OperandRef<'tcx, &'ll Value>],
1901) {
1902    let cx = bx.cx;
1903    let fn_args = instance.args;
1904
1905    let (target_id, target_args) = match fn_args.into_type_list(tcx)[0].kind() {
1906        ty::FnDef(def_id, params) => (def_id, params.no_bound_vars().unwrap()),
1907        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("invalid offload intrinsic arg"), Location::caller())bug!("invalid offload intrinsic arg"),
1908    };
1909
1910    let fn_target = match Instance::try_resolve(tcx, cx.typing_env(), *target_id, target_args) {
1911        Ok(Some(instance)) => instance,
1912        Ok(None) => ::rustc_span::macros::bug_impl(None,
    format_args!("could not resolve ({0:?}, {1:?}) to a specific offload instance",
        target_id, target_args), Location::caller())bug!(
1913            "could not resolve ({:?}, {:?}) to a specific offload instance",
1914            target_id,
1915            target_args
1916        ),
1917        Err(_) => {
1918            // An error has already been emitted
1919            return;
1920        }
1921    };
1922
1923    let offload_dims = OffloadKernelDims::from_operands(bx, &args[1], &args[2]);
1924    let dyn_cache = match args[3].val {
1925        OperandValue::Immediate(val) => val,
1926        _ => { ::core::panicking::panic_fmt(format_args!("unparsable")); }panic!("unparsable"),
1927    };
1928    let device_id = match args[4].val {
1929        OperandValue::Immediate(val) => val,
1930        _ => { ::core::panicking::panic_fmt(format_args!("unparsable")); }panic!("unparsable"),
1931    };
1932    let args = get_args_from_tuple(bx, args[5], fn_target);
1933    let target_symbol = mangle_offload_export(tcx, fn_target);
1934
1935    let sig = tcx.fn_sig(fn_target.def_id()).instantiate(tcx, fn_target.args).skip_norm_wip();
1936    let sig = tcx.instantiate_bound_regions_with_erased(sig);
1937    let inputs = sig.inputs();
1938
1939    let fn_abi = cx.fn_abi_of_instance(fn_target, ty::List::empty());
1940
1941    let mut metadata = Vec::new();
1942    let mut types = Vec::new();
1943
1944    for (i, arg_abi) in fn_abi.args.iter().enumerate() {
1945        let ty = inputs[i];
1946        let decomposed = OffloadMetadata::handle_abi(cx, tcx, ty, arg_abi);
1947
1948        for (meta, entry_ty) in decomposed {
1949            metadata.push(meta);
1950            types.push(bx.cx.layout_of(entry_ty).llvm_type(bx.cx));
1951        }
1952    }
1953
1954    let offload_globals_ref = cx.offload_globals.borrow();
1955    let offload_globals = match offload_globals_ref.as_ref() {
1956        Some(globals) => globals,
1957        None => {
1958            // Offload is not initialized, cannot continue
1959            return;
1960        }
1961    };
1962    let offload_data =
1963        gpu_offload::gen_define_handling(&cx, &metadata, target_symbol, offload_globals);
1964    gpu_offload::gen_call_handling(
1965        bx,
1966        &offload_data,
1967        &args,
1968        &types,
1969        &metadata,
1970        offload_globals,
1971        &offload_dims,
1972        &dyn_cache,
1973        &device_id,
1974    );
1975}
1976
1977fn get_args_from_tuple<'ll, 'tcx>(
1978    bx: &mut Builder<'_, 'll, 'tcx>,
1979    tuple_op: OperandRef<'tcx, &'ll Value>,
1980    fn_instance: Instance<'tcx>,
1981) -> Vec<&'ll Value> {
1982    let cx = bx.cx;
1983    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1984
1985    match tuple_op.val {
1986        OperandValue::Immediate(val) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [val]))vec![val],
1987        OperandValue::Pair(v1, v2) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v1, v2]))vec![v1, v2],
1988        OperandValue::Ref(ptr) => {
1989            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1990
1991            let mut result = Vec::with_capacity(fn_abi.args.len());
1992            let mut tuple_index = 0;
1993
1994            for arg in &fn_abi.args {
1995                match arg.mode {
1996                    PassMode::Ignore => {}
1997                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1998                        let field = tuple_place.project_field(bx, tuple_index);
1999                        let llvm_ty = field.layout.llvm_type(bx.cx);
2000                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
2001                        result.push(val);
2002                        tuple_index += 1;
2003                    }
2004                    PassMode::Pair(_, _) => {
2005                        let field = tuple_place.project_field(bx, tuple_index);
2006                        let llvm_ty = field.layout.llvm_type(bx.cx);
2007                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
2008                        result.push(bx.extract_value(pair_val, 0));
2009                        result.push(bx.extract_value(pair_val, 1));
2010                        tuple_index += 1;
2011                    }
2012                    PassMode::Indirect { .. } => {
2013                        let field = tuple_place.project_field(bx, tuple_index);
2014                        result.push(field.val.llval);
2015                        tuple_index += 1;
2016                    }
2017                    PassMode::IndirectUnsized { .. } => {
2018                        ::rustc_span::macros::bug_impl(None,
    format_args!("autodiff/offload args must not be unsized"),
    Location::caller());bug!("autodiff/offload args must not be unsized");
2019                    }
2020                }
2021            }
2022
2023            result
2024        }
2025
2026        OperandValue::ZeroSized => ::alloc::vec::Vec::new()vec![],
2027    }
2028}
2029
2030fn generic_simd_intrinsic<'ll, 'tcx>(
2031    bx: &mut Builder<'_, 'll, 'tcx>,
2032    name: Symbol,
2033    fn_args: GenericArgsRef<'tcx>,
2034    args: &[OperandRef<'tcx, &'ll Value>],
2035    ret_ty: Ty<'tcx>,
2036    llret_ty: &'ll Type,
2037    span: Span,
2038) -> Result<&'ll Value, ErrorGuaranteed> {
2039    macro_rules! return_error {
2040        ($diag: expr) => {{
2041            let err = bx.sess().dcx().emit_err($diag);
2042            return Err(err);
2043        }};
2044    }
2045
2046    macro_rules! require {
2047        ($cond: expr, $diag: expr) => {
2048            if !$cond {
2049                return_error!($diag);
2050            }
2051        };
2052    }
2053
2054    macro_rules! require_simd {
2055        ($ty: expr, $variant:ident) => {{
2056            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
2057            $ty.simd_size_and_type(bx.tcx())
2058        }};
2059    }
2060
2061    macro_rules! require_simd_or_scalable {
2062        ($ty: expr, $variant:ident) => {{
2063            require!(
2064                $ty.is_simd() || $ty.is_scalable_vector(),
2065                InvalidMonomorphization::$variant { span, name, ty: $ty }
2066            );
2067            if $ty.is_simd() {
2068                let (len, ty) = $ty.simd_size_and_type(bx.tcx());
2069                (len, ty, None)
2070            } else {
2071                let (count, ty, num_vecs) =
2072                    $ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
2073                (count as u64, ty, Some(num_vecs))
2074            }
2075        }};
2076    }
2077
2078    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
2079    macro_rules! require_int_or_uint_ty {
2080        ($ty: expr, $diag: expr) => {
2081            match $ty {
2082                ty::Int(i) => {
2083                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2084                }
2085                ty::Uint(i) => {
2086                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2087                }
2088                _ => {
2089                    return_error!($diag);
2090                }
2091            }
2092        };
2093    }
2094
2095    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
2096    /// down to an i1 based mask that can be used by llvm intrinsics.
2097    ///
2098    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
2099    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
2100    /// but codegen for several targets is better if we consider the highest bit by shifting.
2101    ///
2102    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
2103    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
2104    /// instead the mask can be used as is.
2105    ///
2106    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
2107    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
2108    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
2109        bx: &mut Builder<'a, 'll, 'tcx>,
2110        i_xn: &'ll Value,
2111        in_elem_bitwidth: u64,
2112        in_len: u64,
2113    ) -> &'ll Value {
2114        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
2115        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
2116        let shift_indices = ::alloc::vec::from_elem(shift_idx, in_len as _)vec![shift_idx; in_len as _];
2117        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
2118        // Truncate vector to an <i1 x N>
2119        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
2120    }
2121
2122    // Sanity-check: all vector arguments must be immediates.
2123    if truecfg!(debug_assertions) {
2124        for arg in args {
2125            if arg.layout.ty.is_simd() {
2126                {
    match arg.val {
        OperandValue::Immediate(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "OperandValue::Immediate(_)", ::core::option::Option::None);
        }
    }
};assert_matches!(arg.val, OperandValue::Immediate(_));
2127            }
2128        }
2129    }
2130
2131    if name == sym::simd_select_bitmask {
2132        let (len, _) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdArgument);
2133
2134        let expected_int_bits = len.max(8).next_power_of_two();
2135        let expected_bytes = len.div_ceil(8);
2136
2137        let mask_ty = args[0].layout.ty;
2138        let mask = match mask_ty.kind() {
2139            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2140            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2141            ty::Array(elem, len)
2142                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2143                    && len
2144                        .try_to_target_usize(bx.tcx)
2145                        .expect("expected monomorphic const in codegen")
2146                        == expected_bytes =>
2147            {
2148                let place = PlaceRef::alloca(bx, args[0].layout);
2149                args[0].val.store(bx, place);
2150                let int_ty = bx.type_ix(expected_bytes * 8);
2151                bx.load(int_ty, place.val.llval, Align::ONE)
2152            }
2153            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::InvalidBitmask {
                span,
                name,
                mask_ty,
                expected_int_bits,
                expected_bytes,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::InvalidBitmask {
2154                span,
2155                name,
2156                mask_ty,
2157                expected_int_bits,
2158                expected_bytes
2159            }),
2160        };
2161
2162        let i1 = bx.type_i1();
2163        let im = bx.type_ix(len);
2164        let i1xn = bx.type_vector(i1, len);
2165        let m_im = bx.trunc(mask, im);
2166        let m_i1s = bx.bitcast(m_im, i1xn);
2167        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2168    }
2169
2170    if name == sym::simd_splat {
2171        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2172
2173        if !(args[0].layout.ty == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
                    span,
                    name,
                    expected_element: out_ty,
                    vector_type: ret_ty,
                });
        return Err(err);
    };
};require!(
2174            args[0].layout.ty == out_ty,
2175            InvalidMonomorphization::ExpectedVectorElementType {
2176                span,
2177                name,
2178                expected_element: out_ty,
2179                vector_type: ret_ty,
2180            }
2181        );
2182
2183        // `insertelement <N x elem> poison, elem %x, i32 0`
2184        let poison_vec = bx.const_poison(llret_ty);
2185        let idx0 = bx.const_i32(0);
2186        let v0 = bx.insert_element(poison_vec, args[0].immediate(), idx0);
2187
2188        // `shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer`
2189        // The masks is all zeros, so this splats lane 0 (which has our element in it).
2190        let mask_ty = bx.type_vector(bx.type_i32(), out_len);
2191        let splat = bx.shuffle_vector(v0, poison_vec, bx.const_null(mask_ty));
2192
2193        return Ok(splat);
2194    }
2195
2196    let supports_scalable = match name {
2197        sym::simd_cast | sym::simd_select => true,
2198        _ => false,
2199    };
2200
2201    // Every intrinsic below takes a SIMD vector as its first argument. Some intrinsics also accept
2202    // scalable vectors. `require_simd_or_scalable` is used regardless as it'll do the right thing
2203    // for non-scalable vectors, and an additional check to prohibit scalable vectors for those
2204    // intrinsics that do not support them is added.
2205    if !supports_scalable {
2206        let _ = {
    if !args[0].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                        span,
                        name,
                        ty: args[0].layout.ty,
                    });
            return Err(err);
        };
    };
    args[0].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[0].layout.ty, SimdInput);
2207    }
2208    let (in_len, in_elem, in_num_vecs) = {
    if !(args[0].layout.ty.is_simd() ||
                args[0].layout.ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                        span,
                        name,
                        ty: args[0].layout.ty,
                    });
            return Err(err);
        };
    };
    if args[0].layout.ty.is_simd() {
        let (len, ty) = args[0].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[0].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[0].layout.ty, SimdInput);
2209    let in_ty = args[0].layout.ty;
2210
2211    let comparison = match name {
2212        sym::simd_eq => Some(BinOp::Eq),
2213        sym::simd_ne => Some(BinOp::Ne),
2214        sym::simd_lt => Some(BinOp::Lt),
2215        sym::simd_le => Some(BinOp::Le),
2216        sym::simd_gt => Some(BinOp::Gt),
2217        sym::simd_ge => Some(BinOp::Ge),
2218        _ => None,
2219    };
2220
2221    if let Some(cmp_op) = comparison {
2222        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2223
2224        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2225            in_len == out_len,
2226            InvalidMonomorphization::ReturnLengthInputType {
2227                span,
2228                name,
2229                in_len,
2230                in_ty,
2231                ret_ty,
2232                out_len
2233            }
2234        );
2235        if !(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnIntegerType {
                    span,
                    name,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2236            bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
2237            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
2238        );
2239
2240        return Ok(compare_simd_types(
2241            bx,
2242            args[0].immediate(),
2243            args[1].immediate(),
2244            in_elem,
2245            llret_ty,
2246            cmp_op,
2247        ));
2248    }
2249
2250    if name == sym::simd_shuffle_const_generic {
2251        let idx = fn_args[2].expect_const().to_branch();
2252        let n = idx.len() as u64;
2253
2254        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2255        if !(out_len == n) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                    span,
                    name,
                    in_len: n,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2256            out_len == n,
2257            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2258        );
2259        if !(in_elem == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2260            in_elem == out_ty,
2261            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2262        );
2263
2264        let total_len = in_len * 2;
2265
2266        let indices: Option<Vec<_>> = idx
2267            .iter()
2268            .enumerate()
2269            .map(|(arg_idx, val)| {
2270                let idx = val.to_leaf().to_i32();
2271                if idx >= i32::try_from(total_len).unwrap() {
2272                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
2273                        span,
2274                        name,
2275                        arg_idx: arg_idx as u64,
2276                        total_len: total_len.into(),
2277                    });
2278                    None
2279                } else {
2280                    Some(bx.const_i32(idx))
2281                }
2282            })
2283            .collect();
2284        let Some(indices) = indices else {
2285            return Ok(bx.const_null(llret_ty));
2286        };
2287
2288        return Ok(bx.shuffle_vector(
2289            args[0].immediate(),
2290            args[1].immediate(),
2291            bx.const_vector(&indices),
2292        ));
2293    }
2294
2295    if name == sym::simd_shuffle {
2296        // Make sure this is actually a SIMD vector.
2297        let idx_ty = args[2].layout.ty;
2298        let n: u64 = if idx_ty.is_simd()
2299            && #[allow(non_exhaustive_omitted_patterns)] match idx_ty.simd_size_and_type(bx.cx.tcx).1.kind()
    {
    ty::Uint(ty::UintTy::U32) => true,
    _ => false,
}matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
2300        {
2301            idx_ty.simd_size_and_type(bx.cx.tcx).0
2302        } else {
2303            {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdShuffle {
                span,
                name,
                ty: idx_ty,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
2304        };
2305
2306        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2307        if !(out_len == n) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                    span,
                    name,
                    in_len: n,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2308            out_len == n,
2309            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2310        );
2311        if !(in_elem == out_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                    out_ty,
                });
        return Err(err);
    };
};require!(
2312            in_elem == out_ty,
2313            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2314        );
2315
2316        let total_len = u128::from(in_len) * 2;
2317
2318        // Check that the indices are in-bounds.
2319        let indices = args[2].immediate();
2320        for i in 0..n {
2321            let val = bx.const_get_elt(indices, i as u64);
2322            let idx = bx
2323                .const_to_opt_u128(val, true)
2324                .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("typeck should have already ensured that these are const"),
    Location::caller())bug!("typeck should have already ensured that these are const"));
2325            if idx >= total_len {
2326                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: i,
                total_len,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2327                    span,
2328                    name,
2329                    arg_idx: i,
2330                    total_len,
2331                });
2332            }
2333        }
2334
2335        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
2336    }
2337
2338    if name == sym::simd_insert || name == sym::simd_insert_dyn {
2339        if !(in_elem == args[2].layout.ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::InsertedType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    out_ty: args[2].layout.ty,
                });
        return Err(err);
    };
};require!(
2340            in_elem == args[2].layout.ty,
2341            InvalidMonomorphization::InsertedType {
2342                span,
2343                name,
2344                in_elem,
2345                in_ty,
2346                out_ty: args[2].layout.ty
2347            }
2348        );
2349
2350        let index_imm = if name == sym::simd_insert {
2351            let idx = bx
2352                .const_to_opt_u128(args[1].immediate(), false)
2353                .expect("typeck should have ensure that this is a const");
2354            if idx >= in_len.into() {
2355                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: 1,
                total_len: in_len.into(),
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2356                    span,
2357                    name,
2358                    arg_idx: 1,
2359                    total_len: in_len.into(),
2360                });
2361            }
2362            bx.const_i32(idx as i32)
2363        } else {
2364            args[1].immediate()
2365        };
2366
2367        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
2368    }
2369    if name == sym::simd_extract || name == sym::simd_extract_dyn {
2370        if !(ret_ty == in_elem) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2371            ret_ty == in_elem,
2372            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2373        );
2374        let index_imm = if name == sym::simd_extract {
2375            let idx = bx
2376                .const_to_opt_u128(args[1].immediate(), false)
2377                .expect("typeck should have ensure that this is a const");
2378            if idx >= in_len.into() {
2379                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: 1,
                total_len: in_len.into(),
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2380                    span,
2381                    name,
2382                    arg_idx: 1,
2383                    total_len: in_len.into(),
2384                });
2385            }
2386            bx.const_i32(idx as i32)
2387        } else {
2388            args[1].immediate()
2389        };
2390
2391        return Ok(bx.extract_element(args[0].immediate(), index_imm));
2392    }
2393
2394    if name == sym::simd_select {
2395        let m_elem_ty = in_elem;
2396        let m_len = in_len;
2397        let (v_len, _, _) = {
    if !(args[1].layout.ty.is_simd() ||
                args[1].layout.ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    if args[1].layout.ty.is_simd() {
        let (len, ty) = args[1].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[1].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[1].layout.ty, SimdArgument);
2398        if !(m_len == v_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::MismatchedLengths {
                    span,
                    name,
                    m_len,
                    v_len,
                });
        return Err(err);
    };
};require!(
2399            m_len == v_len,
2400            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
2401        );
2402
2403        let m_i1s = if args[1].layout.ty.is_scalable_vector() {
2404            match m_elem_ty.kind() {
2405                ty::Bool => {}
2406                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                span,
                name,
                ty: m_elem_ty,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::MaskWrongElementType {
2407                    span,
2408                    name,
2409                    ty: m_elem_ty
2410                }),
2411            };
2412            let i1 = bx.type_i1();
2413            let i1xn = bx.type_scalable_vector(i1, m_len as u64);
2414            bx.trunc(args[0].immediate(), i1xn)
2415        } else {
2416            let in_elem_bitwidth = match m_elem_ty.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: m_elem_ty,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2417                m_elem_ty.kind(),
2418                InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
2419            );
2420            vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len)
2421        };
2422
2423        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2424    }
2425
2426    if name == sym::simd_bitmask {
2427        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
2428        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
2429        // * an unsigned integer
2430        // * an array of `u8`
2431        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
2432        //
2433        // The bit order of the result depends on the byte endianness, LSB-first for little
2434        // endian and MSB-first for big endian.
2435        let expected_int_bits = in_len.max(8).next_power_of_two();
2436        let expected_bytes = in_len.div_ceil(8);
2437
2438        // Integer vector <i{in_bitwidth} x in_len>:
2439        let in_elem_bitwidth = match in_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: in_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2440            in_elem.kind(),
2441            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
2442        );
2443
2444        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
2445        // Bitcast <i1 x N> to iN:
2446        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
2447
2448        match ret_ty.kind() {
2449            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
2450                // Zero-extend iN to the bitmask type:
2451                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
2452            }
2453            ty::Array(elem, len)
2454                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2455                    && len
2456                        .try_to_target_usize(bx.tcx)
2457                        .expect("expected monomorphic const in codegen")
2458                        == expected_bytes =>
2459            {
2460                // Zero-extend iN to the array length:
2461                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
2462
2463                // Convert the integer to a byte array
2464                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
2465                bx.store(ze, ptr, Align::ONE);
2466                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
2467                return Ok(bx.load(array_ty, ptr, Align::ONE));
2468            }
2469            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::CannotReturn {
                span,
                name,
                ret_ty,
                expected_int_bits,
                expected_bytes,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::CannotReturn {
2470                span,
2471                name,
2472                ret_ty,
2473                expected_int_bits,
2474                expected_bytes
2475            }),
2476        }
2477    }
2478
2479    fn simd_simple_float_intrinsic<'ll, 'tcx>(
2480        name: Symbol,
2481        in_elem: Ty<'_>,
2482        in_ty: Ty<'_>,
2483        in_len: u64,
2484        bx: &mut Builder<'_, 'll, 'tcx>,
2485        span: Span,
2486        args: &[OperandRef<'tcx, &'ll Value>],
2487    ) -> Result<&'ll Value, ErrorGuaranteed> {
2488        macro_rules! return_error {
2489            ($diag: expr) => {{
2490                let err = bx.sess().dcx().emit_err($diag);
2491                return Err(err);
2492            }};
2493        }
2494
2495        let ty::Float(f) = in_elem.kind() else {
2496            {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
                span,
                name,
                ty: in_ty,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty });
2497        };
2498        let elem_ty = bx.cx.type_float_from_ty(*f);
2499
2500        let vec_ty = bx.type_vector(elem_ty, in_len);
2501
2502        let intr_name = match name {
2503            sym::simd_ceil => "llvm.ceil",
2504            sym::simd_fabs => "llvm.fabs",
2505            sym::simd_fcos => "llvm.cos",
2506            sym::simd_fexp2 => "llvm.exp2",
2507            sym::simd_fexp => "llvm.exp",
2508            sym::simd_flog10 => "llvm.log10",
2509            sym::simd_flog2 => "llvm.log2",
2510            sym::simd_flog => "llvm.log",
2511            sym::simd_floor => "llvm.floor",
2512            sym::simd_fma => "llvm.fma",
2513            sym::simd_relaxed_fma => "llvm.fmuladd",
2514            sym::simd_fsin => "llvm.sin",
2515            sym::simd_fsqrt => "llvm.sqrt",
2516            sym::simd_round => "llvm.round",
2517            sym::simd_round_ties_even => "llvm.rint",
2518            sym::simd_trunc => "llvm.trunc",
2519            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnrecognizedIntrinsic {
                span,
                name,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
2520        };
2521        Ok(bx.call_intrinsic(
2522            intr_name,
2523            &[vec_ty],
2524            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
2525        ))
2526    }
2527
2528    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_ceil | sym::simd_fabs | sym::simd_fcos | sym::simd_fexp2 |
        sym::simd_fexp | sym::simd_flog10 | sym::simd_flog2 | sym::simd_flog |
        sym::simd_floor | sym::simd_fma | sym::simd_fsin | sym::simd_fsqrt |
        sym::simd_relaxed_fma | sym::simd_round | sym::simd_round_ties_even |
        sym::simd_trunc => true,
    _ => false,
}std::matches!(
2529        name,
2530        sym::simd_ceil
2531            | sym::simd_fabs
2532            | sym::simd_fcos
2533            | sym::simd_fexp2
2534            | sym::simd_fexp
2535            | sym::simd_flog10
2536            | sym::simd_flog2
2537            | sym::simd_flog
2538            | sym::simd_floor
2539            | sym::simd_fma
2540            | sym::simd_fsin
2541            | sym::simd_fsqrt
2542            | sym::simd_relaxed_fma
2543            | sym::simd_round
2544            | sym::simd_round_ties_even
2545            | sym::simd_trunc
2546    ) {
2547        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
2548    }
2549
2550    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> &'ll Type {
2551        let elem_ty = match *elem_ty.kind() {
2552            ty::Int(v) => cx.type_int_from_ty(v),
2553            ty::Uint(v) => cx.type_uint_from_ty(v),
2554            ty::Float(v) => cx.type_float_from_ty(v),
2555            ty::RawPtr(_, _) => cx.type_ptr(),
2556            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2557        };
2558        cx.type_vector(elem_ty, vec_len)
2559    }
2560
2561    if name == sym::simd_gather {
2562        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
2563        //             mask: <N x i{M}>) -> <N x T>
2564        // * N: number of elements in the input vectors
2565        // * T: type of the element to load
2566        // * M: any integer width is supported, will be truncated to i1
2567
2568        // All types must be simd vector types
2569
2570        // The second argument must be a simd vector with an element type that's a pointer
2571        // to the element type of the first argument
2572        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                        span,
                        name,
                        ty: in_ty,
                    });
            return Err(err);
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2573        let (out_len, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2574        // The element type of the third argument must be a signed integer type of any width:
2575        let (out_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: args[2].layout.ty,
                    });
            return Err(err);
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2576        {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2577
2578        // Of the same length:
2579        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[1].layout.ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
2580            in_len == out_len,
2581            InvalidMonomorphization::SecondArgumentLength {
2582                span,
2583                name,
2584                in_len,
2585                in_ty,
2586                arg_ty: args[1].layout.ty,
2587                out_len
2588            }
2589        );
2590        if !(in_len == out_len2) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[2].layout.ty,
                    out_len: out_len2,
                });
        return Err(err);
    };
};require!(
2591            in_len == out_len2,
2592            InvalidMonomorphization::ThirdArgumentLength {
2593                span,
2594                name,
2595                in_len,
2596                in_ty,
2597                arg_ty: args[2].layout.ty,
2598                out_len: out_len2
2599            }
2600        );
2601
2602        // The return type must match the first argument type
2603        if !(ret_ty == in_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                    span,
                    name,
                    in_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2604            ret_ty == in_ty,
2605            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
2606        );
2607
2608        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == in_elem && p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: element_ty1,
                    second_arg: args[1].layout.ty,
                    in_elem,
                    in_ty,
                    mutability: ExpectedPointerMutability::Not,
                });
        return Err(err);
    };
};require!(
2609            matches!(
2610                *element_ty1.kind(),
2611                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
2612            ),
2613            InvalidMonomorphization::ExpectedElementType {
2614                span,
2615                name,
2616                expected_element: element_ty1,
2617                second_arg: args[1].layout.ty,
2618                in_elem,
2619                in_ty,
2620                mutability: ExpectedPointerMutability::Not,
2621            }
2622        );
2623
2624        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: element_ty2,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2625            element_ty2.kind(),
2626            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2627        );
2628
2629        // Alignment of T, must be a constant integer value:
2630        let alignment = bx.align_of(in_elem).bytes();
2631
2632        // Truncate the mask vector to a vector of i1s:
2633        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2634
2635        // Type of the vector of pointers:
2636        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2637
2638        // Type of the vector of elements:
2639        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2640
2641        let call = bx.call_intrinsic(
2642            "llvm.masked.gather",
2643            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2644            &[args[1].immediate(), mask, args[0].immediate()],
2645        );
2646        crate::attributes::apply_to_callsite(
2647            call,
2648            crate::llvm::AttributePlace::Argument(0),
2649            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2650        );
2651        return Ok(call);
2652    }
2653
2654    fn llvm_alignment<'ll, 'tcx>(
2655        bx: &mut Builder<'_, 'll, 'tcx>,
2656        alignment: SimdAlign,
2657        vector_ty: Ty<'tcx>,
2658        element_ty: Ty<'tcx>,
2659    ) -> u64 {
2660        match alignment {
2661            SimdAlign::Unaligned => 1,
2662            SimdAlign::Element => bx.align_of(element_ty).bytes(),
2663            SimdAlign::Vector => bx.align_of(vector_ty).bytes(),
2664        }
2665    }
2666
2667    if name == sym::simd_masked_load {
2668        // simd_masked_load<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
2669        // * N: number of elements in the input vectors
2670        // * T: type of the element to load
2671        // * M: any integer width is supported, will be truncated to i1
2672        // Loads contiguous elements from memory behind `pointer`, but only for
2673        // those lanes whose `mask` bit is enabled.
2674        // The memory addresses corresponding to the “off” lanes are not accessed.
2675
2676        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2677
2678        // The element type of the "mask" argument must be a signed integer type of any width
2679        let mask_ty = in_ty;
2680        let (mask_len, mask_elem) = (in_len, in_elem);
2681
2682        // The second argument must be a pointer matching the element type
2683        let pointer_ty = args[1].layout.ty;
2684
2685        // The last argument is a passthrough vector providing values for disabled lanes
2686        let values_ty = args[2].layout.ty;
2687        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: values_ty,
                    });
            return Err(err);
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2688
2689        {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2690
2691        // Of the same length:
2692        if !(values_len == mask_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len: mask_len,
                    in_ty: mask_ty,
                    arg_ty: values_ty,
                    out_len: values_len,
                });
        return Err(err);
    };
};require!(
2693            values_len == mask_len,
2694            InvalidMonomorphization::ThirdArgumentLength {
2695                span,
2696                name,
2697                in_len: mask_len,
2698                in_ty: mask_ty,
2699                arg_ty: values_ty,
2700                out_len: values_len
2701            }
2702        );
2703
2704        // The return type must match the last argument type
2705        if !(ret_ty == values_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                    span,
                    name,
                    in_ty: values_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2706            ret_ty == values_ty,
2707            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
2708        );
2709
2710        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() =>
                true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: values_elem,
                    second_arg: pointer_ty,
                    in_elem: values_elem,
                    in_ty: values_ty,
                    mutability: ExpectedPointerMutability::Not,
                });
        return Err(err);
    };
};require!(
2711            matches!(
2712                *pointer_ty.kind(),
2713                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
2714            ),
2715            InvalidMonomorphization::ExpectedElementType {
2716                span,
2717                name,
2718                expected_element: values_elem,
2719                second_arg: pointer_ty,
2720                in_elem: values_elem,
2721                in_ty: values_ty,
2722                mutability: ExpectedPointerMutability::Not,
2723            }
2724        );
2725
2726        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: mask_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2727            mask_elem.kind(),
2728            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2729        );
2730
2731        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2732
2733        // Alignment of T, must be a constant integer value:
2734        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2735
2736        let llvm_pointer = bx.type_ptr();
2737
2738        // Type of the vector of elements:
2739        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2740
2741        let call = bx.call_intrinsic(
2742            "llvm.masked.load",
2743            &[llvm_elem_vec_ty, llvm_pointer],
2744            &[args[1].immediate(), mask, args[2].immediate()],
2745        );
2746        crate::attributes::apply_to_callsite(
2747            call,
2748            crate::llvm::AttributePlace::Argument(0),
2749            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2750        );
2751        return Ok(call);
2752    }
2753
2754    if name == sym::simd_masked_store {
2755        // simd_masked_store<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
2756        // * N: number of elements in the input vectors
2757        // * T: type of the element to load
2758        // * M: any integer width is supported, will be truncated to i1
2759        // Stores contiguous elements to memory behind `pointer`, but only for
2760        // those lanes whose `mask` bit is enabled.
2761        // The memory addresses corresponding to the “off” lanes are not accessed.
2762
2763        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2764
2765        // The element type of the "mask" argument must be a signed integer type of any width
2766        let mask_ty = in_ty;
2767        let (mask_len, mask_elem) = (in_len, in_elem);
2768
2769        // The second argument must be a pointer matching the element type
2770        let pointer_ty = args[1].layout.ty;
2771
2772        // The last argument specifies the values to store to memory
2773        let values_ty = args[2].layout.ty;
2774        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: values_ty,
                    });
            return Err(err);
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2775
2776        // Of the same length:
2777        if !(values_len == mask_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len: mask_len,
                    in_ty: mask_ty,
                    arg_ty: values_ty,
                    out_len: values_len,
                });
        return Err(err);
    };
};require!(
2778            values_len == mask_len,
2779            InvalidMonomorphization::ThirdArgumentLength {
2780                span,
2781                name,
2782                in_len: mask_len,
2783                in_ty: mask_ty,
2784                arg_ty: values_ty,
2785                out_len: values_len
2786            }
2787        );
2788
2789        // The second argument must be a mutable pointer type matching the element type
2790        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() &&
                    p_mutbl.is_mut() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: values_elem,
                    second_arg: pointer_ty,
                    in_elem: values_elem,
                    in_ty: values_ty,
                    mutability: ExpectedPointerMutability::Mut,
                });
        return Err(err);
    };
};require!(
2791            matches!(
2792                *pointer_ty.kind(),
2793                ty::RawPtr(p_ty, p_mutbl)
2794                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
2795            ),
2796            InvalidMonomorphization::ExpectedElementType {
2797                span,
2798                name,
2799                expected_element: values_elem,
2800                second_arg: pointer_ty,
2801                in_elem: values_elem,
2802                in_ty: values_ty,
2803                mutability: ExpectedPointerMutability::Mut,
2804            }
2805        );
2806
2807        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: mask_elem,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2808            mask_elem.kind(),
2809            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2810        );
2811
2812        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2813
2814        // Alignment of T, must be a constant integer value:
2815        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2816
2817        let llvm_pointer = bx.type_ptr();
2818
2819        // Type of the vector of elements:
2820        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2821
2822        let call = bx.call_intrinsic(
2823            "llvm.masked.store",
2824            &[llvm_elem_vec_ty, llvm_pointer],
2825            &[args[2].immediate(), args[1].immediate(), mask],
2826        );
2827        crate::attributes::apply_to_callsite(
2828            call,
2829            crate::llvm::AttributePlace::Argument(1),
2830            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2831        );
2832        return Ok(call);
2833    }
2834
2835    if name == sym::simd_scatter {
2836        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
2837        //             mask: <N x i{M}>) -> ()
2838        // * N: number of elements in the input vectors
2839        // * T: type of the element to load
2840        // * M: any integer width is supported, will be truncated to i1
2841
2842        // All types must be simd vector types
2843        // The second argument must be a simd vector with an element type that's a pointer
2844        // to the element type of the first argument
2845        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                        span,
                        name,
                        ty: in_ty,
                    });
            return Err(err);
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2846        let (element_len1, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                        span,
                        name,
                        ty: args[1].layout.ty,
                    });
            return Err(err);
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2847        let (element_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                        span,
                        name,
                        ty: args[2].layout.ty,
                    });
            return Err(err);
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2848
2849        // Of the same length:
2850        if !(in_len == element_len1) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[1].layout.ty,
                    out_len: element_len1,
                });
        return Err(err);
    };
};require!(
2851            in_len == element_len1,
2852            InvalidMonomorphization::SecondArgumentLength {
2853                span,
2854                name,
2855                in_len,
2856                in_ty,
2857                arg_ty: args[1].layout.ty,
2858                out_len: element_len1
2859            }
2860        );
2861        if !(in_len == element_len2) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                    span,
                    name,
                    in_len,
                    in_ty,
                    arg_ty: args[2].layout.ty,
                    out_len: element_len2,
                });
        return Err(err);
    };
};require!(
2862            in_len == element_len2,
2863            InvalidMonomorphization::ThirdArgumentLength {
2864                span,
2865                name,
2866                in_len,
2867                in_ty,
2868                arg_ty: args[2].layout.ty,
2869                out_len: element_len2
2870            }
2871        );
2872
2873        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == in_elem && p_mutbl.is_mut() &&
                    p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                    span,
                    name,
                    expected_element: element_ty1,
                    second_arg: args[1].layout.ty,
                    in_elem,
                    in_ty,
                    mutability: ExpectedPointerMutability::Mut,
                });
        return Err(err);
    };
};require!(
2874            matches!(
2875                *element_ty1.kind(),
2876                ty::RawPtr(p_ty, p_mutbl)
2877                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2878            ),
2879            InvalidMonomorphization::ExpectedElementType {
2880                span,
2881                name,
2882                expected_element: element_ty1,
2883                second_arg: args[1].layout.ty,
2884                in_elem,
2885                in_ty,
2886                mutability: ExpectedPointerMutability::Mut,
2887            }
2888        );
2889
2890        // The element type of the third argument must be an integer type of any width:
2891        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                        span,
                        name,
                        ty: element_ty2,
                    });
            return Err(err);
        };
    }
}require_int_or_uint_ty!(
2892            element_ty2.kind(),
2893            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2894        );
2895
2896        // Alignment of T, must be a constant integer value:
2897        let alignment = bx.align_of(in_elem).bytes();
2898
2899        // Truncate the mask vector to a vector of i1s:
2900        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2901
2902        // Type of the vector of pointers:
2903        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2904
2905        // Type of the vector of elements:
2906        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2907
2908        let call = bx.call_intrinsic(
2909            "llvm.masked.scatter",
2910            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2911            &[args[0].immediate(), args[1].immediate(), mask],
2912        );
2913        crate::attributes::apply_to_callsite(
2914            call,
2915            crate::llvm::AttributePlace::Argument(1),
2916            &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2917        );
2918        return Ok(call);
2919    }
2920
2921    macro_rules! arith_red {
2922        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2923         $identity:expr) => {
2924            if name == sym::$name {
2925                require!(
2926                    ret_ty == in_elem,
2927                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2928                );
2929                return match in_elem.kind() {
2930                    ty::Int(_) | ty::Uint(_) => {
2931                        let r = bx.$integer_reduce(args[0].immediate());
2932                        if $ordered {
2933                            // if overflow occurs, the result is the
2934                            // mathematical result modulo 2^n:
2935                            Ok(bx.$op(args[1].immediate(), r))
2936                        } else {
2937                            Ok(bx.$integer_reduce(args[0].immediate()))
2938                        }
2939                    }
2940                    ty::Float(f) => {
2941                        let acc = if $ordered {
2942                            // ordered arithmetic reductions take an accumulator
2943                            args[1].immediate()
2944                        } else {
2945                            // unordered arithmetic reductions use the identity accumulator
2946                            match f.bit_width() {
2947                                32 => bx.const_real(bx.type_f32(), $identity),
2948                                64 => bx.const_real(bx.type_f64(), $identity),
2949                                v => return_error!(
2950                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2951                                        span,
2952                                        name,
2953                                        symbol: sym::$name,
2954                                        in_ty,
2955                                        in_elem,
2956                                        size: v,
2957                                        ret_ty
2958                                    }
2959                                ),
2960                            }
2961                        };
2962                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2963                    }
2964                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2965                        span,
2966                        name,
2967                        symbol: sym::$name,
2968                        in_ty,
2969                        in_elem,
2970                        ret_ty
2971                    }),
2972                };
2973            }
2974        };
2975    }
2976
2977    if name == sym::simd_reduce_add_ordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if true {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_add_ordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_add_ordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, -0.0);
2978    if name == sym::simd_reduce_mul_ordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if true {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_mul_ordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_mul_ordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
2979    if name == sym::simd_reduce_add_unordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if false {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_add_unordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd_reassoc(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_add_unordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(
2980        simd_reduce_add_unordered: vector_reduce_add,
2981        vector_reduce_fadd_reassoc,
2982        false,
2983        add,
2984        -0.0
2985    );
2986    if name == sym::simd_reduce_mul_unordered {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if false {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                let err =
                                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                            span,
                                            name,
                                            symbol: sym::simd_reduce_mul_unordered,
                                            in_ty,
                                            in_elem,
                                            size: v,
                                            ret_ty,
                                        });
                                return Err(err);
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul_reassoc(acc, args[0].immediate()))
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_mul_unordered,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};arith_red!(
2987        simd_reduce_mul_unordered: vector_reduce_mul,
2988        vector_reduce_fmul_reassoc,
2989        false,
2990        mul,
2991        1.0
2992    );
2993
2994    macro_rules! minmax_red {
2995        ($name:ident: $int_red:ident) => {
2996            if name == sym::$name {
2997                require!(
2998                    ret_ty == in_elem,
2999                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
3000                );
3001                return match in_elem.kind() {
3002                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
3003                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
3004                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3005                        span,
3006                        name,
3007                        symbol: sym::$name,
3008                        in_ty,
3009                        in_elem,
3010                        ret_ty
3011                    }),
3012                };
3013            }
3014        };
3015    }
3016
3017    // Currently no support for float due to <https://github.com/llvm/llvm-project/issues/185827>.
3018    if name == sym::simd_reduce_min {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), false)),
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_min,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};minmax_red!(simd_reduce_min: vector_reduce_min);
3019    if name == sym::simd_reduce_max {
    if !(ret_ty == in_elem) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                        span,
                        name,
                        in_elem,
                        in_ty,
                        ret_ty,
                    });
            return Err(err);
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), false)),
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_max,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};minmax_red!(simd_reduce_max: vector_reduce_max);
3020
3021    macro_rules! bitwise_red {
3022        ($name:ident : $red:ident, $boolean:expr) => {
3023            if name == sym::$name {
3024                let input = if !$boolean {
3025                    require!(
3026                        ret_ty == in_elem,
3027                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
3028                    );
3029                    args[0].immediate()
3030                } else {
3031                    let bitwidth = match in_elem.kind() {
3032                        ty::Int(i) => {
3033                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
3034                        }
3035                        ty::Uint(i) => {
3036                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
3037                        }
3038                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3039                            span,
3040                            name,
3041                            symbol: sym::$name,
3042                            in_ty,
3043                            in_elem,
3044                            ret_ty
3045                        }),
3046                    };
3047
3048                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
3049                };
3050                return match in_elem.kind() {
3051                    ty::Int(_) | ty::Uint(_) => {
3052                        let r = bx.$red(input);
3053                        Ok(r)
3054                    }
3055                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3056                        span,
3057                        name,
3058                        symbol: sym::$name,
3059                        in_ty,
3060                        in_elem,
3061                        ret_ty
3062                    }),
3063                };
3064            }
3065        };
3066    }
3067
3068    if name == sym::simd_reduce_and {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_and,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_and,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_and: vector_reduce_and, false);
3069    if name == sym::simd_reduce_or {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_or,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_or,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_or: vector_reduce_or, false);
3070    if name == sym::simd_reduce_xor {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_xor,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_xor(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_xor,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
3071    if name == sym::simd_reduce_all {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_all,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_all,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_all: vector_reduce_and, true);
3072    if name == sym::simd_reduce_any {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    let err =
                        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                                span,
                                name,
                                in_elem,
                                in_ty,
                                ret_ty,
                            });
                    return Err(err);
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        let err =
                            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                    span,
                                    name,
                                    symbol: sym::simd_reduce_any,
                                    in_ty,
                                    in_elem,
                                    ret_ty,
                                });
                        return Err(err);
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(r)
            }
            _ => {
                let err =
                    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                            span,
                            name,
                            symbol: sym::simd_reduce_any,
                            in_ty,
                            in_elem,
                            ret_ty,
                        });
                return Err(err);
            }
        };
};bitwise_red!(simd_reduce_any: vector_reduce_or, true);
3073
3074    if name == sym::simd_cast_ptr {
3075        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3076        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3077            in_len == out_len,
3078            InvalidMonomorphization::ReturnLengthInputType {
3079                span,
3080                name,
3081                in_len,
3082                in_ty,
3083                ret_ty,
3084                out_len
3085            }
3086        );
3087
3088        match in_elem.kind() {
3089            ty::RawPtr(p_ty, _) => {
3090                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3091                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3092                });
3093                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: in_elem,
                });
        return Err(err);
    };
};require!(
3094                    metadata.is_unit(),
3095                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
3096                );
3097            }
3098            _ => {
3099                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3100            }
3101        }
3102        match out_elem.kind() {
3103            ty::RawPtr(p_ty, _) => {
3104                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3105                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3106                });
3107                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: out_elem,
                });
        return Err(err);
    };
};require!(
3108                    metadata.is_unit(),
3109                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
3110                );
3111            }
3112            _ => {
3113                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3114            }
3115        }
3116
3117        return Ok(args[0].immediate());
3118    }
3119
3120    if name == sym::simd_expose_provenance {
3121        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3122        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3123            in_len == out_len,
3124            InvalidMonomorphization::ReturnLengthInputType {
3125                span,
3126                name,
3127                in_len,
3128                in_ty,
3129                ret_ty,
3130                out_len
3131            }
3132        );
3133
3134        match in_elem.kind() {
3135            ty::RawPtr(_, _) => {}
3136            _ => {
3137                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3138            }
3139        }
3140        match out_elem.kind() {
3141            ty::Uint(ty::UintTy::Usize) => {}
3142            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: out_elem }),
3143        }
3144
3145        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
3146    }
3147
3148    if name == sym::simd_with_exposed_provenance {
3149        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3150        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3151            in_len == out_len,
3152            InvalidMonomorphization::ReturnLengthInputType {
3153                span,
3154                name,
3155                in_len,
3156                in_ty,
3157                ret_ty,
3158                out_len
3159            }
3160        );
3161
3162        match in_elem.kind() {
3163            ty::Uint(ty::UintTy::Usize) => {}
3164            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
                span,
                name,
                ty: in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: in_elem }),
3165        }
3166        match out_elem.kind() {
3167            ty::RawPtr(_, _) => {}
3168            _ => {
3169                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
                span,
                name,
                ty: out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3170            }
3171        }
3172
3173        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
3174    }
3175
3176    if name == sym::simd_cast || name == sym::simd_as {
3177        let (out_len, out_elem, out_num_vecs) = {
    if !(ret_ty.is_simd() || ret_ty.is_scalable_vector()) {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    if ret_ty.is_simd() {
        let (len, ty) = ret_ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            ret_ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(ret_ty, SimdReturn);
3178        if !(in_len == out_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                    span,
                    name,
                    in_len,
                    in_ty,
                    ret_ty,
                    out_len,
                });
        return Err(err);
    };
};require!(
3179            in_len == out_len,
3180            InvalidMonomorphization::ReturnLengthInputType {
3181                span,
3182                name,
3183                in_len,
3184                in_ty,
3185                ret_ty,
3186                out_len
3187            }
3188        );
3189        if !(in_num_vecs == out_num_vecs) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnNumVecsInputType {
                    span,
                    name,
                    in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
                    in_ty,
                    ret_ty,
                    out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1)),
                });
        return Err(err);
    };
};require!(
3190            in_num_vecs == out_num_vecs,
3191            InvalidMonomorphization::ReturnNumVecsInputType {
3192                span,
3193                name,
3194                in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
3195                in_ty,
3196                ret_ty,
3197                out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1))
3198            }
3199        );
3200
3201        // Casting cares about nominal type, not just structural type
3202        if in_elem == out_elem {
3203            return Ok(args[0].immediate());
3204        }
3205
3206        #[derive(#[automatically_derived]
impl ::core::marker::Copy for Sign { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Sign { }
#[automatically_derived]
impl ::core::clone::Clone for Sign {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone)]
3207        enum Sign {
3208            Unsigned,
3209            Signed,
3210        }
3211        use Sign::*;
3212
3213        enum Style {
3214            Float,
3215            Int(Sign),
3216            Unsupported,
3217        }
3218
3219        let (in_style, in_width) = match in_elem.kind() {
3220            // vectors of pointer-sized integers should've been
3221            // disallowed before here, so this unwrap is safe.
3222            ty::Int(i) => (
3223                Style::Int(Signed),
3224                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3225            ),
3226            ty::Uint(u) => (
3227                Style::Int(Unsigned),
3228                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3229            ),
3230            ty::Float(f) => (Style::Float, f.bit_width()),
3231            _ => (Style::Unsupported, 0),
3232        };
3233        let (out_style, out_width) = match out_elem.kind() {
3234            ty::Int(i) => (
3235                Style::Int(Signed),
3236                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3237            ),
3238            ty::Uint(u) => (
3239                Style::Int(Unsigned),
3240                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3241            ),
3242            ty::Float(f) => (Style::Float, f.bit_width()),
3243            _ => (Style::Unsupported, 0),
3244        };
3245
3246        match (in_style, out_style) {
3247            (Style::Int(sign), Style::Int(_)) => {
3248                return Ok(match in_width.cmp(&out_width) {
3249                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
3250                    Ordering::Equal => args[0].immediate(),
3251                    Ordering::Less => match sign {
3252                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
3253                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
3254                    },
3255                });
3256            }
3257            (Style::Int(Sign::Signed), Style::Float) => {
3258                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
3259            }
3260            (Style::Int(Sign::Unsigned), Style::Float) => {
3261                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
3262            }
3263            (Style::Float, Style::Int(sign)) => {
3264                return Ok(match (sign, name == sym::simd_as) {
3265                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
3266                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
3267                    (_, true) => bx.cast_float_to_int(
3268                        #[allow(non_exhaustive_omitted_patterns)] match sign {
    Sign::Signed => true,
    _ => false,
}matches!(sign, Sign::Signed),
3269                        args[0].immediate(),
3270                        llret_ty,
3271                    ),
3272                });
3273            }
3274            (Style::Float, Style::Float) => {
3275                return Ok(match in_width.cmp(&out_width) {
3276                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
3277                    Ordering::Equal => args[0].immediate(),
3278                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
3279                });
3280            }
3281            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedCast {
                span,
                name,
                in_ty,
                in_elem,
                ret_ty,
                out_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnsupportedCast {
3282                span,
3283                name,
3284                in_ty,
3285                in_elem,
3286                ret_ty,
3287                out_elem
3288            }),
3289        }
3290    }
3291    macro_rules! arith_binary {
3292        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3293            $(if name == sym::$name {
3294                match in_elem.kind() {
3295                    $($(ty::$p(_))|* => {
3296                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
3297                    })*
3298                    _ => {},
3299                }
3300                return_error!(
3301                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3302                );
3303            })*
3304        }
3305    }
3306    if name == sym::simd_add {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.add(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fadd(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_sub {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.sub(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fsub(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_mul {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.mul(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fmul(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_div {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.udiv(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.sdiv(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.fdiv(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_rem {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.urem(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.srem(args[0].immediate(), args[1].immediate()))
        }
        ty::Float(_) => {
            return Ok(bx.frem(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_shl {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.shl(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_shr {
    match in_elem.kind() {
        ty::Uint(_) => {
            return Ok(bx.lshr(args[0].immediate(), args[1].immediate()))
        }
        ty::Int(_) => {
            return Ok(bx.ashr(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_and {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.and(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_or {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.or(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_xor {
    match in_elem.kind() {
        ty::Uint(_) | ty::Int(_) => {
            return Ok(bx.xor(args[0].immediate(), args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_maximum_number_nsz {
    match in_elem.kind() {
        ty::Float(_) => {
            return Ok(bx.maximum_number_nsz(args[0].immediate(),
                        args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}
if name == sym::simd_minimum_number_nsz {
    match in_elem.kind() {
        ty::Float(_) => {
            return Ok(bx.minimum_number_nsz(args[0].immediate(),
                        args[1].immediate()))
        }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}arith_binary! {
3307        simd_add: Uint, Int => add, Float => fadd;
3308        simd_sub: Uint, Int => sub, Float => fsub;
3309        simd_mul: Uint, Int => mul, Float => fmul;
3310        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
3311        simd_rem: Uint => urem, Int => srem, Float => frem;
3312        simd_shl: Uint, Int => shl;
3313        simd_shr: Uint => lshr, Int => ashr;
3314        simd_and: Uint, Int => and;
3315        simd_or: Uint, Int => or;
3316        simd_xor: Uint, Int => xor;
3317        simd_maximum_number_nsz: Float => maximum_number_nsz;
3318        simd_minimum_number_nsz: Float => minimum_number_nsz;
3319
3320    }
3321    macro_rules! arith_unary {
3322        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3323            $(if name == sym::$name {
3324                match in_elem.kind() {
3325                    $($(ty::$p(_))|* => {
3326                        return Ok(bx.$call(args[0].immediate()))
3327                    })*
3328                    _ => {},
3329                }
3330                return_error!(
3331                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3332                );
3333            })*
3334        }
3335    }
3336    if name == sym::simd_neg {
    match in_elem.kind() {
        ty::Int(_) => { return Ok(bx.neg(args[0].immediate())) }
        ty::Float(_) => { return Ok(bx.fneg(args[0].immediate())) }
        _ => {}
    }
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                    span,
                    name,
                    in_ty,
                    in_elem,
                });
        return Err(err);
    };
}arith_unary! {
3337        simd_neg: Int => neg, Float => fneg;
3338    }
3339
3340    // Unary integer intrinsics
3341    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctlz | sym::simd_ctpop
        | sym::simd_cttz | sym::simd_carryless_mul | sym::simd_funnel_shl |
        sym::simd_funnel_shr => true,
    _ => false,
}matches!(
3342        name,
3343        sym::simd_bswap
3344            | sym::simd_bitreverse
3345            | sym::simd_ctlz
3346            | sym::simd_ctpop
3347            | sym::simd_cttz
3348            | sym::simd_carryless_mul
3349            | sym::simd_funnel_shl
3350            | sym::simd_funnel_shr
3351    ) {
3352        let vec_ty = bx.cx.type_vector(
3353            match *in_elem.kind() {
3354                ty::Int(i) => bx.cx.type_int_from_ty(i),
3355                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
3356                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                span,
                name,
                in_ty,
                in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnsupportedOperation {
3357                    span,
3358                    name,
3359                    in_ty,
3360                    in_elem
3361                }),
3362            },
3363            in_len as u64,
3364        );
3365        let llvm_intrinsic = match name {
3366            sym::simd_bswap => "llvm.bswap",
3367            sym::simd_bitreverse => "llvm.bitreverse",
3368            sym::simd_ctlz => "llvm.ctlz",
3369            sym::simd_ctpop => "llvm.ctpop",
3370            sym::simd_cttz => "llvm.cttz",
3371            sym::simd_funnel_shl => "llvm.fshl",
3372            sym::simd_funnel_shr => "llvm.fshr",
3373            sym::simd_carryless_mul => "llvm.clmul",
3374            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
3375        };
3376        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
3377
3378        return match name {
3379            // byte swap is no-op for i8/u8
3380            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
3381            sym::simd_ctlz | sym::simd_cttz => {
3382                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
3383                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
3384                Ok(bx.call_intrinsic(
3385                    llvm_intrinsic,
3386                    &[vec_ty],
3387                    &[args[0].immediate(), dont_poison_on_zero],
3388                ))
3389            }
3390            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
3391                // simple unary argument cases
3392                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
3393            }
3394            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
3395                llvm_intrinsic,
3396                &[vec_ty],
3397                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
3398            )),
3399            sym::simd_carryless_mul => Ok(bx.call_intrinsic(
3400                llvm_intrinsic,
3401                &[vec_ty],
3402                &[args[0].immediate(), args[1].immediate()],
3403            )),
3404            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
3405        };
3406    }
3407
3408    if name == sym::simd_arith_offset {
3409        // This also checks that the first operand is a ptr type.
3410        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
3411            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("must be called with a vector of pointer types as first argument"),
    Location::caller())span_bug!(span, "must be called with a vector of pointer types as first argument")
3412        });
3413        let layout = bx.layout_of(pointee);
3414        let ptrs = args[0].immediate();
3415        // The second argument must be a ptr-sized integer.
3416        // (We don't care about the signedness, this is wrapping anyway.)
3417        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
3418        if !#[allow(non_exhaustive_omitted_patterns)] match offsets_elem.kind() {
    ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize) => true,
    _ => false,
}matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
3419            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("must be called with a vector of pointer-sized integers as second argument"),
    Location::caller());span_bug!(
3420                span,
3421                "must be called with a vector of pointer-sized integers as second argument"
3422            );
3423        }
3424        let offsets = args[1].immediate();
3425
3426        return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
3427    }
3428
3429    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
3430        let lhs = args[0].immediate();
3431        let rhs = args[1].immediate();
3432        let is_add = name == sym::simd_saturating_add;
3433        let (signed, elem_ty) = match *in_elem.kind() {
3434            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
3435            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
3436            _ => {
3437                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
                span,
                name,
                expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
                vector_type: args[0].layout.ty,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::ExpectedVectorElementType {
3438                    span,
3439                    name,
3440                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
3441                    vector_type: args[0].layout.ty
3442                });
3443            }
3444        };
3445        let llvm_intrinsic = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
3446            "llvm.{}{}.sat",
3447            if signed { 's' } else { 'u' },
3448            if is_add { "add" } else { "sub" },
3449        );
3450        let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
3451
3452        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
3453    }
3454
3455    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("unknown SIMD intrinsic"), Location::caller());span_bug!(span, "unknown SIMD intrinsic");
3456}
3457
3458fn codegen_codeview_annotation<'ll, 'tcx>(
3459    bx: &mut Builder<'_, 'll, 'tcx>,
3460    instance: ty::Instance<'tcx>,
3461    span: Span,
3462) {
3463    // This function lowers the `codeview_annotation` intrinsic,
3464    // which is declared like this:
3465    //
3466    // trait CodeViewAnnotationArgs {
3467    //     const ARGS: &[&str];
3468    // }
3469    //
3470    // fn codeview_annotation<T: CodeViewAnnotationArgs>() {}
3471    //
3472    // It finds the `T: CodeViewAnnotationArgs` trait bound, locates
3473    // `ARGS`, const evaluates it, reads the strings off the resulting
3474    // allocation and lowers them.
3475
3476    const ARGS_CONST_NAME: &str = "`CodeViewAnnotationArgs::ARGS`";
3477
3478    let tcx = bx.tcx();
3479
3480    // Locate `ARGS`
3481    let Some((args_const_def_id, generic_args)) = tcx
3482        .explicit_clauses_of(instance.def_id())
3483        .instantiate_own(tcx, instance.args)
3484        .filter_map(|(clause, _)| clause.skip_norm_wip().as_trait_clause())
3485        .find_map(|trait_clause| {
3486            let trait_ref = trait_clause.skip_binder().trait_ref;
3487            tcx.associated_items(trait_ref.def_id)
3488                .in_definition_order()
3489                .find(|item| {
3490                    item.tag() == ty::AssocTag::Const
3491                        && tcx.item_name(item.def_id).as_str() == "ARGS"
3492                })
3493                .map(|item| (item.def_id, trait_ref.args))
3494        })
3495    else {
3496        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("could not find {0}", ARGS_CONST_NAME), Location::caller());span_bug!(span, "could not find {ARGS_CONST_NAME}");
3497    };
3498
3499    // Const evaluate `ARGS`
3500    let args_const_val = match tcx.const_eval_resolve(
3501        bx.typing_env(),
3502        mir::UnevaluatedConst::new(args_const_def_id, generic_args),
3503        span,
3504    ) {
3505        Ok(val) => val,
3506        Err(ErrorHandled::Reported(..)) => return,
3507        Err(ErrorHandled::TooGeneric(_)) => {
3508            ::rustc_span::macros::bug_impl(Some(span),
    format_args!("{0} is too generic", ARGS_CONST_NAME), Location::caller())span_bug!(span, "{ARGS_CONST_NAME} is too generic")
3509        }
3510    };
3511
3512    // Read the strings
3513    let array_alloc = match args_const_val {
3514        mir::ConstValue::Indirect { alloc_id, offset } => read_slice_pointer(tcx, alloc_id, offset)
3515            .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} slice pointer", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} slice pointer")),
3516        _ => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("unexpected {0} value: {1:?}", ARGS_CONST_NAME,
        args_const_val), Location::caller())span_bug!(span, "unexpected {ARGS_CONST_NAME} value: {args_const_val:?}"),
3517    };
3518
3519    let strings = array_alloc.into_iter().flat_map(|(array_alloc_id, array_offset, array_len)| {
3520        (0..array_len).map(move |index| {
3521            let elem_size = tcx.data_layout.pointer_size().bytes() * 2; // Multiplying by 2 for fat pointers
3522            let elem_offset = array_offset + Size::from_bytes(index * elem_size);
3523
3524            let (string_alloc_id, string_offset, string_len) =
3525                match read_slice_pointer(tcx, array_alloc_id, elem_offset) {
3526                    Ok(Some(slice)) => slice,
3527                    Ok(None) => return &[] as &[u8],
3528                    Err(()) => ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string pointer", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string pointer"),
3529                };
3530
3531            resolve_alloc(tcx, string_alloc_id)
3532                .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string allocation", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string allocation"))
3533                .get_bytes_strip_provenance(
3534                    &tcx,
3535                    alloc_range(string_offset, Size::from_bytes(string_len)),
3536                )
3537                .unwrap_or_else(|_| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("invalid {0} string bytes", ARGS_CONST_NAME),
    Location::caller())span_bug!(span, "invalid {ARGS_CONST_NAME} string bytes"))
3538        })
3539    });
3540
3541    // Lower the strings
3542    let md_strings: Vec<&Metadata> = strings.map(|s| bx.cx.create_metadata(s)).collect();
3543    let md_tuple = bx.cx.md_node_in_context(&md_strings);
3544    let md_value = bx.cx.get_metadata_value(md_tuple);
3545    let (fn_ty, intrinsic_fn) = bx.cx.get_intrinsic("llvm.codeview.annotation".into(), &[]);
3546
3547    bx.call(fn_ty, None, None, intrinsic_fn, ReturnSlot::Direct, &[md_value], None, None);
3548}
3549
3550// Reads the slice pointer stored at `offset` in `alloc_id` and
3551// returns its pointee's allocation ID, relative byte offset
3552// and slice length. Returns `None` for an empty slice.
3553fn read_slice_pointer<'tcx>(
3554    tcx: TyCtxt<'tcx>,
3555    alloc_id: AllocId,
3556    offset: Size,
3557) -> Result<Option<(AllocId, Size, u64)>, ()> {
3558    let alloc = resolve_alloc(tcx, alloc_id)?;
3559    let pointer_size = tcx.data_layout.pointer_size();
3560
3561    let pointer = alloc
3562        .read_scalar(&tcx, alloc_range(offset, pointer_size), true)
3563        .map_err(|_| ())?
3564        .to_pointer(&tcx);
3565
3566    let len = alloc
3567        .read_scalar(&tcx, alloc_range(offset + pointer_size, pointer_size), false)
3568        .map_err(|_| ())?
3569        .to_target_usize(&tcx)
3570        .discard_err()
3571        .ok_or(())?;
3572
3573    if len == 0 {
3574        return Ok(None);
3575    }
3576
3577    let (provenance, offset) =
3578        pointer.into_pointer_or_addr().map_err(|_| ())?.prov_and_relative_offset();
3579
3580    Ok(Some((provenance.alloc_id(), offset, len)))
3581}
3582
3583fn resolve_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId) -> Result<&'tcx Allocation, ()> {
3584    let alloc = match tcx.global_alloc(alloc_id) {
3585        GlobalAlloc::Memory(alloc) => alloc,
3586        GlobalAlloc::Static(def_id) => tcx.eval_static_initializer(def_id).map_err(|_| ())?,
3587        _ => return Err(()),
3588    }
3589    .inner();
3590
3591    Ok(alloc)
3592}