Skip to main content

rucc_codegen/
pipeline.rs

1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling, and the redundant moves a coalescer would take out
24//! are still in the output.
25
26use rucc_base::Interner;
27use rucc_cost::Goal;
28use rucc_ir as ir;
29use rucc_mir as mir;
30use rucc_regalloc::assign::Env;
31use rucc_target::{
32    BitInsts, BranchInsts, CallRegs, FlagInsts, FrameInsts, MachineInsts, PhysReg, RegFile,
33    ShortInsts, TargetInfo, TimingInsts, aarch64, x86_64,
34};
35use rucc_tuple::Arch;
36
37use crate::bits;
38use crate::choice;
39use crate::combine;
40use crate::compare;
41use crate::copies;
42use crate::coverage::Fired;
43use crate::elsewhere::Elsewhere;
44use crate::finish::{Convention, Padding, Probing, Protect, Tracing, far, finish};
45use crate::fold;
46use crate::frame::{self, Frame, Layout};
47use crate::kept;
48use crate::layout;
49use crate::lower::{self, Unsupported};
50use crate::lowering::{self, Lowerings};
51use crate::pressure::{Cost, Pressure};
52use crate::schedule;
53use crate::select::{self, Selector};
54use crate::shorten;
55use crate::slots::{self, Slots};
56use crate::split;
57use crate::tail;
58use crate::usage::{StackUsage, Usage};
59use crate::weights;
60pub use rucc_regalloc::Allocator;
61
62/// Everything about a machine that compiling a function for it needs.
63///
64/// The fields are different kinds of fact and they come from different places: where the
65/// convention puts things, what registers the machine has, which instructions build a frame,
66/// which instructions a branch becomes, and which registers the allocator may hand out. The last
67/// one is not a target fact on its own, because holding a register back as scratch is a decision
68/// about the allocator rather than about the machine, which is why it is built here rather than
69/// in [`rucc_target`].
70#[derive(Debug)]
71pub struct Machine {
72    /// Where the convention this function is compiled for puts things.
73    pub conv: &'static CallRegs,
74    /// The registers the machine has, which is what says how wide a spill slot of a class is.
75    pub file: RegFile,
76    /// The instructions that take a frame and give it back.
77    pub insts: &'static FrameInsts,
78    /// The instructions a branch becomes once the blocks are in an order.
79    pub branch: &'static BranchInsts,
80    /// How much of a register each of the machine's instructions reads and writes.
81    pub bits: &'static BitInsts,
82    /// What each of the machine's instructions leaves in the condition state.
83    pub flags: &'static FlagInsts,
84    /// What shape each of the machine's instructions is, which is what a pass proposing a new one
85    /// has its proposal held against.
86    pub shapes: &'static MachineInsts,
87    /// How long each of the machine's instructions takes, and what it takes it on.
88    pub timing: &'static TimingInsts,
89    /// Which of the machine's instructions have a shorter spelling of the same answer.
90    pub short: &'static ShortInsts,
91    /// What the selector asks of the machine, which is the rules and the instructions it writes
92    /// itself.
93    pub selector: &'static Selector,
94    /// What the allocator may hand out, and what it holds back.
95    pub env: Env,
96}
97
98/// The scratch registers held back from the allocator on x86-64.
99///
100/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
101/// into something, and those can want a register at the same instruction. Two is also what nearly
102/// every instruction wants, including the one that looks larger: an instruction that reads two
103/// spilled values and writes a third sends the answer back into a register an operand arrived in
104/// rather than asking for one of its own, and `rewrite` says why that is allowed.
105///
106/// It is not two because two was enough to start with and nobody looked again. There is no third
107/// to hold back. A scratch register has to be one the convention passes nothing in, since the
108/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
109/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved. On
110/// SysV that is `r10`, `r11` and `rax`, and `rax` is not one to take: it is the return value, so
111/// holding it back costs a move at every return in the program, which is a price paid everywhere
112/// for a shape that turns up almost nowhere.
113///
114/// An instruction that wants a third is the indexed store with its base, its index and its value
115/// all on the stack, which is tamnd/rucc#913. `rewrite` answers that one by borrowing a register
116/// and putting back what was in it, which costs two memory accesses at the instruction that wanted
117/// it and nothing anywhere else.
118pub(crate) const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
119
120/// The scratch registers held back from the allocator on AArch64. See [`Machine::aarch64`].
121pub(crate) const AARCH64_SCRATCH: [PhysReg; 2] = [aarch64::X16, aarch64::X17];
122
123/// How many of each class are held back.
124const SCRATCH_COUNT: usize = SCRATCH.len();
125
126/// The second register file's allocation order and the scratch registers taken out of it, which
127/// are the last two in the order that the convention does not preserve.
128fn held_back(conv: &CallRegs) -> (Vec<PhysReg>, Vec<PhysReg>) {
129    let free: Vec<PhysReg> =
130        conv.sse_order.iter().copied().filter(|&reg| !conv.preserves_sse(reg)).collect();
131    let at = free.len().saturating_sub(SCRATCH_COUNT);
132    let scratch: Vec<PhysReg> = free[at..].to_vec();
133    let order = conv.sse_order.iter().copied().filter(|reg| !scratch.contains(reg)).collect();
134    (order, scratch)
135}
136
137impl Machine {
138    /// The x86-64 machine under that convention.
139    ///
140    /// Both files are offered. A value the selector produces is in one or the other, which is
141    /// decided by its type: an integer and an address are general purpose and a `float` or a
142    /// `double` is in a vector register, and the allocator is given each file separately because
143    /// no move goes between them.
144    #[must_use]
145    pub fn x86_64(conv: &'static CallRegs) -> Self {
146        let order: Vec<PhysReg> =
147            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
148        // The vector file wants its own two, for the same two jobs, and they have to be two the
149        // convention does not preserve: a scratch register is written by a move the rewriter puts
150        // in, which is after the prologue has already been decided, so one the callee owes back
151        // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
152        // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
153        // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
154        let (sse_order, sse_scratch) = held_back(conv);
155        Self {
156            conv,
157            file: x86_64::REGS,
158            insts: &x86_64::FRAME,
159            branch: &x86_64::BRANCH,
160            bits: &x86_64::BITS,
161            flags: &x86_64::FLAGS,
162            shapes: &x86_64::MACHINE,
163            timing: &x86_64::TIMING,
164            short: &x86_64::SHORT,
165            selector: &select::x86_64::SELECTOR,
166            env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
167                x86_64::XMM,
168                &sse_order,
169                &sse_scratch,
170            ),
171        }
172    }
173
174    /// The AArch64 machine under that convention.
175    ///
176    /// The scratch registers are `x16` and `x17`, which the convention already keeps out of the
177    /// allocation order because a linker's veneer may write them between a call and the function
178    /// it reaches. That is the property a scratch register wants: nothing lives in one across
179    /// anything the compiler did not write, so a move the rewriter puts in can have it. The vector
180    /// file's two are picked the way the x86 ones are, which lands on `v30` and `v31`.
181    ///
182    /// Nothing selects AArch64 instructions yet, so [`Machine::for_target`] does not return this.
183    #[must_use]
184    pub fn aarch64(conv: &'static CallRegs) -> Self {
185        let order: Vec<PhysReg> =
186            conv.int_order.iter().copied().filter(|reg| !AARCH64_SCRATCH.contains(reg)).collect();
187        let (fp_order, fp_scratch) = held_back(conv);
188        Self {
189            conv,
190            file: aarch64::REGS,
191            insts: &aarch64::FRAME,
192            branch: &aarch64::BRANCH,
193            bits: &aarch64::BITS,
194            flags: &aarch64::FLAGS,
195            shapes: &aarch64::MACHINE,
196            timing: &aarch64::TIMING,
197            short: &aarch64::SHORT,
198            selector: &select::aarch64::SELECTOR,
199            env: Env::new().with(aarch64::GPR, &order, &AARCH64_SCRATCH).with(
200                aarch64::FPR,
201                &fp_order,
202                &fp_scratch,
203            ),
204        }
205    }
206
207    /// The machine a target describes, or `None` when no backend in this crate covers it.
208    ///
209    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
210    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
211    /// and register file go with it. RISC-V is `None` until it has a rule file, and a caller that
212    /// gets one reports a target it cannot compile for rather than compiling wrongly.
213    #[must_use]
214    pub fn for_target(target: &TargetInfo) -> Option<Self> {
215        let conv = target.call_regs?;
216        match target.tuple.arch() {
217            Arch::X86_64 => Some(Self::x86_64(conv)),
218            Arch::Aarch64 => Some(Self::aarch64(conv)),
219            _ => None,
220        }
221    }
222}
223
224/// Whether every function calls a profiler on the way in, and where that call goes.
225///
226/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
227/// has already been made against the target by the time this is built, which is why there is no
228/// answer here for a command line that named neither.
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
230pub enum Profile {
231    /// It does not, which is what nearly every command line asks for.
232    #[default]
233    No,
234    /// In front of the prologue, which is the hook a tracer can replace while the program runs.
235    Early,
236    /// Once the frame is taken, which is the hook that reads the frame pointer.
237    Late,
238}
239
240/// How much room every function opens with for something to be written over it later.
241///
242/// What `-fpatchable-function-entry=` asks for, as the two halves a prologue deals in rather than
243/// as the total and the part the flag is written in. The room can be on either side of the
244/// function's own label and the two sides are not the same thing: what is after the label is inside
245/// the function, which is what a patcher redirecting a call into it wants, and what is in front of
246/// it is outside, which is where a patcher that needs a whole instruction it can reach from the
247/// first one puts it.
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
249pub struct Room {
250    /// How many bytes go after the function's own label.
251    pub after: u32,
252    /// How many go in front of it.
253    pub before: u32,
254}
255
256impl Room {
257    /// Whether any room at all was asked for, which is what decides whether a function gets one.
258    ///
259    /// `=0` is a command line that asked for none, and gcc takes it and writes nothing, so the
260    /// question is about the numbers rather than about whether the flag was written.
261    #[must_use]
262    pub const fn any(self) -> bool {
263        self.after > 0 || self.before > 0
264    }
265}
266
267/// What the command line says, as opposed to what the machine says.
268///
269/// Most of it is about a frame, which is what this held to begin with, and the rest is passes being
270/// asked for or turned off by name. [`Flags::goal`] is neither: it is the one thing here that no
271/// flag names on its own and that every pass below selection may read.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub struct Flags {
274    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
275    pub frame_pointer: bool,
276    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
277    pub red_zone: bool,
278    /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
279    pub stack_clash: bool,
280    /// Whether every address an indirect branch may arrive at opens with a landing pad, which
281    /// `-fcf-protection=branch` asks for. That is every function, and every label of a function
282    /// whose address the program took.
283    pub landing: bool,
284    /// Whether every function calls a profiler on the way in, which `-pg` asks for.
285    pub profile: Profile,
286    /// How much room every function opens with for a patcher, which
287    /// `-fpatchable-function-entry=` asks for. See [`Room`].
288    pub patch: Room,
289    /// Whether the blocks are put in the order the weights say rather than in the order the
290    /// shape of the graph says, which `-freorder-blocks` asks for and every level above `-O0`
291    /// turns on. See [`crate::layout`].
292    pub reorder: bool,
293    /// Whether two locals that are never both wanted may be the same bytes, which
294    /// `-fstack-reuse=none` turns off and `-O0` does not ask for. Spill slots share whatever this
295    /// says, since a spill slot is not a variable and nothing can ask a debugger for one. See
296    /// [`crate::slots`].
297    pub reuse: bool,
298    /// Whether the instructions of a block are put in the order the machine finishes soonest,
299    /// which `-fschedule-insns2` asks for and every level from `-O2` turns on. See
300    /// [`crate::schedule`].
301    pub schedule: bool,
302    /// Whether the head of every hot loop is found, so that the loop can be padded to stay inside
303    /// one line, which `-falign-loops` asks for and no level turns on by itself yet. See
304    /// [`crate::layout::heads`].
305    pub align_loops: bool,
306    /// Whether the target's timing model is believed about the machine's units as well as about
307    /// its latencies, which `-Zcycle-accurate-model=` says and the model itself answers otherwise.
308    ///
309    /// `None` is a command line that did not say, which is nearly every one, and then the model's
310    /// own answer decides. It is here rather than only on the model because section 38.1 asks for
311    /// a way to say the model is better or worse than it claims without editing the model, and
312    /// because the measurement section 38.8 owes is the same corpus compiled both ways.
313    pub accurate: Option<bool>,
314    /// Whether the register allocator runs its own checks on a build that has assertions compiled
315    /// out, which `-Zverify-each` asks for. See [`rucc_regalloc::run`].
316    pub verify: bool,
317    /// Which register allocator decides where the values go, which `-Zregalloc=` says. See
318    /// [`rucc_regalloc::Allocator`].
319    pub allocator: Allocator,
320    /// Whether the level asked for small code or for fast code.
321    ///
322    /// The level itself lives in `rucc-session`, which is above this crate, so what arrives here is
323    /// the answer rather than the question. It is on the flags rather than on the [`Machine`]
324    /// because it is not a fact about a machine: the same machine compiles the same function both
325    /// ways, and which way is what the command line said.
326    ///
327    /// tamnd/rucc#741 is the issue about this not being here at all, and about `-Os` having been a
328    /// shorter list of middle end passes and nothing else. [`crate::shorten`] is the first pass
329    /// below selection to read it.
330    pub goal: Goal,
331    /// The shape `-Zswitch=` forces on every `switch`, which is `None` unless somebody is
332    /// measuring what each shape costs. See [`crate::switch::Force`].
333    pub switch: Option<crate::switch::Force>,
334    /// Whether a call in tail position becomes a jump, which `-foptimize-sibling-calls` asks for
335    /// and `-O2` and `-Os` turn on. See [`crate::tail`].
336    pub sibling: bool,
337    /// Whether the build writes debugging information, which `-g` asks for. Where each local is
338    /// over which instructions is worked out only then, since nothing else reads it. See
339    /// [`crate::kept`].
340    pub debug: bool,
341}
342
343impl Default for Flags {
344    /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad,
345    /// no profiling, no room for a patcher, the blocks in the order the graph's shape gives,
346    /// nothing in the frame sharing with anything, no scheduling, no loop padded to a boundary and
347    /// code that is meant to be fast rather than small, with no debugging information, which is
348    /// what a convention that has a red zone says at `-O0` when nobody on the command line has said
349    /// otherwise.
350    fn default() -> Self {
351        Self {
352            frame_pointer: false,
353            red_zone: true,
354            stack_clash: false,
355            landing: false,
356            profile: Profile::No,
357            patch: Room::default(),
358            reorder: false,
359            reuse: false,
360            schedule: false,
361            align_loops: false,
362            accurate: None,
363            verify: false,
364            allocator: Allocator::Single,
365            goal: Goal::Speed,
366            switch: None,
367            sibling: false,
368            debug: false,
369        }
370    }
371}
372
373/// Compiles one function, from the IR the middle end produced to machine instructions.
374///
375/// The function is taken by reference that can be written through, because the first pass is an
376/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
377/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
378/// selection is not quite the IR the middle end produced, and this is the only place that is true.
379/// `--emit=ir` prints before any of this runs.
380///
381/// `elsewhere` is the one thing here that is a fact about the module rather than about the
382/// function, and it is passed in rather than looked up because this only ever sees the one
383/// function. What it decides is how the address of a name is come by, which is the difference
384/// between an address this file can measure to and one only the linker knows.
385///
386/// # Errors
387///
388/// The first thing in it this cannot lower, which is what [`lower::func`] reports, and one thing
389/// after it that is about the shape of the function rather than about an instruction, which is a
390/// frame that grows while it runs in a function whose flags say no frame may. Everything else after
391/// lowering works on machine instructions that exist, so it either runs or it is a bug in this
392/// crate.
393pub fn compile(
394    source: &mut ir::Func,
395    names: &mut Interner,
396    machine: &Machine,
397    elsewhere: &Elsewhere,
398    flags: Flags,
399) -> Result<mir::Func, Unsupported> {
400    let (mut fired, mut pressure, mut lowerings, mut stack) =
401        (Fired::new(), Pressure::new(), Lowerings::new(), StackUsage::new());
402    compile_recording(
403        source,
404        names,
405        machine,
406        elsewhere,
407        flags,
408        &mut Recording {
409            fired: &mut fired,
410            pressure: &mut pressure,
411            lowerings: &mut lowerings,
412            stack: &mut stack,
413        },
414    )
415}
416
417/// Somewhere to put what a compilation did along the way, for the flags that ask.
418///
419/// One of these rather than three parameters, because they are one thing: a caller either wants
420/// the measurements or does not, and a caller that does wants the same three to cover every
421/// function of every file on the command line.
422#[derive(Debug)]
423pub struct Recording<'a> {
424    /// Which lowering rules fired, for `-Zrule-coverage`.
425    pub fired: &'a mut Fired,
426    /// What the allocator had to put on the stack, for `-Zregister-pressure`.
427    pub pressure: &'a mut Pressure,
428    /// What the pre-selection lowering group did, for `-Zlowering`.
429    pub lowerings: &'a mut Lowerings,
430    /// How much stack each function takes, for `-fstack-usage`.
431    pub stack: &'a mut StackUsage,
432}
433
434/// The same compilation, with what it did along the way recorded.
435///
436/// Two functions rather than one that takes options, because a caller that does not want the
437/// numbers should not have to say so. What each field of the [`Recording`] is for is on the field,
438/// and all of them are added to rather than replaced, so a caller passes the same one for every
439/// function of a module and every module of a command line and gets the answer for all of them.
440///
441/// # Errors
442///
443/// The same as [`compile`]. A function that was refused contributes nothing to any of them, since
444/// a function that did not compile is not evidence about what a rule set or a frame would have
445/// done.
446pub fn compile_recording(
447    source: &mut ir::Func,
448    names: &mut Interner,
449    machine: &Machine,
450    elsewhere: &Elsewhere,
451    flags: Flags,
452    recording: &mut Recording<'_>,
453) -> Result<mir::Func, Unsupported> {
454    // Everything the machine has no rule for, rewritten into things it has, as one group rather
455    // than as a dozen lines here. What is in the group and what the order between its members is
456    // for are both in `crate::lowering`, which is where a new lowering is added.
457    let counting = recording.lowerings.wanted();
458    let ran = lowering::group(source, names, machine.conv, flags.goal, flags.switch, counting);
459    if !ran.switches.is_empty() {
460        let called = names.resolve(source.name).to_owned();
461        recording.lowerings.switched(&called, &ran.switches);
462    }
463    if counting {
464        let called = names.resolve(source.name).to_owned();
465        recording.lowerings.record(&called, ran);
466    }
467    // The function the program said it writes the whole of itself, which is what decides most of
468    // the frame below rather than being one more thing in it. Read here rather than beside the rest
469    // of the layout because the refusal a few lines down is the earliest thing that asks.
470    let naked = source.attrs.set.contains(ir::AttrSet::NAKED);
471    // Last thing before selection, because a `tail_call` ends its block and every lowering above
472    // is written against blocks that end the way the middle end left them. Only on a machine that
473    // can jump to a name, since the call stays a call on one that cannot.
474    if flags.sibling && machine.insts.away.is_some() {
475        tail::mark(source, names, elsewhere);
476    }
477    // Asked of the IR, where a call still says whom it calls. See [`tail::comes_back`].
478    let alone = tail::comes_back(source, names, elsewhere);
479    let lowered =
480        lower::func_for(source, names, machine.selector, machine.conv, elsewhere, flags.debug)?;
481    recording.fired.merge(&lowered.fired);
482    let lower::Lowered { mut func, mut stack, blocks, .. } = lowered;
483    // Straight after selection, because this is the last moment the machine blocks and the IR
484    // blocks still stand one for one, and the pass that reads the numbers is the very last one
485    // there is. See `crate::weights`.
486    if flags.reorder {
487        weights::carry(source, &blocks, &mut func);
488    }
489    // The one thing a frame that grows while it runs cannot be asked for, which is a refusal rather
490    // than wrong code.
491    if let Some(inst) = stack.grown_at {
492        // And the one thing a naked function cannot be asked for either, from the other side of the
493        // same fact. A frame that grows is reached from a frame pointer the prologue establishes,
494        // and there is no prologue here, so the address the array hands out would be counted from a
495        // register holding whatever the caller left in it.
496        if naked {
497            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Naked });
498        }
499        // The lowering refuses a variable length array that asks for more alignment than a call
500        // leaves the stack pointer on. A fixed local asking for it in the same function is the same
501        // refusal arrived at from the other side: the prologue would force the alignment, and
502        // forcing it and moving the stack pointer afterwards are two frames that each want the one
503        // register that still reaches the rest of the frame. See `Growing` in [`crate::frame`].
504        if stack.locals.iter().any(|local| local.align > machine.conv.stack_align) {
505            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Aligned });
506        }
507    }
508
509    // Before the fold below, which is the order section 37.6 puts the two in. A widening this takes
510    // out is one whose readers are sent to its source, and one of those readers may be an address
511    // computation, so asking which bits are read first means the fold sees the addresses as they
512    // will be rather than as they were.
513    bits::dead(&mut func, machine.bits, machine.shapes, names);
514
515    // After selection, because the address instruction and the one that reads it are both machine
516    // instructions only once selection has written them, and before allocation, because what makes
517    // the pair safe to put together is that a virtual register is written once. The addresses into
518    // the frame and into the caller's argument area go through it like anything else, and the two
519    // lists `finish` reads are rewritten as they do, so an address that ends up inside its reader
520    // is still an address the frame layout knows to write an offset into.
521    // A constant added to an index goes into the displacement first, so an address that took one
522    // is handed on to its readers with it already inside.
523    fold::offsets(&mut func, machine.insts, machine.shapes, names);
524    let mut pending = fold::Pending {
525        addresses: &mut stack.addresses,
526        arguments: &mut stack.arguments,
527        dynamic: &mut stack.dynamic,
528    };
529    fold::addresses(&mut func, machine.insts, machine.shapes, names, &mut pending);
530
531    // After that fold rather than before it, because what this puts inside an arithmetic
532    // instruction is a load's addressing mode and a load whose address is still a `lea` in front of
533    // it has nothing in its own mode worth carrying. Before allocation for the reason the fold is:
534    // a virtual register is written once, which is the whole of why the value the load produced
535    // cannot have changed between the two instructions this joins.
536    // The run that reads a place, computes on it and writes it back goes first, because it is three
537    // instructions the selector wrote and taking the load out of the middle one first would leave
538    // the same run written a second way.
539    combine::stores(&mut func, machine.shapes, machine.flags, names, &mut pending);
540    combine::loads(&mut func, machine.shapes, names, &mut pending);
541
542    // Whether this function carries a canary is the front end's answer, because what
543    // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
544    // here. What the machine does about it is this crate's answer, and a target with nowhere to
545    // keep the word a canary is copied from does nothing, which is what the driver refuses a
546    // command line over before any of this runs.
547    // Not in a naked function, whatever the command line asked of every function. The canary is a
548    // word the prologue copies into the frame and the check at the end reads back, so a function
549    // with neither has nowhere to put it and nowhere to read it from. gcc leaves one out too.
550    let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT) && !naked;
551    let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
552    // Nothing at all on a target with no hook to call, which is the same answer the protector gives
553    // on a target with nowhere to keep its word, and the driver refuses the command line over it
554    // before any of this runs.
555    let profile = match machine.conv.trace {
556        Some(_) => flags.profile,
557        None => Profile::No,
558    };
559    let base = stack.layout(Layout::new(machine.conv, machine.file));
560    let layout = Layout {
561        // The later hook reads the frame pointer to find out who called this function, so a
562        // function that calls it is given one whether or not anything else asked. A function that
563        // asked where its own frame is has the same claim on one, and for a plainer reason: the
564        // register is the answer.
565        //
566        // And not at all in a naked function, whatever any of that says. Establishing one is two
567        // instructions of a prologue there is none of, and a function that saves the machine state
568        // by hand is usually saving the frame pointer among it, which is what micropython's
569        // `nlr_push` does on its third line.
570        frame_pointer: !naked
571            && (flags.frame_pointer
572                || profile == Profile::Late
573                || stack.walks_frames
574                || stack.saves_place),
575        // And not in a naked function either, which is not about what the red zone costs but about
576        // what the refusal below has to be able to see. A local small enough to live below the
577        // stack pointer takes no bytes off it, so the frame comes out empty and a function that
578        // wanted somewhere to keep something would be told it asked for nothing. Taking the red
579        // zone away makes every local show up as bytes, and bytes are what gets refused.
580        red_zone: flags.red_zone && !naked,
581        protect: guard.is_some(),
582        naked,
583        // A protected function calls the one that does not come back, on the arm where the check
584        // failed, so it is not a leaf however few calls the program wrote in it. That is what
585        // takes the red zone away from it and what makes its frame leave the stack pointer where
586        // a call needs it. The later hook is a call in the same position and costs the same.
587        //
588        // The earlier one is not, and this is the one place the difference shows. It runs before
589        // the prologue has written anything, so the bytes below the stack pointer it uses are ones
590        // this function has not put anything in yet, and a leaf that keeps its locals down there
591        // stays a leaf. gcc leaves it alone too.
592        leaf: base.leaf && guard.is_none() && profile != Profile::Late,
593        ..base
594    };
595
596    // Before allocation as well, and asked here rather than where it is used because what it asks
597    // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
598    // written once and a physical one is not, so after allocation that question no longer has an
599    // answer.
600    let fusable = layout::fusable(&func, machine.branch, names);
601    // The same question about the selects on a comparison's byte, asked here for the same reason.
602    let choosable = choice::fusable(&func, machine.branch, names);
603
604    // In front of the splitting below, because what it does is take the values off the edges out of
605    // a computed `goto` and the splitting has no answer for one of those: the block they leave ends
606    // in a jump already, so neither end of the edge is somewhere a move can go.
607    split::indirect(&mut func, machine.branch, machine.insts, names);
608
609    // And after it, because what it puts a pad at is the block an address names and the pass above
610    // is what settles which block that is. The pad the prologue opens with is written much later,
611    // with the rest of the prologue, since the address it answers for is the function's own.
612    //
613    // Nothing at all on a target with nothing that marks an address as one an indirect branch may
614    // arrive at, which is the same answer the stack protector gives on a target with nowhere to
615    // keep its word, and the driver refuses the command line over it before any of this runs.
616    let landing = flags.landing.then_some(machine.insts.landing).flatten();
617    split::pads(&mut func, machine.insts, landing, names);
618
619    // Before allocation, because an edge that carries values into a block arrived at more than
620    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
621    // values turn into, and the allocator asserts rather than guessing.
622    split::critical(&mut func);
623
624    // Before allocation, because how far the address of a local gets is a question about values and
625    // a value is written once only until the allocator's rewrite has been through. What is done
626    // with the answer waits until afterwards, since the liveness it is read against is the
627    // allocator's. See [`crate::slots`].
628    //
629    // Only asked at all where the locals are allowed to share, since this is the whole of what says
630    // whether a local may. The spill slots are laid out either way and this says nothing about
631    // them.
632    let reach = (flags.reuse && !alone)
633        .then(|| slots::reach(&func, &stack.addresses, stack.locals.len(), machine.insts, names));
634
635    // The instructions as they are now, for the locals the front end kept in values. The
636    // allocator's liveness is counted along this order and the rewrite is about to put spills,
637    // reloads and edge moves in among them, so the list has to be taken before it runs. Only in a
638    // function that named something, since a function that named nothing has no use for it. See
639    // [`crate::kept`].
640    //
641    // Or where a local the program declared may share its bytes, which is only where there is a
642    // `reach`, since a local that shares is in the frame over part of the function and the part is
643    // asked about the same way.
644    //
645    // Only for a build that writes debugging information, since the stretches are read by nothing
646    // else.
647    let line = (flags.debug
648        && (!func.named.is_empty() || (reach.is_some() && !stack.declared.is_empty())))
649    .then(|| kept::before(&func));
650
651    // Which arithmetic reads its two sources either way round, so the allocator may write the
652    // answer over whichever of the two is finished with. Marked here rather than at selection
653    // because every pass in between that rewrites an instruction would have to carry the mark.
654    commuting(&mut func, machine.shapes, names);
655
656    // The single pass allocator in a function that can be come back into. A value live across the
657    // call that comes back has to be read by the second arrival from memory the first arm did not
658    // write, and the backtracking allocator is free to leave it in a register the first arm writes.
659    let allocator = if alone { Allocator::Single } else { flags.allocator };
660    let called = names.resolve(func.name).to_owned();
661    let allocation =
662        rucc_regalloc::run_with(&mut func, &machine.env, &called, flags.verify, allocator);
663    recording.pressure.record(&called, Cost::of(&allocation));
664
665    // After allocation, because the largest area in most frames is the spill slots and nothing
666    // knows how many of those there are until the allocator has finished running out of registers,
667    // and because a spill slot cannot be shared with a local until it is known there is one.
668    let widths = frame::widths(&layout, &allocation);
669    // Nothing shares in a function that can be come back into, since the second arrival reads
670    // bytes the liveness says nobody wants. See [`tail::comes_back`].
671    let share = if alone {
672        Slots::apart(&stack.locals, &widths)
673    } else {
674        Slots::share(&func, reach.as_ref(), &allocation, &stack.locals, &widths)
675    };
676    let layout = Layout { share: Some(&share), ..layout };
677    let frame = Frame::of(&func, &allocation, &layout);
678    // The one thing a naked function cannot be given. Everything else the attribute asks for is
679    // something left out, and leaving something out always works; bytes are the one thing the body
680    // may want that only a prologue provides. A local, a spilled value and the arguments of a call
681    // are the three ways to want them, and the answer to all three is the same sentence.
682    if naked && frame.size() > 0 {
683        return Err(Unsupported::Naked { bytes: frame.size() });
684    }
685    // Here because the frame is settled and nothing after this changes how big it is. The name is
686    // the one the source spelled, since that is what gcc's report says and what a person reading
687    // it looks for, and a renamed function is the one place it differs from the symbol.
688    recording.stack.record(Usage {
689        name: names.resolve(source.spelled.unwrap_or(source.name)).to_owned(),
690        named: source.named,
691        declared: source.declared,
692        bytes: frame.usage(),
693        dynamic: frame.grows(),
694    });
695
696    // Here because this is where the two halves of the answer are both in hand: which local is
697    // which declaration came down from selection, and where a local is was settled a line ago.
698    // Nothing further on could work it out, since the frame is not carried past this function and
699    // an offset in a finished instruction says nothing about what the bytes it reaches are for.
700    //
701    // Whatever the command line said about debugging information, because the list is one entry
702    // per local the program named and a function has tens of those at most. Asking the flags would
703    // cost more to thread down here than the list costs to build.
704    //
705    // A local that went in beside something else is left off, because its bytes are its own only
706    // where it is wanted and an answer good at every address would have a debugger print whatever
707    // took its place. It gets stretches instead, at the end with the locals kept in values.
708    func.locals = stack
709        .declared
710        .iter()
711        .filter(|&&(local, _)| share.shared(local).is_none())
712        .filter_map(|&(local, decl)| Some((decl, frame.from_frame_base(local)?)))
713        .collect();
714    let framed: Vec<(u32, i32, &[rucc_regalloc::live::Range])> = stack
715        .declared
716        .iter()
717        .filter_map(|&(local, decl)| {
718            Some((decl, frame.from_frame_base(local)?, share.shared(local)?))
719        })
720        .collect();
721    func.sharing = framed.iter().map(|&(decl, _, _)| decl).collect();
722
723    let scratch = machine.env.scratch(machine.conv.int_class);
724    let protect = guard.map(|guard| Protect {
725        guard,
726        branch: machine.branch,
727        scratch: [scratch[0], scratch[1]],
728    });
729    // A target with no instruction that touches a page without changing it does nothing about the
730    // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
731    // Every target this crate has a back end for has one.
732    //
733    // Or where the platform reaches the pages of every frame whatever the command line said, which
734    // is Windows. The prologue there calls a routine rather than walking, but a frame that grows
735    // while it runs is walked in the body either way: the routine takes its size in a register the
736    // allocator hands out and destroys two more, which is answerable in a prologue and not in the
737    // middle of a function, and the walk needs nothing but the two registers already held back.
738    let probe = (flags.stack_clash || machine.conv.chkstk.is_some())
739        .then_some(machine.insts.probe.as_ref())
740        .flatten()
741        .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
742    let trace = machine.conv.trace.and_then(|trace| match profile {
743        Profile::No => None,
744        Profile::Early => Some(Tracing { name: trace.early, early: true }),
745        Profile::Late => Some(Tracing { name: trace.late, early: false }),
746    });
747    // And once more for the room a patcher was promised, which is a run of the shortest
748    // instruction that does nothing and so needs the target to have one. Nothing is written on a
749    // target that does not, rather than a run of something longer: the flag counts bytes, and a
750    // patcher writing over the room starts at its front and wants every byte in it to be a place
751    // it could have started at.
752    let pad = flags.patch.any().then_some(machine.insts.pad).flatten().map(|name| Padding {
753        name,
754        before: flags.patch.before,
755        after: flags.patch.after,
756    });
757    let convention = Convention {
758        protect,
759        probe,
760        landing,
761        trace,
762        pad,
763        ..Convention::new(machine.conv, machine.insts)
764    };
765    let moves = finish(&mut func, &allocation, &frame, &stack, convention, names);
766
767    // After the moves are written, because a spill and the reload of it are written by different
768    // decisions of the allocator and what stands between the two is settled by the function they
769    // both went into. Before the layout, because the layout is where the instruction sequence
770    // stops being something a pass may edit.
771    copies::clean(&mut func, &moves, machine.shapes, machine.insts, machine.conv, names);
772
773    // After the moves are cleaned up, since that pass follows what the scratch registers hold, and
774    // before the schedule, which should see the extra `add` as the instruction it is.
775    far(&mut func, machine.insts, machine.conv, scratch, names);
776
777    // After the allocator's moves have been cleaned up, because a schedule chosen around a move
778    // that is about to be taken out is a schedule built around an instruction that is not in the
779    // output. Before the layout, because the layout is the freeze: it writes the jumps the block
780    // order needs and it puts a comparison and the branch that reads it together, and neither
781    // survives an instruction being moved in afterwards. That is section 38.6's placement, and the
782    // reason it is after allocation rather than before is in [`crate::schedule`].
783    if flags.schedule {
784        schedule::insts(
785            &mut func,
786            machine.timing,
787            machine.shapes,
788            machine.flags,
789            names,
790            flags.accurate.unwrap_or(machine.timing.accurate),
791            &fusable,
792        );
793    }
794
795    // Last, because everything before this finds the blocks a function returns from by looking
796    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
797    layout::blocks(&mut func, machine.branch, names, &fusable, flags.reorder);
798
799    // After the layout for the reason the branches wait for it: a select that reads what a
800    // comparison left is a pair with nothing allowed between, and nothing past here puts anything
801    // there. Before the compare pass, since the comparison this keeps is one that pass may find
802    // was already made.
803    choice::moves(&mut func, machine.branch, machine.flags, machine.shapes, names, &choosable);
804
805    // After the layout rather than before it, which is the whole of what makes it safe. What a
806    // comparison leaves for the instruction behind it to read is not a register and nothing may
807    // come between the two, and the layout is the other pass that writes such a pair. Running
808    // here means there is nothing left that could put an instruction in the middle of one.
809    compare::redundant(&mut func, machine.flags, machine.shapes, names);
810
811    // After that rather than before it, because a comparison it takes out is a write of the
812    // condition state that is gone with it, and this pass is asking which writes of that state are
813    // read. Running in front would see writes the output does not have and turn down rewrites that
814    // are allowed. Nothing here moves an instruction or changes a block, so being behind the
815    // layout's freeze costs it nothing.
816    shorten::shorter(&mut func, machine.short, machine.flags, machine.shapes, names, flags.goal);
817
818    // Once the blocks will not move again, since a head is a block a jump runs backwards to and
819    // which way a jump runs is the layout's answer. Nothing below adds or takes out a block.
820    if flags.align_loops {
821        func.heads = layout::heads(&func);
822    }
823
824    // After everything that edits instructions, because a call is the one instruction all of them
825    // leave alone and a jump out of the function is one some of them would not know about. Nothing
826    // before this sees anything but a call, a return and an epilogue, which is right on its own.
827    tail::jumps(&mut func, &stack.tails, machine.insts, names);
828
829    // Last of all, because a stretch is named by the instructions at either end of it and every
830    // pass above is free to take an instruction out or move one. The frame is wanted here as well
831    // as above, since a value the allocator spilled is in the frame over its stretch rather than in
832    // a register, and it is the same distance from the call frame address the locals were given.
833    func.kept = match line {
834        Some(line) => kept::of(&func, &line, &allocation, &frame, &framed),
835        None => Vec::new(),
836    };
837    Ok(func)
838}
839
840/// Marks every instruction the machine says reads its two sources either way round.
841fn commuting(func: &mut mir::Func, shapes: &MachineInsts, names: &Interner) {
842    let insts: Vec<mir::Inst> = func.blocks().flat_map(|block| func.insts(block)).collect();
843    for inst in insts {
844        if shapes.commutes(names.resolve(func[inst].opcode.name())) {
845            func[inst].flags = func[inst].flags.with(mir::Flags::COMMUTES);
846        }
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
853    use rucc_target::x86_64::{REGS, SYSV, WIN64};
854
855    use super::*;
856
857    /// A function of two integers, and the block to fill.
858    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
859        let mut names = Interner::new();
860        let mut func = Func::new(names.intern("f"), Signature::new());
861        let block = func.create_block();
862        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
863        (names, func, block, values)
864    }
865
866    /// The AArch64 machine holds back the two registers a veneer may write and two vector
867    /// registers nothing is passed in, and hands out everything else the convention orders.
868    #[test]
869    fn the_aarch64_machine_holds_back_what_a_veneer_writes() {
870        use rucc_target::aarch64::{self, AAPCS64, FPR, GPR, v};
871        let machine = Machine::aarch64(&AAPCS64);
872        assert_eq!(machine.env.scratch(GPR), [aarch64::X16, aarch64::X17]);
873        assert_eq!(machine.env.scratch(FPR), [v(30), v(31)]);
874        assert_eq!(machine.env.order(GPR), AAPCS64.int_order);
875        assert_eq!(machine.env.order(FPR).len(), 30);
876        assert_eq!(machine.insts.prefix, "a64.");
877        assert_eq!(machine.timing.prefix, machine.shapes.prefix);
878    }
879
880    /// `int f(int a) { return g(a) + a; }` compiled for AArch64 and printed.
881    fn aarch64_call() -> String {
882        let i32 = Type::int(32);
883        let (mut names, mut source, block, args) = blank(&[i32]);
884        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
885        let callee = names.intern("g");
886        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
887        let got = source[call].first_result.expect("an integer comes back");
888        let mut build = Builder::new(&mut source, block);
889        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
890        build.ret(&[sum]);
891
892        let machine = Machine::aarch64(&aarch64::AAPCS64);
893        let out =
894            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
895                .expect("every instruction has a rule");
896        mir::print_func(&out, &names, &aarch64::REGS)
897    }
898
899    #[test]
900    fn an_aarch64_function_that_calls_keeps_its_return_address_in_a_frame_record() {
901        let text = aarch64_call();
902        let lines: Vec<&str> = text.lines().map(str::trim).collect();
903        let first = |what: &str| lines.iter().position(|line| line.contains(what));
904        // The call writes over x30, so it goes on the stack with x29 before anything else, and the
905        // frame pointer is pointed at the pair.
906        let record = first("a64.push_pair_64 $x29, $x30").unwrap_or_else(|| panic!("{text}"));
907        let pointed = first("$x29 = a64.mov_rr_64 $sp").unwrap_or_else(|| panic!("{text}"));
908        let call = first("a64.bl").unwrap_or_else(|| panic!("{text}"));
909        let back = first("a64.pop_pair_64").unwrap_or_else(|| panic!("{text}"));
910        let ret =
911            lines.iter().position(|&line| line == "a64.ret").unwrap_or_else(|| panic!("{text}"));
912        assert!(record < pointed && pointed < call && call < back && back < ret, "{text}");
913        // Every push moves the stack pointer by sixteen, so whatever the frame takes on top of them
914        // is a multiple of sixteen too, and nothing is taken for the word x86 would have owed.
915        for line in &lines {
916            if let Some(rest) = line.split("a64.sub_ri_64 $sp, ").nth(1) {
917                let size: u32 = rest.parse().unwrap_or_else(|_| panic!("{text}"));
918                assert_eq!(size % 16, 0, "{text}");
919            }
920        }
921    }
922
923    #[test]
924    fn an_aarch64_leaf_keeps_no_frame_record() {
925        let i32 = Type::int(32);
926        let (mut names, mut source, block, args) = blank(&[i32, i32]);
927        let mut build = Builder::new(&mut source, block);
928        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
929        build.ret(&[sum]);
930
931        let machine = Machine::aarch64(&aarch64::AAPCS64);
932        let out =
933            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
934                .expect("every instruction has a rule");
935        let text = mir::print_func(&out, &names, &aarch64::REGS);
936        assert!(!text.contains("push"), "{text}");
937        assert!(text.contains("a64.add_rr_32"), "{text}");
938    }
939
940    #[test]
941    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
942        let i32 = Type::int(32);
943        let (mut names, mut source, block, args) = blank(&[i32, i32]);
944        let mut build = Builder::new(&mut source, block);
945        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
946        build.ret(&[sum]);
947
948        let machine = Machine::x86_64(&SYSV);
949        let out =
950            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
951                .expect("every instruction has a rule");
952
953        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
954        // frame at all, so there is no prologue to see. The one move left is the one the machine's
955        // addition needs, since the sum is written into the register one of the two operands was
956        // read from and the return wants it in `rax`. The addition is marked as reading them
957        // either way round, which is why the allocator was free to pick.
958        assert_eq!(
959            mir::print_func(&out, &names, &REGS),
960            "mfunc @f {\n\
961             block0:\n    \
962             $rdi($rdi) = x64.arg_val_32\n    \
963             $rsi($rsi) = x64.arg_val_32\n    \
964             $rdi(reuse 1) = x64.add_rr_32 commutes $rdi, $rsi\n    \
965             $rax = x64.mov_rr_64 $rdi\n    \
966             x64.ret_val_32 $rax($rax)\n    \
967             x64.ret\n\
968             }\n"
969        );
970    }
971
972    #[test]
973    fn a_declared_local_comes_out_saying_how_far_below_the_call_frame_address_it_is() {
974        let i32 = Type::int(32);
975        let (mut names, mut source, block, args) = blank(&[i32]);
976        let mut build = Builder::new(&mut source, block);
977        let info = rucc_ir::MemInfo {
978            size: 4,
979            align: 4,
980            order: rucc_ir::MemOrder::NotAtomic,
981            tbaa: None,
982            owns: 0,
983            restrict: Restrict::NONE,
984        };
985        let mem = build.func().add_mem(info);
986        let slot = build.value(
987            ir::InstData { extra: ir::Extra::Mem(mem), ..ir::InstData::new(Opcode::Alloca) },
988            Type::PTR,
989        );
990        build.func().declare_mem(mem, 5);
991        build.store(args[0], slot, info, IrFlags::default());
992        let loaded = build.load(i32, slot, info, IrFlags::default());
993        build.ret(&[loaded]);
994
995        let machine = Machine::x86_64(&SYSV);
996        let out =
997            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
998                .expect("every instruction has a rule");
999
1000        // `int f(int a) { int x = a; return x; }` with the address of `x` taken, so it is four
1001        // bytes in the frame. A leaf this small lives in the red zone, so the stack pointer never
1002        // moves. What is below it is a whole word, since everything a frame holds is counted in
1003        // words whether or not it fills one, and the call frame address is one more word above the
1004        // stack pointer for the return address the call pushed.
1005        assert_eq!(out.locals, vec![(5, -16)]);
1006    }
1007
1008    #[test]
1009    fn a_local_kept_in_a_value_comes_out_saying_which_register_holds_it_and_over_what() {
1010        let i32 = Type::int(32);
1011        let (mut names, mut source, block, args) = blank(&[i32]);
1012        let mut build = Builder::new(&mut source, block);
1013        let sum = build.binary(Opcode::Add, args[0], args[0], IrFlags::default());
1014        build.func().declare_value(sum, 5);
1015        build.ret(&[sum]);
1016
1017        let machine = Machine::x86_64(&SYSV);
1018        let flags = Flags { debug: true, ..Flags::default() };
1019        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1020            .expect("every instruction has a rule");
1021
1022        // `int f(int a) { int x = a + a; return x; }` with nothing taking the address of `x`, so
1023        // it never reaches the frame and the only answer about it is a register. The sum is
1024        // written by the addition and read by the move that puts it where the return wants it, so
1025        // the stretch is one instruction long and it is the move rather than the addition.
1026        assert_eq!(out.kept.len(), 1, "one stretch: {:?}", out.kept);
1027        assert_eq!(out.kept[0].decl, 5);
1028        assert!(matches!(out.kept[0].at, mir::Where::Reg { .. }), "a register: {:?}", out.kept[0]);
1029        assert!(out.locals.is_empty(), "nothing in the frame: {:?}", out.locals);
1030    }
1031
1032    /// What `-Zlowering` is built out of, and the reason it is worth a test here rather than only
1033    /// in `crate::lowering`: the group has to be the thing this pipeline runs. A lowering added to
1034    /// a line of this function instead of to `Step::GROUP` would still work and would still be
1035    /// untested, and the record coming back with one entry per member is what catches it.
1036    #[test]
1037    fn every_member_of_the_lowering_group_is_run_by_the_compilation_and_says_what_it_did() {
1038        let i32 = Type::int(32);
1039        let (mut names, mut source, block, args) = blank(&[i32]);
1040        let mut build = Builder::new(&mut source, block);
1041        let swapped = build.unary(Opcode::Bswap, args[0], i32);
1042        build.ret(&[swapped]);
1043
1044        let mut lowerings = Lowerings::asked(true);
1045        compile_recording(
1046            &mut source,
1047            &mut names,
1048            &Machine::x86_64(&SYSV),
1049            &Elsewhere::default(),
1050            Flags::default(),
1051            &mut Recording {
1052                fired: &mut Fired::new(),
1053                pressure: &mut Pressure::new(),
1054                stack: &mut StackUsage::new(),
1055                lowerings: &mut lowerings,
1056            },
1057        )
1058        .expect("every instruction has a rule");
1059
1060        assert_eq!(lowerings.functions(), 1);
1061        let listing = lowerings.listing();
1062        assert!(listing.contains("lowering f\n"), "{listing}");
1063        for step in lowering::Step::GROUP {
1064            assert!(listing.contains(step.name()), "{} did not run: {listing}", step.name());
1065        }
1066        // The byte reversal went through the group rather than reaching the selector, which has no
1067        // rule for one.
1068        assert!(listing.contains("bytes"), "{listing}");
1069        assert!(!listing.contains("left 1"), "something the group answers for survived: {listing}");
1070    }
1071
1072    /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
1073    /// The second function adds to the first rather than replacing it, which is what makes one of
1074    /// these files the answer for a whole command line rather than for whichever function was last.
1075    #[test]
1076    fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
1077        let i32 = Type::int(32);
1078        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1079        let mut build = Builder::new(&mut source, block);
1080        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
1081        build.ret(&[sum]);
1082
1083        let machine = Machine::x86_64(&SYSV);
1084        let mut fired = Fired::new();
1085        compile_recording(
1086            &mut source,
1087            &mut names,
1088            &machine,
1089            &Elsewhere::default(),
1090            Flags::default(),
1091            &mut Recording {
1092                fired: &mut fired,
1093                pressure: &mut Pressure::new(),
1094                stack: &mut StackUsage::new(),
1095                lowerings: &mut Lowerings::asked(true),
1096            },
1097        )
1098        .expect("every instruction has a rule");
1099        let one = fired.count();
1100        assert!(one > 0, "an add and a return went through the table and nothing was recorded");
1101
1102        let listing = fired.listing(&select::x86_64::TABLE);
1103        assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
1104        assert!(
1105            listing.contains(&format!("{one} of ")),
1106            "{}",
1107            listing.lines().next().unwrap_or("")
1108        );
1109
1110        // The same rules again plus the ones a subtraction needs, into the same record.
1111        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1112        let mut build = Builder::new(&mut source, block);
1113        let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
1114        build.ret(&[difference]);
1115        compile_recording(
1116            &mut source,
1117            &mut names,
1118            &machine,
1119            &Elsewhere::default(),
1120            Flags::default(),
1121            &mut Recording {
1122                fired: &mut fired,
1123                pressure: &mut Pressure::new(),
1124                stack: &mut StackUsage::new(),
1125                lowerings: &mut Lowerings::asked(true),
1126            },
1127        )
1128        .expect("every instruction has a rule");
1129        assert!(fired.count() > one, "a subtraction is not an addition");
1130    }
1131
1132    #[test]
1133    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
1134        let i32 = Type::int(32);
1135        let (mut names, mut source, block, args) = blank(&[i32]);
1136        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1137        let callee = names.intern("g");
1138        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1139        let got = source[call].first_result.expect("an integer comes back");
1140        let mut build = Builder::new(&mut source, block);
1141        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
1142        build.ret(&[sum]);
1143
1144        let machine = Machine::x86_64(&SYSV);
1145        let out =
1146            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1147                .expect("every instruction has a rule");
1148
1149        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
1150        // register the value that outlives the call went to is one the prologue saves.
1151        let text = mir::print_func(&out, &names, &REGS);
1152        assert!(text.contains("x64.push_64 $rbx"), "{text}");
1153        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
1154        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
1155        assert!(!text.contains('%'), "{text}");
1156    }
1157
1158    /// `int f(int a, ...) { return g(a, ...); }` with that many arguments, compiled with sibling
1159    /// calls on or off, as the machine code that comes out.
1160    fn tail(count: usize, sibling: bool) -> String {
1161        let i32 = Type::int(32);
1162        let params = vec![i32; count];
1163        let mut names = Interner::new();
1164        let signature = Signature::new().with_params(&params).with_returns(&[i32]);
1165        let mut source = Func::new(names.intern("f"), signature.clone());
1166        let block = source.create_block();
1167        let args: Vec<_> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
1168        let sig = source.add_signature(signature);
1169        let callee = names.intern("g");
1170        let call = Builder::new(&mut source, block).call(callee, sig, &args);
1171        let got = source[call].first_result.expect("an integer comes back");
1172        Builder::new(&mut source, block).ret(&[got]);
1173
1174        let machine = Machine::x86_64(&SYSV);
1175        let flags = Flags { sibling, ..Flags::default() };
1176        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1177            .expect("every instruction has a rule");
1178        mir::print_func(&out, &names, &REGS)
1179    }
1180
1181    /// A call whose answer is the answer ends in a jump to it once the frame is given back, and
1182    /// only when the flag says so.
1183    #[test]
1184    fn a_call_in_tail_position_is_a_jump_when_asked_for() {
1185        let text = tail(2, true);
1186        assert!(text.contains("x64.jmp_away @g"), "{text}");
1187        assert!(!text.contains("x64.call"), "{text}");
1188        assert!(!text.contains("x64.ret"), "{text}");
1189
1190        let text = tail(2, false);
1191        assert!(text.contains("x64.call"), "{text}");
1192        assert!(text.contains("x64.ret"), "{text}");
1193    }
1194
1195    /// Eight arguments are two more than there are registers for, so two go in the argument area
1196    /// at the bottom of this frame, and the call has to be made while the frame is still there.
1197    #[test]
1198    fn a_call_that_needs_the_argument_area_stays_a_call() {
1199        let text = tail(8, true);
1200        assert!(text.contains("x64.call"), "{text}");
1201        assert!(!text.contains("x64.jmp_away"), "{text}");
1202    }
1203
1204    #[test]
1205    fn the_other_convention_is_the_same_function_somewhere_else() {
1206        let i32 = Type::int(32);
1207        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1208        let mut build = Builder::new(&mut source, block);
1209        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
1210        build.ret(&[sum]);
1211
1212        let machine = Machine::x86_64(&WIN64);
1213        let out =
1214            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1215                .expect("every instruction has a rule");
1216
1217        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
1218        // the whole of what changed, and it changed because the convention was asked.
1219        let text = mir::print_func(&out, &names, &REGS);
1220        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
1221        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
1222        assert!(!text.contains("$rdi"), "{text}");
1223    }
1224
1225    #[test]
1226    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
1227        let i32 = Type::int(32);
1228        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1229        let then = source.create_block();
1230        let join = source.create_block();
1231        let got = source.append_param(join, i32);
1232        let mut build = Builder::new(&mut source, entry);
1233        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1234        build.br_if(cond, then, &[], join, &[args[1]]);
1235        Builder::new(&mut source, then).jump(join, &[args[0]]);
1236        Builder::new(&mut source, join).ret(&[got]);
1237
1238        let machine = Machine::x86_64(&SYSV);
1239        let out =
1240            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1241                .expect("every instruction has a rule");
1242
1243        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
1244        // there, which is the pass between lowering and allocation doing its job. Without it the
1245        // allocator would have asserted rather than compiled this.
1246        assert_eq!(out.block_count(), 4);
1247
1248        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
1249        // this pins. The branch became a test and one jump, and it is the jump taken when the
1250        // condition failed, because the arm the condition is true for is the block laid out next
1251        // and a block falls into the block laid out next. The other arm is the empty block the
1252        // edge splitting left, which is where the move the edge carries ended up, and it falls
1253        // into the join as well. What is left is one jump in the whole function. Both arms write
1254        // the join's parameter straight into `rax`, because the return at the bottom insists on
1255        // that register and the moves the edges carry are free to name it.
1256        let text = mir::print_func(&out, &names, &REGS);
1257        assert_eq!(
1258            text,
1259            "mfunc @f {\n\
1260             block0:\n    \
1261             $rdi($rdi) = x64.arg_val_32\n    \
1262             $rsi($rsi) = x64.arg_val_32\n    \
1263             x64.cmp_rr_32 $rdi, $rsi\n    \
1264             x64.jcc_ge block2, block1\n\
1265             \nblock1:\n    \
1266             $rax = x64.mov_rr_64 $rdi\n    \
1267             x64.jmp block3\n\
1268             \nblock2:\n    \
1269             $rax = x64.mov_rr_64 $rsi, block3\n\
1270             \nblock3:\n    \
1271             x64.ret_val_32 $rax($rax)\n    \
1272             x64.ret\n\
1273             }\n"
1274        );
1275    }
1276
1277    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
1278    /// the smallest program that caught two ways of losing a value. Both were found by running
1279    /// what came out rather than by reading it, and both are pinned here rather than only where
1280    /// they were fixed, because what is wrong with either of them is only visible in the whole
1281    /// function.
1282    #[test]
1283    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
1284        let i32 = Type::int(32);
1285        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1286        let head = source.create_block();
1287        let body = source.create_block();
1288        let exit = source.create_block();
1289        let left = source.append_param(head, i32);
1290        let right = source.append_param(head, i32);
1291        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
1292        let mut build = Builder::new(&mut source, head);
1293        let zero = build.iconst(i32, 0);
1294        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
1295        build.br_if(more, body, &[], exit, &[left]);
1296        let mut build = Builder::new(&mut source, body);
1297        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
1298        build.jump(head, &[right, rest]);
1299        let result = source.append_param(exit, i32);
1300        Builder::new(&mut source, exit).ret(&[result]);
1301
1302        let machine = Machine::x86_64(&SYSV);
1303        let out =
1304            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1305                .expect("every instruction has a rule");
1306
1307        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
1308        // things in here were wrong and each of them returned three from a program that gcc
1309        // returns forty two from.
1310        //
1311        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
1312        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
1313        // of a block used to go in front of the last instruction, on the reasoning that the last
1314        // instruction is the branch, and the block's jump is not an instruction until the layout
1315        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
1316        //
1317        // The second is in the loop body. A division writes both a quotient and a remainder, and
1318        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
1319        // be given the same register as the remainder, because a value written early was live at
1320        // one point and that point was in front of where the remainder was written. The copy that
1321        // takes the quotient nowhere then landed on top of the remainder. The remainder is written
1322        // early as well now, which is a separate thing the target has to say and is why both
1323        // answers read `early` here: `rdx` is filled by the sign extension before the division
1324        // reads its divisor, so nothing else may be sitting in it at that point either.
1325        //
1326        // What asks whether the second argument is zero reads as a test rather than a comparison
1327        // because `crate::shorten` runs last and writes the shorter of the two, which asks the
1328        // machine the same thing and leaves the same condition state for the jump behind it.
1329        assert_eq!(
1330            mir::print_func(&out, &names, &REGS),
1331            "mfunc @f {\n\
1332             block0:\n    \
1333             $rdi($rdi) = x64.arg_val_32\n    \
1334             $rsi($rsi) = x64.arg_val_32\n    \
1335             $rcx = x64.mov_rr_64 $rdi, block1\n\
1336             \nblock1:\n    \
1337             x64.test_rr_32 $rsi\n    \
1338             x64.jcc_e block3, block2\n\
1339             \nblock2:\n    \
1340             $rax = x64.mov_rr_64 $rcx\n    \
1341             early $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
1342             $rdi = x64.mov_rr_64 $rax\n    \
1343             $rcx = x64.mov_rr_64 $rsi\n    \
1344             $rsi = x64.mov_rr_64 $rdx\n    \
1345             x64.jmp block1\n\
1346             \nblock3:\n    \
1347             $rax = x64.mov_rr_64 $rcx\n    \
1348             x64.ret_val_32 $rax($rax)\n    \
1349             x64.ret\n\
1350             }\n"
1351        );
1352    }
1353
1354    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
1355    /// a branch in it is the one where that is worth checking: after the layout has run, where a
1356    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
1357    /// parser has to put it back on the block it came off.
1358    #[test]
1359    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
1360        let i32 = Type::int(32);
1361        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1362        let then = source.create_block();
1363        let join = source.create_block();
1364        let got = source.append_param(join, i32);
1365        let mut build = Builder::new(&mut source, entry);
1366        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1367        build.br_if(cond, then, &[], join, &[args[1]]);
1368        Builder::new(&mut source, then).jump(join, &[args[0]]);
1369        Builder::new(&mut source, join).ret(&[got]);
1370
1371        let machine = Machine::x86_64(&SYSV);
1372        let out =
1373            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1374                .expect("every instruction has a rule");
1375
1376        let text = mir::print_func(&out, &names, &REGS);
1377        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
1378        assert_eq!(mir::print(&read, &names, &REGS), text);
1379    }
1380
1381    #[test]
1382    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
1383        let f80 = Type::float(rucc_ir::Float::F80);
1384        let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
1385        Builder::new(&mut source, block).ret(&args);
1386
1387        // One of these comes back on the x87 stack and the other in a register, and the only pair
1388        // that stack holds is two `long double` halves of one complex value. So this is refused
1389        // rather than lowered, and it is the convention that refuses it rather than anything about
1390        // the instructions.
1391        let machine = Machine::x86_64(&SYSV);
1392        let failed =
1393            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1394                .expect_err("a long double cannot come back beside another value");
1395        assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
1396    }
1397
1398    /// A `long double` in and a `long double` out, which is the whole of what the convention says
1399    /// about the type and is two different answers rather than one.
1400    ///
1401    /// It arrives in the caller's argument area, so what the parameter is is the address of the
1402    /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
1403    /// return is an `fld` and nothing else, and the value is still on that stack when the function
1404    /// returns, which is the one time anything here leaves it that way.
1405    ///
1406    /// The addresses are gone from the instruction listing, which is [`crate::fold`]: an argument's
1407    /// address is a `lea` off the stack pointer and the `fld` that reads it has room for that
1408    /// address itself, so the offset the frame layout works out is written into the `fld`.
1409    #[test]
1410    fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
1411        let f80 = Type::float(rucc_ir::Float::F80);
1412        let (mut names, mut source, block, args) = blank(&[f80, f80]);
1413        let mut build = Builder::new(&mut source, block);
1414        let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
1415        build.ret(&[sum]);
1416
1417        let machine = Machine::x86_64(&SYSV);
1418        let out =
1419            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1420                .expect("every instruction has a rule");
1421
1422        let text = mir::print_func(&out, &names, &REGS);
1423        // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
1424        // of a register, and the answer left on the stack by the last instruction in the function.
1425        assert!(text.contains("x64.fld_t [$rsp + 32]"), "{text}");
1426        assert!(text.contains("x64.fld_t [$rsp + 48]"), "{text}");
1427        assert!(!text.contains("x64.lea_64"), "an address every reader took is gone: {text}");
1428        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
1429        // What comes after the `fld` is the epilogue, which gives the frame back and touches
1430        // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
1431        let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
1432        assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rsp]"], "{text}");
1433    }
1434
1435    /// A `_Complex long double` goes back on the x87 stack as two values, the real half on top.
1436    ///
1437    /// Each half arrives in memory like any `long double`, and the return loads the imaginary half
1438    /// first so that the real one is in `st(0)` above it, which is where the caller looks for each.
1439    /// A call to such a function takes both off again, the real half first, so the stack is empty
1440    /// by the time anything else touches it.
1441    #[test]
1442    fn a_complex_long_double_goes_back_on_the_x87_stack_as_a_pair() {
1443        let f80 = Type::float(rucc_ir::Float::F80);
1444        let (mut names, mut source, block, args) = blank(&[f80, f80]);
1445        Builder::new(&mut source, block).ret(&[args[1], args[0]]);
1446
1447        let machine = Machine::x86_64(&SYSV);
1448        let out =
1449            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1450                .expect("the pair is what the convention asks for");
1451        let text = mir::print_func(&out, &names, &REGS);
1452        // The second parameter is the real half here, so it is loaded last and ends up on top. There
1453        // is no frame, so the first parameter is right above the return address.
1454        let lines: Vec<&str> = text.lines().map(str::trim).collect();
1455        let imaginary = lines.iter().position(|&line| line == "x64.fld_t [$rsp + 8]");
1456        let real = lines.iter().position(|&line| line == "x64.fld_t [$rsp + 24]");
1457        assert!(imaginary.is_some() && real == imaginary.map(|at| at + 1), "{text}");
1458        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
1459
1460        let (mut names, mut source, block, _) = blank(&[]);
1461        let sig = source.add_signature(Signature::new().with_returns(&[f80, f80]));
1462        let callee = names.intern("g");
1463        let call = Builder::new(&mut source, block).call(callee, sig, &[]);
1464        let halves: Vec<ir::Value> = source[call].results().collect();
1465        Builder::new(&mut source, block).ret(&[halves[1], halves[0]]);
1466        let out =
1467            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1468                .expect("a call can take the pair off");
1469        let text = mir::print_func(&out, &names, &REGS);
1470        assert_eq!(text.matches("x64.fstp_t").count(), 2, "{text}");
1471        assert_eq!(text.matches("x64.fld_t").count(), 2, "{text}");
1472    }
1473
1474    /// The whole of the second register class, end to end: two floats arrive in vector registers,
1475    /// the arithmetic happens in one, and the answer goes back in the register the convention
1476    /// names. Nothing here touches the general purpose file, which is the point.
1477    #[test]
1478    fn a_float_is_added_in_the_register_file_it_arrives_in() {
1479        let f32 = Type::float(rucc_ir::Float::F32);
1480        let (mut names, mut source, block, args) = blank(&[f32, f32]);
1481        let mut build = Builder::new(&mut source, block);
1482        let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
1483        build.ret(&[sum]);
1484
1485        let machine = Machine::x86_64(&SYSV);
1486        let out =
1487            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1488                .expect("every instruction has a rule");
1489
1490        let text = mir::print_func(&out, &names, &REGS);
1491        assert!(text.contains("x64.addss_rr"), "{text}");
1492        assert!(text.contains("$xmm0"), "{text}");
1493        assert!(!text.contains("$rax"), "{text}");
1494    }
1495
1496    /// A float moved between a register and memory, which is the instruction that decides which
1497    /// file the value is in and is a different one from the `mov` that moves the same four bytes.
1498    #[test]
1499    fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
1500        let f64 = Type::float(rucc_ir::Float::F64);
1501        let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
1502        let mut build = Builder::new(&mut source, block);
1503        let info = rucc_ir::MemInfo {
1504            size: 8,
1505            align: 8,
1506            order: rucc_ir::MemOrder::NotAtomic,
1507            tbaa: None,
1508            owns: 0,
1509            restrict: Restrict::NONE,
1510        };
1511        let read = build.load(f64, args[0], info, ir::Flags::default());
1512        let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
1513        build.store(sum, args[0], info, ir::Flags::default());
1514        build.ret(&[sum]);
1515
1516        let machine = Machine::x86_64(&SYSV);
1517        let out =
1518            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1519                .expect("every instruction has a rule");
1520
1521        let text = mir::print_func(&out, &names, &REGS);
1522        assert!(text.contains("x64.movsd_rm"), "{text}");
1523        assert!(text.contains("x64.movsd_mr"), "{text}");
1524        // Not the aligned whole register move, which is what a spill uses and is the one
1525        // instruction here that would read and write more than the program asked for.
1526        assert!(!text.contains("x64.movaps_rm"), "{text}");
1527        assert!(!text.contains("x64.movaps_mr"), "{text}");
1528    }
1529
1530    /// The same journey at the format the machine only moves, which is the whole of what it can do
1531    /// with one: in from memory, back out to memory, in and out of a register, and back to the
1532    /// caller.
1533    ///
1534    /// No arithmetic, because there is no instruction for any and every one of them is a call to
1535    /// the runtime. What this says is that the value gets where a call would need it to be.
1536    #[test]
1537    fn a_quad_float_read_from_memory_and_written_back_uses_the_whole_register_move() {
1538        let quad = Type::float(rucc_ir::Float::F128);
1539        let (mut names, mut source, block, args) = blank(&[Type::PTR, quad]);
1540        let mut build = Builder::new(&mut source, block);
1541        let info = rucc_ir::MemInfo {
1542            size: 16,
1543            align: 16,
1544            order: rucc_ir::MemOrder::NotAtomic,
1545            tbaa: None,
1546            owns: 0,
1547            restrict: Restrict::NONE,
1548        };
1549        let read = build.load(quad, args[0], info, ir::Flags::default());
1550        build.store(args[1], args[0], info, ir::Flags::default());
1551        build.ret(&[read]);
1552
1553        let machine = Machine::x86_64(&SYSV);
1554        let out =
1555            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1556                .expect("every instruction has a rule");
1557
1558        let text = mir::print_func(&out, &names, &REGS);
1559        assert!(text.contains("x64.movaps_rm"), "{text}");
1560        assert!(text.contains("x64.movaps_mr"), "{text}");
1561        assert!(text.contains("x64.arg_val_f128"), "{text}");
1562        assert!(text.contains("x64.ret_val_f128"), "{text}");
1563        // In the vector file and not the general purpose one, which is where the two eightbytes
1564        // of this value would have gone if it had been classified as a pair of integers.
1565        assert!(text.contains("$xmm0"), "{text}");
1566        assert!(!text.contains("gpr($rax)"), "{text}");
1567    }
1568
1569    /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
1570    ///
1571    /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
1572    /// together in two different files, and this is where they meet. The rewrite is free to write
1573    /// any instruction it likes at any width, and at this width almost none of them can be
1574    /// lowered, so a correction written the way the narrower ones are written would pass its own
1575    /// tests next door and fail here.
1576    #[test]
1577    fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
1578        let f80 = Type::float(rucc_ir::Float::F80);
1579        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1580        let mut build = Builder::new(&mut source, block);
1581        let info = rucc_ir::MemInfo {
1582            size: 16,
1583            align: 16,
1584            order: rucc_ir::MemOrder::NotAtomic,
1585            tbaa: None,
1586            owns: 0,
1587            restrict: Restrict::NONE,
1588        };
1589        let wide = build.unary(Opcode::UIToFP, args[1], f80);
1590        build.store(wide, args[0], info, ir::Flags::default());
1591        let read = build.load(f80, args[0], info, ir::Flags::default());
1592        let back = build.unary(Opcode::FPToUI, read, Type::int(64));
1593        build.ret(&[back]);
1594
1595        let machine = Machine::x86_64(&SYSV);
1596        let out =
1597            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1598                .expect("every instruction has a rule");
1599
1600        let text = mir::print_func(&out, &names, &REGS);
1601        // The signed conversions in both directions, the constants that correct them, and the
1602        // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
1603        assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
1604        assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
1605        assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
1606        assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
1607        assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
1608        assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
1609    }
1610
1611    /// A value carried from one register file to the other, which is what a conversion is. The
1612    /// instruction reads one file and writes the other, and the allocator has to know that: a
1613    /// conversion whose operands were both said to be in one file would put the answer in a
1614    /// register the next instruction cannot reach.
1615    #[test]
1616    fn a_conversion_carries_the_value_into_the_other_register_file() {
1617        let f64 = Type::float(rucc_ir::Float::F64);
1618        let (mut names, mut source, block, args) = blank(&[f64]);
1619        let mut build = Builder::new(&mut source, block);
1620        let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
1621        let back = build.unary(Opcode::SIToFP, whole, f64);
1622        build.ret(&[back]);
1623
1624        let machine = Machine::x86_64(&SYSV);
1625        let out =
1626            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1627                .expect("every instruction has a rule");
1628
1629        // The conversion that cuts towards zero rather than the one that rounds, which is what C
1630        // means by the cast, and the argument and the answer in the register the convention names.
1631        let text = mir::print_func(&out, &names, &REGS);
1632        assert!(text.contains("x64.cvttsd2si_32"), "{text}");
1633        assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
1634        assert!(text.contains("$xmm0"), "{text}");
1635    }
1636
1637    /// The other way of putting a float and a number together, which keeps every bit rather than
1638    /// the value and is what a program reading the bits of a `double` asks for.
1639    #[test]
1640    fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
1641        let f64 = Type::float(rucc_ir::Float::F64);
1642        let (mut names, mut source, block, args) = blank(&[f64]);
1643        let mut build = Builder::new(&mut source, block);
1644        let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
1645        build.ret(&[bits]);
1646
1647        let machine = Machine::x86_64(&SYSV);
1648        let out =
1649            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1650                .expect("every instruction has a rule");
1651
1652        let text = mir::print_func(&out, &names, &REGS);
1653        assert!(text.contains("x64.movq_from_xmm"), "{text}");
1654        assert!(!text.contains("cvt"), "{text}");
1655    }
1656
1657    /// A comparison whose answer the machine has a condition for, which is most of them.
1658    #[test]
1659    fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
1660        let f64 = Type::float(rucc_ir::Float::F64);
1661        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1662        let mut build = Builder::new(&mut source, block);
1663        let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
1664        let wide = build.unary(Opcode::ZExt, less, Type::int(32));
1665        build.ret(&[wide]);
1666
1667        let machine = Machine::x86_64(&SYSV);
1668        let out =
1669            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1670                .expect("every instruction has a rule");
1671
1672        // Less than is greater than with the operands the other way round, and the machine has no
1673        // condition for the first, so the rule that fires is the one that swaps them.
1674        let text = mir::print_func(&out, &names, &REGS);
1675        assert!(text.contains("x64.ucomisd_set_a"), "{text}");
1676    }
1677
1678    /// The two comparisons that are not one condition. An ordered equality is the flag that means
1679    /// equal or unordered and the flag that says it was ordered, so the instruction writes a
1680    /// second byte and reads it back, and what this is about is that the second byte gets a
1681    /// register of its own rather than the one the answer is in.
1682    #[test]
1683    fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
1684        let f64 = Type::float(rucc_ir::Float::F64);
1685        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1686        let mut build = Builder::new(&mut source, block);
1687        let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
1688        let wide = build.unary(Opcode::ZExt, same, Type::int(32));
1689        build.ret(&[wide]);
1690
1691        let machine = Machine::x86_64(&SYSV);
1692        let out =
1693            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1694                .expect("every instruction has a rule");
1695
1696        let text = mir::print_func(&out, &names, &REGS);
1697        let line = text
1698            .lines()
1699            .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
1700            .expect("the rule for an ordered equality fired");
1701        let written: Vec<&str> = line
1702            .split_once('=')
1703            .expect("the instruction writes something")
1704            .0
1705            .split(',')
1706            .map(str::trim)
1707            .collect();
1708        assert_eq!(written.len(), 2, "{line}");
1709        assert_ne!(written[0], written[1], "{line}");
1710    }
1711
1712    /// A float literal, which is the last float thing a C program writes that had no lowering.
1713    /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
1714    /// halves meet: the constant is spelled in a general purpose register and moved across.
1715    #[test]
1716    fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
1717        let f64 = Type::float(rucc_ir::Float::F64);
1718        let (mut names, mut source, block, _) = blank(&[]);
1719        let mut build = Builder::new(&mut source, block);
1720        let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
1721        build.ret(&[half]);
1722
1723        let machine = Machine::x86_64(&SYSV);
1724        let out =
1725            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1726                .expect("every instruction has a rule");
1727
1728        let text = mir::print_func(&out, &names, &REGS);
1729        assert!(text.contains("x64.mov_ri_64"), "{text}");
1730        assert!(text.contains("x64.movq_to_xmm"), "{text}");
1731    }
1732
1733    /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
1734    /// does is an exclusive or in a general purpose register rather than any float instruction.
1735    #[test]
1736    fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
1737        let f64 = Type::float(rucc_ir::Float::F64);
1738        let (mut names, mut source, block, args) = blank(&[f64]);
1739        let mut build = Builder::new(&mut source, block);
1740        let less = build.unary(Opcode::FNeg, args[0], f64);
1741        build.ret(&[less]);
1742
1743        let machine = Machine::x86_64(&SYSV);
1744        let out =
1745            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1746                .expect("every instruction has a rule");
1747
1748        let text = mir::print_func(&out, &names, &REGS);
1749        assert!(text.contains("x64.xor_rr_64"), "{text}");
1750        assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
1751    }
1752
1753    #[test]
1754    fn the_flags_reach_the_frame() {
1755        let i32 = Type::int(32);
1756        let (mut names, mut source, block, args) = blank(&[i32]);
1757        Builder::new(&mut source, block).ret(&[args[0]]);
1758
1759        let machine = Machine::x86_64(&SYSV);
1760        let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
1761        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1762            .expect("every instruction has a rule");
1763
1764        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
1765        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
1766        let text = mir::print_func(&out, &names, &REGS);
1767        assert!(text.contains("x64.push_64 $rbp"), "{text}");
1768        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
1769    }
1770
1771    #[test]
1772    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
1773        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1774        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1775        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1776        assert!(std::ptr::eq(machine.conv, &SYSV));
1777
1778        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1779        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1780        assert!(std::ptr::eq(machine.conv, &WIN64));
1781
1782        // The AArch64 machine, with its own selector, so nothing compiles x86-64 instructions for
1783        // an AArch64 program.
1784        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1785        let machine = Machine::for_target(&info).expect("aarch64 has a back end");
1786        assert!(std::ptr::eq(machine.conv, &aarch64::AAPCS64));
1787        assert!(std::ptr::eq(machine.selector, &select::aarch64::SELECTOR));
1788
1789        // Not a target this crate has a back end for, and saying so is the whole point.
1790        let info = TargetInfo::new(triple("riscv64-unknown-linux-gnu"));
1791        assert!(Machine::for_target(&info).is_none());
1792    }
1793}