rustc_codegen_llvm/
abi.rs

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