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