Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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