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