Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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