rucc_abi/classify.rs
1//! The one classifier every ABI is run through, and the four mechanisms it is built from.
2//!
3//! Design: `spec/cross-compile/06-abis.md` section 6.7.
4//!
5//! [`crate::describe`] argues for the split between mechanism and policy. This is the mechanism
6//! half. There are four things in here that look inside an aggregate, and every ABI in
7//! [`crate::abis`] is one of them plus a size rule plus an order.
8//!
9//! # Ask about the return value first
10//!
11//! On three of the five ABIs described here, a return value that comes back in memory takes an
12//! argument register with it on the way past, so a function returning a large structure has one
13//! argument register fewer than the same function returning `int`. Classifying the arguments
14//! before the return value gives a different answer for the last argument, and it is a different
15//! answer rather than an error, which is the worst kind.
16//!
17//! [`Call::returns`] therefore comes first and [`Call::argument`] is asked once per argument in
18//! source order. Asking out of order answers for a different program.
19
20use crate::describe::{
21 AbiDescription, Banks, ReturnPointer, Rule, Scalars, Short, Test, Travel, Variadic,
22};
23use crate::shape::{Arg, Format, Kind, Pass, Scalar, Shape, Slot};
24
25/// The registers one call has left.
26///
27/// Made by [`AbiDescription::call`], asked about the return value first and then about each
28/// argument in order.
29#[derive(Debug, Clone)]
30pub struct Call {
31 /// The ABI being followed.
32 abi: &'static AbiDescription,
33 /// General purpose argument registers left. On an ABI whose banks are shared this is the
34 /// argument positions left, since there both kinds of register share them.
35 integer: u32,
36 /// Floating point argument registers left.
37 float: u32,
38}
39
40impl AbiDescription {
41 /// The start of one call, with every argument register still to spend.
42 #[must_use]
43 pub const fn call(&'static self) -> Call {
44 Call { abi: self, integer: self.banks.integer, float: self.banks.float }
45 }
46}
47
48impl Call {
49 /// The ABI this call follows.
50 #[must_use]
51 pub const fn abi(&self) -> &'static AbiDescription {
52 self.abi
53 }
54
55 /// General purpose argument registers left, which is what a test asserts about draining.
56 #[must_use]
57 pub const fn integer_left(&self) -> u32 {
58 self.integer
59 }
60
61 /// Floating point argument registers left.
62 #[must_use]
63 pub const fn float_left(&self) -> u32 {
64 self.float
65 }
66
67 /// How the return value comes back, which is asked before anything else.
68 #[must_use]
69 pub fn returns(&mut self, arg: &Arg<'_>) -> Pass {
70 let shape = match arg {
71 // A returned scalar comes back in the first register of its bank and spends nothing,
72 // because the registers a return value uses are not the ones arguments use. Unless no
73 // register holds it, where the caller passes somewhere to put it and the callee
74 // writes it there, the same as for an aggregate of that size.
75 Arg::Void => return Pass::Ignore,
76 Arg::Scalar(scalar) if self.by_reference(*scalar) => {
77 // Except for the one the ABI brings back in a vector register anyway, which is
78 // an `__int128` on Windows: it goes out as an address and comes back in xmm0.
79 let vector = self.abi.scalars.wide_integer_returns_in;
80 if let (Kind::Integer, Some(format)) = (scalar.kind, vector) {
81 return Pass::Pieces(vec![Slot::Float { offset: 0, format }]);
82 }
83 if self.abi.return_pointer == ReturnPointer::FirstArgument {
84 self.integer = self.integer.saturating_sub(1);
85 }
86 return Pass::Reference;
87 }
88 Arg::Scalar(_) => return Pass::Direct,
89 Arg::Aggregate(shape) => *shape,
90 };
91 self.apply(self.abi.returns, &shape, true)
92 }
93
94 /// How the next fixed argument travels, which spends whatever registers it takes.
95 #[must_use]
96 pub fn argument(&mut self, arg: &Arg<'_>) -> Pass {
97 let shape = match arg {
98 Arg::Void => return Pass::Ignore,
99 Arg::Scalar(scalar) => return self.scalar(*scalar),
100 Arg::Aggregate(shape) => *shape,
101 };
102 self.apply(self.abi.arguments, &shape, false)
103 }
104
105 /// How the next argument past the `...` travels.
106 ///
107 /// Only one of the three policies changes the answer this crate gives. Under
108 /// [`Variadic::AlwaysMemory`] the argument is classified as though no argument registers were
109 /// left, which is Darwin arm64's rule stated in the one form that needs no new mechanism.
110 /// [`Variadic::BothBanks`] is a fact about which registers the backend has to write, not
111 /// about the form the value travels in, so the answer here is the same as for a fixed
112 /// argument and the description carries the flag for the backend to read.
113 #[must_use]
114 pub fn variadic_argument(&mut self, arg: &Arg<'_>) -> Pass {
115 match self.abi.variadic {
116 Variadic::SameAsFixed | Variadic::BothBanks => self.argument(arg),
117 Variadic::AlwaysMemory => {
118 let shape = match arg {
119 Arg::Void => return Pass::Ignore,
120 // On the stack, in the same form, spending nothing.
121 Arg::Scalar(_) => return Pass::Direct,
122 Arg::Aggregate(shape) => *shape,
123 };
124 // A scratch call with nothing left. Every rule that wanted a register runs
125 // short, which is exactly what "always on the stack" means, and the real banks
126 // are untouched because a variadic argument does not spend one.
127 let mut empty = Self { abi: self.abi, integer: 0, float: 0 };
128 empty.apply(self.abi.arguments, &shape, false)
129 }
130 }
131 }
132
133 /// Whether a scalar travels as the address of a copy rather than as itself.
134 ///
135 /// The size rule of the one ABI that does this is written over the size of the object and
136 /// says nothing about what is in it, so it is asked here the same way and of the same sizes
137 /// the aggregate rules in [`crate::abis`] are written with. That is also why the rule itself
138 /// is on the description rather than here: a back end pass writing a call to a runtime routine
139 /// has to ask the same question with a width and no C type behind it.
140 fn by_reference(&self, scalar: Scalar) -> bool {
141 self.abi.scalar_is_by_reference(scalar.size)
142 }
143
144 /// How a scalar argument travels, which is as itself wherever a register holds it, and what it
145 /// costs.
146 fn scalar(&mut self, scalar: Scalar) -> Pass {
147 let Banks { shared, integer_width, float_width, .. } = self.abi.banks;
148 let Scalars { in_memory, wide_integer_is_all_or_nothing, .. } = self.abi.scalars;
149 // A scalar no register holds is the address of a copy the caller made, which costs the
150 // one position that address travels in and nothing else.
151 if self.by_reference(scalar) {
152 self.integer = self.integer.saturating_sub(1);
153 return Pass::Reference;
154 }
155 // A `long double` argument on SysV is in the argument area and there is no register file
156 // it could have gone in, so it costs nothing and leaves the banks alone.
157 if matches!(scalar.kind, Kind::Float(format) if Some(format) == in_memory) {
158 return Pass::Direct;
159 }
160 let want = registers(scalar.size, integer_width);
161 match scalar.kind {
162 // Shared banks mean there is one sequence of positions and every value takes the
163 // next one, whichever kind of register it ends up in.
164 _ if shared => self.integer = self.integer.saturating_sub(1),
165 Kind::Float(_) if scalar.size <= float_width => {
166 self.float = self.float.saturating_sub(1);
167 }
168 // Wider than a vector register holds, which is a `long double` on RISC-V LP64D. It
169 // travels in general purpose registers like an integer of the same size.
170 Kind::Float(_) => self.integer = self.integer.saturating_sub(want),
171 Kind::Integer if wide_integer_is_all_or_nothing => {
172 if want <= self.integer {
173 self.integer -= want;
174 }
175 }
176 Kind::Integer => self.integer = self.integer.saturating_sub(want),
177 }
178 Pass::Direct
179 }
180
181 /// The first rule whose test matches, with what it costs applied.
182 fn apply(&mut self, rules: &'static [Rule], shape: &Shape<'_>, returning: bool) -> Pass {
183 for rule in rules {
184 let Some(found) = self.matches(rule.when, shape) else { continue };
185 match self.travel(rule, &found, shape, returning) {
186 Some(pass) => return pass,
187 // The rule ran short of registers and said to try the next one.
188 None => continue,
189 }
190 }
191 // A description whose last rule is not `Test::Anything` has a hole in it, and the test
192 // in `abis.rs` is what stops one being written. Reaching here means that test is gone.
193 unreachable!("every rule list ends with a rule that matches anything")
194 }
195
196 /// Whether a test matches, and the slots it found if it is one of the tests that looks
197 /// inside.
198 fn matches(&self, test: Test, shape: &Shape<'_>) -> Option<Vec<Slot>> {
199 let Banks { integer_width, float_width, .. } = self.abi.banks;
200 match test {
201 Test::Anything => Some(Vec::new()),
202 Test::Empty => (shape.size == 0).then(Vec::new),
203 Test::SizeOneOf(sizes) => sizes.contains(&shape.size).then(Vec::new),
204 Test::SizeAtMost(limit) => (shape.size <= limit).then(Vec::new),
205 Test::Homogeneous { limit } => homogeneous(shape, limit),
206 Test::FloatPair => float_pair(shape, integer_width, float_width),
207 Test::X87Stack => x87_stack(shape),
208 Test::Eightbytes { limit } => eightbytes(shape, limit),
209 }
210 }
211
212 /// The pass a matched rule produces, and [`None`] if it ran short and said to try the next
213 /// rule.
214 fn travel(
215 &mut self,
216 rule: &Rule,
217 found: &[Slot],
218 shape: &Shape<'_>,
219 returning: bool,
220 ) -> Option<Pass> {
221 let width = self.abi.banks.integer_width;
222 let slots = match rule.then {
223 Travel::Ignore => return Some(Pass::Ignore),
224 Travel::InMemory => return Some(Pass::Memory),
225 Travel::ByReference => {
226 // As an argument the address is one more argument. As a return value it is
227 // whichever register this ABI reserves for the purpose, and on AAPCS64 that is
228 // not an argument register at all.
229 if !returning || self.abi.return_pointer == ReturnPointer::FirstArgument {
230 self.integer = self.integer.saturating_sub(1);
231 }
232 return Some(Pass::Reference);
233 }
234 Travel::AsFound => found.to_vec(),
235 Travel::AsIntegers => integer_slots(shape.size, width),
236 Travel::AsOneInteger => {
237 vec![Slot::Integer { offset: 0, size: u32::try_from(shape.size).unwrap_or(8) }]
238 }
239 };
240 // A return value in registers spends nothing: the registers a value comes back in are
241 // not the ones arguments go out in.
242 if returning {
243 return Some(Pass::Pieces(slots));
244 }
245 let (integer, float) = self.cost(&slots);
246 if integer <= self.integer && float <= self.float {
247 self.integer -= integer;
248 self.float -= float;
249 return Some(Pass::Pieces(slots));
250 }
251 match rule.short {
252 Short::Unchanged => {
253 self.integer = self.integer.saturating_sub(integer);
254 self.float = self.float.saturating_sub(float);
255 Some(Pass::Pieces(slots))
256 }
257 Short::Memory => Some(Pass::Memory),
258 Short::MemoryAndDrain => {
259 // Whichever bank it could not be served from is spent, so that nothing after it
260 // gets a register the ABI would have had to skip over.
261 if integer > self.integer {
262 self.integer = 0;
263 }
264 if float > self.float {
265 self.float = 0;
266 }
267 Some(Pass::Memory)
268 }
269 Short::TryNextRule => None,
270 }
271 }
272
273 /// What a run of slots costs, as general purpose registers and then vector registers.
274 fn cost(&self, slots: &[Slot]) -> (u32, u32) {
275 let count = u32::try_from(slots.len()).unwrap_or(u32::MAX);
276 if self.abi.banks.shared {
277 // One position per register's worth, whichever bank it lands in.
278 return (count, 0);
279 }
280 let float =
281 u32::try_from(slots.iter().filter(|slot| slot.is_float()).count()).unwrap_or(u32::MAX);
282 (count - float, float)
283 }
284}
285
286/// How many registers of this width a value of this size takes, which is at least one.
287fn registers(size: u64, width: u64) -> u32 {
288 u32::try_from(size.div_ceil(width.max(1))).unwrap_or(1).max(1)
289}
290
291/// An object of this size as a run of integer registers, the last one holding only what is left.
292///
293/// The last slot being narrow is not tidiness. A twelve byte structure at the end of a page is
294/// twelve readable bytes followed by four that are not, and a load of the full register width
295/// there faults on a program that is correct.
296fn integer_slots(size: u64, width: u64) -> Vec<Slot> {
297 let width = width.max(1);
298 (0..size.div_ceil(width))
299 .map(|index| Slot::Integer {
300 offset: index * width,
301 size: u32::try_from((size - index * width).min(width)).unwrap_or(8),
302 })
303 .collect()
304}
305
306/// The vector registers of a homogeneous floating point aggregate, and [`None`] for anything
307/// else.
308///
309/// Homogeneous means every scalar is the same floating point type once arrays and nested records
310/// are flattened out, and that they fill the aggregate. The second half is what rules out
311/// `struct { float a; char pad[8]; }`, which has one floating point member and is not an HFA,
312/// and anything a zero width bit-field has stretched.
313fn homogeneous(shape: &Shape<'_>, limit: usize) -> Option<Vec<Slot>> {
314 let first = shape.pieces.first()?;
315 let Kind::Float(format) = first.scalar.kind else { return None };
316 let count = shape.pieces.len();
317 if count > limit || shape.pieces.iter().any(|piece| piece.scalar != first.scalar) {
318 return None;
319 }
320 let fills = first.scalar.size.checked_mul(count as u64) == Some(shape.size);
321 fills.then(|| {
322 shape.pieces.iter().map(|piece| Slot::Float { offset: piece.offset, format }).collect()
323 })
324}
325
326/// The registers a one or two member aggregate travels in under the RISC-V floating point rule,
327/// and [`None`] for one the rule does not reach.
328///
329/// A member wider than a floating point register is not a floating point member for this
330/// purpose, which is why a `long double` on LP64D makes the aggregate holding it an ordinary
331/// integer pair.
332fn float_pair(shape: &Shape<'_>, integer_width: u64, float_width: u64) -> Option<Vec<Slot>> {
333 let slot = |piece: &crate::shape::Piece| match piece.scalar.kind {
334 Kind::Float(format) if piece.scalar.size <= float_width => {
335 Some(Slot::Float { offset: piece.offset, format })
336 }
337 Kind::Integer if piece.scalar.size <= integer_width => Some(Slot::Integer {
338 offset: piece.offset,
339 size: u32::try_from(piece.scalar.size).ok()?,
340 }),
341 _ => None,
342 };
343 let floats = shape.pieces.iter().filter(|piece| piece.scalar.is_float()).count();
344 match shape.pieces {
345 // One floating point member, in the register the member itself would have used.
346 [only] if floats == 1 => Some(vec![slot(only)?]),
347 // Two members with at least one floating point member between them. Two integers are not
348 // this: they are the ordinary size rule, and the ordinary size rule gives them the same
349 // two registers anyway.
350 [first, second] if floats > 0 => Some(vec![slot(first)?, slot(second)?]),
351 _ => None,
352 }
353}
354
355/// The x87 stack registers a `long double` or a `_Complex long double` comes back in, and
356/// [`None`] for anything else.
357fn x87_stack(shape: &Shape<'_>) -> Option<Vec<Slot>> {
358 let one_value = shape.pieces.len() == 1 || (shape.pieces.len() == 2 && shape.complex);
359 let all_x87 = shape.is_all_of(Format::X87Extended);
360 (all_x87 && one_value).then(|| {
361 shape
362 .pieces
363 .iter()
364 .map(|piece| Slot::Float { offset: piece.offset, format: Format::X87Extended })
365 .collect()
366 })
367}
368
369/// The class of one eightbyte, section 3.2.3 of the SysV psABI.
370///
371/// X87UP is not here. It means "the second eightbyte of the `long double` before this one", and
372/// an x87 value in an aggregate goes to memory on every path through here anyway, so the two
373/// classes would have the same answer.
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375enum Class {
376 /// Nothing reaches into it, which takes padding or an empty member.
377 None,
378 /// A general purpose register.
379 Integer,
380 /// A vector register.
381 Sse,
382 /// The rest of the value whose first eightbyte was [`Class::Sse`], which is what the upper
383 /// half of a `_Float128` is. The pair travels in one vector register rather than two.
384 SseUp,
385 /// The x87 stack.
386 X87,
387 /// Memory, which takes the whole argument with it.
388 Memory,
389}
390
391/// Two classes over one eightbyte, section 3.2.3's merge rule.
392fn merge(left: Class, right: Class) -> Class {
393 match (left, right) {
394 (a, b) if a == b => a,
395 (Class::None, other) | (other, Class::None) => other,
396 (Class::Memory, _) | (_, Class::Memory) => Class::Memory,
397 // An x87 value shares an eightbyte with something else only in a packed record, and
398 // there is no way to pass the two of them together.
399 (Class::X87, _) | (_, Class::X87) => Class::Memory,
400 // The rule that surprises people: one `int` in an eightbyte sends the `float` beside it
401 // into a general purpose register.
402 (Class::Integer, _) | (_, Class::Integer) => Class::Integer,
403 // An upper half sharing its eightbyte with anything else is no longer an upper half, so
404 // the two of them are an ordinary vector register between them.
405 _ => Class::Sse,
406 }
407}
408
409/// The slots the SysV classification produces, and [`None`] when the answer is memory.
410///
411/// x87 counts as memory here. As an argument that is the right answer directly, and as a return
412/// value the x87 stack rule is a separate rule earlier in the list, so by the time this runs an
413/// x87 class means the value goes back in memory either way.
414fn eightbytes(shape: &Shape<'_>, limit: u64) -> Option<Vec<Slot>> {
415 if shape.size > limit {
416 return None;
417 }
418 let mut classes = vec![Class::None; usize::try_from(shape.size.div_ceil(8)).ok()?];
419 for piece in shape.pieces {
420 // A member away from its natural alignment is what `packed` makes, and it is the second
421 // of the two things section 3.2.3 sends straight to memory.
422 if piece.scalar.align > 1 && piece.offset % piece.scalar.align != 0 {
423 return None;
424 }
425 let class = match piece.scalar.kind {
426 Kind::Integer => Class::Integer,
427 Kind::Float(Format::X87Extended) => Class::X87,
428 Kind::Float(_) => Class::Sse,
429 };
430 let first = piece.offset / 8;
431 for at in first..=(piece.end() - 1) / 8 {
432 let slot = classes.get_mut(usize::try_from(at).ok()?)?;
433 // A member wider than an eightbyte is one value and not two. Its first eightbyte
434 // carries the class and every later one says "the same value again", which is what
435 // sends a `_Float128` into one vector register instead of two. An integer member is
436 // not this: `__int128` is two general purpose registers and the psABI classifies
437 // both of its eightbytes as INTEGER.
438 let class = if at > first && class == Class::Sse { Class::SseUp } else { class };
439 *slot = merge(*slot, class);
440 }
441 }
442 if classes.iter().any(|class| matches!(class, Class::Memory | Class::X87)) {
443 return None;
444 }
445 // Post merge rule (d). An upper half whose lower half was classified as something else is
446 // not the continuation of anything, so it stands on its own as an ordinary vector register.
447 // `union { _Float128 q; long a; }` is the shape that gets here: the first eightbyte is
448 // INTEGER because of the `long` and the second is the top of the `_Float128` with nothing
449 // above it any more.
450 for index in 0..classes.len() {
451 let above = index > 0 && matches!(classes[index - 1], Class::Sse | Class::SseUp);
452 if classes[index] == Class::SseUp && !above {
453 classes[index] = Class::Sse;
454 }
455 }
456 let mut slots = Vec::with_capacity(classes.len());
457 for (index, class) in classes.iter().enumerate() {
458 // An upper half is already part of the slot the eightbyte below it pushed.
459 if *class == Class::SseUp {
460 continue;
461 }
462 let offset = index as u64 * 8;
463 let bytes = (shape.size - offset).min(8);
464 slots.push(match class {
465 // A lower half with its upper half above it is the whole sixteen byte value in one
466 // register, and the only member that makes that shape is a `_Float128`.
467 Class::Sse if classes.get(index + 1) == Some(&Class::SseUp) => {
468 Slot::Float { offset, format: Format::Quad }
469 }
470 // Four bytes or fewer of floating point is one `float`. More than that is a
471 // `double` or two `float`s, which arrive in the same register either way.
472 Class::Sse if bytes <= 4 => Slot::Float { offset, format: Format::Single },
473 Class::Sse => Slot::Float { offset, format: Format::Double },
474 // An eightbyte nothing reaches into still travels, and it travels in a general
475 // purpose register, because an ABI does not leave a hole in the middle of an
476 // argument.
477 _ => Slot::Integer { offset, size: u32::try_from(bytes).unwrap_or(8) },
478 });
479 }
480 Some(slots)
481}