rustc_target/callconv/mod.rs
1use std::str::FromStr;
2use std::{fmt, iter};
3
4use rustc_abi::{
5 AddressSpace, Align, BackendRepr, ExternAbi, HasDataLayout, Primitive, Reg, RegKind, Scalar,
6 Size, TyAbiInterface, TyAndLayout,
7};
8use rustc_macros::HashStable_Generic;
9
10use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi};
11
12mod aarch64;
13mod amdgpu;
14mod arm;
15mod avr;
16mod bpf;
17mod csky;
18mod hexagon;
19mod loongarch;
20mod m68k;
21mod mips;
22mod mips64;
23mod msp430;
24mod nvptx64;
25mod powerpc;
26mod powerpc64;
27mod riscv;
28mod s390x;
29mod sparc;
30mod sparc64;
31mod wasm;
32mod x86;
33mod x86_64;
34mod x86_win32;
35mod x86_win64;
36mod xtensa;
37
38#[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
39pub enum PassMode {
40 /// Ignore the argument.
41 ///
42 /// The argument is a ZST.
43 Ignore,
44 /// Pass the argument directly.
45 ///
46 /// The argument has a layout abi of `Scalar` or `Vector`.
47 /// Unfortunately due to past mistakes, in rare cases on wasm, it can also be `Aggregate`.
48 /// This is bad since it leaks LLVM implementation details into the ABI.
49 /// (Also see <https://github.com/rust-lang/rust/issues/115666>.)
50 Direct(ArgAttributes),
51 /// Pass a pair's elements directly in two arguments.
52 ///
53 /// The argument has a layout abi of `ScalarPair`.
54 Pair(ArgAttributes, ArgAttributes),
55 /// Pass the argument after casting it. See the `CastTarget` docs for details.
56 ///
57 /// `pad_i32` indicates if a `Reg::i32()` dummy argument is emitted before the real argument.
58 Cast { pad_i32: bool, cast: Box<CastTarget> },
59 /// Pass the argument indirectly via a hidden pointer.
60 ///
61 /// The `meta_attrs` value, if any, is for the metadata (vtable or length) of an unsized
62 /// argument. (This is the only mode that supports unsized arguments.)
63 ///
64 /// `on_stack` defines that the value should be passed at a fixed stack offset in accordance to
65 /// the ABI rather than passed using a pointer. This corresponds to the `byval` LLVM argument
66 /// attribute. The `byval` argument will use a byte array with the same size as the Rust type
67 /// (which ensures that padding is preserved and that we do not rely on LLVM's struct layout),
68 /// and will use the alignment specified in `attrs.pointee_align` (if `Some`) or the type's
69 /// alignment (if `None`). This means that the alignment will not always
70 /// match the Rust type's alignment; see documentation of `pass_by_stack_offset` for more info.
71 ///
72 /// `on_stack` cannot be true for unsized arguments, i.e., when `meta_attrs` is `Some`.
73 Indirect { attrs: ArgAttributes, meta_attrs: Option<ArgAttributes>, on_stack: bool },
74}
75
76impl PassMode {
77 /// Checks if these two `PassMode` are equal enough to be considered "the same for all
78 /// function call ABIs". However, the `Layout` can also impact ABI decisions,
79 /// so that needs to be compared as well!
80 pub fn eq_abi(&self, other: &Self) -> bool {
81 match (self, other) {
82 (PassMode::Ignore, PassMode::Ignore) => true,
83 (PassMode::Direct(a1), PassMode::Direct(a2)) => a1.eq_abi(a2),
84 (PassMode::Pair(a1, b1), PassMode::Pair(a2, b2)) => a1.eq_abi(a2) && b1.eq_abi(b2),
85 (
86 PassMode::Cast { cast: c1, pad_i32: pad1 },
87 PassMode::Cast { cast: c2, pad_i32: pad2 },
88 ) => c1.eq_abi(c2) && pad1 == pad2,
89 (
90 PassMode::Indirect { attrs: a1, meta_attrs: None, on_stack: s1 },
91 PassMode::Indirect { attrs: a2, meta_attrs: None, on_stack: s2 },
92 ) => a1.eq_abi(a2) && s1 == s2,
93 (
94 PassMode::Indirect { attrs: a1, meta_attrs: Some(e1), on_stack: s1 },
95 PassMode::Indirect { attrs: a2, meta_attrs: Some(e2), on_stack: s2 },
96 ) => a1.eq_abi(a2) && e1.eq_abi(e2) && s1 == s2,
97 _ => false,
98 }
99 }
100}
101
102// Hack to disable non_upper_case_globals only for the bitflags! and not for the rest
103// of this module
104pub use attr_impl::ArgAttribute;
105
106#[allow(non_upper_case_globals)]
107#[allow(unused)]
108mod attr_impl {
109 use rustc_macros::HashStable_Generic;
110
111 // The subset of llvm::Attribute needed for arguments, packed into a bitfield.
112 #[derive(Clone, Copy, Default, Hash, PartialEq, Eq, HashStable_Generic)]
113 pub struct ArgAttribute(u8);
114 bitflags::bitflags! {
115 impl ArgAttribute: u8 {
116 const NoAlias = 1 << 1;
117 const NoCapture = 1 << 2;
118 const NonNull = 1 << 3;
119 const ReadOnly = 1 << 4;
120 const InReg = 1 << 5;
121 const NoUndef = 1 << 6;
122 }
123 }
124 rustc_data_structures::external_bitflags_debug! { ArgAttribute }
125}
126
127/// Sometimes an ABI requires small integers to be extended to a full or partial register. This enum
128/// defines if this extension should be zero-extension or sign-extension when necessary. When it is
129/// not necessary to extend the argument, this enum is ignored.
130#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
131pub enum ArgExtension {
132 None,
133 Zext,
134 Sext,
135}
136
137/// A compact representation of LLVM attributes (at least those relevant for this module)
138/// that can be manipulated without interacting with LLVM's Attribute machinery.
139#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
140pub struct ArgAttributes {
141 pub regular: ArgAttribute,
142 pub arg_ext: ArgExtension,
143 /// The minimum size of the pointee, guaranteed to be valid for the duration of the whole call
144 /// (corresponding to LLVM's dereferenceable_or_null attributes, i.e., it is okay for this to be
145 /// set on a null pointer, but all non-null pointers must be dereferenceable).
146 pub pointee_size: Size,
147 /// The minimum alignment of the pointee, if any.
148 pub pointee_align: Option<Align>,
149}
150
151impl ArgAttributes {
152 pub fn new() -> Self {
153 ArgAttributes {
154 regular: ArgAttribute::default(),
155 arg_ext: ArgExtension::None,
156 pointee_size: Size::ZERO,
157 pointee_align: None,
158 }
159 }
160
161 pub fn ext(&mut self, ext: ArgExtension) -> &mut Self {
162 assert!(
163 self.arg_ext == ArgExtension::None || self.arg_ext == ext,
164 "cannot set {:?} when {:?} is already set",
165 ext,
166 self.arg_ext
167 );
168 self.arg_ext = ext;
169 self
170 }
171
172 pub fn set(&mut self, attr: ArgAttribute) -> &mut Self {
173 self.regular |= attr;
174 self
175 }
176
177 pub fn contains(&self, attr: ArgAttribute) -> bool {
178 self.regular.contains(attr)
179 }
180
181 /// Checks if these two `ArgAttributes` are equal enough to be considered "the same for all
182 /// function call ABIs".
183 pub fn eq_abi(&self, other: &Self) -> bool {
184 // There's only one regular attribute that matters for the call ABI: InReg.
185 // Everything else is things like noalias, dereferenceable, nonnull, ...
186 // (This also applies to pointee_size, pointee_align.)
187 if self.regular.contains(ArgAttribute::InReg) != other.regular.contains(ArgAttribute::InReg)
188 {
189 return false;
190 }
191 // We also compare the sign extension mode -- this could let the callee make assumptions
192 // about bits that conceptually were not even passed.
193 if self.arg_ext != other.arg_ext {
194 return false;
195 }
196 true
197 }
198}
199
200/// An argument passed entirely registers with the
201/// same kind (e.g., HFA / HVA on PPC64 and AArch64).
202#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
203pub struct Uniform {
204 pub unit: Reg,
205
206 /// The total size of the argument, which can be:
207 /// * equal to `unit.size` (one scalar/vector),
208 /// * a multiple of `unit.size` (an array of scalar/vectors),
209 /// * if `unit.kind` is `Integer`, the last element can be shorter, i.e., `{ i64, i64, i32 }`
210 /// for 64-bit integers with a total size of 20 bytes. When the argument is actually passed,
211 /// this size will be rounded up to the nearest multiple of `unit.size`.
212 pub total: Size,
213
214 /// Indicate that the argument is consecutive, in the sense that either all values need to be
215 /// passed in register, or all on the stack. If they are passed on the stack, there should be
216 /// no additional padding between elements.
217 pub is_consecutive: bool,
218}
219
220impl From<Reg> for Uniform {
221 fn from(unit: Reg) -> Uniform {
222 Uniform { unit, total: unit.size, is_consecutive: false }
223 }
224}
225
226impl Uniform {
227 pub fn align<C: HasDataLayout>(&self, cx: &C) -> Align {
228 self.unit.align(cx)
229 }
230
231 /// Pass using one or more values of the given type, without requiring them to be consecutive.
232 /// That is, some values may be passed in register and some on the stack.
233 pub fn new(unit: Reg, total: Size) -> Self {
234 Uniform { unit, total, is_consecutive: false }
235 }
236
237 /// Pass using one or more consecutive values of the given type. Either all values will be
238 /// passed in registers, or all on the stack.
239 pub fn consecutive(unit: Reg, total: Size) -> Self {
240 Uniform { unit, total, is_consecutive: true }
241 }
242}
243
244/// Describes the type used for `PassMode::Cast`.
245///
246/// Passing arguments in this mode works as follows: the registers in the `prefix` (the ones that
247/// are `Some`) get laid out one after the other (using `repr(C)` layout rules). Then the
248/// `rest.unit` register type gets repeated often enough to cover `rest.size`. This describes the
249/// actual type used for the call; the Rust type of the argument is then transmuted to this ABI type
250/// (and all data in the padding between the registers is dropped).
251#[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
252pub struct CastTarget {
253 pub prefix: [Option<Reg>; 8],
254 pub rest: Uniform,
255 pub attrs: ArgAttributes,
256}
257
258impl From<Reg> for CastTarget {
259 fn from(unit: Reg) -> CastTarget {
260 CastTarget::from(Uniform::from(unit))
261 }
262}
263
264impl From<Uniform> for CastTarget {
265 fn from(uniform: Uniform) -> CastTarget {
266 CastTarget {
267 prefix: [None; 8],
268 rest: uniform,
269 attrs: ArgAttributes {
270 regular: ArgAttribute::default(),
271 arg_ext: ArgExtension::None,
272 pointee_size: Size::ZERO,
273 pointee_align: None,
274 },
275 }
276 }
277}
278
279impl CastTarget {
280 pub fn pair(a: Reg, b: Reg) -> CastTarget {
281 CastTarget {
282 prefix: [Some(a), None, None, None, None, None, None, None],
283 rest: Uniform::from(b),
284 attrs: ArgAttributes {
285 regular: ArgAttribute::default(),
286 arg_ext: ArgExtension::None,
287 pointee_size: Size::ZERO,
288 pointee_align: None,
289 },
290 }
291 }
292
293 /// When you only access the range containing valid data, you can use this unaligned size;
294 /// otherwise, use the safer `size` method.
295 pub fn unaligned_size<C: HasDataLayout>(&self, _cx: &C) -> Size {
296 // Prefix arguments are passed in specific designated registers
297 let prefix_size = self
298 .prefix
299 .iter()
300 .filter_map(|x| x.map(|reg| reg.size))
301 .fold(Size::ZERO, |acc, size| acc + size);
302 // Remaining arguments are passed in chunks of the unit size
303 let rest_size =
304 self.rest.unit.size * self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes());
305
306 prefix_size + rest_size
307 }
308
309 pub fn size<C: HasDataLayout>(&self, cx: &C) -> Size {
310 self.unaligned_size(cx).align_to(self.align(cx))
311 }
312
313 pub fn align<C: HasDataLayout>(&self, cx: &C) -> Align {
314 self.prefix
315 .iter()
316 .filter_map(|x| x.map(|reg| reg.align(cx)))
317 .fold(cx.data_layout().aggregate_align.abi.max(self.rest.align(cx)), |acc, align| {
318 acc.max(align)
319 })
320 }
321
322 /// Checks if these two `CastTarget` are equal enough to be considered "the same for all
323 /// function call ABIs".
324 pub fn eq_abi(&self, other: &Self) -> bool {
325 let CastTarget { prefix: prefix_l, rest: rest_l, attrs: attrs_l } = self;
326 let CastTarget { prefix: prefix_r, rest: rest_r, attrs: attrs_r } = other;
327 prefix_l == prefix_r && rest_l == rest_r && attrs_l.eq_abi(attrs_r)
328 }
329}
330
331/// Information about how to pass an argument to,
332/// or return a value from, a function, under some ABI.
333#[derive(Clone, PartialEq, Eq, Hash, HashStable_Generic)]
334pub struct ArgAbi<'a, Ty> {
335 pub layout: TyAndLayout<'a, Ty>,
336 pub mode: PassMode,
337}
338
339// Needs to be a custom impl because of the bounds on the `TyAndLayout` debug impl.
340impl<'a, Ty: fmt::Display> fmt::Debug for ArgAbi<'a, Ty> {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 let ArgAbi { layout, mode } = self;
343 f.debug_struct("ArgAbi").field("layout", layout).field("mode", mode).finish()
344 }
345}
346
347impl<'a, Ty> ArgAbi<'a, Ty> {
348 /// This defines the "default ABI" for that type, that is then later adjusted in `fn_abi_adjust_for_abi`.
349 pub fn new(
350 cx: &impl HasDataLayout,
351 layout: TyAndLayout<'a, Ty>,
352 scalar_attrs: impl Fn(&TyAndLayout<'a, Ty>, Scalar, Size) -> ArgAttributes,
353 ) -> Self {
354 let mode = match layout.backend_repr {
355 BackendRepr::Scalar(scalar) => {
356 PassMode::Direct(scalar_attrs(&layout, scalar, Size::ZERO))
357 }
358 BackendRepr::ScalarPair(a, b) => PassMode::Pair(
359 scalar_attrs(&layout, a, Size::ZERO),
360 scalar_attrs(&layout, b, a.size(cx).align_to(b.align(cx).abi)),
361 ),
362 BackendRepr::SimdVector { .. } => PassMode::Direct(ArgAttributes::new()),
363 BackendRepr::Memory { .. } => Self::indirect_pass_mode(&layout),
364 };
365 ArgAbi { layout, mode }
366 }
367
368 fn indirect_pass_mode(layout: &TyAndLayout<'a, Ty>) -> PassMode {
369 let mut attrs = ArgAttributes::new();
370
371 // For non-immediate arguments the callee gets its own copy of
372 // the value on the stack, so there are no aliases. It's also
373 // program-invisible so can't possibly capture
374 attrs
375 .set(ArgAttribute::NoAlias)
376 .set(ArgAttribute::NoCapture)
377 .set(ArgAttribute::NonNull)
378 .set(ArgAttribute::NoUndef);
379 attrs.pointee_size = layout.size;
380 attrs.pointee_align = Some(layout.align.abi);
381
382 let meta_attrs = layout.is_unsized().then_some(ArgAttributes::new());
383
384 PassMode::Indirect { attrs, meta_attrs, on_stack: false }
385 }
386
387 /// Pass this argument directly instead. Should NOT be used!
388 /// Only exists because of past ABI mistakes that will take time to fix
389 /// (see <https://github.com/rust-lang/rust/issues/115666>).
390 #[track_caller]
391 pub fn make_direct_deprecated(&mut self) {
392 match self.mode {
393 PassMode::Indirect { .. } => {
394 self.mode = PassMode::Direct(ArgAttributes::new());
395 }
396 PassMode::Ignore | PassMode::Direct(_) | PassMode::Pair(_, _) => {} // already direct
397 _ => panic!("Tried to make {:?} direct", self.mode),
398 }
399 }
400
401 /// Pass this argument indirectly, by passing a (thin or wide) pointer to the argument instead.
402 /// This is valid for both sized and unsized arguments.
403 #[track_caller]
404 pub fn make_indirect(&mut self) {
405 match self.mode {
406 PassMode::Direct(_) | PassMode::Pair(_, _) => {
407 self.mode = Self::indirect_pass_mode(&self.layout);
408 }
409 PassMode::Indirect { attrs: _, meta_attrs: _, on_stack: false } => {
410 // already indirect
411 }
412 _ => panic!("Tried to make {:?} indirect", self.mode),
413 }
414 }
415
416 /// Same as `make_indirect`, but for arguments that are ignored. Only needed for ABIs that pass
417 /// ZSTs indirectly.
418 #[track_caller]
419 pub fn make_indirect_from_ignore(&mut self) {
420 match self.mode {
421 PassMode::Ignore => {
422 self.mode = Self::indirect_pass_mode(&self.layout);
423 }
424 PassMode::Indirect { attrs: _, meta_attrs: _, on_stack: false } => {
425 // already indirect
426 }
427 _ => panic!("Tried to make {:?} indirect (expected `PassMode::Ignore`)", self.mode),
428 }
429 }
430
431 /// Pass this argument indirectly, by placing it at a fixed stack offset.
432 /// This corresponds to the `byval` LLVM argument attribute.
433 /// This is only valid for sized arguments.
434 ///
435 /// `byval_align` specifies the alignment of the `byval` stack slot, which does not need to
436 /// correspond to the type's alignment. This will be `Some` if the target's ABI specifies that
437 /// stack slots used for arguments passed by-value have specific alignment requirements which
438 /// differ from the alignment used in other situations.
439 ///
440 /// If `None`, the type's alignment is used.
441 ///
442 /// If the resulting alignment differs from the type's alignment,
443 /// the argument will be copied to an alloca with sufficient alignment,
444 /// either in the caller (if the type's alignment is lower than the byval alignment)
445 /// or in the callee (if the type's alignment is higher than the byval alignment),
446 /// to ensure that Rust code never sees an underaligned pointer.
447 pub fn pass_by_stack_offset(&mut self, byval_align: Option<Align>) {
448 assert!(!self.layout.is_unsized(), "used byval ABI for unsized layout");
449 self.make_indirect();
450 match self.mode {
451 PassMode::Indirect { ref mut attrs, meta_attrs: _, ref mut on_stack } => {
452 *on_stack = true;
453
454 // Some platforms, like 32-bit x86, change the alignment of the type when passing
455 // `byval`. Account for that.
456 if let Some(byval_align) = byval_align {
457 // On all targets with byval align this is currently true, so let's assert it.
458 debug_assert!(byval_align >= Align::from_bytes(4).unwrap());
459 attrs.pointee_align = Some(byval_align);
460 }
461 }
462 _ => unreachable!(),
463 }
464 }
465
466 pub fn extend_integer_width_to(&mut self, bits: u64) {
467 // Only integers have signedness
468 if let BackendRepr::Scalar(scalar) = self.layout.backend_repr {
469 if let Primitive::Int(i, signed) = scalar.primitive() {
470 if i.size().bits() < bits {
471 if let PassMode::Direct(ref mut attrs) = self.mode {
472 if signed {
473 attrs.ext(ArgExtension::Sext)
474 } else {
475 attrs.ext(ArgExtension::Zext)
476 };
477 }
478 }
479 }
480 }
481 }
482
483 pub fn cast_to<T: Into<CastTarget>>(&mut self, target: T) {
484 self.mode = PassMode::Cast { cast: Box::new(target.into()), pad_i32: false };
485 }
486
487 pub fn cast_to_and_pad_i32<T: Into<CastTarget>>(&mut self, target: T, pad_i32: bool) {
488 self.mode = PassMode::Cast { cast: Box::new(target.into()), pad_i32 };
489 }
490
491 pub fn is_indirect(&self) -> bool {
492 matches!(self.mode, PassMode::Indirect { .. })
493 }
494
495 pub fn is_sized_indirect(&self) -> bool {
496 matches!(self.mode, PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: _ })
497 }
498
499 pub fn is_unsized_indirect(&self) -> bool {
500 matches!(self.mode, PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ })
501 }
502
503 pub fn is_ignore(&self) -> bool {
504 matches!(self.mode, PassMode::Ignore)
505 }
506
507 /// Checks if these two `ArgAbi` are equal enough to be considered "the same for all
508 /// function call ABIs".
509 pub fn eq_abi(&self, other: &Self) -> bool
510 where
511 Ty: PartialEq,
512 {
513 // Ideally we'd just compare the `mode`, but that is not enough -- for some modes LLVM will look
514 // at the type.
515 self.layout.eq_abi(&other.layout) && self.mode.eq_abi(&other.mode) && {
516 // `fn_arg_sanity_check` accepts `PassMode::Direct` for some aggregates.
517 // That elevates any type difference to an ABI difference since we just use the
518 // full Rust type as the LLVM argument/return type.
519 if matches!(self.mode, PassMode::Direct(..))
520 && matches!(self.layout.backend_repr, BackendRepr::Memory { .. })
521 {
522 // For aggregates in `Direct` mode to be compatible, the types need to be equal.
523 self.layout.ty == other.layout.ty
524 } else {
525 true
526 }
527 }
528 }
529}
530
531#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
532pub enum Conv {
533 // General language calling conventions, for which every target
534 // should have its own backend (e.g. LLVM) support.
535 C,
536 Rust,
537
538 Cold,
539 PreserveMost,
540 PreserveAll,
541
542 // Target-specific calling conventions.
543 ArmAapcs,
544 CCmseNonSecureCall,
545 CCmseNonSecureEntry,
546
547 Msp430Intr,
548
549 GpuKernel,
550
551 X86Fastcall,
552 X86Intr,
553 X86Stdcall,
554 X86ThisCall,
555 X86VectorCall,
556
557 X86_64SysV,
558 X86_64Win64,
559
560 AvrInterrupt,
561 AvrNonBlockingInterrupt,
562
563 RiscvInterrupt { kind: RiscvInterruptKind },
564}
565
566#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
567pub enum RiscvInterruptKind {
568 Machine,
569 Supervisor,
570}
571
572impl RiscvInterruptKind {
573 pub fn as_str(&self) -> &'static str {
574 match self {
575 Self::Machine => "machine",
576 Self::Supervisor => "supervisor",
577 }
578 }
579}
580
581/// Metadata describing how the arguments to a native function
582/// should be passed in order to respect the native ABI.
583///
584/// The signature represented by this type may not match the MIR function signature.
585/// Certain attributes, like `#[track_caller]` can introduce additional arguments, which are present in [`FnAbi`], but not in `FnSig`.
586/// While this difference is rarely relevant, it should still be kept in mind.
587///
588/// I will do my best to describe this structure, but these
589/// comments are reverse-engineered and may be inaccurate. -NDM
590#[derive(Clone, PartialEq, Eq, Hash, HashStable_Generic)]
591pub struct FnAbi<'a, Ty> {
592 /// The type, layout, and information about how each argument is passed.
593 pub args: Box<[ArgAbi<'a, Ty>]>,
594
595 /// The layout, type, and the way a value is returned from this function.
596 pub ret: ArgAbi<'a, Ty>,
597
598 /// Marks this function as variadic (accepting a variable number of arguments).
599 pub c_variadic: bool,
600
601 /// The count of non-variadic arguments.
602 ///
603 /// Should only be different from args.len() when c_variadic is true.
604 /// This can be used to know whether an argument is variadic or not.
605 pub fixed_count: u32,
606 /// The calling convention of this function.
607 pub conv: Conv,
608 /// Indicates if an unwind may happen across a call to this function.
609 pub can_unwind: bool,
610}
611
612// Needs to be a custom impl because of the bounds on the `TyAndLayout` debug impl.
613impl<'a, Ty: fmt::Display> fmt::Debug for FnAbi<'a, Ty> {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 let FnAbi { args, ret, c_variadic, fixed_count, conv, can_unwind } = self;
616 f.debug_struct("FnAbi")
617 .field("args", args)
618 .field("ret", ret)
619 .field("c_variadic", c_variadic)
620 .field("fixed_count", fixed_count)
621 .field("conv", conv)
622 .field("can_unwind", can_unwind)
623 .finish()
624 }
625}
626
627impl<'a, Ty> FnAbi<'a, Ty> {
628 pub fn adjust_for_foreign_abi<C>(&mut self, cx: &C, abi: ExternAbi)
629 where
630 Ty: TyAbiInterface<'a, C> + Copy,
631 C: HasDataLayout + HasTargetSpec + HasWasmCAbiOpt + HasX86AbiOpt,
632 {
633 if abi == ExternAbi::X86Interrupt {
634 if let Some(arg) = self.args.first_mut() {
635 arg.pass_by_stack_offset(None);
636 }
637 return;
638 }
639
640 let spec = cx.target_spec();
641 match &spec.arch[..] {
642 "x86" => {
643 let (flavor, regparm) = match abi {
644 ExternAbi::Fastcall { .. } | ExternAbi::Vectorcall { .. } => {
645 (x86::Flavor::FastcallOrVectorcall, None)
646 }
647 ExternAbi::C { .. } | ExternAbi::Cdecl { .. } | ExternAbi::Stdcall { .. } => {
648 (x86::Flavor::General, cx.x86_abi_opt().regparm)
649 }
650 _ => (x86::Flavor::General, None),
651 };
652 let reg_struct_return = cx.x86_abi_opt().reg_struct_return;
653 let opts = x86::X86Options { flavor, regparm, reg_struct_return };
654 if spec.is_like_msvc {
655 x86_win32::compute_abi_info(cx, self, opts);
656 } else {
657 x86::compute_abi_info(cx, self, opts);
658 }
659 }
660 "x86_64" => match abi {
661 ExternAbi::SysV64 { .. } => x86_64::compute_abi_info(cx, self),
662 ExternAbi::Win64 { .. } | ExternAbi::Vectorcall { .. } => {
663 x86_win64::compute_abi_info(cx, self)
664 }
665 _ => {
666 if cx.target_spec().is_like_windows {
667 x86_win64::compute_abi_info(cx, self)
668 } else {
669 x86_64::compute_abi_info(cx, self)
670 }
671 }
672 },
673 "aarch64" | "arm64ec" => {
674 let kind = if cx.target_spec().is_like_darwin {
675 aarch64::AbiKind::DarwinPCS
676 } else if cx.target_spec().is_like_windows {
677 aarch64::AbiKind::Win64
678 } else {
679 aarch64::AbiKind::AAPCS
680 };
681 aarch64::compute_abi_info(cx, self, kind)
682 }
683 "amdgpu" => amdgpu::compute_abi_info(cx, self),
684 "arm" => arm::compute_abi_info(cx, self),
685 "avr" => avr::compute_abi_info(self),
686 "loongarch64" => loongarch::compute_abi_info(cx, self),
687 "m68k" => m68k::compute_abi_info(self),
688 "csky" => csky::compute_abi_info(self),
689 "mips" | "mips32r6" => mips::compute_abi_info(cx, self),
690 "mips64" | "mips64r6" => mips64::compute_abi_info(cx, self),
691 "powerpc" => powerpc::compute_abi_info(cx, self),
692 "powerpc64" => powerpc64::compute_abi_info(cx, self),
693 "s390x" => s390x::compute_abi_info(cx, self),
694 "msp430" => msp430::compute_abi_info(self),
695 "sparc" => sparc::compute_abi_info(cx, self),
696 "sparc64" => sparc64::compute_abi_info(cx, self),
697 "nvptx64" => {
698 let abi = cx.target_spec().adjust_abi(abi, self.c_variadic);
699 if abi == ExternAbi::PtxKernel || abi == ExternAbi::GpuKernel {
700 nvptx64::compute_ptx_kernel_abi_info(cx, self)
701 } else {
702 nvptx64::compute_abi_info(self)
703 }
704 }
705 "hexagon" => hexagon::compute_abi_info(self),
706 "xtensa" => xtensa::compute_abi_info(cx, self),
707 "riscv32" | "riscv64" => riscv::compute_abi_info(cx, self),
708 "wasm32" => {
709 if spec.os == "unknown" && matches!(cx.wasm_c_abi_opt(), WasmCAbi::Legacy { .. }) {
710 wasm::compute_wasm_abi_info(self)
711 } else {
712 wasm::compute_c_abi_info(cx, self)
713 }
714 }
715 "wasm64" => wasm::compute_c_abi_info(cx, self),
716 "bpf" => bpf::compute_abi_info(self),
717 arch => panic!("no lowering implemented for {arch}"),
718 }
719 }
720
721 pub fn adjust_for_rust_abi<C>(&mut self, cx: &C)
722 where
723 Ty: TyAbiInterface<'a, C> + Copy,
724 C: HasDataLayout + HasTargetSpec,
725 {
726 let spec = cx.target_spec();
727 match &*spec.arch {
728 "x86" => x86::compute_rust_abi_info(cx, self),
729 "riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self),
730 "loongarch64" => loongarch::compute_rust_abi_info(cx, self),
731 "aarch64" => aarch64::compute_rust_abi_info(cx, self),
732 _ => {}
733 };
734
735 for (arg_idx, arg) in self
736 .args
737 .iter_mut()
738 .enumerate()
739 .map(|(idx, arg)| (Some(idx), arg))
740 .chain(iter::once((None, &mut self.ret)))
741 {
742 // If the logic above already picked a specific type to cast the argument to, leave that
743 // in place.
744 if matches!(arg.mode, PassMode::Ignore | PassMode::Cast { .. }) {
745 continue;
746 }
747
748 if arg_idx.is_none()
749 && arg.layout.size > Primitive::Pointer(AddressSpace::DATA).size(cx) * 2
750 && !matches!(arg.layout.backend_repr, BackendRepr::SimdVector { .. })
751 {
752 // Return values larger than 2 registers using a return area
753 // pointer. LLVM and Cranelift disagree about how to return
754 // values that don't fit in the registers designated for return
755 // values. LLVM will force the entire return value to be passed
756 // by return area pointer, while Cranelift will look at each IR level
757 // return value independently and decide to pass it in a
758 // register or not, which would result in the return value
759 // being passed partially in registers and partially through a
760 // return area pointer. For large IR-level values such as `i128`,
761 // cranelift will even split up the value into smaller chunks.
762 //
763 // While Cranelift may need to be fixed as the LLVM behavior is
764 // generally more correct with respect to the surface language,
765 // forcing this behavior in rustc itself makes it easier for
766 // other backends to conform to the Rust ABI and for the C ABI
767 // rustc already handles this behavior anyway.
768 //
769 // In addition LLVM's decision to pass the return value in
770 // registers or using a return area pointer depends on how
771 // exactly the return type is lowered to an LLVM IR type. For
772 // example `Option<u128>` can be lowered as `{ i128, i128 }`
773 // in which case the x86_64 backend would use a return area
774 // pointer, or it could be passed as `{ i32, i128 }` in which
775 // case the x86_64 backend would pass it in registers by taking
776 // advantage of an LLVM ABI extension that allows using 3
777 // registers for the x86_64 sysv call conv rather than the
778 // officially specified 2 registers.
779 //
780 // FIXME: Technically we should look at the amount of available
781 // return registers rather than guessing that there are 2
782 // registers for return values. In practice only a couple of
783 // architectures have less than 2 return registers. None of
784 // which supported by Cranelift.
785 //
786 // NOTE: This adjustment is only necessary for the Rust ABI as
787 // for other ABI's the calling convention implementations in
788 // rustc_target already ensure any return value which doesn't
789 // fit in the available amount of return registers is passed in
790 // the right way for the current target.
791 //
792 // The adjustment is not necessary nor desired for types with a vector
793 // representation; those are handled below.
794 arg.make_indirect();
795 continue;
796 }
797
798 match arg.layout.backend_repr {
799 BackendRepr::Memory { .. } => {
800 // Compute `Aggregate` ABI.
801
802 let is_indirect_not_on_stack =
803 matches!(arg.mode, PassMode::Indirect { on_stack: false, .. });
804 assert!(is_indirect_not_on_stack);
805
806 let size = arg.layout.size;
807 if arg.layout.is_sized()
808 && size <= Primitive::Pointer(AddressSpace::DATA).size(cx)
809 {
810 // We want to pass small aggregates as immediates, but using
811 // an LLVM aggregate type for this leads to bad optimizations,
812 // so we pick an appropriately sized integer type instead.
813 arg.cast_to(Reg { kind: RegKind::Integer, size });
814 }
815 }
816
817 BackendRepr::SimdVector { .. } => {
818 // This is a fun case! The gist of what this is doing is
819 // that we want callers and callees to always agree on the
820 // ABI of how they pass SIMD arguments. If we were to *not*
821 // make these arguments indirect then they'd be immediates
822 // in LLVM, which means that they'd used whatever the
823 // appropriate ABI is for the callee and the caller. That
824 // means, for example, if the caller doesn't have AVX
825 // enabled but the callee does, then passing an AVX argument
826 // across this boundary would cause corrupt data to show up.
827 //
828 // This problem is fixed by unconditionally passing SIMD
829 // arguments through memory between callers and callees
830 // which should get them all to agree on ABI regardless of
831 // target feature sets. Some more information about this
832 // issue can be found in #44367.
833 //
834 // We *could* do better in some cases, e.g. on x86_64 targets where SSE2 is
835 // required. However, it turns out that that makes LLVM worse at optimizing this
836 // code, so we pass things indirectly even there. See #139029 for more on that.
837 if spec.simd_types_indirect {
838 arg.make_indirect();
839 }
840 }
841
842 _ => {}
843 }
844 }
845 }
846}
847
848impl FromStr for Conv {
849 type Err = String;
850
851 fn from_str(s: &str) -> Result<Self, Self::Err> {
852 match s {
853 "C" => Ok(Conv::C),
854 "Rust" => Ok(Conv::Rust),
855 "RustCold" => Ok(Conv::Rust),
856 "ArmAapcs" => Ok(Conv::ArmAapcs),
857 "CCmseNonSecureCall" => Ok(Conv::CCmseNonSecureCall),
858 "CCmseNonSecureEntry" => Ok(Conv::CCmseNonSecureEntry),
859 "Msp430Intr" => Ok(Conv::Msp430Intr),
860 "X86Fastcall" => Ok(Conv::X86Fastcall),
861 "X86Intr" => Ok(Conv::X86Intr),
862 "X86Stdcall" => Ok(Conv::X86Stdcall),
863 "X86ThisCall" => Ok(Conv::X86ThisCall),
864 "X86VectorCall" => Ok(Conv::X86VectorCall),
865 "X86_64SysV" => Ok(Conv::X86_64SysV),
866 "X86_64Win64" => Ok(Conv::X86_64Win64),
867 "GpuKernel" => Ok(Conv::GpuKernel),
868 "AvrInterrupt" => Ok(Conv::AvrInterrupt),
869 "AvrNonBlockingInterrupt" => Ok(Conv::AvrNonBlockingInterrupt),
870 "RiscvInterrupt(machine)" => {
871 Ok(Conv::RiscvInterrupt { kind: RiscvInterruptKind::Machine })
872 }
873 "RiscvInterrupt(supervisor)" => {
874 Ok(Conv::RiscvInterrupt { kind: RiscvInterruptKind::Supervisor })
875 }
876 _ => Err(format!("'{s}' is not a valid value for entry function call convention.")),
877 }
878 }
879}
880
881// Some types are used a lot. Make sure they don't unintentionally get bigger.
882#[cfg(target_pointer_width = "64")]
883mod size_asserts {
884 use rustc_data_structures::static_assert_size;
885
886 use super::*;
887 // tidy-alphabetical-start
888 static_assert_size!(ArgAbi<'_, usize>, 56);
889 static_assert_size!(FnAbi<'_, usize>, 80);
890 // tidy-alphabetical-end
891}