rucc_abi/describe.rs
1//! The language an ABI is described in.
2//!
3//! Design: `spec/cross-compile/06-abis.md` section 6.7.
4//!
5//! # The argument, restated
6//!
7//! `spec/cross-compile/06-abis.md` section 6.1 lists fifteen psABIs and the compiler has four of them today,
8//! hand written, at about a thousand lines. Fifteen at that rate is six to ten thousand lines of
9//! the most bug prone code in a compiler, and `spec/cross-compile/02-the-goal.md` claim 3 says the per target
10//! line count outside the target crate and the rule set has to be zero.
11//!
12//! # Where the line is drawn, and why here
13//!
14//! The tempting version of this idea is to make everything data, and it does not work. The SysV
15//! eightbyte merge is a real algorithm with a real fixed point, the homogeneous aggregate scan
16//! walks a list and compares members, and writing either as a table produces an interpreter that
17//! is longer than the four functions it replaced and slower than all of them.
18//!
19//! So the split is between mechanism and policy. The mechanisms are code, in [`crate::classify`],
20//! and there are four of them across the five ABIs described here: cut into eightbytes and merge,
21//! look for a homogeneous run of floating point members, look for a one or two member aggregate
22//! with a floating point member in it, and check the size against a list. The policies are data,
23//! and a policy is which mechanisms an ABI applies, in what order, with what limits, and what
24//! happens when the registers a mechanism wanted are not there.
25//!
26//! That split is what makes the count work. The fifth ABI reuses a mechanism and costs a
27//! description. The eleventh probably does too. A new mechanism is a real cost and it is paid
28//! once per idea rather than once per target, and there are far fewer ideas than targets.
29//!
30//! # The performance objection
31//!
32//! Section 6.7 raises it against itself: a compile time decision becoming a run time table walk,
33//! on the hot path. Two answers. The classifier runs once per call site and once per function
34//! signature rather than once per instruction, so the exposure is bounded, and the descriptions
35//! are `const` data reached through a `&'static`, so the branch predictor sees the same rule list
36//! for every call in a translation unit.
37//!
38//! Bounded is a prediction rather than a measurement, and the measurement is `spec/cross-compile/02-the-goal.md`
39//! claim 2's benchmark at the migration point. The fallback if it fails is written down in
40//! section 6.7: the descriptions stay as the source of truth for the tests and the documentation
41//! and the classifiers go back to being hand written, which loses claim 3 and keeps claim 2.
42//! Claim 2 outranks claim 3.
43
44use crate::shape::Format;
45
46/// One psABI, completely.
47///
48/// Everything an ABI decides about how a value travels is in here. What is deliberately not in
49/// here is in [`AbiDescription::stack_args`]'s note: prologue emission, register allocation
50/// constraints and unwind emission are per architecture code with per ABI parameters, and
51/// section 6.7 is explicit that turning those into tables costs more than the duplication.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct AbiDescription {
54 /// What the ABI is called, which is the name that goes in a diagnostic and in the report.
55 pub name: &'static str,
56 /// The registers a call starts with, and how a scalar spends them.
57 pub banks: Banks,
58 /// How a scalar spends registers, which differs between ABIs more than it looks like it
59 /// should.
60 pub scalars: Scalars,
61 /// The rules for a return value, tried in order.
62 pub returns: &'static [Rule],
63 /// The rules for an argument, tried in order.
64 pub arguments: &'static [Rule],
65 /// Where the address of a return value that comes back in memory travels.
66 pub return_pointer: ReturnPointer,
67 /// What a variadic argument does differently.
68 pub variadic: Variadic,
69 /// How arguments that did not get a register sit in the argument area.
70 ///
71 /// Nothing in this crate reads it. It is here because it is a fact about the ABI and section
72 /// 6.7 wants the description to be the source of truth for the whole ABI rather than for the
73 /// half of it that happens to be classification, and because the backend that does read it
74 /// should be reading it from the same place the tests are generated from.
75 pub stack_args: StackArgs,
76}
77
78/// The registers a call starts with.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct Banks {
81 /// General purpose argument registers.
82 pub integer: u32,
83 /// Floating point argument registers.
84 pub float: u32,
85 /// Whether the two banks share argument positions.
86 ///
87 /// True on Windows x64, where rcx, rdx, r8 and r9 and xmm0 to xmm3 are the same four
88 /// positions, so a call taking an `int` and then a `double` uses rcx and xmm1 and never
89 /// xmm0. When this is set the floating point bank is not counted separately and every spend
90 /// comes out of the integer one, which is why [`Banks::float`] is zero on such a target.
91 pub shared: bool,
92 /// The width of a general purpose register in bytes, which is how wide one integer slot is.
93 pub integer_width: u64,
94 /// The widest floating point value a vector register holds, in bytes.
95 ///
96 /// Eight on RISC-V LP64D, where a sixteen byte `long double` therefore travels in integer
97 /// registers, and sixteen on AAPCS64, where it does not. This is the field that makes the
98 /// difference between those two ABIs' otherwise identical treatment of a wide float.
99 pub float_width: u64,
100}
101
102/// How a scalar spends registers.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct Scalars {
105 /// A floating point value in this format travels in the argument area and spends nothing.
106 ///
107 /// `Some(Format::X87Extended)` on SysV AMD64, where a `long double` argument is on the stack
108 /// and there is no register file it could have gone in. `None` everywhere else.
109 pub in_memory: Option<Format>,
110 /// Whether an integer wider than one register takes every register it needs or none of them.
111 ///
112 /// True on SysV AMD64, where an `__int128` takes two consecutive general purpose registers,
113 /// and taking one of them would spend a register on half a value and deny it to an argument
114 /// after it that could have used the whole thing.
115 pub wide_integer_is_all_or_nothing: bool,
116}
117
118/// Where the address of a return value that comes back in memory travels.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum ReturnPointer {
121 /// A hidden first argument, which spends an argument register.
122 ///
123 /// SysV AMD64, Windows x64 and RISC-V. This is why the return value is classified before the
124 /// arguments: on these three, a function returning a large structure has one argument
125 /// register fewer than the same function returning `int`, and classifying the arguments
126 /// first gives the wrong answer for the last one of them.
127 FirstArgument,
128 /// A register outside the argument bank, which spends nothing.
129 ///
130 /// AAPCS64's x8. A function returning a large structure still has all eight argument
131 /// registers for what it was called with.
132 Dedicated,
133}
134
135/// What a variadic argument does differently.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum Variadic {
138 /// Nothing. A variadic argument is classified the same way a fixed one is.
139 SameAsFixed,
140 /// Every variadic argument is in the argument area, whatever registers are left.
141 ///
142 /// Darwin arm64, and the divergence that makes it a separate ABI rather than AAPCS64 with
143 /// notes, per `spec/cross-compile/06-abis.md` section 6.3. It is also the reason a variadic call there is
144 /// ABI-incompatible with a non-variadic one, so calling an unprototyped function works until
145 /// the day it does not.
146 AlwaysMemory,
147 /// A floating point argument travels in both its vector register and the corresponding
148 /// general purpose one.
149 ///
150 /// Windows x64, because the callee of a variadic function does not know which bank to read.
151 BothBanks,
152}
153
154/// How arguments that did not get a register sit in the argument area.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum StackArgs {
157 /// Each argument occupies a whole number of registers' worth of the argument area, so a
158 /// `char` takes eight bytes. Every ELF ABI here.
159 RegisterSized,
160 /// Each argument occupies its natural size and alignment, so a `char` takes one byte.
161 ///
162 /// Darwin arm64. Getting this wrong produces functions whose ninth argument onward is
163 /// garbage, on Darwin only, which is `spec/cross-compile/06-abis.md` section 6.3's first row.
164 Packed,
165}
166
167/// One rule: what an aggregate has to look like, how it travels if it does, and what happens
168/// when the registers it wanted are not there.
169///
170/// The rules are tried in order and the first one whose test matches wins, so a rule list reads
171/// the way the psABI document it came from is written: the special cases first, the general size
172/// rule after them, and the catch-all last.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct Rule {
175 /// What the aggregate has to look like.
176 pub when: Test,
177 /// How it travels if it does.
178 pub then: Travel,
179 /// What happens if the registers it wanted are not there.
180 pub short: Short,
181}
182
183impl Rule {
184 /// A rule that cannot run short of registers, which is every rule whose result does not
185 /// depend on how many are left.
186 #[must_use]
187 pub const fn new(when: Test, then: Travel) -> Self {
188 Self { when, then, short: Short::Unchanged }
189 }
190
191 /// The same rule, with what happens when the registers are gone.
192 #[must_use]
193 pub const fn short(self, short: Short) -> Self {
194 Self { short, ..self }
195 }
196}
197
198/// What an aggregate has to look like for a rule to apply.
199///
200/// Four of these look inside the aggregate and the rest read its size. The four are the
201/// mechanisms of this crate, and the claim in section 6.7 is that the number of them grows much
202/// more slowly than the number of ABIs.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum Test {
205 /// Anything, which is what the last rule in a list is.
206 Anything,
207 /// An aggregate of no size, which is a GNU empty struct and travels nowhere.
208 Empty,
209 /// A size that is exactly one of these.
210 ///
211 /// Windows x64's rule, and the sharpest one on the list: anything not exactly one, two, four
212 /// or eight bytes travels as an address, so a three byte structure and a three hundred byte
213 /// structure are passed the same way. Also s390x's, with the same list.
214 SizeOneOf(&'static [u64]),
215 /// A size at most this many bytes.
216 SizeAtMost(u64),
217 /// A homogeneous floating point aggregate of at most this many members.
218 ///
219 /// AAPCS64's HFA, and the same idea with a different limit on AAPCS32 hard float and on
220 /// ELFv2. Homogeneous means every scalar in it is the same floating point type once arrays
221 /// and nested records are flattened, and that they fill the aggregate with no padding left
222 /// over. The second half is what rules out `struct { float a; char pad[8]; }` and anything a
223 /// zero width bit-field has stretched.
224 Homogeneous {
225 /// The most members it can have and still travel in vector registers.
226 limit: usize,
227 },
228 /// One or two members with at least one floating point member between them, each fitting one
229 /// register.
230 ///
231 /// The RISC-V rule, and LoongArch's. `struct { double re, im; }` is two floating point
232 /// registers and `struct { double value; int tag; }` is one of each, which no other ABI on
233 /// the list does. A member wider than a floating point register is not a floating point
234 /// member for this purpose, which is what makes a `long double` here behave like an integer
235 /// pair.
236 FloatPair,
237 /// Every scalar is an x87 `long double`, and there is one of them, or two if it is a
238 /// `_Complex`.
239 ///
240 /// The SysV return path, where a `long double` comes back in st(0) and a `_Complex long
241 /// double` in st(0) and st(1). A record holding two of them is the same thirty two bytes and
242 /// comes back in memory, which is the only thing [`crate::Shape::complex`] is for.
243 X87Stack,
244 /// The SysV eightbyte classification succeeds, and no eightbyte came out x87.
245 ///
246 /// The intricate one. The aggregate is cut into eight byte chunks, each chunk gets a class
247 /// from merging the classes of every scalar reaching into it, and any chunk that comes out
248 /// MEMORY takes the whole argument to memory with it. The cases that catch people are all in
249 /// the merge: an eightbyte holding an `int` and a `float` together is INTEGER, so the float
250 /// travels in a general purpose register, and a member away from its natural alignment sends
251 /// the whole thing to memory.
252 Eightbytes {
253 /// The largest aggregate that can be classified at all, sixteen bytes on SysV.
254 ///
255 /// It is a consequence of the eight eightbyte limit rather than an independent rule: an
256 /// aggregate over two eightbytes travels in registers only when every eightbyte after
257 /// the first is SSEUP, and only a vector produces those.
258 limit: u64,
259 },
260}
261
262/// How a value travels when a rule's test matched.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum Travel {
265 /// Nothing travels.
266 Ignore,
267 /// In the slots the test found, which is only meaningful after a test that finds some.
268 AsFound,
269 /// As a run of integer registers covering the object, one per register width, the last one
270 /// holding only what is left.
271 AsIntegers,
272 /// As one integer register of the object's exact size, whatever is in it.
273 ///
274 /// Windows x64, where a `struct { float x, y; }` arrives in rcx rather than in xmm0.
275 AsOneInteger,
276 /// As the address of a copy.
277 ByReference,
278 /// As the object's own bytes in the argument area.
279 InMemory,
280}
281
282/// What happens when the registers a rule wanted are not there.
283///
284/// This is the part of a psABI that is easiest to get wrong and hardest to notice, because every
285/// test anybody writes by hand passes few enough arguments that it never comes up. The ninth
286/// argument of a call is not classified the way the first one is on three of the five ABIs here.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum Short {
289 /// Running out changes nothing. The value goes in the argument area in the same form it
290 /// would have had in a register, and the spend saturates.
291 ///
292 /// Every scalar, and every aggregate on Windows x64, where an argument past the fourth
293 /// travels the way the first one does.
294 Unchanged,
295 /// The argument goes in the argument area, and the registers that are left stay available
296 /// for the arguments after it.
297 ///
298 /// SysV AMD64. An aggregate that did not fit does not stop a later scalar from getting a
299 /// register, which is the opposite of what AAPCS64 does with the same situation.
300 Memory,
301 /// The argument goes in the argument area, and every remaining register of that bank goes
302 /// with it.
303 ///
304 /// AAPCS64 and RISC-V. The draining is the surprising half: once one aggregate has been put
305 /// on the stack for want of registers, a later argument that would have fitted goes on the
306 /// stack too, because the ABI will not leave a hole in the register sequence.
307 MemoryAndDrain,
308 /// The rule does not apply after all, and the rules after it are tried.
309 ///
310 /// The RISC-V floating point pair, which is a bonus rather than a requirement: an aggregate
311 /// the rule reached but the registers did not is classified by the ordinary size rules and
312 /// still travels in registers if those find any.
313 TryNextRule,
314}