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