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