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