rustc_codegen_llvm/
abi.rs

1use std::borrow::Borrow;
2use std::cmp;
3
4use libc::c_uint;
5use rustc_abi::{
6    ArmCall, BackendRepr, CanonAbi, HasDataLayout, InterruptKind, Primitive, Reg, RegKind, Size,
7    X86Call,
8};
9use rustc_codegen_ssa::MemFlags;
10use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
11use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
12use rustc_codegen_ssa::traits::*;
13use rustc_middle::ty::Ty;
14use rustc_middle::ty::layout::LayoutOf;
15use rustc_middle::{bug, ty};
16use rustc_session::config;
17use rustc_target::callconv::{
18    ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, FnAbi, PassMode,
19};
20use rustc_target::spec::SanitizerSet;
21use smallvec::SmallVec;
22
23use crate::attributes::{self, llfn_attrs_from_instance};
24use crate::builder::Builder;
25use crate::context::CodegenCx;
26use crate::llvm::{self, Attribute, AttributePlace};
27use crate::llvm_util;
28use crate::type_::Type;
29use crate::type_of::LayoutLlvmExt;
30use crate::value::Value;
31
32trait ArgAttributesExt {
33    fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
34    fn apply_attrs_to_callsite(
35        &self,
36        idx: AttributePlace,
37        cx: &CodegenCx<'_, '_>,
38        callsite: &Value,
39    );
40}
41
42const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
43    [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
44
45const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 5] = [
46    (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
47    (ArgAttribute::NoCapture, llvm::AttributeKind::NoCapture),
48    (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
49    (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
50    (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
51];
52
53fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
54    let mut regular = this.regular;
55
56    let mut attrs = SmallVec::new();
57
58    // ABI-affecting attributes must always be applied
59    for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
60        if regular.contains(attr) {
61            attrs.push(llattr.create_attr(cx.llcx));
62        }
63    }
64    if let Some(align) = this.pointee_align {
65        attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
66    }
67    match this.arg_ext {
68        ArgExtension::None => {}
69        ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
70        ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
71    }
72
73    // Only apply remaining attributes when optimizing
74    if cx.sess().opts.optimize != config::OptLevel::No {
75        let deref = this.pointee_size.bytes();
76        if deref != 0 {
77            if regular.contains(ArgAttribute::NonNull) {
78                attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
79            } else {
80                attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
81            }
82            regular -= ArgAttribute::NonNull;
83        }
84        for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
85            if regular.contains(attr) {
86                attrs.push(llattr.create_attr(cx.llcx));
87            }
88        }
89    } else if cx.tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
90        // If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
91        // memory sanitizer's behavior.
92
93        if regular.contains(ArgAttribute::NoUndef) {
94            attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
95        }
96    }
97
98    attrs
99}
100
101impl ArgAttributesExt for ArgAttributes {
102    fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
103        let attrs = get_attrs(self, cx);
104        attributes::apply_to_llfn(llfn, idx, &attrs);
105    }
106
107    fn apply_attrs_to_callsite(
108        &self,
109        idx: AttributePlace,
110        cx: &CodegenCx<'_, '_>,
111        callsite: &Value,
112    ) {
113        let attrs = get_attrs(self, cx);
114        attributes::apply_to_callsite(callsite, idx, &attrs);
115    }
116}
117
118pub(crate) trait LlvmType {
119    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
120}
121
122impl LlvmType for Reg {
123    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
124        match self.kind {
125            RegKind::Integer => cx.type_ix(self.size.bits()),
126            RegKind::Float => match self.size.bits() {
127                16 => cx.type_f16(),
128                32 => cx.type_f32(),
129                64 => cx.type_f64(),
130                128 => cx.type_f128(),
131                _ => bug!("unsupported float: {:?}", self),
132            },
133            RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
134        }
135    }
136}
137
138impl LlvmType for CastTarget {
139    fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
140        let rest_ll_unit = self.rest.unit.llvm_type(cx);
141        let rest_count = if self.rest.total == Size::ZERO {
142            0
143        } else {
144            assert_ne!(
145                self.rest.unit.size,
146                Size::ZERO,
147                "total size {:?} cannot be divided into units of zero size",
148                self.rest.total
149            );
150            if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
151                assert_eq!(self.rest.unit.kind, RegKind::Integer, "only int regs can be split");
152            }
153            self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
154        };
155
156        // Simplify to a single unit or an array if there's no prefix.
157        // This produces the same layout, but using a simpler type.
158        if self.prefix.iter().all(|x| x.is_none()) {
159            // We can't do this if is_consecutive is set and the unit would get
160            // split on the target. Currently, this is only relevant for i128
161            // registers.
162            if rest_count == 1 && (!self.rest.is_consecutive || self.rest.unit != Reg::i128()) {
163                return rest_ll_unit;
164            }
165
166            return cx.type_array(rest_ll_unit, rest_count);
167        }
168
169        // Generate a struct type with the prefix and the "rest" arguments.
170        let prefix_args =
171            self.prefix.iter().flat_map(|option_reg| option_reg.map(|reg| reg.llvm_type(cx)));
172        let rest_args = (0..rest_count).map(|_| rest_ll_unit);
173        let args: Vec<_> = prefix_args.chain(rest_args).collect();
174        cx.type_struct(&args, false)
175    }
176}
177
178trait ArgAbiExt<'ll, 'tcx> {
179    fn store(
180        &self,
181        bx: &mut Builder<'_, 'll, 'tcx>,
182        val: &'ll Value,
183        dst: PlaceRef<'tcx, &'ll Value>,
184    );
185    fn store_fn_arg(
186        &self,
187        bx: &mut Builder<'_, 'll, 'tcx>,
188        idx: &mut usize,
189        dst: PlaceRef<'tcx, &'ll Value>,
190    );
191}
192
193impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
194    /// Stores a direct/indirect value described by this ArgAbi into a
195    /// place for the original Rust type of this argument/return.
196    /// Can be used for both storing formal arguments into Rust variables
197    /// or results of call/invoke instructions into their destinations.
198    fn store(
199        &self,
200        bx: &mut Builder<'_, 'll, 'tcx>,
201        val: &'ll Value,
202        dst: PlaceRef<'tcx, &'ll Value>,
203    ) {
204        match &self.mode {
205            PassMode::Ignore => {}
206            // Sized indirect arguments
207            PassMode::Indirect { attrs, meta_attrs: None, on_stack: _ } => {
208                let align = attrs.pointee_align.unwrap_or(self.layout.align.abi);
209                OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
210            }
211            // Unsized indirect qrguments
212            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
213                bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
214            }
215            PassMode::Cast { cast, pad_i32: _ } => {
216                // The ABI mandates that the value is passed as a different struct representation.
217                // Spill and reload it from the stack to convert from the ABI representation to
218                // the Rust representation.
219                let scratch_size = cast.size(bx);
220                let scratch_align = cast.align(bx);
221                // Note that the ABI type may be either larger or smaller than the Rust type,
222                // due to the presence or absence of trailing padding. For example:
223                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
224                //   when passed by value, making it smaller.
225                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
226                //   when passed by value, making it larger.
227                let copy_bytes =
228                    cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
229                // Allocate some scratch space...
230                let llscratch = bx.alloca(scratch_size, scratch_align);
231                bx.lifetime_start(llscratch, scratch_size);
232                // ...store the value...
233                rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
234                // ... and then memcpy it to the intended destination.
235                bx.memcpy(
236                    dst.val.llval,
237                    self.layout.align.abi,
238                    llscratch,
239                    scratch_align,
240                    bx.const_usize(copy_bytes),
241                    MemFlags::empty(),
242                );
243                bx.lifetime_end(llscratch, scratch_size);
244            }
245            _ => {
246                OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
247            }
248        }
249    }
250
251    fn store_fn_arg(
252        &self,
253        bx: &mut Builder<'_, 'll, 'tcx>,
254        idx: &mut usize,
255        dst: PlaceRef<'tcx, &'ll Value>,
256    ) {
257        let mut next = || {
258            let val = llvm::get_param(bx.llfn(), *idx as c_uint);
259            *idx += 1;
260            val
261        };
262        match self.mode {
263            PassMode::Ignore => {}
264            PassMode::Pair(..) => {
265                OperandValue::Pair(next(), next()).store(bx, dst);
266            }
267            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
268                let place_val = PlaceValue {
269                    llval: next(),
270                    llextra: Some(next()),
271                    align: self.layout.align.abi,
272                };
273                OperandValue::Ref(place_val).store(bx, dst);
274            }
275            PassMode::Direct(_)
276            | PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ }
277            | PassMode::Cast { .. } => {
278                let next_arg = next();
279                self.store(bx, next_arg, dst);
280            }
281        }
282    }
283}
284
285impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
286    fn store_fn_arg(
287        &mut self,
288        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
289        idx: &mut usize,
290        dst: PlaceRef<'tcx, Self::Value>,
291    ) {
292        arg_abi.store_fn_arg(self, idx, dst)
293    }
294    fn store_arg(
295        &mut self,
296        arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
297        val: &'ll Value,
298        dst: PlaceRef<'tcx, &'ll Value>,
299    ) {
300        arg_abi.store(self, val, dst)
301    }
302}
303
304pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
305    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
306    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
307    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
308
309    /// Apply attributes to a function declaration/definition.
310    fn apply_attrs_llfn(
311        &self,
312        cx: &CodegenCx<'ll, 'tcx>,
313        llfn: &'ll Value,
314        instance: Option<ty::Instance<'tcx>>,
315    );
316
317    /// Apply attributes to a function call.
318    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
319}
320
321impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
322    fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
323        // Ignore "extra" args from the call site for C variadic functions.
324        // Only the "fixed" args are part of the LLVM function signature.
325        let args =
326            if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
327
328        // This capacity calculation is approximate.
329        let mut llargument_tys = Vec::with_capacity(
330            self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
331        );
332
333        let llreturn_ty = match &self.ret.mode {
334            PassMode::Ignore => cx.type_void(),
335            PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
336            PassMode::Cast { cast, pad_i32: _ } => cast.llvm_type(cx),
337            PassMode::Indirect { .. } => {
338                llargument_tys.push(cx.type_ptr());
339                cx.type_void()
340            }
341        };
342
343        for arg in args {
344            // Note that the exact number of arguments pushed here is carefully synchronized with
345            // code all over the place, both in the codegen_llvm and codegen_ssa crates. That's how
346            // other code then knows which LLVM argument(s) correspond to the n-th Rust argument.
347            let llarg_ty = match &arg.mode {
348                PassMode::Ignore => continue,
349                PassMode::Direct(_) => {
350                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
351                    // and for Scalar ABIs the LLVM type is fully determined by `layout.abi`,
352                    // guaranteeing that we generate ABI-compatible LLVM IR.
353                    arg.layout.immediate_llvm_type(cx)
354                }
355                PassMode::Pair(..) => {
356                    // ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
357                    // so for ScalarPair we can easily be sure that we are generating ABI-compatible
358                    // LLVM IR.
359                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
360                    llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
361                    continue;
362                }
363                PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
364                    // Construct the type of a (wide) pointer to `ty`, and pass its two fields.
365                    // Any two ABI-compatible unsized types have the same metadata type and
366                    // moreover the same metadata value leads to the same dynamic size and
367                    // alignment, so this respects ABI compatibility.
368                    let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
369                    let ptr_layout = cx.layout_of(ptr_ty);
370                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
371                    llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
372                    continue;
373                }
374                PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ } => cx.type_ptr(),
375                PassMode::Cast { cast, pad_i32 } => {
376                    // add padding
377                    if *pad_i32 {
378                        llargument_tys.push(Reg::i32().llvm_type(cx));
379                    }
380                    // Compute the LLVM type we use for this function from the cast type.
381                    // We assume here that ABI-compatible Rust types have the same cast type.
382                    cast.llvm_type(cx)
383                }
384            };
385            llargument_tys.push(llarg_ty);
386        }
387
388        if self.c_variadic {
389            cx.type_variadic_func(&llargument_tys, llreturn_ty)
390        } else {
391            cx.type_func(&llargument_tys, llreturn_ty)
392        }
393    }
394
395    fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
396        cx.type_ptr_ext(cx.data_layout().instruction_address_space)
397    }
398
399    fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
400        llvm::CallConv::from_conv(self.conv, cx.tcx.sess.target.arch.borrow())
401    }
402
403    fn apply_attrs_llfn(
404        &self,
405        cx: &CodegenCx<'ll, 'tcx>,
406        llfn: &'ll Value,
407        instance: Option<ty::Instance<'tcx>>,
408    ) {
409        let mut func_attrs = SmallVec::<[_; 3]>::new();
410        if self.ret.layout.is_uninhabited() {
411            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
412        }
413        if !self.can_unwind {
414            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
415        }
416        match self.conv {
417            CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
418                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
419            }
420            CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
421                func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
422            }
423            CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
424                func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
425            }
426            _ => (),
427        }
428        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
429
430        let mut i = 0;
431        let mut apply = |attrs: &ArgAttributes| {
432            attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
433            i += 1;
434            i - 1
435        };
436
437        let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
438            if cx.sess().opts.optimize != config::OptLevel::No
439                && matches!(scalar.primitive(), Primitive::Int(..))
440                // If the value is a boolean, the range is 0..2 and that ultimately
441                // become 0..0 when the type becomes i1, which would be rejected
442                // by the LLVM verifier.
443                && !scalar.is_bool()
444                // LLVM also rejects full range.
445                && !scalar.is_always_valid(cx)
446            {
447                attributes::apply_to_llfn(
448                    llfn,
449                    idx,
450                    &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
451                );
452            }
453        };
454
455        match &self.ret.mode {
456            PassMode::Direct(attrs) => {
457                attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
458                if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
459                    apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
460                }
461            }
462            PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
463                assert!(!on_stack);
464                let i = apply(attrs);
465                let sret = llvm::CreateStructRetAttr(
466                    cx.llcx,
467                    cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
468                );
469                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
470                if cx.sess().opts.optimize != config::OptLevel::No {
471                    attributes::apply_to_llfn(
472                        llfn,
473                        llvm::AttributePlace::Argument(i),
474                        &[
475                            llvm::AttributeKind::Writable.create_attr(cx.llcx),
476                            llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
477                        ],
478                    );
479                }
480            }
481            PassMode::Cast { cast, pad_i32: _ } => {
482                cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
483            }
484            _ => {}
485        }
486        for arg in self.args.iter() {
487            match &arg.mode {
488                PassMode::Ignore => {}
489                PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
490                    let i = apply(attrs);
491                    let byval = llvm::CreateByValAttr(
492                        cx.llcx,
493                        cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
494                    );
495                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
496                }
497                PassMode::Direct(attrs) => {
498                    let i = apply(attrs);
499                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
500                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
501                    }
502                }
503                PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
504                    let i = apply(attrs);
505                    if cx.sess().opts.optimize != config::OptLevel::No
506                        && llvm_util::get_version() >= (21, 0, 0)
507                    {
508                        attributes::apply_to_llfn(
509                            llfn,
510                            llvm::AttributePlace::Argument(i),
511                            &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
512                        );
513                    }
514                }
515                PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => {
516                    assert!(!on_stack);
517                    apply(attrs);
518                    apply(meta_attrs);
519                }
520                PassMode::Pair(a, b) => {
521                    let i = apply(a);
522                    let ii = apply(b);
523                    if let BackendRepr::ScalarPair(scalar_a, scalar_b) = arg.layout.backend_repr {
524                        apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
525                        apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
526                    }
527                }
528                PassMode::Cast { cast, pad_i32 } => {
529                    if *pad_i32 {
530                        apply(&ArgAttributes::new());
531                    }
532                    apply(&cast.attrs);
533                }
534            }
535        }
536
537        // If the declaration has an associated instance, compute extra attributes based on that.
538        if let Some(instance) = instance {
539            llfn_attrs_from_instance(cx, llfn, instance);
540        }
541    }
542
543    fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
544        let mut func_attrs = SmallVec::<[_; 2]>::new();
545        if self.ret.layout.is_uninhabited() {
546            func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
547        }
548        if !self.can_unwind {
549            func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
550        }
551        attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
552
553        let mut i = 0;
554        let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
555            attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
556            i += 1;
557            i - 1
558        };
559        match &self.ret.mode {
560            PassMode::Direct(attrs) => {
561                attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
562            }
563            PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
564                assert!(!on_stack);
565                let i = apply(bx.cx, attrs);
566                let sret = llvm::CreateStructRetAttr(
567                    bx.cx.llcx,
568                    bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
569                );
570                attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
571            }
572            PassMode::Cast { cast, pad_i32: _ } => {
573                cast.attrs.apply_attrs_to_callsite(
574                    llvm::AttributePlace::ReturnValue,
575                    bx.cx,
576                    callsite,
577                );
578            }
579            _ => {}
580        }
581        for arg in self.args.iter() {
582            match &arg.mode {
583                PassMode::Ignore => {}
584                PassMode::Indirect { attrs, meta_attrs: None, on_stack: true } => {
585                    let i = apply(bx.cx, attrs);
586                    let byval = llvm::CreateByValAttr(
587                        bx.cx.llcx,
588                        bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
589                    );
590                    attributes::apply_to_callsite(
591                        callsite,
592                        llvm::AttributePlace::Argument(i),
593                        &[byval],
594                    );
595                }
596                PassMode::Direct(attrs)
597                | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
598                    apply(bx.cx, attrs);
599                }
600                PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack: _ } => {
601                    apply(bx.cx, attrs);
602                    apply(bx.cx, meta_attrs);
603                }
604                PassMode::Pair(a, b) => {
605                    apply(bx.cx, a);
606                    apply(bx.cx, b);
607                }
608                PassMode::Cast { cast, pad_i32 } => {
609                    if *pad_i32 {
610                        apply(bx.cx, &ArgAttributes::new());
611                    }
612                    apply(bx.cx, &cast.attrs);
613                }
614            }
615        }
616
617        let cconv = self.llvm_cconv(&bx.cx);
618        if cconv != llvm::CCallConv {
619            llvm::SetInstructionCallConv(callsite, cconv);
620        }
621
622        if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
623            // This will probably get ignored on all targets but those supporting the TrustZone-M
624            // extension (thumbv8m targets).
625            let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
626            attributes::apply_to_callsite(
627                callsite,
628                llvm::AttributePlace::Function,
629                &[cmse_nonsecure_call],
630            );
631        }
632
633        // Some intrinsics require that an elementtype attribute (with the pointee type of a
634        // pointer argument) is added to the callsite.
635        let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
636        if element_type_index >= 0 {
637            let arg_ty = self.args[element_type_index as usize].layout.ty;
638            let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
639            let element_type_attr = unsafe {
640                llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
641            };
642            attributes::apply_to_callsite(
643                callsite,
644                llvm::AttributePlace::Argument(element_type_index as u32),
645                &[element_type_attr],
646            );
647        }
648    }
649}
650
651impl AbiBuilderMethods for Builder<'_, '_, '_> {
652    fn get_param(&mut self, index: usize) -> Self::Value {
653        llvm::get_param(self.llfn(), index as c_uint)
654    }
655}
656
657impl llvm::CallConv {
658    pub(crate) fn from_conv(conv: CanonAbi, arch: &str) -> Self {
659        match conv {
660            CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
661            CanonAbi::RustCold => llvm::PreserveMost,
662            // Functions with this calling convention can only be called from assembly, but it is
663            // possible to declare an `extern "custom"` block, so the backend still needs a calling
664            // convention for declaring foreign functions.
665            CanonAbi::Custom => llvm::CCallConv,
666            CanonAbi::GpuKernel => {
667                if arch == "amdgpu" {
668                    llvm::AmdgpuKernel
669                } else if arch == "nvptx64" {
670                    llvm::PtxKernel
671                } else {
672                    panic!("Architecture {arch} does not support GpuKernel calling convention");
673                }
674            }
675            CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
676                InterruptKind::Avr => llvm::AvrInterrupt,
677                InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
678                InterruptKind::Msp430 => llvm::Msp430Intr,
679                InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
680                InterruptKind::X86 => llvm::X86_Intr,
681            },
682            CanonAbi::Arm(arm_call) => match arm_call {
683                ArmCall::Aapcs => llvm::ArmAapcsCallConv,
684                ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
685            },
686            CanonAbi::X86(x86_call) => match x86_call {
687                X86Call::Fastcall => llvm::X86FastcallCallConv,
688                X86Call::Stdcall => llvm::X86StdcallCallConv,
689                X86Call::SysV64 => llvm::X86_64_SysV,
690                X86Call::Thiscall => llvm::X86_ThisCall,
691                X86Call::Vectorcall => llvm::X86_VectorCall,
692                X86Call::Win64 => llvm::X86_64_Win64,
693            },
694        }
695    }
696}