rucc_codegen/varargs.rs
1//! What a function does to read the arguments its own signature does not name.
2//!
3//! Design: `spec/12-abi-and-runtime.md`, which is where the layout below comes from.
4//!
5//! A variadic callee has a problem an ordinary one does not. Six of its arguments arrived in
6//! general purpose registers and eight more in vector ones, and it cannot know which of those hold
7//! anything, because what it was passed is a thing only the caller knew. Registers are also not
8//! addressable, and `va_arg` walks arguments one after another at run time, which is walking
9//! addresses. So the convention says the callee spills all fourteen of them into a block of its own
10//! frame on the way in, and from then on every argument it was passed is somewhere in memory: the
11//! ones that came in registers are in that block, and the ones that did not are in the caller's
12//! argument area where they were left.
13//!
14//! That block is the register save area, and a `va_list` is four fields saying how far into the
15//! arguments the walk has got:
16//!
17//! ```text
18//! offset 0 gp_offset bytes into the save area of the next argument from a gpr
19//! offset 4 fp_offset bytes into the save area of the next argument from an xmm
20//! offset 8 overflow_arg_area the next argument that came in the caller's memory
21//! offset 16 reg_save_area the bottom of the save area
22//! ```
23//!
24//! `va_start` fills all four in. The two offsets do not start at zero: the arguments the signature
25//! does name took registers too, and they took the first ones, so each offset starts past them.
26//! `va_arg` is then one question asked at run time, which is whether the offset for its file has run
27//! off the end of the save area. If it has not, the argument is in the save area and the offset
28//! steps on by a slot. If it has, the argument is in the caller's memory and the overflow pointer
29//! steps on by a word instead.
30//!
31//! # Why the layout is exactly the psABI's and not a convenient one
32//!
33//! Nothing outside the function can see the save area, so its shape looks like a private decision.
34//! It is not one, because a `va_list` is a thing a program hands to another function, and the
35//! function it usually hands it to is `vfprintf` in the C library, which somebody else compiled and
36//! which walks the list by the rules in the psABI document. So the offsets are the document's
37//! offsets, the area is the document's one hundred and seventy six bytes, and the eight bytes
38//! between two general purpose slots and the sixteen between two vector ones are the document's too.
39//!
40//! The upper half of a vector slot is the document's too, and what is in it is the top of a
41//! `_Float128`. A slot is sixteen bytes wide because the register is, and a quad is the one type
42//! here that fills one, so the spill writes all sixteen bytes of every vector register and a
43//! `va_arg` of a quad reads all sixteen back. gcc writes the same sixteen with the same instruction,
44//! which is what makes a list built here readable by a walk somebody else compiled. Anything wider
45//! than a register would be a vector type, which is issue #200 and is not a thing yet.
46//!
47//! # What is here and what is next door
48//!
49//! `va_arg` becomes a compare and a branch, and this is where, because a rewrite that needs new
50//! blocks has to happen before selection for the reason [`crate::expand`] gives. Everything it needs
51//! is in the list it was handed, so it needs nothing from the frame and can run here.
52//!
53//! An aggregate read off a list is the same instruction under another name, because an aggregate is
54//! not a value and there is nothing for one result to be, so that one answers where the object is
55//! instead. Over two eightbytes it is class MEMORY whatever its members are, which means it is in
56//! the caller's argument area and there is no question to ask about which half of the walk it is
57//! in: the overflow pointer says where it is and steps on past it. Sixteen bytes and under arrived
58//! in registers, and then the question is the one a scalar asks, with two differences. The object
59//! takes a register of each file for each of its eightbytes, so the room in the save area has to be
60//! there for all of them at once and the offsets step on by all of them at once. And the halves of
61//! it in the save area are not next to each other, so the answer cannot be an address in the area:
62//! the eightbytes are copied out into a buffer of the function's own and the answer is that.
63//!
64//! Which file each eightbyte came from is the classification, which is an answer about a C type and
65//! not one the size and the alignment give. It arrives on the instruction, worked out by the front
66//! end, which is the last thing to hold a type. An object with no slots on it is one the
67//! classification sent to the argument area, and that is what tells the two halves below apart.
68//!
69//! `va_start` is the other way round. Three of the four fields it writes are distances into a frame
70//! that does not exist yet, so it stays an instruction as far as [`crate::lower`], which builds it
71//! out of the frame the way it builds an `alloca`. The spill that fills the save area is written
72//! there for the same reason.
73//!
74//! # The other kind of list
75//!
76//! Windows has none of that. Its convention counts the two register files as one run of positions,
77//! so an argument's position says which register of either file it is in and the two walks above
78//! are one walk. It also gives every argument exactly one eight byte slot whatever it is: anything
79//! that is not one, two, four or eight bytes travels as the address of a copy the caller owns, and
80//! a float beyond the ones the signature names travels in the general purpose register at its
81//! position as well as in the vector one, because a callee with no prototype has no way to know
82//! which file to look in.
83//!
84//! What that comes to is that every argument a variadic callee was passed is already one contiguous
85//! run of words in the caller's argument area, since the first four of them are homed in the thirty
86//! two bytes of shadow space the caller reserved above the return address and the rest follow.
87//! There is nothing to gather and nowhere to gather it to. So a `va_list` is a `char *` pointing at
88//! the next of those words, `va_start` is one `lea` and one store, and `va_arg` is a load and an
89//! eight byte step with no compare, no branch and no second file. The register save area of the
90//! four field list is, on this convention, the caller's shadow space, and the callee's prologue
91//! writes its leftover argument registers into it rather than into a block of its own.
92//!
93//! An argument that travelled by reference costs one more load and that is the whole of the
94//! difference: the slot holds the address of the copy rather than the copy. Which arguments those
95//! are is a question about the size and nothing else, so the classification the front end put on a
96//! `va_object` is not read here at all.
97
98pub mod aapcs;
99
100use rucc_base::float::Format;
101use rucc_ir::{
102 Block, Builder, Extra, Flags, Float, Func, Imm, Inst, InstData, IntPred, MemInfo, MemOrder,
103 Opcode, Restrict, Type, Value,
104};
105use rucc_target::{CallRegs, Slot, VaList, Variadic};
106
107/// Where the count of general purpose register bytes already walked is.
108pub const GP_OFFSET: i64 = 0;
109/// Where the count of vector register bytes already walked is.
110pub const FP_OFFSET: i64 = 4;
111/// Where the pointer to the next argument in the caller's memory is.
112pub const OVERFLOW: i64 = 8;
113/// Where the pointer to the bottom of the register save area is.
114pub const SAVE_AREA: i64 = 16;
115/// How many bytes the four field `va_list` is, which is what a `va_copy` of one moves.
116pub const SIZE: u64 = 24;
117/// How wide the slot one vector register is saved in is, which is how wide the register is whatever
118/// this actually writes into it.
119pub const VECTOR_SLOT: u32 = 16;
120
121/// How big a callee's register save area is and where its two halves are.
122///
123/// Worked out from the convention rather than written down, so that a convention with a different
124/// number of argument registers gets an area the right size for it without anything here changing.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct Area {
127 /// How many bytes of it the general purpose registers take, which is also where the vector half
128 /// begins, since the general purpose half is first and starts at nothing.
129 pub floats_at: u32,
130 /// How many bytes the whole of it is.
131 pub size: u32,
132 /// How many registers of each file it holds, general purpose first.
133 counts: (u32, u32),
134 /// How far apart two general purpose slots are, which is a word.
135 word: u32,
136}
137
138impl Area {
139 /// The save area a variadic callee under that convention needs.
140 ///
141 /// Two shapes, and what tells them apart is the convention's own answer about how it counts
142 /// argument positions. One that counts the two files apart spills all of both into a block of
143 /// the callee's own frame, which is the psABI's register save area and is what the four field
144 /// list walks. One that counts them as one run homes each register argument in the word of the
145 /// caller's argument area that belongs to its position, and that run of words is the area. The
146 /// vector file has nothing in it there: a float beyond the ones the signature names travels in
147 /// the general purpose register at its position as well, so the copy a walk reads is that one.
148 #[must_use]
149 pub fn of(conv: &CallRegs) -> Self {
150 let ints = u32::try_from(conv.int_args.len()).unwrap_or(0);
151 let floats = u32::try_from(conv.sse_args.len()).unwrap_or(0);
152 if conv.shared_positions {
153 let size = conv.word * ints;
154 return Self { floats_at: size, size, counts: (ints, 0), word: conv.word };
155 }
156 let floats_at = conv.word * ints;
157 Self {
158 floats_at,
159 size: floats_at + VECTOR_SLOT * floats,
160 counts: (ints, floats),
161 word: conv.word,
162 }
163 }
164
165 /// How far apart two of a file's slots are.
166 #[must_use]
167 pub fn stride(self, float: bool) -> u32 {
168 if float { VECTOR_SLOT } else { self.word }
169 }
170
171 /// Where a file's first slot is, which is what `va_start` writes into that file's field when
172 /// the signature named no argument that file carried.
173 #[must_use]
174 pub fn starts_at(self, float: bool) -> u32 {
175 if float { self.floats_at } else { 0 }
176 }
177
178 /// Where a file's slots end, which is where the vector half begins for the general purpose
179 /// file and the end of the whole area for the vector one.
180 ///
181 /// This is what an object taking more than one register of a file is measured against: the
182 /// psABI asks whether the offset is at or below the end less a slot for each register the
183 /// object wants, and one register of it is the same question [`Area::last`] asks.
184 #[must_use]
185 pub fn ends_at(self, float: bool) -> u32 {
186 if float { self.size } else { self.floats_at }
187 }
188
189 /// How many registers of a file the area holds.
190 #[must_use]
191 pub fn holds(self, float: bool) -> u32 {
192 if float { self.counts.1 } else { self.counts.0 }
193 }
194
195 /// The offset of a file's last slot, which is the threshold `va_arg` compares against.
196 ///
197 /// The last slot's own offset and not the end of the area, because an offset equal to the end
198 /// is one slot past the last argument while an offset a slot below the end is the last argument
199 /// itself. An empty file has no such offset and nothing here has one.
200 #[must_use]
201 pub fn last(self, float: bool) -> Option<u32> {
202 let last = self.holds(float).checked_sub(1)?;
203 Some(self.starts_at(float) + self.stride(float) * last)
204 }
205}
206
207/// Rewrites every `va_arg`, `va_copy` and `va_end` in the function, and leaves `va_start` alone.
208///
209/// Those three are the ones made only of reads and writes of a list some pointer already reaches,
210/// so none of them needs to know anything about the frame and all three can be done here.
211/// `va_start` is the one that does need the frame, and [`crate::lower`] has it.
212///
213/// A convention whose list is a plain pointer gets the walk the module doc's last section
214/// describes instead, which is the same three rewrites over a list of one field, and AAPCS64 gets
215/// the walk [`aapcs`] describes. Apple's AArch64 has the plain pointer, and its scalars take the
216/// same walk, but an object there is as many words as it needs rather than one, which is the
217/// memory half of the AAPCS64 walk and is `aapcs::stacked`.
218pub fn lists(func: &mut Func, conv: &CallRegs) {
219 let area = Area::of(conv);
220 let word = u64::from(conv.word);
221 let found: Vec<Inst> =
222 func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
223 for inst in found {
224 match (func[inst].opcode, conv.list) {
225 (Opcode::VaArg, VaList::SysV) => next(func, inst, area),
226 (Opcode::VaArg, VaList::Aapcs) => aapcs::next(func, inst),
227 (Opcode::VaArg, VaList::CharPointer | VaList::VoidPointer) => value(func, inst, word),
228 (Opcode::VaObject, VaList::SysV) => object(func, inst, area),
229 (Opcode::VaObject, VaList::Aapcs) => aapcs::object(func, inst),
230 (Opcode::VaObject, VaList::CharPointer)
231 if conv.abi.variadic == Variadic::AlwaysMemory =>
232 {
233 aapcs::stacked(func, inst);
234 }
235 (Opcode::VaObject, VaList::CharPointer | VaList::VoidPointer) => {
236 held(func, inst, word);
237 }
238 (Opcode::VaCopy, VaList::SysV) => copy(func, inst, SIZE),
239 (Opcode::VaCopy, VaList::Aapcs) => copy(func, inst, aapcs::SIZE),
240 (Opcode::VaCopy, VaList::CharPointer | VaList::VoidPointer) => copy(func, inst, word),
241 // Nothing at all, which is what the psABI says it is. The instruction was still worth
242 // emitting, because it says the list stops being read here, and here is where that
243 // stops being worth saying.
244 (Opcode::VaEnd, _) => func.remove_inst(inst),
245 _ => {}
246 }
247 }
248}
249
250/// One `va_arg`, as the branch on whether the argument it wants is still in the save area.
251///
252/// The block the instruction was in is cut in two at the instruction. What was above it stays where
253/// it is and gets the compare and the branch, what was below it moves into a new block that takes
254/// the address as a parameter, and the `va_arg` itself becomes the load at the top of that block.
255/// Turning it into the load rather than replacing it keeps the value the rest of the function reads
256/// the value it already read, so nothing has to be substituted anywhere, and the two paths meet at a
257/// block parameter because the IR has no variables for them to meet at.
258fn next(func: &mut Func, inst: Inst, area: Area) {
259 let Some(result) = func[inst].first_result else { return };
260 let Some(&list) = func[func[inst].args].first() else { return };
261 let ty = func[result].ty;
262 let Some(block) = func.block_of(inst) else { return };
263 let span = func.span(inst);
264 // A `long double` is class X87, which is a class with no register in the save area, so it is
265 // always in the caller's argument area and there is no question to ask about it. That is this
266 // walk with the register half deleted, which is little enough to be written out separately
267 // rather than folded in as a special case of a branch that is never taken.
268 if ty.is_float() && ty.bits() == 80 {
269 x87(func, inst, area);
270 return;
271 }
272 // A `_Float128` is the one value wider than a general purpose register that a single register
273 // still holds. It is class SSE followed by SSEUP, which name one vector register between them,
274 // so it walks the vector half the way a `double` does and takes the whole of a slot instead of
275 // the low half of one. Where it stops being a wider `double` is the caller's argument area,
276 // which gives it two words aligned to two rather than the one word every value the machine
277 // computes in gets.
278 let quad = ty.is_float() && ty.bits() == 128;
279 // A scalar of a width a register holds, which is every type the algorithm below is right about.
280 // An `__int128` takes two slots with an alignment rule of its own, which is the walk `object`
281 // makes for a small structure, so `rucc-lower` reads one as that and it never arrives here.
282 // Anything else wider is left alone and refused by name further down.
283 if !quad
284 && (!ty.is_scalar() || ty.bits() > 64 || !(ty.is_int() || ty.is_float() || ty.is_ptr()))
285 {
286 return;
287 }
288 let float = ty.is_float();
289 let Some(last) = area.last(float) else { return };
290 let field = if float { FP_OFFSET } else { GP_OFFSET };
291
292 // Everything below the instruction, taken out before anything is built, because the builder
293 // appends to a block and this block has to end at the branch.
294 let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
295 let taken = func.create_block();
296 let overflowed = func.create_block();
297 let join = func.create_block();
298 let addr = func.append_param(join, Type::PTR);
299 func.remove_inst(inst);
300 for &at in &rest {
301 func.remove_inst(at);
302 }
303
304 // The question, in the block the `va_arg` used to be in. Unsigned, because an offset into the
305 // save area counts bytes and is never negative, and because what the field holds once the
306 // register arguments have all been walked is a number past the end rather than a small one.
307 let mut build = Builder::new(func, block).at(span);
308 let counter = offset(&mut build, list, field);
309 let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
310 let end = build.iconst(Type::int(32), i128::from(last));
311 let inside = build.icmp(IntPred::Ule, walked, end);
312 build.br_if(inside, taken, &[], overflowed, &[]);
313
314 // The register path: the argument is in the save area at the offset the field holds, and the
315 // field steps on by one slot of its file.
316 let mut build = Builder::new(func, taken).at(span);
317 let base = offset(&mut build, list, SAVE_AREA);
318 let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
319 let wide = build.unary(Opcode::ZExt, walked, Type::int(64));
320 let found = added(&mut build, save, wide);
321 let stride = build.iconst(Type::int(32), i128::from(area.stride(float)));
322 let stepped = build.binary(Opcode::Add, walked, stride, Flags::default());
323 let counter = offset(&mut build, list, field);
324 build.store(stepped, counter, info(4, 4), Flags::default());
325 build.jump(join, &[found]);
326
327 // The memory path: the argument is where the caller left it, and the pointer steps on past it.
328 // By a word for everything the machine computes in, because the caller's argument area is a run
329 // of whole words whatever is in them, and by two words rounded up to two for a quad, which is
330 // the slot the class gets from a function that names it as well as from one that does not.
331 let mut build = Builder::new(func, overflowed).at(span);
332 let (slot, want) = if quad {
333 (u64::from(VECTOR_SLOT), VECTOR_SLOT)
334 } else {
335 (u64::from(area.word), area.word)
336 };
337 let at = overflow(&mut build, list, area, slot, want);
338 let here = build.unary(Opcode::IntToPtr, at, Type::PTR);
339 build.jump(join, &[here]);
340
341 // And the load the program actually wrote, over the address the two paths agreed on, with
342 // everything that used to follow it behind it in the order it was written.
343 let bytes = ty.bits() / 8;
344 let mem = func.add_mem(info(u64::from(bytes), bytes));
345 let args = func.push_values(&[addr]);
346 let data = &mut func[inst];
347 data.opcode = Opcode::Load;
348 data.args = args;
349 data.extra = Extra::Mem(mem);
350 data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
351 func.append_inst(join, inst);
352 for at in rest {
353 func.append_inst(join, at);
354 }
355}
356
357/// One `va_arg` of a `long double`, which is the memory half of the walk and nothing else.
358///
359/// The psABI gives a `long double` class X87 and there is no x87 register among the ones a variadic
360/// callee spills, so a `long double` passed to one is in the caller's argument area whatever else
361/// the call passed and however few arguments came before it. Nothing is asked, no block is made,
362/// and the overflow pointer is rounded up, read and stepped on.
363///
364/// Sixteen bytes and sixteen byte alignment are the psABI's numbers for the class rather than the
365/// type's own: the value is ten bytes of x87 and the argument slot it sits in is padded out to two
366/// words, which is why the load below is ten bytes wide and the step is sixteen.
367fn x87(func: &mut Func, inst: Inst, area: Area) {
368 /// What one of these takes in the argument area.
369 const SLOT: u64 = 16;
370 /// What the argument area aligns one to.
371 const ALIGN: u32 = 16;
372
373 let Some(result) = func[inst].first_result else { return };
374 let Some(&list) = func[func[inst].args].first() else { return };
375 let Some(block) = func.block_of(inst) else { return };
376 let bytes = func[result].ty.bits() / 8;
377 let span = func.span(inst);
378
379 // Everything below the instruction, taken out before anything is built, for the reason the
380 // branching walk takes it out: a builder appends to a block, and the instruction has to end up
381 // behind what is built and in front of what followed it.
382 let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
383 func.remove_inst(inst);
384 for &at in &rest {
385 func.remove_inst(at);
386 }
387
388 let mut build = Builder::new(func, block).at(span);
389 let at = overflow(&mut build, list, area, SLOT, ALIGN);
390 let addr = build.unary(Opcode::IntToPtr, at, Type::PTR);
391
392 let mem = func.add_mem(info(u64::from(bytes), ALIGN));
393 let args = func.push_values(&[addr]);
394 let data = &mut func[inst];
395 data.opcode = Opcode::Load;
396 data.args = args;
397 data.extra = Extra::Mem(mem);
398 data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
399 func.append_inst(block, inst);
400 for at in rest {
401 func.append_inst(block, at);
402 }
403}
404
405/// One `va_object`, as the address the object can be read from.
406///
407/// Two shapes, and the slots on the instruction are what say which. An object with none is one the
408/// classification sent to the caller's argument area, which is what everything over two eightbytes
409/// is whatever its members are. There is no question to ask about that one: the overflow pointer
410/// says where it is and steps on past it, and no block is needed.
411///
412/// An object with slots arrived in registers, and that is the branch [`next`] builds for a scalar
413/// with the object's own two differences: the room has to be there for every one of its slots at
414/// once, and what is answered is a buffer the slots were copied into rather than an address in the
415/// save area, because two eightbytes of one object are not next to each other in there.
416///
417/// The address is answered rather than a copy of the object, which is what the instruction is for
418/// and what gcc does with the same argument. An object in the caller's memory is already somewhere
419/// addressable, and the copy the C standard describes is the assignment the caller of `va_arg`
420/// wrote, which the front end has already built around this.
421fn object(func: &mut Func, inst: Inst, area: Area) {
422 let Extra::VaObject(at) = func[inst].extra else { return };
423 let object = func[at];
424 let MemInfo { size, align, .. } = func[object.mem];
425 let slots: Vec<Slot> = func[object.slots].to_vec();
426 let Some(&list) = func[func[inst].args].first() else { return };
427 let Some(block) = func.block_of(inst) else { return };
428 if func[inst].first_result.is_none() || !fits(&slots, area) {
429 return;
430 }
431 let span = func.span(inst);
432
433 // The buffer the register form copies into, made before anything else, because an alloca of
434 // a fixed size belongs in the entry block and the walk below is built where the instruction
435 // is. It is as big as the slots reach rather than as big as the object, which is more for an
436 // object whose last eightbyte is a part of one: five bytes travel in a whole register and
437 // come out of the area as a whole register, so the buffer has eight bytes for them to land
438 // in and the three past the object are never read.
439 // It is also aligned to whatever the widest slot has to be stored at rather than to whatever
440 // the object asked for, which is the same number for every object a C program can write and is
441 // not the same statement. A slot holding a whole vector register moves as a `movaps`, and a
442 // `movaps` faults on an address that is not a multiple of sixteen, so the buffer says sixteen
443 // because the copy needs it and not because the type happened to ask.
444 let reach = slots.iter().map(|&slot| slot.offset() + width(slot)).max().unwrap_or(0);
445 let wants = slots
446 .iter()
447 .map(|&slot| slot_align(area, is_float(slot), width(slot)))
448 .max()
449 .unwrap_or(1)
450 .max(align);
451 let room = buffer(func, inst, reach.max(size), wants);
452
453 // Everything below the instruction, taken out before anything is built, because a builder
454 // appends to a block and the register form ends this one at a branch.
455 let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
456 func.remove_inst(inst);
457 for &at in &rest {
458 func.remove_inst(at);
459 }
460
461 let (ends, address) = match room {
462 Some(room) if !slots.is_empty() => {
463 let read = Read { list, area, slots: &slots, size, align, room, wants };
464 registers(func, block, inst, read)
465 }
466 _ => {
467 let mut build = Builder::new(func, block).at(span);
468 (block, overflow(&mut build, list, area, size, align))
469 }
470 };
471
472 // And the instruction itself is that address, so that everything reading it goes on reading
473 // the value it already read and nothing has to be substituted anywhere.
474 let args = func.push_values(&[address]);
475 let data = &mut func[inst];
476 data.opcode = Opcode::IntToPtr;
477 data.args = args;
478 data.extra = Extra::None;
479 data.flags = data.flags.intersection(Flags::legal_on(Opcode::IntToPtr));
480 func.append_inst(ends, inst);
481 for at in rest {
482 func.append_inst(ends, at);
483 }
484}
485
486/// One object read off one list, which is what both halves of the walk are about.
487#[derive(Clone, Copy)]
488struct Read<'a> {
489 /// The list it is read from.
490 list: Value,
491 /// The save area of the function doing the reading.
492 area: Area,
493 /// Which register each of the object's eightbytes arrived in, and empty for an object that
494 /// arrived in the caller's memory.
495 slots: &'a [Slot],
496 /// How many bytes the object is.
497 size: u64,
498 /// What it is aligned to, which is what the caller's argument area put it at.
499 align: u32,
500 /// The buffer of the function's own the register form copies the object into.
501 room: Value,
502 /// What that buffer is aligned to, which is the object's alignment or what the widest slot
503 /// needs, whichever is the larger.
504 wants: u32,
505}
506
507/// Whether the classification is one this knows how to read out of the save area.
508///
509/// A slot wider than a register or more of them than the area holds is a classification from some
510/// other machine or from a rule this has not been taught. Turning it down here leaves the
511/// instruction alone, and an instruction left alone is refused by name further down, which is a
512/// message about `va_arg` rather than whatever a half built walk would do at run time.
513fn fits(slots: &[Slot], area: Area) -> bool {
514 let mut counts = [0, 0];
515 for &slot in slots {
516 let float = is_float(slot);
517 if !in_a_register(slot) || width(slot) > u64::from(area.stride(float)) {
518 return false;
519 }
520 counts[usize::from(float)] += 1;
521 }
522 counts[0] <= area.holds(false) && counts[1] <= area.holds(true)
523}
524
525/// Whether a slot is one of the registers a variadic callee spills.
526///
527/// The width does not say on its own. A `long double` is ten bytes and would sit inside a vector
528/// slot with room to spare, and it is class X87, which has no register among the fourteen, so a
529/// classification carrying one is a classification this walk cannot read. The formats a vector
530/// register does hold are named rather than the ones it does not, so a format added later is one
531/// this leaves alone until somebody says where it travels.
532fn in_a_register(slot: Slot) -> bool {
533 match slot {
534 Slot::Integer { .. } => true,
535 Slot::Float { format, .. } => matches!(
536 format,
537 Format::Half | Format::BFloat16 | Format::Single | Format::Double | Format::Quad
538 ),
539 }
540}
541
542/// The register form: the room in the save area is asked about once per file, and the object is
543/// copied out of the area into a buffer when it is there and read from the caller's memory when it
544/// is not.
545///
546/// The question is asked once per file the object takes a register of, and both have to say yes,
547/// because the psABI puts the whole object in the caller's memory when there is not room in the
548/// area for all of it. A file the object takes nothing of has room by definition and is not asked
549/// about, which is every object of one class and is most of them.
550///
551/// Gives back the block the walk ends in and the address, as an integer, that the two paths agreed
552/// on.
553fn registers(func: &mut Func, block: Block, inst: Inst, read: Read<'_>) -> (Block, Value) {
554 let span = func.span(inst);
555 let area = read.area;
556 let counts = [taken_of(read.slots, false), taken_of(read.slots, true)];
557 let saved = func.create_block();
558 let overflowed = func.create_block();
559 let join = func.create_block();
560 let address = func.append_param(join, Type::int(64));
561
562 // The questions, each in its own block, because two of them are two branches and the second
563 // is only asked when the first said yes.
564 let asked: Vec<bool> =
565 [false, true].into_iter().filter(|&float| counts[usize::from(float)] > 0).collect();
566 let mut at = block;
567 for (index, &float) in asked.iter().enumerate() {
568 let next = if index + 1 == asked.len() { saved } else { func.create_block() };
569 // The psABI's own threshold: the end of the file's half of the area, less a slot for each
570 // register the object wants, so that an offset at it leaves room for all of them.
571 let room =
572 area.ends_at(float).saturating_sub(area.stride(float) * counts[usize::from(float)]);
573 let mut build = Builder::new(func, at).at(span);
574 let counter = offset(&mut build, read.list, field_of(float));
575 let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
576 let end = build.iconst(Type::int(32), i128::from(room));
577 let inside = build.icmp(IntPred::Ule, walked, end);
578 build.br_if(inside, next, &[], overflowed, &[]);
579 at = next;
580 }
581
582 let mut build = Builder::new(func, saved).at(span);
583 let found = copied(&mut build, read, counts);
584 build.jump(join, &[found]);
585
586 let mut build = Builder::new(func, overflowed).at(span);
587 let here = overflow(&mut build, read.list, area, read.size, read.align);
588 build.jump(join, &[here]);
589
590 (join, address)
591}
592
593/// The object copied out of the save area into the buffer, as the address of the buffer.
594///
595/// A buffer and not an address in the area because the eightbytes of one object are not next to
596/// each other in there: two integer eightbytes are eight bytes apart and two vector ones are
597/// sixteen, and an object of one of each has them in different halves of the area entirely. So
598/// there is nowhere in the area the object is, and the one place it can be made to be is somewhere
599/// else.
600fn copied(build: &mut Builder<'_>, read: Read<'_>, counts: [u32; 2]) -> Value {
601 let area = read.area;
602 let base = offset(build, read.list, SAVE_AREA);
603 let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
604
605 // Where each file's next slot is, which is the one thing the offsets in the list say, and the
606 // counter itself, which is what steps on by every slot the object took of that file.
607 let mut walked = [None, None];
608 let mut nexts = [None, None];
609 for float in [false, true] {
610 let file = usize::from(float);
611 if counts[file] == 0 {
612 continue;
613 }
614 let counter = offset(build, read.list, field_of(float));
615 let read = build.load(Type::int(32), counter, info(4, 4), Flags::default());
616 let wide = build.unary(Opcode::ZExt, read, Type::int(64));
617 walked[file] = Some(read);
618 nexts[file] = Some(added(build, save, wide));
619 }
620
621 let mut seen = [0, 0];
622 for &slot in read.slots {
623 let float = is_float(slot);
624 let file = usize::from(float);
625 let Some(from) = nexts[file] else { continue };
626 let step = i64::from(area.stride(float) * seen[file]);
627 seen[file] += 1;
628 let bytes = width(slot);
629 let ty = moved_as(area, float, bytes);
630 let aligned = slot_align(area, float, bytes);
631 let at = offset(build, from, step);
632 let value = build.load(ty, at, info(bytes, aligned), Flags::default());
633 let into = offset(build, read.room, i64::try_from(slot.offset()).unwrap_or(0));
634 let holds = info(bytes, part(read.wants, slot.offset()));
635 build.store(value, into, holds, Flags::default());
636 }
637
638 // And the counters step on by every slot the object took, since the whole of it came out of
639 // the area and the argument behind it starts past all of it.
640 for float in [false, true] {
641 let file = usize::from(float);
642 let Some(counter) = walked[file] else { continue };
643 let by = build.iconst(Type::int(32), i128::from(area.stride(float) * counts[file]));
644 let stepped = build.binary(Opcode::Add, counter, by, Flags::default());
645 let at = offset(build, read.list, field_of(float));
646 build.store(stepped, at, info(4, 4), Flags::default());
647 }
648 build.unary(Opcode::PtrToInt, read.room, Type::int(64))
649}
650
651/// A buffer at the front of the entry block, which is where an alloca of a fixed size belongs.
652///
653/// Not where the walk is, because a walk inside a loop would then be an alloca inside a loop,
654/// which is a frame that grows every time round. One buffer per `va_arg` of an object, made once
655/// and written every time the object is read, which is what the front end would have written if
656/// the temporary had a name.
657fn buffer(func: &mut Func, inst: Inst, size: u64, align: u32) -> Option<Value> {
658 let entry = func.entry()?;
659 let span = func.span(inst);
660 let mem = func.add_mem(info(size, align.max(1)));
661 let data = InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) };
662 let made = func.create_inst(data, &[Type::PTR], span);
663 let first = func.insts(entry).next();
664 match first {
665 Some(first) => func.insert_before(made, first),
666 None => func.append_inst(entry, made),
667 }
668 func[made].first_result
669}
670
671/// Where the argument the caller left in memory is, with the overflow pointer stepped on past it,
672/// as an integer address.
673///
674/// The pointer is rounded up first for an object that wants more alignment than a word. The
675/// argument area is a run of words, so anything asking for eight or less is where it is already,
676/// and anything asking for more was put at the next multiple of what it asked for by whoever
677/// passed it.
678fn overflow(build: &mut Builder<'_>, list: Value, area: Area, size: u64, align: u32) -> Value {
679 let word = u64::from(area.word);
680 let wide = Type::int(64);
681 let pointer = offset(build, list, OVERFLOW);
682 let here = build.load(Type::PTR, pointer, info(word, area.word), Flags::default());
683
684 // As an integer, because rounding up is an add and a mask and neither is a thing to do to a
685 // pointer. Both casts are free: the two are the same bits on this machine and nothing is
686 // written for either.
687 let mut at = build.unary(Opcode::PtrToInt, here, wide);
688 if u64::from(align) > word {
689 // Up to the next multiple of a power of two, which is the round up every alignment is.
690 // The mask is the negative of the alignment because that is what the complement of one
691 // less than it comes to, and writing it that way keeps it inside a signed sixty four bit
692 // constant.
693 let bump = build.iconst(wide, i128::from(align) - 1);
694 at = build.binary(Opcode::Add, at, bump, Flags::default());
695 let mask = build.iconst(wide, -i128::from(align));
696 at = build.binary(Opcode::And, at, mask, Flags::default());
697 }
698
699 // Past it, rounded up to a whole number of words, because the argument area holds words and
700 // the argument behind this one starts at one of them.
701 let by = build.iconst(wide, i128::from(size.next_multiple_of(word)));
702 let onward = build.binary(Opcode::Add, at, by, Flags::default());
703 let onward = build.unary(Opcode::IntToPtr, onward, Type::PTR);
704 build.store(onward, pointer, info(word, area.word), Flags::default());
705 at
706}
707
708/// Which of the two counters a file's slots are walked with.
709fn field_of(float: bool) -> i64 {
710 if float { FP_OFFSET } else { GP_OFFSET }
711}
712
713/// Whether a slot is one of the vector file's.
714fn is_float(slot: Slot) -> bool {
715 matches!(slot, Slot::Float { .. })
716}
717
718/// How many registers of a file an object takes.
719fn taken_of(slots: &[Slot], float: bool) -> u32 {
720 u32::try_from(slots.iter().filter(|&&slot| is_float(slot) == float).count()).unwrap_or(0)
721}
722
723/// What one slot's bytes are moved as.
724///
725/// An integer of the slot's width whatever file it came from, because what this is is a copy of the
726/// object's bytes and nothing here reads them as anything. A slot the whole width of a vector
727/// register is the exception and has to be: there is no integer that wide on this machine, and the
728/// file the bytes are already in is the one that moves all sixteen of them at once.
729fn moved_as(area: Area, float: bool, bytes: u64) -> Type {
730 if float && bytes > u64::from(area.word) {
731 return Type::float(Float::F128);
732 }
733 Type::int(u32::try_from(bytes).unwrap_or(1) * 8)
734}
735
736/// What the address of a slot in the save area is known to be aligned to.
737///
738/// The area begins on a vector slot boundary and every slot in it is a whole number of its file's
739/// strides along from there, so a value as wide as its file's stride sits at a multiple of the
740/// stride and everything narrower sits at a multiple of a word. The wide case is the one that has
741/// to be right, since what moves a whole vector register is a `movaps` and a `movaps` faults on an
742/// address that is not a multiple of sixteen rather than being slow about it.
743fn slot_align(area: Area, float: bool, bytes: u64) -> u32 {
744 if bytes > u64::from(area.word) { area.stride(float) } else { area.word }
745}
746
747/// How many bytes one slot moves, which is its own width rounded up to one the machine has a load
748/// for.
749fn width(slot: Slot) -> u64 {
750 match slot {
751 Slot::Integer { size, .. } => u64::from(size.next_power_of_two().clamp(1, 8)),
752 Slot::Float { format, .. } => u64::from(format.width()).div_ceil(8),
753 }
754}
755
756/// What a part of an object at that offset is aligned to, which is what the object is aligned to
757/// for the part at the front of it and how far into the object the part sits for every other.
758fn part(align: u32, offset: u64) -> u32 {
759 let align = align.max(1);
760 if offset == 0 {
761 return align;
762 }
763 u32::try_from(1_u64 << offset.trailing_zeros()).unwrap_or(align).min(align)
764}
765
766/// Whether an argument of that size travelled as the address of a copy rather than as itself.
767///
768/// The platform's rule stated as a size and nothing else: an argument that is not one, two, four or
769/// eight bytes is passed as a pointer to a copy the caller made, whatever the argument is made of.
770/// A three byte structure is one and so is a sixteen byte float, and no classification is asked
771/// about either, which is why the slots the front end put on a `va_object` go unread on this side.
772fn by_reference(size: u64) -> bool {
773 !matches!(size, 1 | 2 | 4 | 8)
774}
775
776/// The slot the walk is at, with the list stepped on past it, written in front of an instruction.
777///
778/// One word whatever is in the slot, because this convention gives every argument exactly one and
779/// pays for the ones that do not fit by passing their address instead. So there is nothing to round
780/// up, nothing to ask and nothing to branch on.
781fn slot(func: &mut Func, inst: Inst, list: Value, word: u64) -> Value {
782 let here = read(func, inst, list, Type::PTR, word);
783 let step = field(func, inst, here, i64::try_from(word).unwrap_or(0));
784 let mem = func.add_mem(info(word, u32::try_from(word).unwrap_or(1)));
785 let args = func.push_values(&[step, list]);
786 let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) };
787 let span = func.span(inst);
788 let made = func.create_inst(data, &[], span);
789 func.insert_before(made, inst);
790 here
791}
792
793/// A load written in front of an instruction, at the alignment its own width gives it.
794fn read(func: &mut Func, inst: Inst, from: Value, ty: Type, size: u64) -> Value {
795 let mem = func.add_mem(info(size, u32::try_from(size).unwrap_or(1)));
796 let args = func.push_values(&[from]);
797 let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) };
798 ahead(func, inst, data, ty)
799}
800
801/// How many bytes of a scalar the one field walk moves, or nothing for a type it is not right
802/// about.
803///
804/// A pointer has no width of its own here and is as wide as the convention's word, which is the one
805/// question this has to ask the target rather than the type.
806///
807/// A `long double`, a `_Float128` and an `__int128` are answered for as well, and what the slot
808/// holds for one of those is the address of the copy the caller made rather than the value. That is
809/// [`by_reference`] of the width, the same question the object walk below asks, and the load at the
810/// end of it is the same load either way.
811fn travels(ty: Type, word: u64) -> Option<u64> {
812 if !ty.is_scalar() || !(ty.is_int() || ty.is_float() || ty.is_ptr()) {
813 return None;
814 }
815 if ty.is_ptr() {
816 return Some(word);
817 }
818 Some(u64::from(ty.bits().div_ceil(8)))
819}
820
821/// One `va_arg` on a convention whose list is a plain pointer, as the load at the slot the walk is
822/// at.
823///
824/// The instruction becomes that load rather than being replaced by one, for the reason the
825/// branching walk gives: the value the rest of the function reads stays the value it already read,
826/// so nothing has to be substituted anywhere. Everything the load needs is written in front of it,
827/// and since nothing here branches the instruction does not move and the block is not cut.
828///
829/// A scalar of a width the convention passes whole is in the slot, and the load is the whole of it.
830/// One of the three the convention passes as an address is not, and the slot holds where the caller
831/// put its copy, so the value is one load further on. That is the same question the object walk
832/// below asks and it is asked of the width alone, which is what keeps the two answers together.
833fn value(func: &mut Func, inst: Inst, word: u64) {
834 let Some(result) = func[inst].first_result else { return };
835 let Some(&list) = func[func[inst].args].first() else { return };
836 let ty = func[result].ty;
837 let Some(bytes) = travels(ty, word) else { return };
838
839 let here = slot(func, inst, list, word);
840 let from = if by_reference(bytes) { read(func, inst, here, Type::PTR, word) } else { here };
841 // The next power of two up from the width, which is the width itself for everything the slot
842 // holds and is sixteen for the ten bytes of an x87 value, since the copy the caller made is an
843 // object of the type and the type is sixteen bytes here.
844 let align = u32::try_from(bytes.next_power_of_two()).unwrap_or(1);
845 let mem = func.add_mem(info(bytes, align));
846 let args = func.push_values(&[from]);
847 let data = &mut func[inst];
848 data.opcode = Opcode::Load;
849 data.args = args;
850 data.extra = Extra::Mem(mem);
851 data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
852}
853
854/// One `va_object` on the same convention, as the address the object can be read from.
855///
856/// The slot itself for an object of a width the convention passes whole, and what the slot holds
857/// for every other one, which is the address of the copy the caller made. That is the same question
858/// [`by_reference`] answers for a scalar and it is asked of the size alone, so an object of three
859/// bytes and an object of a hundred take the two different paths for the one reason.
860///
861/// The address is answered rather than a copy of the object, which is what the instruction is for:
862/// the object is already somewhere addressable either way, and the copy the C standard describes is
863/// the assignment the caller of `va_arg` wrote.
864fn held(func: &mut Func, inst: Inst, word: u64) {
865 let Extra::VaObject(at) = func[inst].extra else { return };
866 let MemInfo { size, .. } = func[func[at].mem];
867 let Some(&list) = func[func[inst].args].first() else { return };
868 if func[inst].first_result.is_none() {
869 return;
870 }
871
872 let here = slot(func, inst, list, word);
873 let from = if by_reference(size) { read(func, inst, here, Type::PTR, word) } else { here };
874 // Through an integer and back, which is what the branching walk's answer is too and is free
875 // either way: the two are the same bits on this machine and nothing is written for the pair.
876 let args = func.push_values(&[from]);
877 let data = InstData { args, ..InstData::new(Opcode::PtrToInt) };
878 let address = ahead(func, inst, data, Type::int(64));
879 let args = func.push_values(&[address]);
880 let data = &mut func[inst];
881 data.opcode = Opcode::IntToPtr;
882 data.args = args;
883 data.extra = Extra::None;
884 data.flags = data.flags.intersection(Flags::legal_on(Opcode::IntToPtr));
885}
886
887/// One `va_copy`, as the fields of one list moved into another.
888///
889/// A list is those fields and holds nothing anywhere else, so copying it is copying them, and a
890/// handful of words move as a handful of words rather than as a call to `memcpy`, which is a name
891/// this compiler cannot emit yet and would be the wrong answer for three words in any case. How
892/// many words there are is the convention's answer: three for the four field list, since the two
893/// offsets share one, and one for the list that is a pointer.
894///
895/// Every read is built before any write, so that a list copied onto itself, which is legal and
896/// useless, moves what it held rather than what it has just been given.
897fn copy(func: &mut Func, inst: Inst, bytes: u64) {
898 let [into, from] = func[func[inst].args] else { return };
899 let mut moved = Vec::new();
900 for word in 0..bytes / 8 {
901 let step = i64::try_from(word * 8).unwrap_or(0);
902 let there = field(func, inst, from, step);
903 let mem = func.add_mem(info(8, 8));
904 let args = func.push_values(&[there]);
905 let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) };
906 moved.push((ahead(func, inst, data, Type::int(64)), step));
907 }
908 for (read, step) in moved {
909 let here = field(func, inst, into, step);
910 let mem = func.add_mem(info(8, 8));
911 let args = func.push_values(&[read, here]);
912 let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) };
913 let span = func.span(inst);
914 let made = func.create_inst(data, &[], span);
915 func.insert_before(made, inst);
916 }
917 func.remove_inst(inst);
918}
919
920/// The address that far past a pointer, written in front of an instruction, or the pointer itself
921/// for no distance at all.
922///
923/// A field of a list for the walk that has four of them, and the slot behind this one for the walk
924/// whose list is a pointer.
925fn field(func: &mut Func, inst: Inst, list: Value, at: i64) -> Value {
926 if at == 0 {
927 return list;
928 }
929 let extra = Extra::Imm(func.add_imm(Imm::int(i128::from(at), Type::int(64))));
930 let step =
931 ahead(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, Type::int(64));
932 let args = func.push_values(&[list, step]);
933 ahead(func, inst, InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
934}
935
936/// Puts an instruction in front of another one and gives back the value it produces.
937fn ahead(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
938 let span = func.span(inst);
939 let made = func.create_inst(data, &[ty], span);
940 func.insert_before(made, inst);
941 func[made].first_result.expect("an instruction created with one result has one")
942}
943
944/// The address of a field of a list in a block being filled, or the list itself for the field at
945/// the front of it.
946fn offset(build: &mut Builder<'_>, list: Value, at: i64) -> Value {
947 if at == 0 {
948 return list;
949 }
950 let step = build.iconst(Type::int(64), i128::from(at));
951 added(build, list, step)
952}
953
954/// A pointer with an integer added to it.
955fn added(build: &mut Builder<'_>, pointer: Value, by: Value) -> Value {
956 let args = build.func().push_values(&[pointer, by]);
957 build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
958}
959
960/// An ordinary read or write of that many bytes, aligned that far.
961///
962/// Every access this pass makes is to a field of a list or to an argument, and none of them is
963/// atomic or has anything to say about aliasing.
964fn info(size: u64, align: u32) -> MemInfo {
965 MemInfo {
966 size,
967 align,
968 order: MemOrder::NotAtomic,
969 tbaa: None,
970 owns: 0,
971 restrict: Restrict::NONE,
972 }
973}
974
975#[cfg(test)]
976mod tests {
977 use rucc_base::Interner;
978 use rucc_base::float::Format;
979 use rucc_ir::{Builder, Extra, Func, InstData, Module, Opcode, Signature, Type, VaInfo};
980 use rucc_target::x86_64::{SYSV, WIN64};
981 use rucc_target::{Arch, Env, Os, Slot, TargetInfo, Triple};
982
983 use super::{Area, FP_OFFSET, GP_OFFSET, OVERFLOW, SAVE_AREA, SIZE, VECTOR_SLOT, lists};
984
985 fn target() -> TargetInfo {
986 TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
987 }
988
989 /// `T f(va_list *ap) { return va_arg(*ap, T); }`, or the same shape over whichever of the
990 /// family is asked for, with the list arriving as the pointer it has decayed to by the time
991 /// anything reads it.
992 fn built(opcode: Opcode, ty: Type, lists: usize) -> (Interner, Func) {
993 let mut names = Interner::new();
994 let params = vec![Type::PTR; lists];
995 let mut signature = Signature::new().with_params(¶ms);
996 if !ty.is_void() {
997 signature = signature.with_returns(&[ty]);
998 }
999 let mut func = Func::new(names.intern("f"), signature);
1000 let entry = func.create_block();
1001 let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
1002
1003 let mut build = Builder::new(&mut func, entry);
1004 let list = build.func().push_values(&args);
1005 if ty.is_void() {
1006 build.inst(InstData { args: list, ..InstData::new(opcode) }, &[]);
1007 build.ret(&[]);
1008 } else {
1009 let got = build.value(InstData { args: list, ..InstData::new(opcode) }, ty);
1010 build.ret(&[got]);
1011 }
1012 (names, func)
1013 }
1014
1015 fn printed(func: &Func, names: &mut Interner) -> String {
1016 let module = Module::new(names.intern("va.c"), &target());
1017 rucc_ir::print_func(&module, func, names)
1018 }
1019
1020 fn valid(func: &Func, names: &mut Interner) {
1021 let module = Module::new(names.intern("va.c"), &target());
1022 rucc_ir::verify_func(&module, func, names).expect("the rewrite builds valid IR");
1023 }
1024
1025 /// The numbers in this test are the psABI's own, written out rather than computed, because the
1026 /// whole point of the layout is that it is the document's and not a convenient one. A version
1027 /// of [`Area`] that worked them out differently would agree with itself and disagree with the C
1028 /// library, and this is what would notice.
1029 #[test]
1030 fn the_save_area_is_the_one_the_document_describes() {
1031 let area = Area::of(&SYSV);
1032 assert_eq!(area.floats_at, 48, "six general purpose registers of eight bytes");
1033 assert_eq!(area.size, 176, "and eight vector ones of sixteen");
1034 assert_eq!(area.stride(false), 8);
1035 assert_eq!(area.stride(true), VECTOR_SLOT);
1036 assert_eq!(area.starts_at(false), 0);
1037 assert_eq!(area.starts_at(true), 48);
1038 // The last slot's own offset and not the end of the area, which is what `va_arg` compares
1039 // against: an offset equal to the end is one slot past the last argument.
1040 assert_eq!(area.last(false), Some(40));
1041 assert_eq!(area.last(true), Some(160));
1042 }
1043
1044 /// And the four fields, for the same reason.
1045 #[test]
1046 fn a_list_is_the_four_fields_the_document_describes() {
1047 assert_eq!((GP_OFFSET, FP_OFFSET, OVERFLOW, SAVE_AREA), (0, 4, 8, 16));
1048 assert_eq!(SIZE, 24);
1049 }
1050
1051 #[test]
1052 fn a_va_arg_becomes_the_branch_on_whether_the_argument_is_still_in_the_save_area() {
1053 let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1054 let before = func.blocks().count();
1055 lists(&mut func, &SYSV);
1056 assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
1057
1058 let text = printed(&func, &mut names);
1059 assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1060 assert!(text.contains("icmp ule"), "the threshold is a comparison: {text}");
1061 assert!(text.contains("br_if"), "and it is branched on: {text}");
1062 valid(&func, &mut names);
1063 }
1064
1065 /// Which field it walks is the whole of the difference between the two files, and getting it
1066 /// backwards is a program that reads its integers out of the vector half.
1067 #[test]
1068 fn which_half_of_the_area_is_walked_is_the_type_s_answer() {
1069 for (ty, last, stride) in
1070 [(Type::int(64), 40, 8), (Type::float(rucc_ir::Float::F64), 160, 16)]
1071 {
1072 let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1073 lists(&mut func, &SYSV);
1074 let text = printed(&func, &mut names);
1075 assert!(text.contains(&format!("iconst.i32 {last}")), "{ty:?} stops at {last}: {text}");
1076 assert!(text.contains(&format!("iconst.i32 {stride}")), "and steps by it: {text}");
1077 }
1078 }
1079
1080 /// The value the rest of the function reads has to stay the value it already read, since the
1081 /// rewrite substitutes nothing anywhere. It stays it by the `va_arg` becoming the load rather
1082 /// than being replaced by one, so the instruction is the same instruction under a new opcode
1083 /// and in a new block.
1084 #[test]
1085 fn what_reads_the_argument_reads_the_same_value_it_did_before() {
1086 let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1087 let entry = func.entry().expect("an entry block");
1088 let inst = func.insts(entry).next().expect("the va_arg is first");
1089 let read = func[inst].first_result.expect("it produces the argument");
1090
1091 lists(&mut func, &SYSV);
1092 assert_eq!(func[inst].opcode, Opcode::Load, "the same instruction, lowered");
1093 assert_eq!(func[inst].first_result, Some(read), "producing the same value");
1094 assert_ne!(func.block_of(inst), Some(entry), "in the block the two paths meet at");
1095 valid(&func, &mut names);
1096 }
1097
1098 #[test]
1099 fn a_va_end_is_nothing_at_all() {
1100 let (mut names, mut func) = built(Opcode::VaEnd, Type::VOID, 1);
1101 lists(&mut func, &SYSV);
1102 let text = printed(&func, &mut names);
1103 assert!(!text.contains("va_end"), "{text}");
1104 assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
1105 valid(&func, &mut names);
1106 }
1107
1108 /// Three words and no branch, because a list is three words and holds nothing anywhere else.
1109 #[test]
1110 fn a_va_copy_is_the_list_moved_a_word_at_a_time() {
1111 let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 2);
1112 lists(&mut func, &SYSV);
1113 let text = printed(&func, &mut names);
1114 assert!(!text.contains("va_copy"), "{text}");
1115 assert_eq!(text.matches("load.i64").count(), 3, "{text}");
1116 assert_eq!(text.matches("store").count(), 3, "{text}");
1117 assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
1118 valid(&func, &mut names);
1119 }
1120
1121 /// Every read before every write, so that `va_copy(ap, ap)` moves what the list held rather
1122 /// than what it has just been given. Useless and legal, which is exactly the combination that
1123 /// gets written once and never tested anywhere else.
1124 #[test]
1125 fn a_list_copied_onto_itself_moves_what_it_held() {
1126 let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 1);
1127 // One parameter, so both operands of the copy are the same list. The builder above pushes
1128 // as many operands as there are parameters, so the second is added here.
1129 let entry = func.entry().expect("an entry block");
1130 let inst = func.insts(entry).next().expect("the copy is first");
1131 let list = func[func[inst].args][0];
1132 let args = func.push_values(&[list, list]);
1133 func[inst].args = args;
1134
1135 lists(&mut func, &SYSV);
1136 let text = printed(&func, &mut names);
1137 let first = text.find("store").expect("a write");
1138 let last = text.rfind("load.i64").expect("a read");
1139 assert!(last < first, "every read is above every write: {text}");
1140 valid(&func, &mut names);
1141 }
1142
1143 /// `struct s f(va_list *ap) { return va_arg(*ap, struct s); }`, where the structure is that
1144 /// many bytes wanting that much alignment and arrived in those registers. The object form of
1145 /// the instruction rather than the value one, because an aggregate is not a value and answers
1146 /// where it is instead.
1147 ///
1148 /// No slots is the object the classification sent to the caller's argument area, which is what
1149 /// everything over two eightbytes is.
1150 fn object(size: u64, align: u32, slots: &[Slot]) -> (Interner, Func) {
1151 let mut names = Interner::new();
1152 let signature = Signature::new().with_params(&[Type::PTR]).with_returns(&[Type::PTR]);
1153 let mut func = Func::new(names.intern("f"), signature);
1154 let entry = func.create_block();
1155 let list = func.append_param(entry, Type::PTR);
1156 let mem = func.add_mem(super::info(size, align));
1157 let slots = func.push_slots(slots);
1158 let at = func.add_va_object(VaInfo { mem, slots });
1159 let mut build = Builder::new(&mut func, entry);
1160 let args = build.func().push_values(&[list]);
1161 let data = InstData { args, extra: Extra::VaObject(at), ..InstData::new(Opcode::VaObject) };
1162 let got = build.value(data, Type::PTR);
1163 build.ret(&[got]);
1164 (names, func)
1165 }
1166
1167 /// One eightbyte of an object in the general purpose file, at that offset.
1168 fn gpr(offset: u64, size: u32) -> Slot {
1169 Slot::Integer { offset, size }
1170 }
1171
1172 /// One in the vector file, holding a `double`, which is what a whole eightbyte of floating
1173 /// point data is read as whichever way the members divide it up.
1174 fn sse(offset: u64) -> Slot {
1175 Slot::Float { offset, format: Format::Double }
1176 }
1177
1178 /// Over two eightbytes is class MEMORY whatever the members are, so there is one place it can
1179 /// be and no question to ask about which.
1180 #[test]
1181 fn an_object_too_big_for_the_registers_is_read_out_of_the_caller_s_memory() {
1182 let (mut names, mut func) = object(24, 8, &[]);
1183 lists(&mut func, &SYSV);
1184 let text = printed(&func, &mut names);
1185 assert!(!text.contains("va_object"), "{text}");
1186 assert_eq!(func.blocks().count(), 1, "no branch, so no new block: {text}");
1187 assert!(text.contains("iconst.i64 8"), "the overflow field is at eight: {text}");
1188 assert!(text.contains("iconst.i64 24"), "and the pointer steps past the object: {text}");
1189 assert!(!text.contains("gp_offset"), "{text}");
1190 valid(&func, &mut names);
1191 }
1192
1193 /// The size the pointer steps on by is the size rounded up to a word, because the argument
1194 /// area holds words and the argument behind this one starts at one of them.
1195 #[test]
1196 fn a_size_that_is_not_a_whole_number_of_words_steps_on_by_the_next_one() {
1197 let (mut names, mut func) = object(28, 4, &[]);
1198 lists(&mut func, &SYSV);
1199 let text = printed(&func, &mut names);
1200 assert!(text.contains("iconst.i64 32"), "twenty eight bytes step on by thirty two: {text}");
1201 valid(&func, &mut names);
1202 }
1203
1204 /// An object wanting more than a word is at the next multiple of what it wants, and one
1205 /// wanting a word or less is where the pointer already is, since the area is a run of words.
1206 #[test]
1207 fn an_object_wanting_more_alignment_than_a_word_is_rounded_up_to_it() {
1208 let (mut names, mut func) = object(32, 16, &[]);
1209 lists(&mut func, &SYSV);
1210 let text = printed(&func, &mut names);
1211 assert!(text.contains("iconst.i64 15"), "up to the next sixteen: {text}");
1212 assert!(text.contains("iconst.i64 -16"), "and down to a multiple of it: {text}");
1213 assert!(text.contains(" = and "), "which is an add and a mask: {text}");
1214 valid(&func, &mut names);
1215
1216 let (mut names, mut func) = object(24, 8, &[]);
1217 lists(&mut func, &SYSV);
1218 assert!(!printed(&func, &mut names).contains(" = and "), "a word wants no rounding");
1219 }
1220
1221 /// An object that arrived in registers is in the save area, and reading it is the branch a
1222 /// scalar asks with the object's own threshold: two eightbytes want two slots, so an offset
1223 /// that leaves room for one is not room enough.
1224 #[test]
1225 fn an_object_that_arrived_in_registers_is_copied_out_of_the_save_area() {
1226 let (mut names, mut func) = object(16, 8, &[gpr(0, 8), gpr(8, 8)]);
1227 let before = func.blocks().count();
1228 lists(&mut func, &SYSV);
1229 assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
1230
1231 let text = printed(&func, &mut names);
1232 assert!(!text.contains("va_object"), "{text}");
1233 assert!(text.contains("iconst.i32 32"), "forty eight less two slots: {text}");
1234 assert!(text.contains("icmp ule"), "which is the threshold: {text}");
1235 assert!(text.contains("alloca, size 16"), "the object lands in a buffer: {text}");
1236 assert!(text.contains("iconst.i32 16"), "and the counter steps by both slots: {text}");
1237 valid(&func, &mut names);
1238 }
1239
1240 /// An object of one eightbyte of each file has to have room in both halves of the area, and
1241 /// the psABI puts the whole of it in the caller's memory when either of them is out. So there
1242 /// are two questions, and the second is only asked when the first said yes.
1243 #[test]
1244 fn an_object_in_both_files_asks_about_both_of_them() {
1245 let (mut names, mut func) = object(16, 8, &[gpr(0, 8), sse(8)]);
1246 lists(&mut func, &SYSV);
1247 let text = printed(&func, &mut names);
1248 assert_eq!(text.matches("br_if").count(), 2, "one question per file: {text}");
1249 assert!(text.contains("iconst.i32 40"), "forty eight less one slot: {text}");
1250 assert!(text.contains("iconst.i32 160"), "and a hundred and seventy six less one: {text}");
1251 assert!(text.contains("iconst.i32 8"), "each counter steps by its own slot: {text}");
1252 valid(&func, &mut names);
1253 }
1254
1255 /// An object whose last eightbyte is a part of one still comes out of the area as a whole
1256 /// register, so the buffer has room for the whole register and the bytes past the object are
1257 /// never read.
1258 #[test]
1259 fn the_buffer_is_as_big_as_the_registers_reach() {
1260 let (mut names, mut func) = object(5, 1, &[gpr(0, 5)]);
1261 lists(&mut func, &SYSV);
1262 let text = printed(&func, &mut names);
1263 assert!(text.contains("alloca, size 8"), "five bytes travel in a whole register: {text}");
1264 valid(&func, &mut names);
1265 }
1266
1267 /// A classification this cannot read out of the area is left alone, which is what makes the
1268 /// function refused by name further down rather than compiled into half a walk.
1269 ///
1270 /// Class X87 is the one to ask about, because the width alone would say yes: ten bytes sit
1271 /// inside a vector slot with room to spare, and there is no x87 register among the fourteen a
1272 /// variadic callee spills, so there is nothing in the area for this to read.
1273 #[test]
1274 fn a_classification_that_does_not_fit_the_area_is_left_alone() {
1275 let x87 = [Slot::Float { offset: 0, format: Format::X87Extended }];
1276 let (mut names, mut func) = object(16, 16, &x87);
1277 let before = printed(&func, &mut names);
1278 lists(&mut func, &SYSV);
1279 assert_eq!(printed(&func, &mut names), before);
1280 }
1281
1282 /// A `_Float128` walks the vector half with a slot of the whole register.
1283 ///
1284 /// One register and not two, which is the same answer the classification gives a quad passed to
1285 /// a function that names it: the offset stops at the last slot rather than the last but one,
1286 /// and it steps on by sixteen. What is read is sixteen bytes of float, which is a `movaps`
1287 /// further down and is the instruction gcc reads the same slot with.
1288 #[test]
1289 fn a_quad_takes_a_whole_vector_slot_of_the_save_area() {
1290 let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F128), 1);
1291 lists(&mut func, &SYSV);
1292 valid(&func, &mut names);
1293 let text = printed(&func, &mut names);
1294 assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1295 assert!(text.contains("iconst.i32 160"), "a hundred and seventy six less one slot: {text}");
1296 assert!(text.contains("iconst.i32 16"), "and the counter steps by a whole one: {text}");
1297 assert!(text.contains("load.f128"), "read as the sixteen bytes it is: {text}");
1298 }
1299
1300 /// And the argument area gives it two words aligned to two, which is where it stops being a
1301 /// wider `double`. Every other value the machine computes in is where the pointer already is
1302 /// and steps it on by a word.
1303 #[test]
1304 fn a_quad_the_registers_ran_out_before_is_rounded_up_to_sixteen() {
1305 let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F128), 1);
1306 lists(&mut func, &SYSV);
1307 let text = printed(&func, &mut names);
1308 assert!(text.contains("iconst.i64 15"), "up to the next sixteen: {text}");
1309 assert!(text.contains("iconst.i64 -16"), "and down to a multiple of it: {text}");
1310 assert!(text.contains(" = and "), "which is an add and a mask: {text}");
1311
1312 let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F64), 1);
1313 lists(&mut func, &SYSV);
1314 let text = printed(&func, &mut names);
1315 assert!(!text.contains(" = and "), "a double is where the pointer already is: {text}");
1316 assert!(text.contains("iconst.i64 8"), "and steps it on by a word: {text}");
1317 }
1318
1319 /// An object holding a quad is one slot of the vector file, so the question is a single one
1320 /// and the copy moves all sixteen bytes at once.
1321 ///
1322 /// The buffer it lands in is sixteen byte aligned, which is what the store needs rather than
1323 /// what the object asked for, although for this object the two are the same number.
1324 #[test]
1325 fn an_object_holding_a_quad_is_copied_out_as_one_whole_register() {
1326 let quad = [Slot::Float { offset: 0, format: Format::Quad }];
1327 let (mut names, mut func) = object(16, 16, &quad);
1328 lists(&mut func, &SYSV);
1329 valid(&func, &mut names);
1330 let text = printed(&func, &mut names);
1331 assert!(!text.contains("va_object"), "{text}");
1332 assert_eq!(text.matches("br_if").count(), 1, "one file, so one question: {text}");
1333 assert!(text.contains("iconst.i32 160"), "a hundred and seventy six less one slot: {text}");
1334 assert!(text.contains("load.f128"), "moved as the register it is in: {text}");
1335 assert!(text.contains("alloca, size 16, align 16"), "a buffer a movaps accepts: {text}");
1336 }
1337
1338 /// What reads the object goes on reading the value it already read, the same way it does for a
1339 /// value, and for the same reason: the instruction becomes the address rather than being
1340 /// replaced by one, so nothing has to be substituted anywhere.
1341 #[test]
1342 fn what_reads_the_object_reads_the_same_value_it_did_before() {
1343 for slots in [&[][..], &[gpr(0, 8), gpr(8, 8)][..]] {
1344 let (mut names, mut func) = object(if slots.is_empty() { 24 } else { 16 }, 8, slots);
1345 let entry = func.entry().expect("an entry block");
1346 let inst = func.insts(entry).next().expect("the va_object is first");
1347 let read = func[inst].first_result.expect("it answers an address");
1348
1349 lists(&mut func, &SYSV);
1350 assert_eq!(func[inst].opcode, Opcode::IntToPtr, "the same instruction, lowered");
1351 assert_eq!(func[inst].first_result, Some(read), "producing the same value");
1352 valid(&func, &mut names);
1353 }
1354 }
1355
1356 /// Windows describes a list as one pointer, and its walk is that pointer stepped on, so there is
1357 /// nothing to compare and nowhere else to look: the argument is at the pointer, the pointer
1358 /// moves on by a word, and all of it is straight line.
1359 #[test]
1360 fn a_windows_va_arg_is_the_word_at_the_pointer_and_a_step() {
1361 let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1362 lists(&mut func, &WIN64);
1363 valid(&func, &mut names);
1364 let text = printed(&func, &mut names);
1365 assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1366 assert!(!text.contains("br_if"), "and nothing was asked: {text}");
1367 assert_eq!(func.blocks().count(), 1, "so no block was made: {text}");
1368 assert!(text.contains("iconst.i64 8"), "the step is one word: {text}");
1369 assert_eq!(text.matches("= load").count(), 2, "the list and the argument: {text}");
1370 assert_eq!(text.matches("store").count(), 1, "and the list is written back: {text}");
1371 }
1372
1373 /// A pointer is as wide as the convention says a word is, since a type carries no width for
1374 /// one. Reading it as no bytes at all would be every string a `printf` was handed.
1375 #[test]
1376 fn a_windows_pointer_argument_is_the_whole_word() {
1377 let (mut names, mut func) = built(Opcode::VaArg, Type::PTR, 1);
1378 lists(&mut func, &WIN64);
1379 valid(&func, &mut names);
1380 let text = printed(&func, &mut names);
1381 assert_eq!(text.matches("= load").count(), 2, "the list and the argument: {text}");
1382 assert_eq!(text.matches("size 8").count(), 3, "and all three are words: {text}");
1383 }
1384
1385 /// The size is the whole of what says where a Windows argument is, so an object of eight bytes
1386 /// is in the slot and the answer is the slot's own address, and one of twenty four is elsewhere
1387 /// and the answer is what the slot holds. Neither of them asks about the classification.
1388 #[test]
1389 fn a_windows_object_is_in_the_slot_or_behind_it_according_to_its_size() {
1390 for (size, loads) in [(8, 1), (24, 2)] {
1391 let (mut names, mut func) = object(size, 8, &[]);
1392 lists(&mut func, &WIN64);
1393 valid(&func, &mut names);
1394 let text = printed(&func, &mut names);
1395 assert!(!text.contains("va_object"), "{text}");
1396 assert_eq!(func.blocks().count(), 1, "no branch, so no new block: {text}");
1397 assert_eq!(text.matches("= load").count(), loads, "{size} bytes: {text}");
1398 assert!(!text.contains("iconst.i64 24"), "the step is a word either way: {text}");
1399 }
1400 }
1401
1402 /// A list that is one pointer is copied by moving one pointer, and a copy moving three words
1403 /// would read two the caller never wrote and write them somewhere it does not own.
1404 #[test]
1405 fn a_windows_va_copy_moves_the_one_word_a_list_is() {
1406 let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 2);
1407 lists(&mut func, &WIN64);
1408 valid(&func, &mut names);
1409 let text = printed(&func, &mut names);
1410 assert!(!text.contains("va_copy"), "{text}");
1411 assert_eq!(text.matches("load.i64").count(), 1, "{text}");
1412 assert_eq!(text.matches("store").count(), 1, "{text}");
1413 }
1414
1415 /// A scalar wider than a general purpose register is read through the slot rather than out of
1416 /// it, because the convention travels one as the address of a copy the caller made.
1417 ///
1418 /// Two loads and not one: the slot holds the address and the value is behind it. Reading the
1419 /// slot as the value would be reading the low eight bytes of a `long double`, which is the
1420 /// bottom of its significand and no number anybody wrote.
1421 #[test]
1422 fn a_wide_scalar_is_read_through_the_slot_on_windows() {
1423 let wide =
1424 [Type::int(128), Type::float(rucc_ir::Float::F80), Type::float(rucc_ir::Float::F128)];
1425 for ty in wide {
1426 let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1427 lists(&mut func, &WIN64);
1428 valid(&func, &mut names);
1429 let text = printed(&func, &mut names);
1430 assert!(!text.contains("va_arg"), "{ty:?}: {text}");
1431 assert_eq!(text.matches("= load").count(), 3, "{ty:?}: {text}");
1432 // Two of the three are addresses, the list's own and the copy's, and the value is
1433 // the third. A dump writes a pointer load without a type on it.
1434 assert_eq!(text.matches("= load %").count(), 2, "{ty:?}: {text}");
1435 }
1436 }
1437
1438 /// A width the algorithm is not right about is left alone for the same reason. An `__int128`
1439 /// takes two slots under an alignment rule of its own, which is a second algorithm and not a
1440 /// wider reading of this one, so it stays exactly as it was and is refused by name later.
1441 #[test]
1442 fn a_type_that_does_not_travel_in_one_slot_is_left_alone() {
1443 let ty = Type::int(128);
1444 let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1445 let before = printed(&func, &mut names);
1446 lists(&mut func, &SYSV);
1447 assert_eq!(printed(&func, &mut names), before, "{ty:?}");
1448 }
1449
1450 /// A `long double` is class X87, and the class has no register among the fourteen a variadic
1451 /// callee spills, so one is in the caller's argument area whether or not anything came before
1452 /// it. What that means for the rewrite is that the question `va_arg` usually asks has a known
1453 /// answer, so there is no compare, no branch and no join: one block, the overflow pointer
1454 /// rounded up to sixteen and stepped on by sixteen, and the load.
1455 #[test]
1456 fn a_long_double_is_read_straight_out_of_the_callers_argument_area() {
1457 let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F80), 1);
1458 lists(&mut func, &SYSV);
1459 valid(&func, &mut names);
1460 let text = printed(&func, &mut names);
1461 assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1462 assert!(!text.contains("br_if"), "and nothing was asked: {text}");
1463 assert_eq!(func.blocks().count(), 1, "so no block was made: {text}");
1464 // The two numbers the psABI gives the class, in the rounding up and in the step.
1465 assert!(text.contains(" 15"), "rounded up to sixteen: {text}");
1466 assert!(text.contains(" 16"), "and stepped on by sixteen: {text}");
1467 }
1468
1469 /// Nothing else is touched, which matters because this runs over every function whether or not
1470 /// one reads a variable argument.
1471 #[test]
1472 fn a_function_with_no_list_in_it_is_left_exactly_as_it_was() {
1473 let mut names = Interner::new();
1474 let int = Type::int(32);
1475 let mut func =
1476 Func::new(names.intern("f"), Signature::new().with_params(&[int]).with_returns(&[int]));
1477 let entry = func.create_block();
1478 let x = func.append_param(entry, int);
1479 Builder::new(&mut func, entry).ret(&[x]);
1480
1481 let before = printed(&func, &mut names);
1482 lists(&mut func, &SYSV);
1483 assert_eq!(printed(&func, &mut names), before);
1484 }
1485}