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 std::collections::HashSet;
27
28use rucc_base::Interner;
29use rucc_ir as ir;
30use rucc_mir as mir;
31use rucc_regalloc::assign::Env;
32use rucc_target::{BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
33use rucc_tuple::Arch;
34
35use crate::coverage::Fired;
36use crate::elsewhere::Elsewhere;
37use crate::expand;
38use crate::finish::{Convention, Probing, Protect, Tracing, finish};
39use crate::fold;
40use crate::frame::{Frame, Layout};
41use crate::layout;
42use crate::lower::{self, Unsupported};
43use crate::pressure::{Cost, Pressure};
44use crate::retry;
45use crate::split;
46use crate::switch;
47use crate::varargs;
48use crate::widths;
49
50/// Everything about a machine that compiling a function for it needs.
51///
52/// The fields are different kinds of fact and they come from different places: where the
53/// convention puts things, what registers the machine has, which instructions build a frame,
54/// which instructions a branch becomes, and which registers the allocator may hand out. The last
55/// one is not a target fact on its own, because holding a register back as scratch is a decision
56/// about the allocator rather than about the machine, which is why it is built here rather than
57/// in [`rucc_target`].
58#[derive(Debug)]
59pub struct Machine {
60    /// Where the convention this function is compiled for puts things.
61    pub conv: &'static CallRegs,
62    /// The registers the machine has, which is what says how wide a spill slot of a class is.
63    pub file: RegFile,
64    /// The instructions that take a frame and give it back.
65    pub insts: &'static FrameInsts,
66    /// The instructions a branch becomes once the blocks are in an order.
67    pub branch: &'static BranchInsts,
68    /// What the allocator may hand out, and what it holds back.
69    pub env: Env,
70}
71
72/// The scratch registers held back from the allocator on x86-64.
73///
74/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
75/// into something, and those can want a register at the same instruction. Two is also what the
76/// instruction wanting most wants, which is one that reads two spilled values and writes a third,
77/// and `rewrite` says why the answer goes back into a register an operand arrived in rather than
78/// asking for a third.
79///
80/// It is not two because two was enough to start with and nobody looked again. There is no third
81/// to hold back. A scratch register has to be one the convention passes nothing in, since the
82/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
83/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved.
84/// On SysV that is `r10` and `r11` and nothing else, so if the rewriter ever does want a third the
85/// answer is not to take one here.
86const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
87
88/// How many of each class are held back.
89const SCRATCH_COUNT: usize = SCRATCH.len();
90
91impl Machine {
92    /// The x86-64 machine under that convention.
93    ///
94    /// Both files are offered. A value the selector produces is in one or the other, which is
95    /// decided by its type: an integer and an address are general purpose and a `float` or a
96    /// `double` is in a vector register, and the allocator is given each file separately because
97    /// no move goes between them.
98    #[must_use]
99    pub fn x86_64(conv: &'static CallRegs) -> Self {
100        let order: Vec<PhysReg> =
101            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
102        // The vector file wants its own two, for the same two jobs, and they have to be two the
103        // convention does not preserve: a scratch register is written by a move the rewriter puts
104        // in, which is after the prologue has already been decided, so one the callee owes back
105        // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
106        // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
107        // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
108        let free: Vec<PhysReg> =
109            conv.sse_order.iter().copied().filter(|&reg| !conv.preserves_sse(reg)).collect();
110        let at = free.len().saturating_sub(SCRATCH_COUNT);
111        let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
112        let sse_order: Vec<PhysReg> =
113            conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
114        Self {
115            conv,
116            file: x86_64::REGS,
117            insts: &x86_64::FRAME,
118            branch: &x86_64::BRANCH,
119            env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
120                x86_64::XMM,
121                &sse_order,
122                &sse_scratch,
123            ),
124        }
125    }
126
127    /// The machine a target describes, or `None` when no backend in this crate covers it.
128    ///
129    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
130    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
131    /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
132    /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
133    #[must_use]
134    pub fn for_target(target: &TargetInfo) -> Option<Self> {
135        let conv = target.call_regs?;
136        match target.tuple.arch() {
137            Arch::X86_64 => Some(Self::x86_64(conv)),
138            _ => None,
139        }
140    }
141}
142
143/// Whether every function calls a profiler on the way in, and where that call goes.
144///
145/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
146/// has already been made against the target by the time this is built, which is why there is no
147/// answer here for a command line that named neither.
148#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
149pub enum Profile {
150    /// It does not, which is what nearly every command line asks for.
151    #[default]
152    No,
153    /// In front of the prologue, which is the hook a tracer can replace while the program runs.
154    Early,
155    /// Once the frame is taken, which is the hook that reads the frame pointer.
156    Late,
157}
158
159/// What the command line says about a frame, as opposed to what the machine says.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct Flags {
162    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
163    pub frame_pointer: bool,
164    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
165    pub red_zone: bool,
166    /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
167    pub stack_clash: bool,
168    /// Whether every function opens with a landing pad, which `-fcf-protection=branch` asks for.
169    pub landing: bool,
170    /// Whether every function calls a profiler on the way in, which `-pg` asks for.
171    pub profile: Profile,
172}
173
174impl Default for Flags {
175    /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad
176    /// and no profiling, which is what a convention that has a red zone says when nobody on the
177    /// command line has said otherwise.
178    fn default() -> Self {
179        Self {
180            frame_pointer: false,
181            red_zone: true,
182            stack_clash: false,
183            landing: false,
184            profile: Profile::No,
185        }
186    }
187}
188
189/// Compiles one function, from the IR the middle end produced to machine instructions.
190///
191/// The function is taken by reference that can be written through, because the first pass is an
192/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
193/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
194/// selection is not quite the IR the middle end produced, and this is the only place that is true.
195/// `--emit=ir` prints before any of this runs.
196///
197/// `elsewhere` is the one thing here that is a fact about the module rather than about the
198/// function, and it is passed in rather than looked up because this only ever sees the one
199/// function. What it decides is how the address of a name is come by, which is the difference
200/// between an address this file can measure to and one only the linker knows.
201///
202/// # Errors
203///
204/// The first thing in it this cannot lower, which is what [`lower::func`] reports and is the only
205/// pass here that can refuse a function. Everything after lowering works on machine instructions
206/// that exist, so it either runs or it is a bug in this crate.
207pub fn compile(
208    source: &mut ir::Func,
209    names: &mut Interner,
210    machine: &Machine,
211    elsewhere: &Elsewhere,
212    flags: Flags,
213) -> Result<mir::Func, Unsupported> {
214    compile_recording(
215        source,
216        names,
217        machine,
218        elsewhere,
219        flags,
220        &mut Fired::new(),
221        &mut Pressure::new(),
222    )
223}
224
225/// The same compilation, with what it did along the way recorded.
226///
227/// Two functions rather than one that takes options, because a caller that does not want the
228/// numbers should not have to say so. What `fired` is for is `-Zrule-coverage`, which is how the
229/// harness in `tamnd/rucc-compat` turns coverage of the rule set into a number over a corpus. What
230/// `pressure` is for is `-Zregister-pressure`, which is how much of the frame the allocator had to
231/// use and is the metric `spec/safe-memory/13-performance.md` section 13.1 asks for.
232///
233/// Both are added to rather than replaced, so a caller can pass the same pair for every function of
234/// a module and every module of a command line and get the answer for all of them.
235///
236/// # Errors
237///
238/// The same as [`compile`]. A function that was refused contributes nothing to either, since a
239/// function that did not compile is not evidence about what a rule set or a frame would have done.
240pub fn compile_recording(
241    source: &mut ir::Func,
242    names: &mut Interner,
243    machine: &Machine,
244    elsewhere: &Elsewhere,
245    flags: Flags,
246    fired: &mut Fired,
247    pressure: &mut Pressure,
248) -> Result<mir::Func, Unsupported> {
249    switch::switches(source);
250    // Beside the switches rather than down with the rest of the rewriting, because both of them
251    // make blocks and nothing in `expand` may. Before the orderings as well, since the head of the
252    // loop it builds reads with an `atomic_load` and the pass below is what turns that into the
253    // plain load this machine does anyway.
254    retry::loops(source);
255    // Before the width legalisation and everything after it, because what an ordered access
256    // becomes here is a plain one and every pass below is written about a plain one by name.
257    expand::orderings(source, machine.conv.word);
258    // Before everything, because every pass after it is written about widths the machine has and
259    // an integer of forty bits is not one of them.
260    widths::integers(source);
261    expand::bytes(source);
262    expand::counts(source);
263    expand::overflows(source);
264    expand::floats(source);
265    expand::bulk(source, names, machine.conv.word);
266    varargs::lists(source, machine.conv);
267    let lowered = lower::func(source, names, machine.conv, elsewhere)?;
268    fired.merge(&lowered.fired);
269    let lower::Lowered { mut func, stack, .. } = lowered;
270    // Whether this function carries a canary is the front end's answer, because what
271    // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
272    // here. What the machine does about it is this crate's answer, and a target with nowhere to
273    // keep the word a canary is copied from does nothing, which is what the driver refuses a
274    // command line over before any of this runs.
275    let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
276    let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
277    // Nothing at all on a target with no hook to call, which is the same answer the protector gives
278    // on a target with nowhere to keep its word, and the driver refuses the command line over it
279    // before any of this runs.
280    let profile = match machine.conv.trace {
281        Some(_) => flags.profile,
282        None => Profile::No,
283    };
284    let base = stack.layout(Layout::new(machine.conv, machine.file));
285    let layout = Layout {
286        // The later hook reads the frame pointer to find out who called this function, so a
287        // function that calls it is given one whether or not anything else asked.
288        frame_pointer: flags.frame_pointer || profile == Profile::Late,
289        red_zone: flags.red_zone,
290        protect: guard.is_some(),
291        // A protected function calls the one that does not come back, on the arm where the check
292        // failed, so it is not a leaf however few calls the program wrote in it. That is what
293        // takes the red zone away from it and what makes its frame leave the stack pointer where
294        // a call needs it. The later hook is a call in the same position and costs the same.
295        //
296        // The earlier one is not, and this is the one place the difference shows. It runs before
297        // the prologue has written anything, so the bytes below the stack pointer it uses are ones
298        // this function has not put anything in yet, and a leaf that keeps its locals down there
299        // stays a leaf. gcc leaves it alone too.
300        leaf: base.leaf && guard.is_none() && profile != Profile::Late,
301        ..base
302    };
303
304    // After selection, because the address instruction and the one that reads it are both machine
305    // instructions only once selection has written them, and before allocation, because what makes
306    // the pair safe to put together is that a virtual register is written once. The addresses into
307    // the frame and into the caller's argument area are left alone, since `finish` has still to
308    // write their displacements and it finds them by which instruction they are.
309    let waiting: HashSet<mir::Inst> = stack
310        .addresses
311        .iter()
312        .map(|&(inst, _)| inst)
313        .chain(stack.arguments.iter().map(|&(inst, _)| inst))
314        .collect();
315    fold::addresses(&mut func, machine.insts, names, &waiting);
316
317    // Before allocation as well, and asked here rather than where it is used because what it asks
318    // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
319    // written once and a physical one is not, so after allocation that question no longer has an
320    // answer.
321    let fusable = layout::fusable(&func, machine.branch, names);
322
323    // Before allocation, because an edge that carries values into a block arrived at more than
324    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
325    // values turn into, and the allocator asserts rather than guessing.
326    split::critical(&mut func);
327    let called = names.resolve(func.name).to_owned();
328    let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
329    pressure.record(&called, Cost::of(&allocation));
330
331    // After allocation, because the largest area in most frames is the spill slots and nothing
332    // knows how many of those there are until the allocator has finished running out of registers.
333    let frame = Frame::of(&func, &allocation, &layout);
334    let scratch = machine.env.scratch(machine.conv.int_class);
335    let protect = guard.map(|guard| Protect {
336        guard,
337        branch: machine.branch,
338        scratch: [scratch[0], scratch[1]],
339    });
340    // A target with no instruction that touches a page without changing it does nothing about the
341    // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
342    // Every target this crate has a back end for has one.
343    let probe = flags
344        .stack_clash
345        .then_some(machine.insts.probe.as_ref())
346        .flatten()
347        .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
348    // The same answer for a target with nothing that marks an address as one an indirect branch
349    // may arrive at, and the driver refuses the command line for the same reason it refuses the
350    // other two before any of this runs.
351    let landing = flags.landing.then_some(machine.insts.landing).flatten();
352    let trace = machine.conv.trace.and_then(|trace| match profile {
353        Profile::No => None,
354        Profile::Early => Some(Tracing { name: trace.early, early: true }),
355        Profile::Late => Some(Tracing { name: trace.late, early: false }),
356    });
357    let convention = Convention {
358        protect,
359        probe,
360        landing,
361        trace,
362        ..Convention::new(machine.conv, machine.insts)
363    };
364    finish(&mut func, &allocation, &frame, &stack, convention, names);
365
366    // Last, because everything before this finds the blocks a function returns from by looking
367    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
368    layout::blocks(&mut func, machine.branch, names, &fusable);
369    Ok(func)
370}
371
372#[cfg(test)]
373mod tests {
374    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
375    use rucc_target::x86_64::{REGS, SYSV, WIN64};
376
377    use super::*;
378
379    /// A function of two integers, and the block to fill.
380    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
381        let mut names = Interner::new();
382        let mut func = Func::new(names.intern("f"), Signature::new());
383        let block = func.create_block();
384        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
385        (names, func, block, values)
386    }
387
388    #[test]
389    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
390        let i32 = Type::int(32);
391        let (mut names, mut source, block, args) = blank(&[i32, i32]);
392        let mut build = Builder::new(&mut source, block);
393        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
394        build.ret(&[sum]);
395
396        let machine = Machine::x86_64(&SYSV);
397        let out =
398            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
399                .expect("every instruction has a rule");
400
401        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
402        // frame at all, so there is no prologue to see. The one move left is the one the machine's
403        // addition needs, since the sum is written into the register the left operand was read
404        // from and the return wants it in `rax`.
405        assert_eq!(
406            mir::print_func(&out, &names, &REGS),
407            "mfunc @f {\n\
408             block0:\n    \
409             $rdi($rdi) = x64.arg_val_32\n    \
410             $rsi($rsi) = x64.arg_val_32\n    \
411             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    \
412             $rax = x64.mov_rr_64 $rdi\n    \
413             x64.ret_val_32 $rax($rax)\n    \
414             x64.ret\n\
415             }\n"
416        );
417    }
418
419    /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
420    /// The second function adds to the first rather than replacing it, which is what makes one of
421    /// these files the answer for a whole command line rather than for whichever function was last.
422    #[test]
423    fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
424        let i32 = Type::int(32);
425        let (mut names, mut source, block, args) = blank(&[i32, i32]);
426        let mut build = Builder::new(&mut source, block);
427        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
428        build.ret(&[sum]);
429
430        let machine = Machine::x86_64(&SYSV);
431        let mut fired = Fired::new();
432        compile_recording(
433            &mut source,
434            &mut names,
435            &machine,
436            &Elsewhere::default(),
437            Flags::default(),
438            &mut fired,
439            &mut Pressure::new(),
440        )
441        .expect("every instruction has a rule");
442        let one = fired.count();
443        assert!(one > 0, "an add and a return went through the table and nothing was recorded");
444
445        let listing = fired.listing(&crate::select::x86_64::TABLE);
446        assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
447        assert!(
448            listing.contains(&format!("{one} of ")),
449            "{}",
450            listing.lines().next().unwrap_or("")
451        );
452
453        // The same rules again plus the ones a subtraction needs, into the same record.
454        let (mut names, mut source, block, args) = blank(&[i32, i32]);
455        let mut build = Builder::new(&mut source, block);
456        let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
457        build.ret(&[difference]);
458        compile_recording(
459            &mut source,
460            &mut names,
461            &machine,
462            &Elsewhere::default(),
463            Flags::default(),
464            &mut fired,
465            &mut Pressure::new(),
466        )
467        .expect("every instruction has a rule");
468        assert!(fired.count() > one, "a subtraction is not an addition");
469    }
470
471    #[test]
472    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
473        let i32 = Type::int(32);
474        let (mut names, mut source, block, args) = blank(&[i32]);
475        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
476        let callee = names.intern("g");
477        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
478        let got = source[call].first_result.expect("an integer comes back");
479        let mut build = Builder::new(&mut source, block);
480        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
481        build.ret(&[sum]);
482
483        let machine = Machine::x86_64(&SYSV);
484        let out =
485            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
486                .expect("every instruction has a rule");
487
488        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
489        // register the value that outlives the call went to is one the prologue saves.
490        let text = mir::print_func(&out, &names, &REGS);
491        assert!(text.contains("x64.push_64 $rbx"), "{text}");
492        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
493        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
494        assert!(!text.contains('%'), "{text}");
495    }
496
497    #[test]
498    fn the_other_convention_is_the_same_function_somewhere_else() {
499        let i32 = Type::int(32);
500        let (mut names, mut source, block, args) = blank(&[i32, i32]);
501        let mut build = Builder::new(&mut source, block);
502        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
503        build.ret(&[sum]);
504
505        let machine = Machine::x86_64(&WIN64);
506        let out =
507            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
508                .expect("every instruction has a rule");
509
510        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
511        // the whole of what changed, and it changed because the convention was asked.
512        let text = mir::print_func(&out, &names, &REGS);
513        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
514        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
515        assert!(!text.contains("$rdi"), "{text}");
516    }
517
518    #[test]
519    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
520        let i32 = Type::int(32);
521        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
522        let then = source.create_block();
523        let join = source.create_block();
524        let got = source.append_param(join, i32);
525        let mut build = Builder::new(&mut source, entry);
526        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
527        build.br_if(cond, then, &[], join, &[args[1]]);
528        Builder::new(&mut source, then).jump(join, &[args[0]]);
529        Builder::new(&mut source, join).ret(&[got]);
530
531        let machine = Machine::x86_64(&SYSV);
532        let out =
533            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
534                .expect("every instruction has a rule");
535
536        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
537        // there, which is the pass between lowering and allocation doing its job. Without it the
538        // allocator would have asserted rather than compiled this.
539        assert_eq!(out.block_count(), 4);
540
541        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
542        // this pins. The branch became a test and one jump, and it is the jump taken when the
543        // condition failed, because the arm the condition is true for is the block laid out next
544        // and a block falls into the block laid out next. The other arm is the empty block the
545        // edge splitting left, which is where the move the edge carries ended up, and it falls
546        // into the join as well. What is left is one jump in the whole function. Both arms write
547        // the join's parameter straight into `rax`, because the return at the bottom insists on
548        // that register and the moves the edges carry are free to name it.
549        let text = mir::print_func(&out, &names, &REGS);
550        assert_eq!(
551            text,
552            "mfunc @f {\n\
553             block0:\n    \
554             $rdi($rdi) = x64.arg_val_32\n    \
555             $rsi($rsi) = x64.arg_val_32\n    \
556             x64.cmp_rr_32 $rdi, $rsi\n    \
557             x64.jcc_ge block2, block1\n\
558             \nblock1:\n    \
559             $rax = x64.mov_rr_64 $rdi\n    \
560             x64.jmp block3\n\
561             \nblock2:\n    \
562             $rax = x64.mov_rr_64 $rsi, block3\n\
563             \nblock3:\n    \
564             x64.ret_val_32 $rax($rax)\n    \
565             x64.ret\n\
566             }\n"
567        );
568    }
569
570    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
571    /// the smallest program that caught two ways of losing a value. Both were found by running
572    /// what came out rather than by reading it, and both are pinned here rather than only where
573    /// they were fixed, because what is wrong with either of them is only visible in the whole
574    /// function.
575    #[test]
576    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
577        let i32 = Type::int(32);
578        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
579        let head = source.create_block();
580        let body = source.create_block();
581        let exit = source.create_block();
582        let left = source.append_param(head, i32);
583        let right = source.append_param(head, i32);
584        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
585        let mut build = Builder::new(&mut source, head);
586        let zero = build.iconst(i32, 0);
587        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
588        build.br_if(more, body, &[], exit, &[left]);
589        let mut build = Builder::new(&mut source, body);
590        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
591        build.jump(head, &[right, rest]);
592        let result = source.append_param(exit, i32);
593        Builder::new(&mut source, exit).ret(&[result]);
594
595        let machine = Machine::x86_64(&SYSV);
596        let out =
597            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
598                .expect("every instruction has a rule");
599
600        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
601        // things in here were wrong and each of them returned three from a program that gcc
602        // returns forty two from.
603        //
604        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
605        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
606        // of a block used to go in front of the last instruction, on the reasoning that the last
607        // instruction is the branch, and the block's jump is not an instruction until the layout
608        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
609        //
610        // The second is in the loop body. A division writes both a quotient and a remainder, and
611        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
612        // be given the same register as the remainder, because a value written early was live at
613        // one point and that point is in front of where the remainder is written. The copy that
614        // takes the quotient nowhere then landed on top of the remainder.
615        assert_eq!(
616            mir::print_func(&out, &names, &REGS),
617            "mfunc @f {\n\
618             block0:\n    \
619             $rdi($rdi) = x64.arg_val_32\n    \
620             $rsi($rsi) = x64.arg_val_32\n    \
621             $rcx = x64.mov_rr_64 $rdi, block1\n\
622             \nblock1:\n    \
623             x64.cmp_ri_32 $rsi, 0\n    \
624             x64.jcc_e block3, block2\n\
625             \nblock2:\n    \
626             $rax = x64.mov_rr_64 $rcx\n    \
627             $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
628             $rdi = x64.mov_rr_64 $rax\n    \
629             $rcx = x64.mov_rr_64 $rsi\n    \
630             $rsi = x64.mov_rr_64 $rdx\n    \
631             x64.jmp block1\n\
632             \nblock3:\n    \
633             $rax = x64.mov_rr_64 $rcx\n    \
634             x64.ret_val_32 $rax($rax)\n    \
635             x64.ret\n\
636             }\n"
637        );
638    }
639
640    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
641    /// a branch in it is the one where that is worth checking: after the layout has run, where a
642    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
643    /// parser has to put it back on the block it came off.
644    #[test]
645    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
646        let i32 = Type::int(32);
647        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
648        let then = source.create_block();
649        let join = source.create_block();
650        let got = source.append_param(join, i32);
651        let mut build = Builder::new(&mut source, entry);
652        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
653        build.br_if(cond, then, &[], join, &[args[1]]);
654        Builder::new(&mut source, then).jump(join, &[args[0]]);
655        Builder::new(&mut source, join).ret(&[got]);
656
657        let machine = Machine::x86_64(&SYSV);
658        let out =
659            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
660                .expect("every instruction has a rule");
661
662        let text = mir::print_func(&out, &names, &REGS);
663        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
664        assert_eq!(mir::print(&read, &names, &REGS), text);
665    }
666
667    #[test]
668    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
669        let f80 = Type::float(rucc_ir::Float::F80);
670        let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
671        Builder::new(&mut source, block).ret(&args);
672
673        // One of these comes back on the x87 stack and a pair comes back in a pair of registers,
674        // and there is no pair with that stack in it. So this is refused rather than lowered, and
675        // it is the convention that refuses it rather than anything about the instructions.
676        let machine = Machine::x86_64(&SYSV);
677        let failed =
678            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
679                .expect_err("a long double cannot come back beside another value");
680        assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
681    }
682
683    /// A `long double` in and a `long double` out, which is the whole of what the convention says
684    /// about the type and is two different answers rather than one.
685    ///
686    /// It arrives in the caller's argument area, so what the parameter is is the address of the
687    /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
688    /// return is an `fld` and nothing else, and the value is still on that stack when the function
689    /// returns, which is the one time anything here leaves it that way.
690    #[test]
691    fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
692        let f80 = Type::float(rucc_ir::Float::F80);
693        let (mut names, mut source, block, args) = blank(&[f80, f80]);
694        let mut build = Builder::new(&mut source, block);
695        let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
696        build.ret(&[sum]);
697
698        let machine = Machine::x86_64(&SYSV);
699        let out =
700            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
701                .expect("every instruction has a rule");
702
703        let text = mir::print_func(&out, &names, &REGS);
704        // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
705        // of a register, and the answer left on the stack by the last instruction in the function.
706        assert!(text.contains("x64.lea_64 [$rsp + 32]"), "{text}");
707        assert!(text.contains("x64.lea_64 [$rsp + 48]"), "{text}");
708        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
709        // What comes after the `fld` is the epilogue, which gives the frame back and touches
710        // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
711        let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
712        assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rax]"], "{text}");
713    }
714
715    /// The whole of the second register class, end to end: two floats arrive in vector registers,
716    /// the arithmetic happens in one, and the answer goes back in the register the convention
717    /// names. Nothing here touches the general purpose file, which is the point.
718    #[test]
719    fn a_float_is_added_in_the_register_file_it_arrives_in() {
720        let f32 = Type::float(rucc_ir::Float::F32);
721        let (mut names, mut source, block, args) = blank(&[f32, f32]);
722        let mut build = Builder::new(&mut source, block);
723        let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
724        build.ret(&[sum]);
725
726        let machine = Machine::x86_64(&SYSV);
727        let out =
728            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
729                .expect("every instruction has a rule");
730
731        let text = mir::print_func(&out, &names, &REGS);
732        assert!(text.contains("x64.addss_rr"), "{text}");
733        assert!(text.contains("$xmm0"), "{text}");
734        assert!(!text.contains("$rax"), "{text}");
735    }
736
737    /// A float moved between a register and memory, which is the instruction that decides which
738    /// file the value is in and is a different one from the `mov` that moves the same four bytes.
739    #[test]
740    fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
741        let f64 = Type::float(rucc_ir::Float::F64);
742        let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
743        let mut build = Builder::new(&mut source, block);
744        let info = rucc_ir::MemInfo {
745            size: 8,
746            align: 8,
747            order: rucc_ir::MemOrder::NotAtomic,
748            tbaa: None,
749            restrict: Restrict::NONE,
750        };
751        let read = build.load(f64, args[0], info, ir::Flags::default());
752        let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
753        build.store(sum, args[0], info, ir::Flags::default());
754        build.ret(&[sum]);
755
756        let machine = Machine::x86_64(&SYSV);
757        let out =
758            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
759                .expect("every instruction has a rule");
760
761        let text = mir::print_func(&out, &names, &REGS);
762        assert!(text.contains("x64.movsd_rm"), "{text}");
763        assert!(text.contains("x64.movsd_mr"), "{text}");
764        // Not the aligned whole register move, which is what a spill uses and is the one
765        // instruction here that would read and write more than the program asked for.
766        assert!(!text.contains("x64.movaps_rm"), "{text}");
767        assert!(!text.contains("x64.movaps_mr"), "{text}");
768    }
769
770    /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
771    ///
772    /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
773    /// together in two different files, and this is where they meet. The rewrite is free to write
774    /// any instruction it likes at any width, and at this width almost none of them can be
775    /// lowered, so a correction written the way the narrower ones are written would pass its own
776    /// tests next door and fail here.
777    #[test]
778    fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
779        let f80 = Type::float(rucc_ir::Float::F80);
780        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
781        let mut build = Builder::new(&mut source, block);
782        let info = rucc_ir::MemInfo {
783            size: 16,
784            align: 16,
785            order: rucc_ir::MemOrder::NotAtomic,
786            tbaa: None,
787            restrict: Restrict::NONE,
788        };
789        let wide = build.unary(Opcode::UIToFP, args[1], f80);
790        build.store(wide, args[0], info, ir::Flags::default());
791        let read = build.load(f80, args[0], info, ir::Flags::default());
792        let back = build.unary(Opcode::FPToUI, read, Type::int(64));
793        build.ret(&[back]);
794
795        let machine = Machine::x86_64(&SYSV);
796        let out =
797            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
798                .expect("every instruction has a rule");
799
800        let text = mir::print_func(&out, &names, &REGS);
801        // The signed conversions in both directions, the constants that correct them, and the
802        // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
803        assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
804        assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
805        assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
806        assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
807        assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
808        assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
809    }
810
811    /// A value carried from one register file to the other, which is what a conversion is. The
812    /// instruction reads one file and writes the other, and the allocator has to know that: a
813    /// conversion whose operands were both said to be in one file would put the answer in a
814    /// register the next instruction cannot reach.
815    #[test]
816    fn a_conversion_carries_the_value_into_the_other_register_file() {
817        let f64 = Type::float(rucc_ir::Float::F64);
818        let (mut names, mut source, block, args) = blank(&[f64]);
819        let mut build = Builder::new(&mut source, block);
820        let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
821        let back = build.unary(Opcode::SIToFP, whole, f64);
822        build.ret(&[back]);
823
824        let machine = Machine::x86_64(&SYSV);
825        let out =
826            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
827                .expect("every instruction has a rule");
828
829        // The conversion that cuts towards zero rather than the one that rounds, which is what C
830        // means by the cast, and the argument and the answer in the register the convention names.
831        let text = mir::print_func(&out, &names, &REGS);
832        assert!(text.contains("x64.cvttsd2si_32"), "{text}");
833        assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
834        assert!(text.contains("$xmm0"), "{text}");
835    }
836
837    /// The other way of putting a float and a number together, which keeps every bit rather than
838    /// the value and is what a program reading the bits of a `double` asks for.
839    #[test]
840    fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
841        let f64 = Type::float(rucc_ir::Float::F64);
842        let (mut names, mut source, block, args) = blank(&[f64]);
843        let mut build = Builder::new(&mut source, block);
844        let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
845        build.ret(&[bits]);
846
847        let machine = Machine::x86_64(&SYSV);
848        let out =
849            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
850                .expect("every instruction has a rule");
851
852        let text = mir::print_func(&out, &names, &REGS);
853        assert!(text.contains("x64.movq_from_xmm"), "{text}");
854        assert!(!text.contains("cvt"), "{text}");
855    }
856
857    /// A comparison whose answer the machine has a condition for, which is most of them.
858    #[test]
859    fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
860        let f64 = Type::float(rucc_ir::Float::F64);
861        let (mut names, mut source, block, args) = blank(&[f64, f64]);
862        let mut build = Builder::new(&mut source, block);
863        let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
864        let wide = build.unary(Opcode::ZExt, less, Type::int(32));
865        build.ret(&[wide]);
866
867        let machine = Machine::x86_64(&SYSV);
868        let out =
869            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
870                .expect("every instruction has a rule");
871
872        // Less than is greater than with the operands the other way round, and the machine has no
873        // condition for the first, so the rule that fires is the one that swaps them.
874        let text = mir::print_func(&out, &names, &REGS);
875        assert!(text.contains("x64.ucomisd_set_a"), "{text}");
876    }
877
878    /// The two comparisons that are not one condition. An ordered equality is the flag that means
879    /// equal or unordered and the flag that says it was ordered, so the instruction writes a
880    /// second byte and reads it back, and what this is about is that the second byte gets a
881    /// register of its own rather than the one the answer is in.
882    #[test]
883    fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
884        let f64 = Type::float(rucc_ir::Float::F64);
885        let (mut names, mut source, block, args) = blank(&[f64, f64]);
886        let mut build = Builder::new(&mut source, block);
887        let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
888        let wide = build.unary(Opcode::ZExt, same, Type::int(32));
889        build.ret(&[wide]);
890
891        let machine = Machine::x86_64(&SYSV);
892        let out =
893            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
894                .expect("every instruction has a rule");
895
896        let text = mir::print_func(&out, &names, &REGS);
897        let line = text
898            .lines()
899            .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
900            .expect("the rule for an ordered equality fired");
901        let written: Vec<&str> = line
902            .split_once('=')
903            .expect("the instruction writes something")
904            .0
905            .split(',')
906            .map(str::trim)
907            .collect();
908        assert_eq!(written.len(), 2, "{line}");
909        assert_ne!(written[0], written[1], "{line}");
910    }
911
912    /// A float literal, which is the last float thing a C program writes that had no lowering.
913    /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
914    /// halves meet: the constant is spelled in a general purpose register and moved across.
915    #[test]
916    fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
917        let f64 = Type::float(rucc_ir::Float::F64);
918        let (mut names, mut source, block, _) = blank(&[]);
919        let mut build = Builder::new(&mut source, block);
920        let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
921        build.ret(&[half]);
922
923        let machine = Machine::x86_64(&SYSV);
924        let out =
925            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
926                .expect("every instruction has a rule");
927
928        let text = mir::print_func(&out, &names, &REGS);
929        assert!(text.contains("x64.mov_ri_64"), "{text}");
930        assert!(text.contains("x64.movq_to_xmm"), "{text}");
931    }
932
933    /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
934    /// does is an exclusive or in a general purpose register rather than any float instruction.
935    #[test]
936    fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
937        let f64 = Type::float(rucc_ir::Float::F64);
938        let (mut names, mut source, block, args) = blank(&[f64]);
939        let mut build = Builder::new(&mut source, block);
940        let less = build.unary(Opcode::FNeg, args[0], f64);
941        build.ret(&[less]);
942
943        let machine = Machine::x86_64(&SYSV);
944        let out =
945            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
946                .expect("every instruction has a rule");
947
948        let text = mir::print_func(&out, &names, &REGS);
949        assert!(text.contains("x64.xor_rr_64"), "{text}");
950        assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
951    }
952
953    #[test]
954    fn the_flags_reach_the_frame() {
955        let i32 = Type::int(32);
956        let (mut names, mut source, block, args) = blank(&[i32]);
957        Builder::new(&mut source, block).ret(&[args[0]]);
958
959        let machine = Machine::x86_64(&SYSV);
960        let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
961        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
962            .expect("every instruction has a rule");
963
964        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
965        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
966        let text = mir::print_func(&out, &names, &REGS);
967        assert!(text.contains("x64.push_64 $rbp"), "{text}");
968        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
969    }
970
971    #[test]
972    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
973        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
974        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
975        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
976        assert!(std::ptr::eq(machine.conv, &SYSV));
977
978        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
979        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
980        assert!(std::ptr::eq(machine.conv, &WIN64));
981
982        // Not a target this crate has a backend for, and saying so is the whole point: a caller
983        // that got a machine here would compile x86-64 instructions for an AArch64 program.
984        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
985        assert!(Machine::for_target(&info).is_none());
986    }
987}