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