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