Skip to main content

rucc_codegen/
abi.rs

1//! Where a function's arguments already are when it starts running, and where a call puts its own.
2//!
3//! Design: `spec/12-abi-and-runtime.md`.
4//!
5//! This is the one part of the calling convention that is not a lowering rule, and it is worth
6//! saying why, because everything else in this crate is. A rule matches a term and rewrites it,
7//! and which register the third argument arrives in is not a fact about any term: it depends on
8//! the argument's position and on the classification of every argument before it. A pattern has
9//! nowhere to put that. So the arguments are built here, by hand, out of what the convention
10//! says, the same way [`crate::finish`] builds a prologue.
11//!
12//! The classification itself is not here either. `rucc-lower` has already run it by the time a
13//! function reaches this crate, which is why the parameters read here are nearly all plain
14//! scalars: an aggregate has been split into the pieces it travels in, and a return through memory
15//! is an ordinary pointer parameter in front of the rest. What is left for this is the step after
16//! classification, from how a value travels to which register it is actually in, which is
17//! [`rucc_target::Places`].
18//!
19//! The one parameter that is not a scalar is an aggregate the classification put in the argument
20//! area whole, which is [`rucc_ir::Abi::ByVal`]. The IR calls it a pointer, because a pointer is
21//! what an instruction reading it has to have, and the convention says the bytes travel and the
22//! pointer does not. So this is the one place that reads what the classification said rather than
23//! only the type, on both sides of the call, and the two sides are the two halves of one copy.
24//!
25//! # What it writes
26//!
27//! One `x64.arg_val_*` per parameter that arrived in a register, at the top of the entry block,
28//! each defining a fresh register constrained to the one the argument arrived in. They encode to
29//! nothing. The point of them is that a parameter has to be defined somewhere for the allocator to
30//! have anything to move, and the entry block cannot define it as a block parameter: there is no
31//! edge into the entry block for the move to go on, which is what `rucc_regalloc::rewrite` asserts.
32//!
33//! What the allocator does with them is the whole of the argument sequence. A parameter that is
34//! read where it arrived costs nothing, and one that is not gets a copy, which is the same
35//! bargain the return already makes and is decided by the same code.
36//!
37//! A parameter whose bytes travelled is the exception to all of that. Its bytes are already in
38//! this function, at a place in the caller's argument area the same walk gives, so nothing is
39//! brought in at all: what the parameter is is where they are, and that is one `lea`. It waits on
40//! the frame the way the loads below it do, and for the same reason.
41//!
42//! A parameter past the last register arrived in the caller's memory rather than in a register, so
43//! it is a load and not a pseudo, and it is a real instruction that encodes to real bytes. How far
44//! up the caller's argument area it is is a number [`rucc_target::Places`] answers here, but where
45//! that area is from inside this function is a distance into a frame, and no frame exists until
46//! after allocation. So the load is written with nothing in its displacement, which of the two
47//! registers it reads through is left to be settled too, and both are filled in by [`crate::finish`]
48//! out of [`crate::frame::Frame::incoming`]. That is the same bargain an `alloca` already makes,
49//! for the same reason and in the same two places.
50//!
51//! # A call
52//!
53//! The same reasoning the other way round, and one instruction rather than several. `x64.call`
54//! and `x64.call_reg` are the only opcodes in the description whose operand vector is empty
55//! there, because nothing about a call's operands is the same from one call to the next, so they
56//! are built here: one read per argument constrained to the register the convention passes it in,
57//! one definition for the value that comes back constrained to the register it comes back in, and
58//! one definition per register the convention does not preserve.
59//!
60//! A call through an address has one operand more, which is the address, and it is the one
61//! operand of a call that is a fact about the instruction rather than about the signature. It
62//! goes in front of the arguments, because the assembler has to find it and an index into a
63//! vector whose length depends on the convention is not a way of finding anything.
64//!
65//! Those last ones are the clobbers, and they are the whole of what the allocator has to know
66//! about a call besides where the values go. Each is a definition of the physical register itself
67//! rather than of a value, since there is no value: it says the register is written here, which
68//! is exactly what stops the allocator from leaving something in one across the call. A register
69//! an argument or the result already names is not repeated, because naming it once already blocks
70//! it for the length of the instruction, which is all a clobber does.
71//!
72//! An argument past the last register the convention has for it is a store into the outgoing area
73//! rather than an operand of the call, written in front of the call in the same block. Where that
74//! area is does not have to wait for the frame the way the incoming one does, because the outgoing
75//! area is at the bottom of the frame and the bottom of the frame is where the stack pointer is:
76//! that is the whole reason the frame puts it there, since it is where the callee will look. So the
77//! offset [`rucc_target::Places`] gives back is the offset the store is written with.
78//!
79//! An object passed by value in memory is the same thing again and a copy rather than a store. The
80//! caller owes the callee a copy it is free to write to, which is what makes a C call by value
81//! different from passing a pointer the callee must not keep, and the argument area is where the
82//! convention says that copy goes. So the bytes are read out of the object and written into the
83//! area a word at a time, in front of the call, with the words chosen by the same function that
84//! chooses them for a `memcpy`. An object with more words than that unrolls to is turned down,
85//! because the copy it wants is a call to the runtime and one call cannot be built inside another.
86//!
87//! The call still reports how many bytes it needed, because the frame reserves as many as the
88//! widest call in the function asked for and cannot know that until every call has been seen.
89
90use rucc_base::{Interner, Symbol};
91use rucc_ir::{Abi, Param, Type};
92use rucc_mir as mir;
93use rucc_target::x86_64;
94use rucc_target::{CallRegs, Constraint, PhysReg, Places, RegClass, Where};
95
96use crate::varargs::Area;
97
98/// Why a parameter could not be brought in.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Missing {
101    /// It travels on the x87 stack, which is a `long double` and nothing else. That stack is a
102    /// third register file, it is not one the allocator has, and no instruction in the
103    /// description touches it.
104    OnX87,
105    /// It is a float passed to a callee that takes arguments beyond the ones its signature names,
106    /// on a convention that puts such a float in a vector register and in the general purpose
107    /// register at the same position at once. Which arguments are the ones beyond the signature is
108    /// what decides whether the second copy is needed, and a call does not carry that yet.
109    InBothFiles,
110    /// It is a width no pseudo covers, which is anything a machine register does not hold.
111    Width,
112    /// It is a value that comes back in more registers than the convention returns in. A structure
113    /// of at most sixteen bytes comes back in up to two, which is as many as SysV has, and a
114    /// convention with fewer of them returns such a structure through a hidden pointer instead. So
115    /// this is what a signature the classification did not produce would get.
116    NoRoom,
117    /// It is an object whose bytes travel in the argument area and there are more of them than a
118    /// copy a word at a time is worth. Such a copy belongs in a call to the runtime, and the place
119    /// this is decided is in the middle of building a call, where another one cannot go.
120    TooBig,
121}
122
123impl Missing {
124    /// What it says when a function could not be compiled because of it.
125    ///
126    /// Worded so that it reads the same about a value arriving and a value being passed, since
127    /// the two are the same fact seen from the two ends of one call.
128    #[must_use]
129    pub fn why(self) -> &'static str {
130        match self {
131            Missing::OnX87 => "is on the x87 stack",
132            Missing::InBothFiles => "is a float passed to a variadic callee on this convention",
133            Missing::Width => "is a width no argument register holds",
134            Missing::NoRoom => "takes more registers than this convention has for it",
135            Missing::TooBig => "is more bytes than a copy into the argument area unrolls to",
136        }
137    }
138}
139
140/// Which register file a value of that type travels in.
141///
142/// The whole of what the two files mean to this module. A float is in the vector one and
143/// everything else is in the general purpose one, which is what both of this machine's conventions
144/// say, and the `long double` that is in neither is turned away by [`refuses`] before this is
145/// asked.
146fn class_of(ty: Type, conv: &CallRegs) -> RegClass {
147    if ty.is_float() { conv.sse_class } else { conv.int_class }
148}
149
150/// Why a value of that type cannot travel at all, or nothing if it can.
151///
152/// The width question and the file question in one place, so that the two ends of a call give the
153/// same answer about the same type, and so that a `return` this cannot make says the same thing
154/// about a type as the call that would have received it.
155#[must_use]
156pub fn refuses(ty: Type) -> Option<Missing> {
157    if head_of(ty).is_some() {
158        return None;
159    }
160    // A `long double` is the one type here that is in neither of the two files. Saying so is worth
161    // more than calling it a width, because eighty bits is a width this machine computes in and
162    // the file it computes in is what actually stands in the way.
163    if ty.is_float() && ty.bits() == 80 {
164        return Some(Missing::OnX87);
165    }
166    Some(Missing::Width)
167}
168
169/// What a function's parameters came to.
170#[derive(Debug, Default, Clone, PartialEq, Eq)]
171pub struct Arrived {
172    /// The register each parameter is in, in the order the parameters were given, so the caller can
173    /// bind each IR parameter to the one at its position.
174    pub regs: Vec<mir::Reg>,
175    /// The loads that read a parameter out of the caller's argument area, and how far up that area
176    /// each of them reads.
177    ///
178    /// Empty for almost every function, because almost every function has few enough parameters to
179    /// have been handed all of them in registers. The distance is from the bottom of the caller's
180    /// argument area, which is somewhere [`crate::finish`] works out and this cannot.
181    pub stack: Vec<(mir::Inst, u32)>,
182    /// How many general purpose argument registers the parameters took, and how many vector ones.
183    ///
184    /// Nothing about an ordinary function needs this. A variadic one does: the first argument its
185    /// signature does not name is the one after the last it does, so where each of the two walks
186    /// stopped is where `va_start` has to say the next argument begins.
187    pub took: (usize, usize),
188    /// How many bytes of the caller's argument area the parameters took, which is where the first
189    /// argument the signature does not name begins for the same reason.
190    pub used: u32,
191    /// The argument registers left over for the arguments the signature does not name, as the
192    /// register each was bound into and how far up the save area its slot is.
193    ///
194    /// Empty unless a save area was asked for. The ones a named parameter took are not here,
195    /// because their slots are behind where `va_start` sets the two offsets and nothing ever reads
196    /// them, so writing them would be fourteen stores where six are wanted.
197    pub spare: Vec<(mir::Reg, RegClass, u32)>,
198}
199
200/// Binds a function's parameters to where the convention says they arrive.
201///
202/// # Errors
203///
204/// The first parameter this cannot bring in, and why. A function with one is reported rather
205/// than compiled, because the alternative is a function that reads an argument from wherever the
206/// last one happened to leave a register.
207pub fn entry(
208    out: &mut mir::Func,
209    block: mir::Block,
210    params: &[Param],
211    conv: &CallRegs,
212    names: &mut Interner,
213    save: Option<Area>,
214) -> Result<Arrived, (usize, Missing)> {
215    // Where everything is, worked out before anything is written, both so that a parameter this
216    // cannot bring in stops the function before half of one is built and so that the two loops
217    // below can be two loops. Asking for the place of a parameter that cannot be brought in is
218    // still done, because every place after it depends on it and a reader stepping through this
219    // should see the same numbers a working version would.
220    let mut places = Places::new(conv);
221    let mut where_from = Vec::with_capacity(params.len());
222    for (index, &Param { ty, abi }) in params.iter().enumerate() {
223        // A structure the classification put in the argument area arrived as bytes, and the
224        // parameter the IR sees is a pointer to them. So there is nothing to bring in: the bytes
225        // are already in this function's frame, and what the pointer holds is where they are.
226        if let Abi::ByVal { size, align } = abi {
227            let size = u32::try_from(size).map_err(|_| (index, Missing::TooBig))?;
228            where_from.push((ty, places.on_stack(size, align), abi));
229            continue;
230        }
231        let at = if ty.is_float() { places.float() } else { places.integer() };
232        if let Some(missing) = refuses(ty) {
233            return Err((index, missing));
234        }
235        where_from.push((ty, at, abi));
236    }
237    let mut arrived = Arrived {
238        regs: Vec::with_capacity(params.len()),
239        took: (places.integers(), places.floats()),
240        used: places.size(),
241        ..Arrived::default()
242    };
243
244    // Every pseudo first and everything else after, which is not a preference. A pseudo says a
245    // register holds an argument and defines nothing before it, so as far as the allocator can see
246    // the register was dead until then and is free to be used as a scratch. That is true of a
247    // register no pseudo has named yet, and it stops being true the moment one does. Anything that
248    // needs a scratch has to come after all of them, and a load out of the caller's stack needs one
249    // for the value it loads.
250    for (index, &(ty, at, _)) in where_from.iter().enumerate() {
251        let class = class_of(ty, conv);
252        let reg = out.new_vreg(class);
253        arrived.regs.push(reg);
254        let Where::Reg(arrived_in) = at else { continue };
255        let head = head_of(ty).ok_or((index, Missing::Width))?;
256        let opcode = mir::Opcode::new(names.intern(head));
257        let operand = mir::Operand::write(reg, class).with(Constraint::Fixed(arrived_in));
258        out.build(block, opcode).operand(operand).finish();
259    }
260    if let Some(area) = save {
261        arrived.spare = spare(out, block, conv, names, area, arrived.took);
262    }
263
264    let lea = format!("{}{}", crate::lower::PREFIX, x86_64::FRAME.lea);
265    // The stack pointer is written down as the register to read through because it is the one that
266    // reaches the caller's stack in almost every function, and a realigned frame is the exception
267    // that [`crate::finish`] rewrites. Putting something here rather than nothing keeps the
268    // instruction printable and verifiable in between.
269    for (index, &(ty, at, abi)) in where_from.iter().enumerate() {
270        let Where::Stack(up) = at else { continue };
271        let class = class_of(ty, conv);
272        // The bytes of an object that travelled as bytes are read by whatever reads the parameter,
273        // and what the parameter is is their address, so this takes the address rather than a
274        // value out of it. Everything else about it is the load's, including the two fields
275        // [`crate::finish`] fills in, because where the caller's argument area is is the same
276        // question for both.
277        let name = match abi {
278            Abi::ByVal { .. } => lea.as_str(),
279            _ => load_of(ty).ok_or((index, Missing::Width))?,
280        };
281        let opcode = mir::Opcode::new(names.intern(name));
282        let sp = mir::Operand::read(mir::Reg::physical(conv.stack_pointer), conv.int_class);
283        let made =
284            out.build(block, opcode).def(arrived.regs[index], class).mem(mir::Mem::at(sp)).finish();
285        arrived.stack.push((made, up));
286    }
287    Ok(arrived)
288}
289
290/// Binds the argument registers no parameter the signature names took, which are the ones the
291/// arguments it does not name arrived in.
292///
293/// One pseudo each and nothing else, for the reason the loop above them gives: what these do is say
294/// the register holds something, and the stores that put it in the save area are written by
295/// [`crate::lower`] once it has an address to store to, which is after every pseudo in the block.
296fn spare(
297    out: &mut mir::Func,
298    block: mir::Block,
299    conv: &CallRegs,
300    names: &mut Interner,
301    area: Area,
302    took: (usize, usize),
303) -> Vec<(mir::Reg, RegClass, u32)> {
304    let word = Type::int(64);
305    let double = Type::float(rucc_ir::Float::F64);
306    let files = [(conv.int_args, took.0, word, false), (conv.sse_args, took.1, double, true)];
307    let mut spare = Vec::new();
308    for (regs, taken, ty, float) in files {
309        let Some(head) = head_of(ty) else { continue };
310        let class = class_of(ty, conv);
311        for (index, &arrived_in) in regs.iter().enumerate().skip(taken) {
312            let reg = out.new_vreg(class);
313            let opcode = mir::Opcode::new(names.intern(head));
314            let operand = mir::Operand::write(reg, class).with(Constraint::Fixed(arrived_in));
315            out.build(block, opcode).operand(operand).finish();
316            let at = area.starts_at(float) + area.stride(float) * u32::try_from(index).unwrap_or(0);
317            spare.push((reg, class, at));
318        }
319    }
320    spare
321}
322
323/// What the instruction that calls a name is called.
324///
325/// Here rather than in a rule for the same reason the arguments are: a rule pattern sees one term
326/// and a call's operands are whatever the signature made them, so no pattern could name them.
327pub const CALL: &str = "x64.call";
328
329/// What the instruction that calls an address in a register is called.
330///
331/// A different instruction rather than the same one with a different operand, which is what the
332/// machine says too: one carries the distance to somewhere in the program and takes a relocation,
333/// and the other carries the register the address is in and takes none. Sharing an opcode would
334/// mean an instruction whose bytes depend on whether a field beside it happens to be set.
335pub const CALL_REG: &str = "x64.call_reg";
336
337/// One value a call passes.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub struct Passing {
340    /// The type it travels as, which for an object travelling as bytes is the pointer's rather
341    /// than the object's, because the pointer is what the machine IR has.
342    pub ty: Type,
343    /// The register holding it, or holding its address when the bytes are what travel.
344    pub reg: mir::Reg,
345    /// What the classification asked of it. The one thing read here is whether the object behind
346    /// the pointer is the argument, since everything else it can say is about a value that is
347    /// already in a register in the form it travels in.
348    pub abi: Abi,
349}
350
351/// What one call came to.
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub struct Made {
354    /// The registers the value came back in, in the order the signature returns them, which is
355    /// empty for a call that gives nothing back and holds two for a structure that comes back in a
356    /// pair. Which register each of them is is the classification's answer and is worked out here
357    /// rather than in a table, for the reason the second half of [`Calling::returns`] gives.
358    pub results: Vec<mir::Reg>,
359    /// How many bytes below the stack pointer this call needs for the arguments it passes there.
360    ///
361    /// Not always zero for a call that passes everything in registers: a Windows caller reserves
362    /// thirty two bytes for the callee to spill its register arguments into whether it uses them
363    /// or not, and that reservation is this.
364    pub outgoing: u32,
365}
366
367/// Which of a call's values could not be passed, and why.
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369pub struct Refused {
370    /// Its position among the arguments, or `None` for the value that comes back.
371    pub argument: Option<usize>,
372    /// What is wrong with where it travels.
373    pub missing: Missing,
374}
375
376/// What a call goes to.
377///
378/// The whole of the difference between the two calls. Everything else about them, which is what
379/// they pass and what comes back and which registers they destroy, is the signature's answer and
380/// is the same answer either way.
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum Callee {
383    /// A name, which the linker resolves.
384    Named(Symbol),
385    /// An address in a register, which nothing resolves because there is nothing to resolve: the
386    /// value is not known until the program runs.
387    ///
388    /// The register is unconstrained, and it has to be, because every register the convention
389    /// does not preserve is one this instruction writes and every register an argument travels in
390    /// is spoken for. What is left is the registers the callee has to put back, which is where
391    /// the allocator will put the address, and it is the right answer for the same reason it is
392    /// the only one.
393    Through(mir::Reg),
394}
395
396/// One call, as everything about it that is not the function it is being built into.
397#[derive(Debug, Clone, Copy)]
398pub struct Calling<'a> {
399    /// What it calls.
400    pub callee: Callee,
401    /// What it passes, in the order the signature holds them, which is the order the convention
402    /// places them in.
403    pub args: &'a [Passing],
404    /// What comes back, which is empty for a call that gives nothing back, one type for a value,
405    /// and two for a structure small enough to come back in a pair of registers.
406    ///
407    /// A pair is placed here rather than named by a rule for the reason the arguments are: which
408    /// register each half goes in depends on the halves before it, since the two files are walked
409    /// separately, and a pattern over a term cannot see them.
410    pub returns: &'a [Type],
411    /// Whether the callee takes arguments beyond the ones its signature names, which is what says
412    /// whether it reads the count of vector registers the call passed arguments in.
413    pub variadic: bool,
414}
415
416/// Builds one call: what it passes, what comes back, and what it destroys.
417///
418/// # Errors
419///
420/// The first value this cannot pass, and why, before anything is written. A call with one is
421/// reported rather than compiled, because the alternative is a call that leaves an argument
422/// wherever the last one happened to put a register.
423///
424/// # Panics
425///
426/// If a call passes two gigabytes of arguments on the stack, which is a distance no offset in a
427/// frame can hold and a call no program makes.
428pub fn call(
429    out: &mut mir::Func,
430    block: mir::Block,
431    made: &Calling<'_>,
432    conv: &CallRegs,
433    names: &mut Interner,
434) -> Result<Made, Refused> {
435    let &Calling { callee, args, returns, variadic } = made;
436    // Where everything goes, worked out before anything is built, so that a call this cannot make
437    // leaves no half of one behind.
438    let mut places = Places::new(conv);
439    let mut passed = Vec::with_capacity(args.len());
440    // The ones with no register left for them, as the store each of them becomes and how far up
441    // the outgoing area it writes. Almost always empty.
442    let mut on_stack = Vec::new();
443    // How many of them went in vector registers, which is what a SysV variadic callee is told.
444    let mut vectors = 0u32;
445    // The ones whose bytes travel rather than their address, as the register that address is in,
446    // how far up the outgoing area they go and which words the copy is made of. Almost always
447    // empty too, and never at the same time as a register: an object in the argument area is in
448    // the argument area whatever is left of the register files.
449    let mut as_bytes = Vec::new();
450    for (index, &Passing { ty, reg, abi }) in args.iter().enumerate() {
451        let refused = |missing| Refused { argument: Some(index), missing };
452        if let Abi::ByVal { size, align } = abi {
453            let size = u32::try_from(size).map_err(|_| refused(Missing::TooBig))?;
454            let Where::Stack(up) = places.on_stack(size, align) else {
455                unreachable!("an object in the argument area is in the argument area")
456            };
457            let plan = crate::expand::plan(u64::from(size), align, conv.word)
458                .ok_or(refused(Missing::TooBig))?;
459            as_bytes.push((reg, up, plan));
460            continue;
461        }
462        let at = if ty.is_float() { places.float() } else { places.integer() };
463        if let Some(missing) = refuses(ty) {
464            return Err(refused(missing));
465        }
466        // Windows passes a float to a variadic callee in the vector register and in the general
467        // purpose register at the same position, both at once, because the callee has no
468        // prototype to tell it which file to look in. Doing that needs to know which arguments are
469        // the ones the signature does not name, and a call carries whether the callee is variadic
470        // rather than how many arguments it names, so this is turned down rather than passed in
471        // one file and read from the other.
472        if ty.is_float() && variadic && conv.shared_positions {
473            return Err(refused(Missing::InBothFiles));
474        }
475        let class = class_of(ty, conv);
476        match at {
477            Where::Reg(at) => {
478                // Only a register counts, because the count is of registers. An argument that went
479                // to memory is one the callee reads from memory whatever this says.
480                if class == conv.sse_class {
481                    vectors += 1;
482                }
483                passed.push((reg, at, class));
484            }
485            Where::Stack(up) => {
486                let store = store_of(ty).ok_or(refused(Missing::Width))?;
487                on_stack.push((reg, class, names.intern(store), up));
488            }
489        }
490    }
491    let comes_back = places_back(returns, conv)?;
492
493    // A variadic callee on SysV reads how many vector registers the call passed arguments in and
494    // skips saving them when the answer is none, which is what makes `printf` with no floating
495    // point argument cheap. It is an obligation rather than an optimization: leaving whatever was
496    // in the register there makes the callee save a register file it was not given, and a count
497    // that is too low makes it read an argument out of a register nothing put one in.
498    let counted = if variadic { conv.vector_count } else { None };
499
500    // The arguments that go to memory go there now, in front of the call and after everything this
501    // could have refused, so that a call it cannot make leaves no store behind either. The offset
502    // is written straight in rather than left for [`crate::finish`]: the outgoing area is at the
503    // bottom of the frame because that is where the callee looks for it, and the bottom of the
504    // frame is where the stack pointer already is.
505    for (reg, class, store, up) in on_stack {
506        let sp = mir::Operand::read(mir::Reg::physical(conv.stack_pointer), conv.int_class);
507        let up = i32::try_from(up).expect("an argument area under two gigabytes");
508        let build = out.build(block, mir::Opcode::new(store));
509        build.uses(reg, class).mem(mir::Mem::at(sp).plus(up)).finish();
510    }
511
512    // And the objects whose bytes go there, as a load and a store for each word of each of them.
513    // This is the copy the caller owes a callee that takes a structure by value: the callee is
514    // free to write to what it was handed, so what it was handed cannot be the caller's own copy,
515    // and the argument area is where the convention says the caller's copy goes. The words are the
516    // same words `crate::expand` would have chosen for a `memcpy` of the same block, because they
517    // are chosen by the same function.
518    for (from, up, plan) in as_bytes {
519        let up = i32::try_from(up).expect("an argument area under two gigabytes");
520        for (at, width) in plan {
521            let ty = Type::int(width * 8);
522            let at = i32::try_from(at).expect("an object under two gigabytes");
523            let word = out.new_vreg(conv.int_class);
524            let load = names
525                .intern(load_of(ty).ok_or(Refused { argument: None, missing: Missing::Width })?);
526            let there = mir::Operand::read(from, conv.int_class);
527            let build = out.build(block, mir::Opcode::new(load));
528            build.def(word, conv.int_class).mem(mir::Mem::at(there).plus(at)).finish();
529            let store = names
530                .intern(store_of(ty).ok_or(Refused { argument: None, missing: Missing::Width })?);
531            let sp = mir::Operand::read(mir::Reg::physical(conv.stack_pointer), conv.int_class);
532            let build = out.build(block, mir::Opcode::new(store));
533            build.uses(word, conv.int_class).mem(mir::Mem::at(sp).plus(up + at)).finish();
534        }
535    }
536
537    // The definitions first and the reads after, which is the order every operand vector in the
538    // machine IR is in and the order `rucc_mir::defs` counts.
539    let mut operands = Vec::with_capacity(args.len() + conv.int_order.len() + 2);
540    let results: Vec<mir::Reg> = comes_back
541        .iter()
542        .map(|&(at, class)| {
543            let reg = out.new_vreg(class);
544            operands.push(mir::Operand::write(reg, class).with(Constraint::Fixed(at)));
545            reg
546        })
547        .collect();
548    // One list per file, because a physical register is a number and the class is what says which
549    // file it is a number in. One list would have `xmm0` blocking `rax`.
550    let spoken_for = |class: RegClass| -> Vec<PhysReg> {
551        comes_back
552            .iter()
553            .filter(|&&(_, at)| at == class)
554            .map(|&(reg, _)| reg)
555            .chain(counted.filter(|_| class == conv.int_class))
556            .chain(passed.iter().filter(|&&(_, _, at)| at == class).map(|&(_, reg, _)| reg))
557            .collect()
558    };
559    let named = spoken_for(conv.int_class);
560    for &reg in conv.int_order {
561        if !conv.preserves_int(reg) && !named.contains(&reg) {
562            operands.push(mir::Operand::write(mir::Reg::physical(reg), conv.int_class));
563        }
564    }
565    let named = spoken_for(conv.sse_class);
566    for &reg in conv.sse_order {
567        if !conv.preserves_sse(reg) && !named.contains(&reg) {
568            operands.push(mir::Operand::write(mir::Reg::physical(reg), conv.sse_class));
569        }
570    }
571    // The address in front of the arguments, because a call through one is written with the
572    // register it goes through and nothing in the operand vector is at a place a table could name.
573    // First read is a place that does not depend on the signature, which is what
574    // [`rucc_target::x86_64::Arg::Through`] is written against.
575    if let Callee::Through(reg) = callee {
576        operands.push(mir::Operand::read(reg, conv.int_class));
577    }
578    for (reg, at, class) in passed {
579        operands.push(mir::Operand::read(reg, class).with(Constraint::Fixed(at)));
580    }
581    if let Some(at) = counted {
582        let count = out.new_vreg(conv.int_class);
583        let zero = mir::Opcode::new(names.intern("x64.mov_ri_32"));
584        out.build(block, zero).def(count, conv.int_class).imm(i64::from(vectors)).finish();
585        operands.push(mir::Operand::read(count, conv.int_class).with(Constraint::Fixed(at)));
586    }
587
588    let opcode = mir::Opcode::new(names.intern(match callee {
589        Callee::Named(_) => CALL,
590        Callee::Through(_) => CALL_REG,
591    }));
592    let mut build = out.build(block, opcode);
593    if let Callee::Named(symbol) = callee {
594        build = build.symbol(symbol);
595    }
596    for operand in operands {
597        build = build.operand(operand);
598    }
599    build.finish();
600    Ok(Made { results, outgoing: places.size() })
601}
602
603/// Which register each value comes back in, walked the way the arguments are.
604///
605/// The two files are counted separately, because a structure of a `double` and a `long` comes back
606/// with the `double` in the first vector register and the `long` in the first integer one, and a
607/// single count would put the second half one place further along a list it is not on.
608///
609/// # Errors
610///
611/// The first value that cannot come back at all, and why, so that a call this cannot make leaves
612/// nothing behind. Nothing here reports which value it was, because the caller has one answer for
613/// all of them: the value that comes back is not an argument and has no position among them.
614fn places_back(returns: &[Type], conv: &CallRegs) -> Result<Vec<(PhysReg, RegClass)>, Refused> {
615    let refused = |missing| Refused { argument: None, missing };
616    let mut back = Vec::with_capacity(returns.len());
617    let (mut ints, mut sses) = (0usize, 0usize);
618    for &ty in returns {
619        if let Some(missing) = refuses(ty) {
620            return Err(refused(missing));
621        }
622        let class = class_of(ty, conv);
623        let (file, at) = if class == conv.sse_class {
624            (conv.sse_returns, &mut sses)
625        } else {
626            (conv.int_returns, &mut ints)
627        };
628        let reg = *file.get(*at).ok_or_else(|| refused(Missing::NoRoom))?;
629        *at += 1;
630        back.push((reg, class));
631    }
632    Ok(back)
633}
634
635/// What the pseudo for an argument of that type is called.
636///
637/// The width is in the name for the same reason it is in every other opcode here: it is what the
638/// instruction is about. Nothing encodes it, so nothing depends on it being right, but a listing
639/// that says an argument arrived and does not say how much of it did is a listing worth less.
640///
641/// Which widths there are is the question the rule set asks of a type, and not a list of its own,
642/// because it has to be the same list. An argument brought in at a width the rules have no name
643/// for is a register
644/// nothing downstream could then read, and a width the rules cover that this refuses is a
645/// function turned away for no reason. Asking one question in one place is what keeps the two
646/// answers from drifting, and an address is what they used to disagree about.
647#[must_use]
648pub fn head_of(ty: Type) -> Option<&'static str> {
649    if let Some(at) = crate::term::float_slot(ty) {
650        return Some(["x64.arg_val_f32", "x64.arg_val_f64"][at]);
651    }
652    let names = ["x64.arg_val_8", "x64.arg_val_16", "x64.arg_val_32", "x64.arg_val_64"];
653    Some(names[crate::term::slot(ty)?])
654}
655
656/// What the instruction that reads an argument of that type out of memory is called.
657///
658/// Keyed off the same two questions [`head_of`] asks and answering for the same set of types, so
659/// that a parameter this compiler can bring in from a register is one it can bring in from the
660/// caller's stack as well. A width one of them covered and the other did not would be a function
661/// turned away for where its sixth argument happened to land.
662///
663/// Reading a narrow argument at its own width and not at a word is deliberate. The caller wrote a
664/// whole word, but what it put in the part above the value is not something the convention says, so
665/// the bits this reads are exactly the bits that mean anything. That is the same thing an argument
666/// arriving in a register gets: `x64.arg_val_8` says the low byte of that register is the argument
667/// and says nothing at all about the rest of it.
668#[must_use]
669pub fn load_of(ty: Type) -> Option<&'static str> {
670    if let Some(at) = crate::term::float_slot(ty) {
671        return Some(["x64.movss_rm", "x64.movsd_rm"][at]);
672    }
673    let names = ["x64.mov_rm_8", "x64.mov_rm_16", "x64.mov_rm_32", "x64.mov_rm_64"];
674    Some(names[crate::term::slot(ty)?])
675}
676
677/// What the instruction that writes an argument of that type into memory is called.
678///
679/// The mirror of [`load_of`], keyed off the same two questions and answering for the same set of
680/// types, so that the two ends of one call agree about what travels. A type a callee can read out
681/// of the argument area and a caller cannot write into it would be a call turned away for a reason
682/// the function it calls does not have.
683///
684/// Writing a narrow argument at its own width leaves whatever was already in the rest of the word.
685/// That is allowed, and it is what [`load_of`] is written against: the convention does not say what
686/// is above the value, so the callee reads only the bits that mean anything and neither end has to
687/// agree about the rest.
688#[must_use]
689pub fn store_of(ty: Type) -> Option<&'static str> {
690    if let Some(at) = crate::term::float_slot(ty) {
691        return Some(["x64.movss_mr", "x64.movsd_mr"][at]);
692    }
693    let names = ["x64.mov_mr_8", "x64.mov_mr_16", "x64.mov_mr_32", "x64.mov_mr_64"];
694    Some(names[crate::term::slot(ty)?])
695}
696
697/// What the instruction that leaves a returned value in its register is called, for the value at
698/// that place in its own register file.
699///
700/// Keyed off the same two questions [`head_of`] asks, so a type this can give back is a type it can
701/// take in. The place is the one a call counted to when it laid the return out, which is per file
702/// rather than over the whole list: a structure of a `double` and a `long` gives both of them back
703/// at place zero.
704///
705/// The register itself is not here. It is in the operand table in `rucc_target::x86_64`, which is
706/// where the first one has always been, and the two names below are how a value says which of the
707/// two it is. A convention with more than two registers to come back in would need more names, and
708/// there is none, which is what the `None` at the end is about.
709#[must_use]
710pub fn ret_of(ty: Type, at: usize) -> Option<&'static str> {
711    if let Some(width) = crate::term::float_slot(ty) {
712        let names =
713            [["x64.ret_val_f32", "x64.ret_val_f64"], ["x64.ret_val2_f32", "x64.ret_val2_f64"]];
714        return Some(names.get(at)?[width]);
715    }
716    let names = [
717        ["x64.ret_val_8", "x64.ret_val_16", "x64.ret_val_32", "x64.ret_val_64"],
718        ["x64.ret_val2_8", "x64.ret_val2_16", "x64.ret_val2_32", "x64.ret_val2_64"],
719    ];
720    Some(names.get(at)?[crate::term::slot(ty)?])
721}
722
723#[cfg(test)]
724mod tests {
725    use rucc_target::x86_64::{REGS, SYSV, WIN64};
726
727    use super::*;
728
729    /// Those types as parameters that travel as the values they are, which is every one of them
730    /// that is not a structure the classification put in the argument area.
731    fn plain(params: &[Type]) -> Vec<Param> {
732        params.iter().copied().map(Param::new).collect()
733    }
734
735    /// The parameters of a function under a convention, as machine IR text.
736    fn bind(params: &[Type], conv: &CallRegs) -> String {
737        let mut names = Interner::new();
738        let mut out = mir::Func::new(names.intern("f"));
739        let block = out.create_block();
740        entry(&mut out, block, &plain(params), conv, &mut names, None)
741            .expect("every parameter arrives");
742        mir::print_func(&out, &names, &REGS)
743    }
744
745    #[test]
746    fn the_first_arguments_arrive_where_the_convention_puts_them() {
747        let i32 = Type::int(32);
748        assert_eq!(
749            bind(&[i32, i32, Type::int(64)], &SYSV),
750            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
751             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr($rdx) = x64.arg_val_64\n}\n"
752        );
753    }
754
755    #[test]
756    fn the_other_convention_puts_the_same_arguments_somewhere_else() {
757        // The first argument is in `rcx` here and in `rdi` above, which is the difference that
758        // makes a SysV binary calling a Windows one read the wrong value rather than fail.
759        let i64 = Type::int(64);
760        assert_eq!(
761            bind(&[i64, i64], &WIN64),
762            "mfunc @f {\nblock0:\n    %0:gpr($rcx) = x64.arg_val_64\n    \
763             %1:gpr($rdx) = x64.arg_val_64\n}\n"
764        );
765    }
766
767    /// The parameters of a function under a convention, and what each of the ones that arrived in
768    /// memory is waiting on.
769    fn arrive(params: &[Type], conv: &CallRegs) -> (String, Vec<u32>) {
770        let mut names = Interner::new();
771        let mut out = mir::Func::new(names.intern("f"));
772        let block = out.create_block();
773        let arrived = entry(&mut out, block, &plain(params), conv, &mut names, None)
774            .expect("every parameter");
775        let up = arrived.stack.iter().map(|&(_, up)| up).collect();
776        (mir::print_func(&out, &names, &REGS), up)
777    }
778
779    #[test]
780    fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
781        let (text, up) = arrive(&[Type::int(64); 7], &SYSV);
782
783        // Six of them got registers and the seventh did not, so the seventh is a load rather than
784        // a pseudo. It reads through the stack pointer with nothing in its displacement, because
785        // where the caller's argument area is from in here is a distance into a frame that does
786        // not exist yet, and it is at the bottom of that area because it is the first one in it.
787        assert_eq!(up, [0]);
788        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
789        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
790    }
791
792    #[test]
793    fn the_other_convention_runs_out_of_registers_three_arguments_earlier() {
794        let (text, up) = arrive(&[Type::int(64); 7], &WIN64);
795
796        // Windows passes four integers in registers and reserves thirty two bytes below the call
797        // whether they are used or not, so the fifth argument is not at the bottom of the argument
798        // area but above the shadow space, and the three after it follow it a word at a time.
799        assert_eq!(up, [32, 40, 48]);
800        assert_eq!(text.matches("x64.arg_val_64").count(), 4, "{text}");
801        assert!(text.contains("%4:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
802    }
803
804    /// The parameters of a function under a convention, with one of them a structure whose bytes
805    /// travel, and what each of the ones that arrived in memory is waiting on.
806    fn arrive_with(params: &[Param], conv: &CallRegs) -> (String, Vec<u32>) {
807        let mut names = Interner::new();
808        let mut out = mir::Func::new(names.intern("f"));
809        let block = out.create_block();
810        let arrived =
811            entry(&mut out, block, params, conv, &mut names, None).expect("every parameter");
812        let up = arrived.stack.iter().map(|&(_, up)| up).collect();
813        (mir::print_func(&out, &names, &REGS), up)
814    }
815
816    #[test]
817    fn a_structure_that_arrived_as_bytes_is_an_address_and_not_a_load() {
818        let byval = Param::with_abi(Type::PTR, Abi::ByVal { size: 32, align: 8 });
819        let (text, up) =
820            arrive_with(&[Param::new(Type::int(32)), byval, Param::new(Type::int(32))], &SYSV);
821
822        // `int f(int a, struct Big b, int c)`. The bytes of `b` are already in this function, at
823        // the bottom of the caller's argument area, so nothing is read out of them here: what the
824        // parameter is is where they are, which is one address. The two integers still travel in
825        // registers, because an object in the argument area takes no register and the arguments
826        // behind it do not shift along.
827        assert_eq!(up, [0]);
828        assert_eq!(text.matches("x64.arg_val_32").count(), 2, "{text}");
829        assert!(text.contains("%2:gpr = x64.lea_64 [$rsp]"), "{text}");
830        assert!(!text.contains("mov_rm"), "nothing is read out of the bytes: {text}");
831    }
832
833    #[test]
834    fn the_argument_behind_a_structure_that_travelled_as_bytes_is_above_all_of_them() {
835        let byval = Param::with_abi(Type::PTR, Abi::ByVal { size: 24, align: 16 });
836        let params: Vec<Param> = (0..7).map(|_| Param::new(Type::int(64))).collect();
837        let (_, up) = arrive_with(&[&params[..], &[byval], &params[..1]].concat(), &SYSV);
838
839        // Six integers take the six registers, the seventh is at the bottom of the argument area,
840        // and the structure is above it at the alignment its type asks for rather than at a word.
841        // The one behind the structure is above all twenty four of its bytes, rounded up to a
842        // whole number of words, because the area is a run of words.
843        assert_eq!(up, [0, 16, 40]);
844    }
845
846    /// A parameter narrower than a word is read at its own width rather than at a word, and one in
847    /// the other register file is read with the other file's instruction. Both are the same list
848    /// [`head_of`] answers from, which is what stops a function being turned away for the width of
849    /// its seventh argument alone.
850    #[test]
851    fn what_a_stack_argument_is_read_with_is_its_own_width_and_its_own_file() {
852        let f32 = Type::float(rucc_ir::Float::F32);
853        let params = [Type::int(64), Type::int(64), Type::int(64), Type::int(64), Type::int(8)];
854        let (text, up) = arrive(&params, &WIN64);
855        assert_eq!(up, [32]);
856        assert!(text.contains("x64.mov_rm_8 [$rsp]"), "{text}");
857
858        let floats = [f32; 5];
859        let (text, up) = arrive(&floats, &WIN64);
860        assert_eq!(up, [32]);
861        assert!(text.contains("%4:xmm = x64.movss_rm [$rsp]"), "{text}");
862    }
863
864    /// Every type a parameter can arrive in a register at is one it can be read from memory at.
865    /// The two lists are keyed off the same two questions so that they cannot drift, and this is
866    /// what says so: a width one covered and the other did not would be a function turned away for
867    /// where its arguments happened to land rather than for anything about it.
868    #[test]
869    fn the_two_lists_of_widths_answer_for_the_same_types() {
870        let types = [
871            Type::int(1),
872            Type::int(8),
873            Type::int(16),
874            Type::int(32),
875            Type::int(64),
876            Type::int(128),
877            Type::PTR,
878            Type::float(rucc_ir::Float::F32),
879            Type::float(rucc_ir::Float::F64),
880            Type::float(rucc_ir::Float::F80),
881        ];
882        for ty in types {
883            assert_eq!(head_of(ty).is_some(), load_of(ty).is_some(), "{ty:?}");
884        }
885    }
886
887    /// A float arrives in the other file, and the two files are counted apart on SysV: the
888    /// integer here is the first integer argument and the float is the first float one, so they
889    /// are in `rdi` and `xmm0` rather than in the first and second of anything.
890    #[test]
891    fn a_float_arrives_in_a_vector_register_and_is_counted_apart_from_the_integers() {
892        let f32 = Type::float(rucc_ir::Float::F32);
893        let f64 = Type::float(rucc_ir::Float::F64);
894        assert_eq!(
895            bind(&[Type::int(32), f64, f32], &SYSV),
896            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
897             %1:xmm($xmm0) = x64.arg_val_f64\n    %2:xmm($xmm1) = x64.arg_val_f32\n}\n"
898        );
899    }
900
901    /// Windows counts the two files together, so the same three arguments land in different
902    /// registers: the float is the second argument and takes the second vector register rather
903    /// than the first, which is the difference that makes a mismatched call read the wrong value.
904    #[test]
905    fn the_other_convention_counts_the_two_files_as_one_run_of_positions() {
906        let f64 = Type::float(rucc_ir::Float::F64);
907        assert_eq!(
908            bind(&[Type::int(32), f64, Type::int(64)], &WIN64),
909            "mfunc @f {\nblock0:\n    %0:gpr($rcx) = x64.arg_val_32\n    \
910             %1:xmm($xmm1) = x64.arg_val_f64\n    %2:gpr($r8) = x64.arg_val_64\n}\n"
911        );
912    }
913
914    /// A `long double` is in neither file, and what it is turned away for says so rather than
915    /// calling eighty bits a width no register holds. The x87 stack is a register file this
916    /// compiler does not allocate in and has no instruction for.
917    #[test]
918    fn a_long_double_is_reported_as_the_x87_stack_it_travels_on() {
919        let mut names = Interner::new();
920        let mut out = mir::Func::new(names.intern("f"));
921        let block = out.create_block();
922        let params = [Type::int(32), Type::float(rucc_ir::Float::F80)];
923        let made = entry(&mut out, block, &plain(&params), &SYSV, &mut names, None);
924        assert_eq!(made, Err((1, Missing::OnX87)));
925        assert_eq!(
926            make(&[], &[Type::float(rucc_ir::Float::F80)], false, &SYSV).2,
927            Err(Refused { argument: None, missing: Missing::OnX87 })
928        );
929    }
930
931    /// One call to `g`, with a register for each argument arriving in the block that makes it.
932    fn make(
933        args: &[Type],
934        returns: &[Type],
935        variadic: bool,
936        conv: &CallRegs,
937    ) -> (Interner, mir::Func, Result<Made, Refused>) {
938        let mut names = Interner::new();
939        let mut out = mir::Func::new(names.intern("f"));
940        let block = out.create_block();
941        let passed: Vec<Passing> = args
942            .iter()
943            .map(|&ty| Passing {
944                ty,
945                reg: out.append_param(block, class_of(ty, conv)),
946                abi: Abi::Plain,
947            })
948            .collect();
949        let callee = Callee::Named(names.intern("g"));
950        let what = Calling { callee, args: &passed, returns, variadic };
951        let made = call(&mut out, block, &what, conv, &mut names);
952        (names, out, made)
953    }
954
955    /// What the call in that function reads and writes, by register name, in the order the
956    /// operands are in.
957    fn operands(func: &mir::Func) -> (Vec<String>, Vec<String>) {
958        let block = func.entry().expect("a function with a block in it");
959        let call = func.terminator(block).expect("the call is the last thing in the block");
960        let name = |operand: &mir::Operand| match (operand.reg.phys(), operand.constraint) {
961            (Some(reg), _) | (None, Constraint::Fixed(reg)) => {
962                REGS.name(operand.class, reg).expect("a register the file describes").to_string()
963            }
964            _ => format!("{:?}", operand.reg),
965        };
966        let mut written = Vec::new();
967        let mut read = Vec::new();
968        for operand in &func[func[call].operands] {
969            let into = if operand.role == mir::Role::Use { &mut read } else { &mut written };
970            into.push(name(operand));
971        }
972        (written, read)
973    }
974
975    #[test]
976    fn a_call_passes_its_arguments_where_the_convention_puts_them() {
977        let i32 = Type::int(32);
978        let (_, func, made) = make(&[i32, i32, i32], &[], false, &SYSV);
979        assert_eq!(made.expect("three integers all fit in registers").results, []);
980        assert_eq!(operands(&func).1, ["rdi", "rsi", "rdx"]);
981    }
982
983    #[test]
984    fn the_other_convention_passes_the_same_arguments_somewhere_else() {
985        let i64 = Type::int(64);
986        let (_, func, made) = make(&[i64, i64], &[], false, &WIN64);
987        // Thirty two bytes of stack for a call that passes nothing on the stack, which is what
988        // Windows asks a caller to leave the callee whether the callee uses it or not.
989        assert_eq!(made.expect("two integers fit in registers").outgoing, 32);
990        assert_eq!(operands(&func).1, ["rcx", "rdx"]);
991    }
992
993    #[test]
994    fn what_a_call_gives_back_comes_out_of_the_register_the_convention_returns_in() {
995        let (names, func, made) = make(&[], &[Type::int(32)], false, &SYSV);
996        let made = made.expect("an integer comes back");
997        let [result] = made.results[..] else { panic!("one register") };
998        // The first thing written is the result, and it is the only thing written that is a value
999        // rather than a register the callee destroyed.
1000        assert_eq!(operands(&func).0.first().map(String::as_str), Some("rax"));
1001        assert_eq!(func.class_of(result), Some(SYSV.int_class));
1002        assert!(mir::print_func(&func, &names, &REGS).contains("x64.call"));
1003    }
1004
1005    #[test]
1006    fn every_register_the_callee_may_destroy_is_written_by_the_call() {
1007        let (_, func, _) = make(&[Type::int(64)], &[Type::int(64)], false, &SYSV);
1008        let (written, read) = operands(&func);
1009        // The callee saved registers are not here, because a value in one of those survives a
1010        // call and that is the whole difference between the two halves of the convention.
1011        for saved in ["rbx", "rbp", "r12", "r13", "r14", "r15"] {
1012            assert!(!written.contains(&saved.to_string()), "{saved} survives a call");
1013        }
1014        // Every other integer register is, once. The two named ones are named by the result and
1015        // by the argument instead, and naming one twice would be blocking it twice.
1016        for destroyed in ["rcx", "rdx", "rsi", "r8", "r9", "r10", "r11"] {
1017            let count = written.iter().filter(|name| *name == destroyed).count();
1018            assert_eq!(count, 1, "{destroyed} is destroyed by a call and is written {count} times");
1019        }
1020        assert_eq!(written.iter().filter(|name| *name == "rax").count(), 1);
1021        assert_eq!(read, ["rdi"]);
1022        // The vector registers are all destroyed on SysV, and they are in the other class.
1023        assert!(written.contains(&"xmm0".to_string()));
1024    }
1025
1026    #[test]
1027    fn a_variadic_call_says_how_many_vector_registers_it_passed_arguments_in() {
1028        let (names, func, made) = make(&[Type::int(64)], &[], true, &SYSV);
1029        made.expect("an integer argument to a variadic callee");
1030        let (_, read) = operands(&func);
1031        // Zero of them here, and `al` is where a SysV callee looks for it. Leaving whatever was in
1032        // the register there would make a callee that saves its vector registers save ones it was
1033        // never given.
1034        assert_eq!(read, ["rdi", "rax"]);
1035        assert_eq!(
1036            mir::print_func(&func, &names, &REGS).lines().nth(2),
1037            Some("    %1:gpr = x64.mov_ri_32 0")
1038        );
1039
1040        // Two of them here, which is the number that decides how much of the register save area a
1041        // callee like `printf` fills in. A count of zero with a float in `xmm0` would be a callee
1042        // reading its first `%f` out of a register nothing wrote.
1043        let f64 = Type::float(rucc_ir::Float::F64);
1044        let (names, func, made) = make(&[Type::int(64), f64, f64], &[], true, &SYSV);
1045        made.expect("one integer and two floats all fit in registers");
1046        assert_eq!(operands(&func).1, ["rdi", "xmm0", "xmm1", "rax"]);
1047        assert!(mir::print_func(&func, &names, &REGS).contains("x64.mov_ri_32 2"));
1048    }
1049
1050    /// Windows passes a float to a variadic callee in both files at once, and which arguments are
1051    /// the ones the signature does not name is not something a call carries, so it is turned down
1052    /// rather than passed in one file and read from the other.
1053    #[test]
1054    fn a_float_passed_to_a_variadic_callee_on_windows_is_reported() {
1055        let f64 = Type::float(rucc_ir::Float::F64);
1056        assert_eq!(
1057            make(&[Type::int(32), f64], &[], true, &WIN64).2,
1058            Err(Refused { argument: Some(1), missing: Missing::InBothFiles })
1059        );
1060        // The same call to a callee whose signature names both arguments is fine, because there is
1061        // no second copy to make.
1062        assert!(make(&[Type::int(32), f64], &[], false, &WIN64).2.is_ok());
1063    }
1064
1065    #[test]
1066    fn a_call_through_an_address_reads_it_in_front_of_the_arguments() {
1067        let i32 = Type::int(32);
1068        let mut names = Interner::new();
1069        let mut out = mir::Func::new(names.intern("f"));
1070        let block = out.create_block();
1071        let address = out.append_param(block, SYSV.int_class);
1072        let reg = out.append_param(block, SYSV.int_class);
1073        let passed = vec![Passing { ty: i32, reg, abi: Abi::Plain }];
1074        let what = Calling {
1075            callee: Callee::Through(address),
1076            args: &passed,
1077            returns: &[i32],
1078            variadic: false,
1079        };
1080        call(&mut out, block, &what, &SYSV, &mut names).expect("one integer fits in a register");
1081
1082        // The address is the first thing read and the arguments follow it, which is the order the
1083        // assembler counts on, and it is in no particular register because every register a call
1084        // could insist on is one the call has already spoken for.
1085        let text = mir::print_func(&out, &names, &REGS);
1086        assert!(text.contains("= x64.call_reg %0, %1($rdi)\n"), "{text}");
1087        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
1088    }
1089
1090    #[test]
1091    fn a_call_with_no_register_left_writes_the_argument_into_the_outgoing_area() {
1092        let i64 = Type::int(64);
1093        let (names, func, made) = make(&[i64; 7], &[], false, &SYSV);
1094        let made = made.expect("the seventh goes to memory");
1095
1096        // At the stack pointer, because the outgoing area is at the bottom of the frame, and in
1097        // front of the call rather than as an operand of it.
1098        let text = mir::print_func(&func, &names, &REGS);
1099        assert!(text.contains("x64.mov_mr_64 %6, [$rsp]\n"), "{text}");
1100        let store = text.find("x64.mov_mr_64").expect("the store");
1101        assert!(store < text.find("x64.call").expect("the call"), "{text}");
1102        // One word of it, which is what the frame has to reserve for this call.
1103        assert_eq!(made.outgoing, 8);
1104    }
1105
1106    /// One call to `g`, passing that many words, then an object of that size and alignment by
1107    /// value, then one more integer, which is `int g(long.., struct Big, int)` after the
1108    /// classification.
1109    fn pass_bytes(
1110        before: usize,
1111        size: u64,
1112        align: u32,
1113        conv: &CallRegs,
1114    ) -> (Interner, mir::Func, Result<Made, Refused>) {
1115        let mut names = Interner::new();
1116        let mut out = mir::Func::new(names.intern("f"));
1117        let block = out.create_block();
1118        let mut args: Vec<Passing> = (0..before)
1119            .map(|_| Passing {
1120                ty: Type::int(64),
1121                reg: out.append_param(block, conv.int_class),
1122                abi: Abi::Plain,
1123            })
1124            .collect();
1125        args.push(Passing {
1126            ty: Type::PTR,
1127            reg: out.append_param(block, conv.int_class),
1128            abi: Abi::ByVal { size, align },
1129        });
1130        args.push(Passing {
1131            ty: Type::int(32),
1132            reg: out.append_param(block, conv.int_class),
1133            abi: Abi::Plain,
1134        });
1135        let callee = Callee::Named(names.intern("g"));
1136        let what = Calling { callee, args: &args, returns: &[], variadic: false };
1137        let made = call(&mut out, block, &what, conv, &mut names);
1138        (names, out, made)
1139    }
1140
1141    #[test]
1142    fn a_structure_passed_by_value_in_memory_is_copied_into_the_outgoing_area() {
1143        let (names, func, made) = pass_bytes(1, 24, 8, &SYSV);
1144        let made = made.expect("an object of three words is copied a word at a time");
1145
1146        // The bytes travel and the address does not, so the copy is a load and a store for each
1147        // word of it, in front of the call, and the callee's copy is at the bottom of the outgoing
1148        // area. The caller owes it this copy: the callee is free to write to what it was handed,
1149        // so what it was handed cannot be the object itself.
1150        let text = mir::print_func(&func, &names, &REGS);
1151        assert!(text.contains("x64.mov_mr_64 %3, [$rsp]\n"), "{text}");
1152        assert!(text.contains("x64.mov_mr_64 %4, [$rsp + 8]\n"), "{text}");
1153        assert!(text.contains("x64.mov_mr_64 %5, [$rsp + 16]\n"), "{text}");
1154        assert_eq!(text.matches("x64.mov_rm_64").count(), 3, "{text}");
1155        assert!(text.find("x64.mov_mr_64") < text.find("x64.call"), "{text}");
1156        assert_eq!(made.outgoing, 24);
1157    }
1158
1159    #[test]
1160    fn the_integers_beside_it_still_travel_in_registers() {
1161        let (_, func, _) = pass_bytes(1, 24, 8, &SYSV);
1162
1163        // An object in the argument area takes no argument register, so the integer behind it is
1164        // in the second one and not the third. Counting it as a register is the mistake that would
1165        // shift every argument after it along by one.
1166        let (clobbered, read) = operands(&func);
1167        assert_eq!(read, ["rdi", "rsi"]);
1168        assert!(clobbered.contains(&"rdx".to_owned()), "the third is free: {clobbered:?}");
1169    }
1170
1171    #[test]
1172    fn an_object_wanting_more_alignment_than_a_word_gets_it() {
1173        let (names, func, made) = pass_bytes(7, 24, 16, &SYSV);
1174        let made = made.expect("an object of three words");
1175
1176        // Six of the integers took the registers and the seventh is at the bottom of the area, so
1177        // the object cannot start where it left off: sixteen byte alignment moves it up to the
1178        // next multiple of sixteen and leaves a word of nothing behind it. The integer after it is
1179        // above all three of its words.
1180        let text = mir::print_func(&func, &names, &REGS);
1181        assert!(text.contains("x64.mov_mr_64 %9, [$rsp + 16]\n"), "{text}");
1182        assert!(text.contains("x64.mov_mr_32 %8, [$rsp + 40]\n"), "{text}");
1183        assert_eq!(made.outgoing, 48);
1184    }
1185
1186    #[test]
1187    fn an_object_too_large_to_copy_a_word_at_a_time_is_reported_rather_than_passed() {
1188        let (_, _, made) = pass_bytes(1, 4096, 8, &SYSV);
1189
1190        // Five hundred and twelve words is past what unrolling is worth, and the copy that size
1191        // wants is a call to the runtime, which cannot be built in the middle of building a call.
1192        // Saying so is the point: the alternative is a call that passes the address of the object
1193        // where the callee is going to read the object.
1194        assert_eq!(made, Err(Refused { argument: Some(1), missing: Missing::TooBig }));
1195        assert_eq!(
1196            Missing::TooBig.why(),
1197            "is more bytes than a copy into the argument area unrolls to"
1198        );
1199    }
1200
1201    /// The other convention runs out three arguments earlier and starts its argument area above the
1202    /// shadow space it also has to reserve, and both of those are what `Places` already said.
1203    #[test]
1204    fn where_the_outgoing_area_starts_is_the_convention_s_answer() {
1205        let i64 = Type::int(64);
1206        let (names, func, made) = make(&[i64; 7], &[], false, &WIN64);
1207        assert_eq!(made.expect("the last three go to memory").outgoing, 56);
1208
1209        // Thirty two bytes of shadow space first, which the caller writes nothing into and the
1210        // callee owns, and the fifth argument above it.
1211        let text = mir::print_func(&func, &names, &REGS);
1212        assert!(text.contains("x64.mov_mr_64 %4, [$rsp + 32]\n"), "{text}");
1213        assert!(text.contains("x64.mov_mr_64 %5, [$rsp + 40]\n"), "{text}");
1214        assert!(text.contains("x64.mov_mr_64 %6, [$rsp + 48]\n"), "{text}");
1215    }
1216
1217    /// What a stack argument is written with is its own width and its own register file, matching
1218    /// what the callee reads it back with.
1219    #[test]
1220    fn a_narrow_or_floating_argument_keeps_its_own_store() {
1221        let i64 = Type::int(64);
1222        let narrow = [i64, i64, i64, i64, i64, i64, Type::int(8)];
1223        let (names, func, made) = make(&narrow, &[], false, &SYSV);
1224        made.expect("the seventh goes to memory");
1225        let text = mir::print_func(&func, &names, &REGS);
1226        assert!(text.contains("x64.mov_mr_8 %6, [$rsp]\n"), "{text}");
1227
1228        let f32 = Type::float(rucc_ir::Float::F32);
1229        let (names, func, made) = make(&[f32; 9], &[], false, &SYSV);
1230        made.expect("the ninth goes to memory");
1231        let text = mir::print_func(&func, &names, &REGS);
1232        assert!(text.contains("x64.movss_mr %8, [$rsp]\n"), "{text}");
1233    }
1234
1235    /// The count a SysV variadic callee reads is a count of registers, so an argument that went to
1236    /// memory instead is not in it.
1237    #[test]
1238    fn an_argument_in_memory_is_not_counted_as_a_vector_register() {
1239        let f64 = Type::float(rucc_ir::Float::F64);
1240        let (names, func, made) = make(&[f64; 9], &[], true, &SYSV);
1241        made.expect("the ninth goes to memory");
1242        let text = mir::print_func(&func, &names, &REGS);
1243        assert!(text.contains("x64.mov_ri_32 8\n"), "eight registers, not nine: {text}");
1244    }
1245
1246    /// The two lists of widths answer for the same set of types, so that a value the callee can
1247    /// read out of the argument area is one the caller can write into it.
1248    #[test]
1249    fn what_can_be_read_can_be_written() {
1250        let types = [
1251            Type::int(1),
1252            Type::int(8),
1253            Type::int(16),
1254            Type::int(32),
1255            Type::int(64),
1256            Type::int(128),
1257            Type::PTR,
1258            Type::float(rucc_ir::Float::F32),
1259            Type::float(rucc_ir::Float::F64),
1260            Type::float(rucc_ir::Float::F80),
1261        ];
1262        for ty in types {
1263            assert_eq!(load_of(ty).is_some(), store_of(ty).is_some(), "{ty:?}");
1264        }
1265    }
1266
1267    /// A float travels in the other file at both ends of a call, and the register it comes back in
1268    /// is the first of that file rather than the first of the other one.
1269    #[test]
1270    fn a_call_passes_and_returns_a_float_in_a_vector_register() {
1271        let f64 = Type::float(rucc_ir::Float::F64);
1272        let (_, func, made) = make(&[Type::int(32), f64], &[f64], false, &SYSV);
1273        let result = made.expect("an integer and a float both fit in registers");
1274        let (written, read) = operands(&func);
1275        assert_eq!(read, ["rdi", "xmm0"]);
1276        assert_eq!(written.first().map(String::as_str), Some("xmm0"));
1277        assert_eq!(func.class_of(result.results[0]), Some(SYSV.sse_class));
1278        // Written once, because the register the result comes back in is already blocked by being
1279        // named and a clobber that repeated it would be blocking it twice. `rax` is a clobber here
1280        // rather than the result, which is the same register number in the other file and is the
1281        // whole reason the two lists are counted apart.
1282        assert_eq!(written.iter().filter(|name| *name == "xmm0").count(), 1);
1283        assert!(written.contains(&"rax".to_string()));
1284    }
1285
1286    #[test]
1287    fn a_call_at_a_width_no_register_holds_is_reported_on_either_side() {
1288        let i128 = Type::int(128);
1289        assert_eq!(
1290            make(&[i128], &[], false, &SYSV).2,
1291            Err(Refused { argument: Some(0), missing: Missing::Width })
1292        );
1293        assert_eq!(
1294            make(&[], &[i128], false, &SYSV).2,
1295            Err(Refused { argument: None, missing: Missing::Width })
1296        );
1297    }
1298
1299    #[test]
1300    fn an_argument_wider_than_a_register_has_no_name() {
1301        assert_eq!(head_of(Type::int(128)), None);
1302        assert_eq!(head_of(Type::int(8)), Some("x64.arg_val_8"));
1303        assert_eq!(head_of(Type::int(64)), Some("x64.arg_val_64"));
1304    }
1305
1306    /// An address arrives in a general purpose register like any other integer of its width, and
1307    /// used to be turned away here as a width no register holds, which is what issue 274 is.
1308    /// `int g(char *s)` is the smallest program that was.
1309    #[test]
1310    fn an_address_arrives_in_a_register_like_the_integer_it_is() {
1311        assert_eq!(head_of(Type::PTR), Some("x64.arg_val_64"));
1312        assert_eq!(
1313            bind(&[Type::PTR], &SYSV),
1314            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n}\n"
1315        );
1316        // And it travels the same way at a call, on both sides of one.
1317        assert!(make(&[Type::PTR], &[Type::PTR], false, &SYSV).2.is_ok());
1318    }
1319}