Skip to main content

rustc_codegen_llvm/
abi.rs

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