Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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