1use rucc_base::Interner;
27use rucc_ir as ir;
28use rucc_mir as mir;
29use rucc_regalloc::assign::Env;
30use rucc_target::{Arch, BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
31
32use crate::coverage::Fired;
33use crate::expand;
34use crate::finish::finish;
35use crate::frame::{Frame, Layout};
36use crate::layout;
37use crate::lower::{self, Unsupported};
38use crate::split;
39use crate::varargs;
40use crate::widths;
41
42#[derive(Debug)]
51pub struct Machine {
52 pub conv: &'static CallRegs,
54 pub file: RegFile,
56 pub insts: &'static FrameInsts,
58 pub branch: &'static BranchInsts,
60 pub env: Env,
62}
63
64const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
71
72const SCRATCH_COUNT: usize = SCRATCH.len();
74
75impl Machine {
76 #[must_use]
83 pub fn x86_64(conv: &'static CallRegs) -> Self {
84 let order: Vec<PhysReg> =
85 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
86 let free: Vec<PhysReg> =
93 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
94 let at = free.len().saturating_sub(SCRATCH_COUNT);
95 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
96 let sse_order: Vec<PhysReg> =
97 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
98 Self {
99 conv,
100 file: x86_64::REGS,
101 insts: &x86_64::FRAME,
102 branch: &x86_64::BRANCH,
103 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
104 x86_64::XMM,
105 &sse_order,
106 &sse_scratch,
107 ),
108 }
109 }
110
111 #[must_use]
118 pub fn for_target(target: &TargetInfo) -> Option<Self> {
119 let conv = target.call_regs?;
120 match target.triple.arch {
121 Arch::X86_64 => Some(Self::x86_64(conv)),
122 Arch::Aarch64 | Arch::Riscv64 => None,
123 }
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct Flags {
130 pub frame_pointer: bool,
132 pub red_zone: bool,
134}
135
136impl Default for Flags {
137 fn default() -> Self {
140 Self { frame_pointer: false, red_zone: true }
141 }
142}
143
144pub fn compile(
158 source: &mut ir::Func,
159 names: &mut Interner,
160 machine: &Machine,
161 flags: Flags,
162) -> Result<mir::Func, Unsupported> {
163 compile_recording(source, names, machine, flags, &mut Fired::new())
164}
165
166pub fn compile_recording(
180 source: &mut ir::Func,
181 names: &mut Interner,
182 machine: &Machine,
183 flags: Flags,
184 fired: &mut Fired,
185) -> Result<mir::Func, Unsupported> {
186 expand::switches(source);
187 expand::orderings(source, machine.conv.word);
190 widths::integers(source);
193 expand::bytes(source);
194 expand::counts(source);
195 expand::overflows(source);
196 expand::floats(source);
197 expand::bulk(source, names, machine.conv.word);
198 varargs::lists(source, machine.conv);
199 let lowered = lower::func(source, names, machine.conv)?;
200 fired.merge(&lowered.fired);
201 let lower::Lowered { mut func, stack, .. } = lowered;
202 let layout = Layout {
203 frame_pointer: flags.frame_pointer,
204 red_zone: flags.red_zone,
205 ..stack.layout(Layout::new(machine.conv, machine.file))
206 };
207
208 split::critical(&mut func);
212 let allocation = rucc_regalloc::run(&mut func, &machine.env);
213
214 let frame = Frame::of(&func, &allocation, &layout);
217 finish(&mut func, &allocation, &frame, &stack, machine.conv, machine.insts, names);
218
219 layout::blocks(&mut func, machine.branch, names);
222 Ok(func)
223}
224
225#[cfg(test)]
226mod tests {
227 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
228 use rucc_target::x86_64::{REGS, SYSV, WIN64};
229
230 use super::*;
231
232 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
234 let mut names = Interner::new();
235 let mut func = Func::new(names.intern("f"), Signature::new());
236 let block = func.create_block();
237 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
238 (names, func, block, values)
239 }
240
241 #[test]
242 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
243 let i32 = Type::int(32);
244 let (mut names, mut source, block, args) = blank(&[i32, i32]);
245 let mut build = Builder::new(&mut source, block);
246 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
247 build.ret(&[sum]);
248
249 let machine = Machine::x86_64(&SYSV);
250 let out = compile(&mut source, &mut names, &machine, Flags::default())
251 .expect("every instruction has a rule");
252
253 assert_eq!(
258 mir::print_func(&out, &names, ®S),
259 "mfunc @f {\n\
260 block0:\n \
261 $rdi($rdi) = x64.arg_val_32\n \
262 $rsi($rsi) = x64.arg_val_32\n \
263 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
264 $rax = x64.mov_rr_64 $rdi\n \
265 x64.ret_val_32 $rax($rax)\n \
266 x64.ret\n\
267 }\n"
268 );
269 }
270
271 #[test]
275 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
276 let i32 = Type::int(32);
277 let (mut names, mut source, block, args) = blank(&[i32, i32]);
278 let mut build = Builder::new(&mut source, block);
279 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
280 build.ret(&[sum]);
281
282 let machine = Machine::x86_64(&SYSV);
283 let mut fired = Fired::new();
284 compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
285 .expect("every instruction has a rule");
286 let one = fired.count();
287 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
288
289 let listing = fired.listing(&crate::select::x86_64::TABLE);
290 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
291 assert!(
292 listing.contains(&format!("{one} of ")),
293 "{}",
294 listing.lines().next().unwrap_or("")
295 );
296
297 let (mut names, mut source, block, args) = blank(&[i32, i32]);
299 let mut build = Builder::new(&mut source, block);
300 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
301 build.ret(&[difference]);
302 compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
303 .expect("every instruction has a rule");
304 assert!(fired.count() > one, "a subtraction is not an addition");
305 }
306
307 #[test]
308 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
309 let i32 = Type::int(32);
310 let (mut names, mut source, block, args) = blank(&[i32]);
311 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
312 let callee = names.intern("g");
313 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
314 let got = source[call].first_result.expect("an integer comes back");
315 let mut build = Builder::new(&mut source, block);
316 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
317 build.ret(&[sum]);
318
319 let machine = Machine::x86_64(&SYSV);
320 let out = compile(&mut source, &mut names, &machine, Flags::default())
321 .expect("every instruction has a rule");
322
323 let text = mir::print_func(&out, &names, ®S);
326 assert!(text.contains("x64.push_64 $rbx"), "{text}");
327 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
328 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
329 assert!(!text.contains('%'), "{text}");
330 }
331
332 #[test]
333 fn the_other_convention_is_the_same_function_somewhere_else() {
334 let i32 = Type::int(32);
335 let (mut names, mut source, block, args) = blank(&[i32, i32]);
336 let mut build = Builder::new(&mut source, block);
337 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
338 build.ret(&[sum]);
339
340 let machine = Machine::x86_64(&WIN64);
341 let out = compile(&mut source, &mut names, &machine, Flags::default())
342 .expect("every instruction has a rule");
343
344 let text = mir::print_func(&out, &names, ®S);
347 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
348 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
349 assert!(!text.contains("$rdi"), "{text}");
350 }
351
352 #[test]
353 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
354 let i32 = Type::int(32);
355 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
356 let then = source.create_block();
357 let join = source.create_block();
358 let got = source.append_param(join, i32);
359 let mut build = Builder::new(&mut source, entry);
360 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
361 build.br_if(cond, then, &[], join, &[args[1]]);
362 Builder::new(&mut source, then).jump(join, &[args[0]]);
363 Builder::new(&mut source, join).ret(&[got]);
364
365 let machine = Machine::x86_64(&SYSV);
366 let out = compile(&mut source, &mut names, &machine, Flags::default())
367 .expect("every instruction has a rule");
368
369 assert_eq!(out.block_count(), 4);
373
374 let text = mir::print_func(&out, &names, ®S);
383 assert_eq!(
384 text,
385 "mfunc @f {\n\
386 block0:\n \
387 $rdi($rdi) = x64.arg_val_32\n \
388 $rsi($rsi) = x64.arg_val_32\n \
389 $rax = x64.cmp_set_l_32 $rdi, $rsi\n \
390 x64.test_rr_8 $rax\n \
391 x64.jcc_e block2, block1\n\
392 \nblock1:\n \
393 $rax = x64.mov_rr_64 $rdi\n \
394 x64.jmp block3\n\
395 \nblock2:\n \
396 $rax = x64.mov_rr_64 $rsi, block3\n\
397 \nblock3:\n \
398 x64.ret_val_32 $rax($rax)\n \
399 x64.ret\n\
400 }\n"
401 );
402 }
403
404 #[test]
410 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
411 let i32 = Type::int(32);
412 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
413 let head = source.create_block();
414 let body = source.create_block();
415 let exit = source.create_block();
416 let left = source.append_param(head, i32);
417 let right = source.append_param(head, i32);
418 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
419 let mut build = Builder::new(&mut source, head);
420 let zero = build.iconst(i32, 0);
421 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
422 build.br_if(more, body, &[], exit, &[left]);
423 let mut build = Builder::new(&mut source, body);
424 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
425 build.jump(head, &[right, rest]);
426 let result = source.append_param(exit, i32);
427 Builder::new(&mut source, exit).ret(&[result]);
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 assert_eq!(
449 mir::print_func(&out, &names, ®S),
450 "mfunc @f {\n\
451 block0:\n \
452 $rdi($rdi) = x64.arg_val_32\n \
453 $rsi($rsi) = x64.arg_val_32\n \
454 $rcx = x64.mov_rr_64 $rdi, block1\n\
455 \nblock1:\n \
456 $rax = x64.mov_ri_32 0\n \
457 $rax = x64.cmp_set_ne_32 $rsi, $rax\n \
458 x64.test_rr_8 $rax\n \
459 x64.jcc_e block3, block2\n\
460 \nblock2:\n \
461 $rax = x64.mov_rr_64 $rcx\n \
462 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
463 $rdi = x64.mov_rr_64 $rax\n \
464 $rcx = x64.mov_rr_64 $rsi\n \
465 $rsi = x64.mov_rr_64 $rdx\n \
466 x64.jmp block1\n\
467 \nblock3:\n \
468 $rax = x64.mov_rr_64 $rcx\n \
469 x64.ret_val_32 $rax($rax)\n \
470 x64.ret\n\
471 }\n"
472 );
473 }
474
475 #[test]
480 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
481 let i32 = Type::int(32);
482 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
483 let then = source.create_block();
484 let join = source.create_block();
485 let got = source.append_param(join, i32);
486 let mut build = Builder::new(&mut source, entry);
487 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
488 build.br_if(cond, then, &[], join, &[args[1]]);
489 Builder::new(&mut source, then).jump(join, &[args[0]]);
490 Builder::new(&mut source, join).ret(&[got]);
491
492 let machine = Machine::x86_64(&SYSV);
493 let out = compile(&mut source, &mut names, &machine, Flags::default())
494 .expect("every instruction has a rule");
495
496 let text = mir::print_func(&out, &names, ®S);
497 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
498 assert_eq!(mir::print(&read, &names, ®S), text);
499 }
500
501 #[test]
502 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
503 let f80 = Type::float(rucc_ir::Float::F80);
504 let (mut names, mut source, block, args) = blank(&[f80]);
505 Builder::new(&mut source, block).ret(&[args[0]]);
506
507 let machine = Machine::x86_64(&SYSV);
508 let failed = compile(&mut source, &mut names, &machine, Flags::default())
509 .expect_err("a long double arrives on the x87 stack");
510 assert_eq!(failed.to_string(), "parameter 0 is on the x87 stack");
511 }
512
513 #[test]
517 fn a_float_is_added_in_the_register_file_it_arrives_in() {
518 let f32 = Type::float(rucc_ir::Float::F32);
519 let (mut names, mut source, block, args) = blank(&[f32, f32]);
520 let mut build = Builder::new(&mut source, block);
521 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
522 build.ret(&[sum]);
523
524 let machine = Machine::x86_64(&SYSV);
525 let out = compile(&mut source, &mut names, &machine, Flags::default())
526 .expect("every instruction has a rule");
527
528 let text = mir::print_func(&out, &names, ®S);
529 assert!(text.contains("x64.addss_rr"), "{text}");
530 assert!(text.contains("$xmm0"), "{text}");
531 assert!(!text.contains("$rax"), "{text}");
532 }
533
534 #[test]
537 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
538 let f64 = Type::float(rucc_ir::Float::F64);
539 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
540 let mut build = Builder::new(&mut source, block);
541 let info = rucc_ir::MemInfo {
542 size: 8,
543 align: 8,
544 order: rucc_ir::MemOrder::NotAtomic,
545 tbaa: None,
546 restrict: Restrict::NONE,
547 };
548 let read = build.load(f64, args[0], info, ir::Flags::default());
549 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
550 build.store(sum, args[0], info, ir::Flags::default());
551 build.ret(&[sum]);
552
553 let machine = Machine::x86_64(&SYSV);
554 let out = compile(&mut source, &mut names, &machine, Flags::default())
555 .expect("every instruction has a rule");
556
557 let text = mir::print_func(&out, &names, ®S);
558 assert!(text.contains("x64.movsd_rm"), "{text}");
559 assert!(text.contains("x64.movsd_mr"), "{text}");
560 assert!(!text.contains("x64.movaps_rm"), "{text}");
563 assert!(!text.contains("x64.movaps_mr"), "{text}");
564 }
565
566 #[test]
571 fn a_conversion_carries_the_value_into_the_other_register_file() {
572 let f64 = Type::float(rucc_ir::Float::F64);
573 let (mut names, mut source, block, args) = blank(&[f64]);
574 let mut build = Builder::new(&mut source, block);
575 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
576 let back = build.unary(Opcode::SIToFP, whole, f64);
577 build.ret(&[back]);
578
579 let machine = Machine::x86_64(&SYSV);
580 let out = compile(&mut source, &mut names, &machine, Flags::default())
581 .expect("every instruction has a rule");
582
583 let text = mir::print_func(&out, &names, ®S);
586 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
587 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
588 assert!(text.contains("$xmm0"), "{text}");
589 }
590
591 #[test]
594 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
595 let f64 = Type::float(rucc_ir::Float::F64);
596 let (mut names, mut source, block, args) = blank(&[f64]);
597 let mut build = Builder::new(&mut source, block);
598 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
599 build.ret(&[bits]);
600
601 let machine = Machine::x86_64(&SYSV);
602 let out = compile(&mut source, &mut names, &machine, Flags::default())
603 .expect("every instruction has a rule");
604
605 let text = mir::print_func(&out, &names, ®S);
606 assert!(text.contains("x64.movq_from_xmm"), "{text}");
607 assert!(!text.contains("cvt"), "{text}");
608 }
609
610 #[test]
612 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
613 let f64 = Type::float(rucc_ir::Float::F64);
614 let (mut names, mut source, block, args) = blank(&[f64, f64]);
615 let mut build = Builder::new(&mut source, block);
616 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
617 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
618 build.ret(&[wide]);
619
620 let machine = Machine::x86_64(&SYSV);
621 let out = compile(&mut source, &mut names, &machine, Flags::default())
622 .expect("every instruction has a rule");
623
624 let text = mir::print_func(&out, &names, ®S);
627 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
628 }
629
630 #[test]
635 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
636 let f64 = Type::float(rucc_ir::Float::F64);
637 let (mut names, mut source, block, args) = blank(&[f64, f64]);
638 let mut build = Builder::new(&mut source, block);
639 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
640 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
641 build.ret(&[wide]);
642
643 let machine = Machine::x86_64(&SYSV);
644 let out = compile(&mut source, &mut names, &machine, Flags::default())
645 .expect("every instruction has a rule");
646
647 let text = mir::print_func(&out, &names, ®S);
648 let line = text
649 .lines()
650 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
651 .expect("the rule for an ordered equality fired");
652 let written: Vec<&str> = line
653 .split_once('=')
654 .expect("the instruction writes something")
655 .0
656 .split(',')
657 .map(str::trim)
658 .collect();
659 assert_eq!(written.len(), 2, "{line}");
660 assert_ne!(written[0], written[1], "{line}");
661 }
662
663 #[test]
667 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
668 let f64 = Type::float(rucc_ir::Float::F64);
669 let (mut names, mut source, block, _) = blank(&[]);
670 let mut build = Builder::new(&mut source, block);
671 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
672 build.ret(&[half]);
673
674 let machine = Machine::x86_64(&SYSV);
675 let out = compile(&mut source, &mut names, &machine, Flags::default())
676 .expect("every instruction has a rule");
677
678 let text = mir::print_func(&out, &names, ®S);
679 assert!(text.contains("x64.mov_ri_64"), "{text}");
680 assert!(text.contains("x64.movq_to_xmm"), "{text}");
681 }
682
683 #[test]
686 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
687 let f64 = Type::float(rucc_ir::Float::F64);
688 let (mut names, mut source, block, args) = blank(&[f64]);
689 let mut build = Builder::new(&mut source, block);
690 let less = build.unary(Opcode::FNeg, args[0], f64);
691 build.ret(&[less]);
692
693 let machine = Machine::x86_64(&SYSV);
694 let out = compile(&mut source, &mut names, &machine, Flags::default())
695 .expect("every instruction has a rule");
696
697 let text = mir::print_func(&out, &names, ®S);
698 assert!(text.contains("x64.xor_rr_64"), "{text}");
699 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
700 }
701
702 #[test]
703 fn the_flags_reach_the_frame() {
704 let i32 = Type::int(32);
705 let (mut names, mut source, block, args) = blank(&[i32]);
706 Builder::new(&mut source, block).ret(&[args[0]]);
707
708 let machine = Machine::x86_64(&SYSV);
709 let flags = Flags { frame_pointer: true, red_zone: true };
710 let out = compile(&mut source, &mut names, &machine, flags)
711 .expect("every instruction has a rule");
712
713 let text = mir::print_func(&out, &names, ®S);
716 assert!(text.contains("x64.push_64 $rbp"), "{text}");
717 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
718 }
719
720 #[test]
721 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
722 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
723 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
724 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
725 assert!(std::ptr::eq(machine.conv, &SYSV));
726
727 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
728 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
729 assert!(std::ptr::eq(machine.conv, &WIN64));
730
731 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
734 assert!(Machine::for_target(&info).is_none());
735 }
736}