rustc_codegen_llvm/
intrinsic.rs

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