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