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;
13use rustc_middle::ty::Ty;
14use rustc_middle::ty::layout::LayoutOf;
15use rustc_session::{Session, config};
16use rustc_span::bug;
17use rustc_target::callconv::{
18 ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, FnAbi, IndirectMode, PassMode,
19};
20use rustc_target::spec::{Arch, 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, Type, Value};
27use crate::type_of::LayoutLlvmExt;
28
29trait ArgAttributesExt {
30 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
31 fn apply_attrs_to_callsite(
32 &self,
33 idx: AttributePlace,
34 cx: &CodegenCx<'_, '_>,
35 callsite: &Value,
36 );
37}
38
39const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
40 [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
41
42const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 6] = [
43 (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
44 (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
45 (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
46 (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
47 (ArgAttribute::Writable, llvm::AttributeKind::Writable),
48 (ArgAttribute::NoFree, llvm::AttributeKind::NoFree),
52];
53
54const CAPTURES_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 3] = [
55 (ArgAttribute::CapturesNone, llvm::AttributeKind::CapturesNone),
56 (ArgAttribute::CapturesAddress, llvm::AttributeKind::CapturesAddress),
57 (ArgAttribute::CapturesReadOnly, llvm::AttributeKind::CapturesReadOnly),
58];
59
60fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
61 let mut regular = this.regular;
62
63 let mut attrs = SmallVec::new();
64
65 for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
67 if regular.contains(attr) {
68 attrs.push(llattr.create_attr(cx.llcx));
69 }
70 }
71 if let Some(align) = this.pointee_align {
72 attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
73 }
74 match this.arg_ext {
75 ArgExtension::None => {}
76 ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
77 ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
78 }
79
80 if cx.sess().opts.optimize != config::OptLevel::No {
82 let deref = this.pointee_size.bytes();
83 let llvm_version = crate::llvm_util::get_version();
87 if deref != 0 && (llvm_version >= (23, 0, 0) || regular.contains(ArgAttribute::NoFree)) {
88 if regular.contains(ArgAttribute::NonNull) {
89 attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
90 } else {
91 attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
92 }
93 regular -= ArgAttribute::NonNull;
94 }
95 for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
96 if regular.contains(attr) {
97 attrs.push(llattr.create_attr(cx.llcx));
98 }
99 }
100 for (attr, llattr) in CAPTURES_ATTRIBUTES {
101 if regular.contains(attr) {
102 attrs.push(llattr.create_attr(cx.llcx));
103 break;
104 }
105 }
106 } else if cx.tcx.sess.sanitizers().contains(SanitizerSet::MEMORY) {
107 if regular.contains(ArgAttribute::NoUndef) {
111 attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
112 }
113 }
114
115 attrs
116}
117
118impl ArgAttributesExt for ArgAttributes {
119 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
120 let attrs = get_attrs(self, cx);
121 attributes::apply_to_llfn(llfn, idx, &attrs);
122 }
123
124 fn apply_attrs_to_callsite(
125 &self,
126 idx: AttributePlace,
127 cx: &CodegenCx<'_, '_>,
128 callsite: &Value,
129 ) {
130 let attrs = get_attrs(self, cx);
131 attributes::apply_to_callsite(callsite, idx, &attrs);
132 }
133}
134
135pub(crate) trait LlvmType {
136 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
137}
138
139impl LlvmType for Reg {
140 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
141 match self.kind {
142 RegKind::Integer => cx.type_ix(self.size.bits()),
143 RegKind::Float => match self.size.bits() {
144 16 => cx.type_f16(),
145 32 => cx.type_f32(),
146 64 => cx.type_f64(),
147 128 => cx.type_f128(),
148 _ => ::rustc_span::macros::bug_impl(None,
format_args!("unsupported float: {0:?}", self), Location::caller())bug!("unsupported float: {:?}", self),
149 },
150 RegKind::PpcF128 => cx.type_ppcf128(),
151 RegKind::Vector { hint_vector_elem } => {
152 let ty = match hint_vector_elem {
156 Primitive::Int(integer, _) => match integer {
157 Integer::I8 => cx.type_ix(8),
158 Integer::I16 => cx.type_ix(16),
159 Integer::I32 => cx.type_ix(32),
160 Integer::I64 => cx.type_ix(64),
161 Integer::I128 => cx.type_ix(128),
162 },
163 Primitive::Float(float) => match float {
164 Float::F16 => cx.type_f16(),
165 Float::F16B => cx.type_f16b(),
166 Float::F32 => cx.type_f32(),
167 Float::F64 => cx.type_f64(),
168 Float::F128 => cx.type_f128(),
169 Float::PpcF128 => ::rustc_span::macros::bug_impl(None,
format_args!("ppcf128 is not a valid vector element type"),
Location::caller())bug!("ppcf128 is not a valid vector element type"),
170 },
171 Primitive::Pointer(_) => cx.type_ptr(),
172 };
173
174 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()));
175 let len = self.size.bytes() / hint_vector_elem.size(cx).bytes();
176 cx.type_vector(ty, len)
177 }
178 }
179 }
180}
181
182impl LlvmType for CastTarget {
183 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
184 let rest_ll_unit = self.rest.unit.llvm_type(cx);
185 let rest_count = if self.rest.total == Size::ZERO {
186 0
187 } else {
188 {
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!(
189 self.rest.unit.size,
190 Size::ZERO,
191 "total size {:?} cannot be divided into units of zero size",
192 self.rest.total
193 );
194 if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
195 {
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");
196 }
197 self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
198 };
199
200 if self.prefix.is_empty() {
202 if rest_count == 1 && !self.rest.is_consecutive {
210 return rest_ll_unit;
211 }
212
213 return cx.type_array(rest_ll_unit, rest_count);
214 }
215
216 let prefix_args = self.prefix.iter().map(|reg| reg.llvm_type(cx));
218 let rest_args = (0..rest_count).map(|_| rest_ll_unit);
219 let args: Vec<_> = prefix_args.chain(rest_args).collect();
220 cx.type_struct(&args, false)
221 }
222}
223
224trait ArgAbiExt<'ll, 'tcx> {
225 fn store(
226 &self,
227 bx: &mut Builder<'_, 'll, 'tcx>,
228 val: &'ll Value,
229 dst: PlaceRef<'tcx, &'ll Value>,
230 );
231 fn store_fn_arg(
232 &self,
233 bx: &mut Builder<'_, 'll, 'tcx>,
234 idx: &mut usize,
235 dst: PlaceRef<'tcx, &'ll Value>,
236 );
237}
238
239impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
240 fn store(
245 &self,
246 bx: &mut Builder<'_, 'll, 'tcx>,
247 val: &'ll Value,
248 dst: PlaceRef<'tcx, &'ll Value>,
249 ) {
250 match &self.mode {
251 PassMode::Ignore => {}
252 PassMode::Indirect { attrs, address_space: _, mode: _ } => {
254 let align = attrs.pointee_align.unwrap_or(self.layout.align.abi);
255 OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
256 }
257 PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
259 ::rustc_span::macros::bug_impl(None,
format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
260 }
261 PassMode::Cast { cast, pad_i32_count: _ } => {
262 let scratch_size = cast.size(bx);
266 let scratch_align = cast.align(bx);
267 let copy_bytes =
274 cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
275 let llscratch = bx.alloca(scratch_size, scratch_align);
277 bx.lifetime_start(llscratch, scratch_size);
278 rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
280 bx.memcpy(
282 dst.val.llval,
283 self.layout.align.abi,
284 llscratch,
285 scratch_align,
286 bx.const_usize(copy_bytes),
287 MemFlags::empty(),
288 None,
289 );
290 bx.lifetime_end(llscratch, scratch_size);
291 }
292 PassMode::Pair(..) | PassMode::Direct { .. } => {
293 OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
294 }
295 }
296 }
297
298 fn store_fn_arg(
299 &self,
300 bx: &mut Builder<'_, 'll, 'tcx>,
301 idx: &mut usize,
302 dst: PlaceRef<'tcx, &'ll Value>,
303 ) {
304 let mut next = || {
305 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
306 *idx += 1;
307 val
308 };
309 match self.mode {
310 PassMode::Ignore => {}
311 PassMode::Pair(..) => {
312 OperandValue::Pair(next(), next()).store(bx, dst);
313 }
314 PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
315 ::rustc_span::macros::bug_impl(None,
format_args!("unsized `ArgAbi` cannot be stored"), Location::caller());bug!("unsized `ArgAbi` cannot be stored");
316 }
317 PassMode::Direct(_)
318 | PassMode::Indirect { attrs: _, address_space: _, mode: _ }
319 | PassMode::Cast { .. } => {
320 let next_arg = next();
321 self.store(bx, next_arg, dst);
322 }
323 }
324 }
325}
326
327impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
328 fn store_fn_arg(
329 &mut self,
330 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
331 idx: &mut usize,
332 dst: PlaceRef<'tcx, Self::Value>,
333 ) {
334 arg_abi.store_fn_arg(self, idx, dst)
335 }
336 fn store_arg(
337 &mut self,
338 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
339 val: &'ll Value,
340 dst: PlaceRef<'tcx, &'ll Value>,
341 ) {
342 arg_abi.store(self, val, dst)
343 }
344}
345
346pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
347 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
348 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
349 fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
350
351 fn apply_attrs_llfn(
353 &self,
354 cx: &CodegenCx<'ll, 'tcx>,
355 llfn: &'ll Value,
356 instance: Option<ty::Instance<'tcx>>,
357 );
358
359 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
361}
362
363impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
364 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
365 let args =
368 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
369
370 let mut llargument_tys = Vec::with_capacity(
372 self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
373 );
374
375 let llreturn_ty = match &self.ret.mode {
376 PassMode::Ignore => cx.type_void(),
377 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
378 PassMode::Cast { cast, pad_i32_count: _ } => cast.llvm_type(cx),
379 PassMode::Indirect { address_space, .. } => {
380 let ty = if let Some(address_space) = address_space {
381 cx.type_ptr_ext(*address_space)
382 } else {
383 cx.type_ptr()
384 };
385 llargument_tys.push(ty);
386 cx.type_void()
387 }
388 PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
389 };
390
391 for arg in args {
392 let llarg_ty = match &arg.mode {
396 PassMode::Ignore => continue,
397 PassMode::Direct(_) => {
398 arg.layout.immediate_llvm_type(cx)
402 }
403 PassMode::Pair(..) => {
404 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
408 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
409 continue;
410 }
411 PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
412 let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
417 let ptr_layout = cx.layout_of(ptr_ty);
418 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
419 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
420 continue;
421 }
422 PassMode::Indirect { attrs: _, address_space, mode: _ } => {
423 if let Some(address_space) = address_space {
424 cx.type_ptr_ext(*address_space)
425 } else {
426 cx.type_ptr()
427 }
428 }
429 PassMode::Cast { cast, pad_i32_count } => {
430 llargument_tys.extend(std::iter::repeat_n(
432 Reg::i32().llvm_type(cx),
433 usize::from(*pad_i32_count),
434 ));
435
436 cast.llvm_type(cx)
439 }
440 };
441 llargument_tys.push(llarg_ty);
442 }
443
444 if self.c_variadic {
445 cx.type_variadic_func(&llargument_tys, llreturn_ty)
446 } else {
447 cx.type_func(&llargument_tys, llreturn_ty)
448 }
449 }
450
451 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
452 cx.type_ptr_ext(cx.data_layout().instruction_address_space)
453 }
454
455 fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
456 to_llvm_calling_convention(cx.tcx.sess, self.conv)
457 }
458
459 fn apply_attrs_llfn(
460 &self,
461 cx: &CodegenCx<'ll, 'tcx>,
462 llfn: &'ll Value,
463 instance: Option<ty::Instance<'tcx>>,
464 ) {
465 let mut func_attrs = SmallVec::<[_; 3]>::new();
466 if self.ret.layout.is_uninhabited() {
467 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
468 }
469 if !self.can_unwind {
470 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
471 }
472 match self.conv {
473 CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
474 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
475 }
476 CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
477 func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
478 }
479 CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
480 func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
481 }
482 _ => (),
483 }
484 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
485
486 let mut i = 0;
487 let mut apply = |attrs: &ArgAttributes| {
488 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
489 i += 1;
490 i - 1
491 };
492
493 let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
494 if cx.sess().opts.optimize != config::OptLevel::No
495 && #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
Primitive::Int(..) => true,
_ => false,
}matches!(scalar.primitive(), Primitive::Int(..))
496 && !scalar.is_bool()
500 && !scalar.is_always_valid(cx)
502 {
503 attributes::apply_to_llfn(
504 llfn,
505 idx,
506 &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
507 );
508 }
509 };
510
511 match &self.ret.mode {
512 PassMode::Direct(attrs) => {
513 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
514 if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
515 apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
516 }
517 }
518 PassMode::Indirect { attrs, address_space: _, mode } => {
519 if !(*mode == IndirectMode::Pointer) {
::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
520 let i = apply(attrs);
521 let sret = llvm::CreateStructRetAttr(
522 cx.llcx,
523 cx.type_array(cx.type_i8(), self.ret.layout.size.bytes()),
524 );
525 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
526 if cx.sess().opts.optimize != config::OptLevel::No {
527 attributes::apply_to_llfn(
528 llfn,
529 llvm::AttributePlace::Argument(i),
530 &[
531 llvm::AttributeKind::Writable.create_attr(cx.llcx),
532 llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
533 ],
534 );
535 }
536 }
537 PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
538 PassMode::Cast { cast, pad_i32_count: _ } => {
539 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
540 }
541 _ => {}
542 }
543 for arg in self.args.iter() {
544 match &arg.mode {
545 PassMode::Ignore => {}
546 PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::OnStack } => {
547 let i = apply(attrs);
548 let byval = llvm::CreateByValAttr(
549 cx.llcx,
550 cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
551 );
552 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
553 }
554 PassMode::Indirect {
555 attrs,
556 address_space: _,
557 mode: IndirectMode::AmdgpuKernelArg,
558 } => {
559 let i = apply(attrs);
560 let byref = llvm::CreateByRefAttr(
561 cx.llcx,
562 cx.type_array(cx.type_i8(), arg.layout.size.bytes()),
563 );
564 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byref]);
565 }
566 PassMode::Direct(attrs) => {
567 let i = apply(attrs);
568 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
569 apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
570 }
571 }
572 PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::Pointer } => {
573 let i = apply(attrs);
574 if cx.sess().opts.optimize != config::OptLevel::No {
575 attributes::apply_to_llfn(
576 llfn,
577 llvm::AttributePlace::Argument(i),
578 &[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
579 );
580 }
581 }
582 PassMode::IndirectUnsized { attrs, meta_attrs } => {
583 apply(attrs);
584 apply(meta_attrs);
585 }
586 PassMode::Pair(a, b) => {
587 let i = apply(a);
588 let ii = apply(b);
589 if let BackendRepr::ScalarPair { a: scalar_a, b: scalar_b, b_offset: _ } =
590 arg.layout.backend_repr
591 {
592 apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
593 let primitive_b = scalar_b.primitive();
594 let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
595 && let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
596 && let ty::Slice(element_ty) = *pointee_ty.kind()
597 && let elem_size = cx.layout_of(element_ty).size
598 && elem_size != rustc_abi::Size::ZERO
599 {
600 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));
604 let isize_max = int.signed_max() as u64;
605 rustc_abi::Scalar::Initialized {
606 value: primitive_b,
607 valid_range: rustc_abi::WrappingRange {
608 start: 0,
609 end: u128::from(isize_max / elem_size.bytes()),
610 },
611 }
612 } else {
613 scalar_b
614 };
615 apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
616 }
617 }
618 PassMode::Cast { cast, pad_i32_count } => {
619 for _ in 0..*pad_i32_count {
620 apply(&ArgAttributes::new());
621 }
622 apply(&cast.attrs);
623 }
624 }
625 }
626
627 if let Some(instance) = instance {
629 llfn_attrs_from_instance(
630 cx,
631 cx.tcx,
632 llfn,
633 &cx.tcx.codegen_instance_attrs(instance.def),
634 Some(instance),
635 cx.sanitizer_ignorelist.as_ref(),
636 );
637 }
638 }
639
640 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
641 let mut func_attrs = SmallVec::<[_; 2]>::new();
642 if self.ret.layout.is_uninhabited() {
643 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
644 }
645 if !self.can_unwind {
646 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
647 }
648 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
649
650 let mut i = 0;
651 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
652 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
653 i += 1;
654 i - 1
655 };
656 match &self.ret.mode {
657 PassMode::Direct(attrs) => {
658 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
659 }
660 PassMode::Indirect { attrs, address_space: _, mode } => {
661 if !(*mode == IndirectMode::Pointer) {
::core::panicking::panic("assertion failed: *mode == IndirectMode::Pointer")
};assert!(*mode == IndirectMode::Pointer);
662 let i = apply(bx.cx, attrs);
663 let sret = llvm::CreateStructRetAttr(
664 bx.cx.llcx,
665 bx.cx.type_array(bx.cx.type_i8(), self.ret.layout.size.bytes()),
666 );
667 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
668 }
669 PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
670 PassMode::Cast { cast, pad_i32_count: _ } => {
671 cast.attrs.apply_attrs_to_callsite(
672 llvm::AttributePlace::ReturnValue,
673 bx.cx,
674 callsite,
675 );
676 }
677 _ => {}
678 }
679 for arg in self.args.iter() {
680 match &arg.mode {
681 PassMode::Ignore => {}
682 PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::OnStack } => {
683 let i = apply(bx.cx, attrs);
684 let byval = llvm::CreateByValAttr(
685 bx.cx.llcx,
686 bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
687 );
688 attributes::apply_to_callsite(
689 callsite,
690 llvm::AttributePlace::Argument(i),
691 &[byval],
692 );
693 }
694 PassMode::Indirect {
695 attrs,
696 address_space: _,
697 mode: IndirectMode::AmdgpuKernelArg,
698 } => {
699 let i = apply(bx.cx, attrs);
700 let byref = llvm::CreateByRefAttr(
701 bx.cx.llcx,
702 bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()),
703 );
704 attributes::apply_to_callsite(
705 callsite,
706 llvm::AttributePlace::Argument(i),
707 &[byref],
708 );
709 }
710 PassMode::Direct(attrs)
711 | PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::Pointer } => {
712 apply(bx.cx, attrs);
713 }
714 PassMode::IndirectUnsized { attrs, meta_attrs } => {
715 apply(bx.cx, attrs);
716 apply(bx.cx, meta_attrs);
717 }
718 PassMode::Pair(a, b) => {
719 apply(bx.cx, a);
720 apply(bx.cx, b);
721 }
722 PassMode::Cast { cast, pad_i32_count } => {
723 for _ in 0..*pad_i32_count {
724 apply(bx.cx, &ArgAttributes::new());
725 }
726 apply(bx.cx, &cast.attrs);
727 }
728 }
729 }
730
731 let cconv = self.llvm_cconv(&bx.cx);
732 if cconv != llvm::CCallConv {
733 llvm::SetInstructionCallConv(callsite, cconv);
734 }
735
736 if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
737 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
740 attributes::apply_to_callsite(
741 callsite,
742 llvm::AttributePlace::Function,
743 &[cmse_nonsecure_call],
744 );
745 }
746
747 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
750 if element_type_index >= 0 {
751 let arg_ty = self.args[element_type_index as usize].layout.ty;
752 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
753 let element_type_attr = unsafe {
754 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
755 };
756 attributes::apply_to_callsite(
757 callsite,
758 llvm::AttributePlace::Argument(element_type_index as u32),
759 &[element_type_attr],
760 );
761 }
762 }
763}
764
765impl AbiBuilderMethods for Builder<'_, '_, '_> {
766 fn get_param(&mut self, index: usize) -> Self::Value {
767 llvm::get_param(self.llfn(), index as c_uint)
768 }
769}
770
771pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
774 match abi {
775 CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
776 CanonAbi::RustCold => llvm::PreserveMost,
777 CanonAbi::RustPreserveNone => match &sess.target.arch {
778 Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
779 _ => llvm::CCallConv,
780 },
781 CanonAbi::RustTail => match &sess.target.arch {
782 Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
783 _ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
784 },
785 CanonAbi::Custom => llvm::CCallConv,
789 CanonAbi::Swift => llvm::SwiftCallConv,
790 CanonAbi::GpuKernel => match &sess.target.arch {
791 Arch::AmdGpu => llvm::AmdgpuKernel,
792 Arch::Nvptx64 => llvm::PtxKernel,
793 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"),
794 },
795 CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
796 InterruptKind::Avr => llvm::AvrInterrupt,
797 InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
798 InterruptKind::Msp430 => llvm::Msp430Intr,
799 InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
800 InterruptKind::X86 => llvm::X86_Intr,
801 },
802 CanonAbi::Arm(arm_call) => match arm_call {
803 ArmCall::Aapcs => llvm::ArmAapcsCallConv,
804 ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
805 },
806 CanonAbi::X86(x86_call) => match x86_call {
807 X86Call::Fastcall => llvm::X86FastcallCallConv,
808 X86Call::Stdcall => llvm::X86StdcallCallConv,
809 X86Call::SysV64 => llvm::X86_64_SysV,
810 X86Call::Thiscall => llvm::X86_ThisCall,
811 X86Call::Vectorcall => llvm::X86_VectorCall,
812 X86Call::Win64 => llvm::X86_64_Win64,
813 },
814 }
815}