Skip to main content

cranelift_codegen/isa/
call_conv.rs

1use crate::ir::Type;
2use crate::ir::types;
3use crate::settings::{self, LibcallCallConv};
4use core::fmt;
5use core::str;
6use target_lexicon::{CallingConvention, Triple};
7
8#[cfg(feature = "enable-serde")]
9use serde_derive::{Deserialize, Serialize};
10
11/// Calling convention identifiers.
12#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
13#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
14pub enum CallConv {
15    /// Best performance, not ABI-stable.
16    Fast,
17    /// Supports tail calls, not ABI-stable except for exception
18    /// payload registers.
19    ///
20    /// On exception resume, a caller to a `tail`-convention function
21    /// assumes that the exception payload values are in the following
22    /// registers (per platform):
23    /// - x86-64: rax, rdx
24    /// - aarch64: x0, x1
25    /// - riscv64: a0, a1
26    /// - pulley{32,64}: x0, x1
27    //
28    // Currently, this is basically sys-v except that callees pop stack
29    // arguments, rather than callers. Expected to change even more in the
30    // future, however!
31    Tail,
32    /// System V-style convention used on many platforms.
33    SystemV,
34    /// Windows "fastcall" convention, also used for x64 and ARM.
35    WindowsFastcall,
36    /// Mac aarch64 calling convention, which is a tweaked aarch64 ABI.
37    AppleAarch64,
38    /// Specialized convention for the probestack function.
39    Probestack,
40    /// Internal calling convention for Winch-generated functions.
41    /// Cranelift-generated trampolines use the same convention to
42    /// interoperate with them. This convention is not ABI-stable.
43    ///
44    /// Callees reclaim their aligned incoming stack-argument area
45    /// before returning.
46    ///
47    /// Only the last result is returned in a register; any preceding
48    /// results are written to the return area in memory.
49    Winch,
50    /// Calling convention optimized for callsite efficiency, at the
51    /// cost of the callee. It does so by not clobbering any
52    /// registers.
53    ///
54    /// This is designed for a very specific need: we want callsites
55    /// that we can insert as instrumentation (perhaps patchable)
56    /// while affecting surrounding instructions' register allocation
57    /// as little as possible.
58    ///
59    /// The ABI is based on the native register-argument ABI on each
60    /// respective platform. It does not support tail-calls. It also
61    /// does not support return values.
62    PreserveAll,
63}
64
65impl CallConv {
66    /// Return the default calling convention for the given target triple.
67    pub fn triple_default(triple: &Triple) -> Self {
68        match triple.default_calling_convention() {
69            // Default to System V for unknown targets because most everything
70            // uses System V.
71            Ok(CallingConvention::SystemV) | Err(()) => Self::SystemV,
72            Ok(CallingConvention::AppleAarch64) => Self::AppleAarch64,
73            Ok(CallingConvention::WindowsFastcall) => Self::WindowsFastcall,
74            Ok(unimp) => unimplemented!("calling convention: {:?}", unimp),
75        }
76    }
77
78    /// Returns the calling convention used for libcalls according to the current flags.
79    pub fn for_libcall(flags: &settings::Flags, default_call_conv: CallConv) -> Self {
80        match flags.libcall_call_conv() {
81            LibcallCallConv::IsaDefault => default_call_conv,
82            LibcallCallConv::Fast => Self::Fast,
83            LibcallCallConv::SystemV => Self::SystemV,
84            LibcallCallConv::WindowsFastcall => Self::WindowsFastcall,
85            LibcallCallConv::AppleAarch64 => Self::AppleAarch64,
86            LibcallCallConv::PreserveAll => Self::PreserveAll,
87            LibcallCallConv::Probestack => Self::Probestack,
88        }
89    }
90
91    /// Does this calling convention support tail calls?
92    pub fn supports_tail_calls(&self) -> bool {
93        match self {
94            CallConv::Tail => true,
95            _ => false,
96        }
97    }
98
99    /// Does this calling convention support exceptions?
100    pub fn supports_exceptions(&self) -> bool {
101        match self {
102            CallConv::Tail
103            | CallConv::SystemV
104            | CallConv::Winch
105            | CallConv::PreserveAll
106            | CallConv::AppleAarch64 => true,
107            _ => false,
108        }
109    }
110
111    /// What types do the exception payload value(s) have?
112    ///
113    /// Note that this function applies to the *callee* of a `try_call`
114    /// instruction. The calling convention of the callee may differ from the
115    /// caller, but the exceptional payload types available are defined by the
116    /// callee calling convention.
117    ///
118    /// Also note that individual backends are responsible for reporting
119    /// register destinations for exceptional types. Internally Cranelift
120    /// asserts that the backend supports the exact same number of register
121    /// destinations as this return value.
122    pub fn exception_payload_types(&self, pointer_ty: Type) -> &[Type] {
123        match self {
124            CallConv::Tail | CallConv::SystemV | CallConv::PreserveAll | CallConv::AppleAarch64 => {
125                match pointer_ty {
126                    types::I32 => &[types::I32, types::I32],
127                    types::I64 => &[types::I64, types::I64],
128                    _ => unreachable!(),
129                }
130            }
131            _ => &[],
132        }
133    }
134}
135
136impl fmt::Display for CallConv {
137    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138        f.write_str(match *self {
139            Self::Fast => "fast",
140            Self::Tail => "tail",
141            Self::SystemV => "system_v",
142            Self::WindowsFastcall => "windows_fastcall",
143            Self::AppleAarch64 => "apple_aarch64",
144            Self::Probestack => "probestack",
145            Self::Winch => "winch",
146            Self::PreserveAll => "preserve_all",
147        })
148    }
149}
150
151impl str::FromStr for CallConv {
152    type Err = ();
153    fn from_str(s: &str) -> Result<Self, Self::Err> {
154        match s {
155            "fast" => Ok(Self::Fast),
156            "tail" => Ok(Self::Tail),
157            "system_v" => Ok(Self::SystemV),
158            "windows_fastcall" => Ok(Self::WindowsFastcall),
159            "apple_aarch64" => Ok(Self::AppleAarch64),
160            "probestack" => Ok(Self::Probestack),
161            "winch" => Ok(Self::Winch),
162            "preserve_all" => Ok(Self::PreserveAll),
163            _ => Err(()),
164        }
165    }
166}