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