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