Skip to main content

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