Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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