1use std::collections::HashSet;
27
28use rucc_base::Interner;
29use rucc_ir as ir;
30use rucc_mir as mir;
31use rucc_regalloc::assign::Env;
32use rucc_target::{BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
33use rucc_tuple::Arch;
34
35use crate::coverage::Fired;
36use crate::elsewhere::Elsewhere;
37use crate::expand;
38use crate::finish::{Convention, Probing, Protect, finish};
39use crate::fold;
40use crate::frame::{Frame, Layout};
41use crate::layout;
42use crate::lower::{self, Unsupported};
43use crate::pressure::{Cost, Pressure};
44use crate::retry;
45use crate::split;
46use crate::switch;
47use crate::varargs;
48use crate::widths;
49
50#[derive(Debug)]
59pub struct Machine {
60 pub conv: &'static CallRegs,
62 pub file: RegFile,
64 pub insts: &'static FrameInsts,
66 pub branch: &'static BranchInsts,
68 pub env: Env,
70}
71
72const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
87
88const SCRATCH_COUNT: usize = SCRATCH.len();
90
91impl Machine {
92 #[must_use]
99 pub fn x86_64(conv: &'static CallRegs) -> Self {
100 let order: Vec<PhysReg> =
101 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
102 let free: Vec<PhysReg> =
109 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
110 let at = free.len().saturating_sub(SCRATCH_COUNT);
111 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
112 let sse_order: Vec<PhysReg> =
113 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
114 Self {
115 conv,
116 file: x86_64::REGS,
117 insts: &x86_64::FRAME,
118 branch: &x86_64::BRANCH,
119 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
120 x86_64::XMM,
121 &sse_order,
122 &sse_scratch,
123 ),
124 }
125 }
126
127 #[must_use]
134 pub fn for_target(target: &TargetInfo) -> Option<Self> {
135 let conv = target.call_regs?;
136 match target.tuple.arch() {
137 Arch::X86_64 => Some(Self::x86_64(conv)),
138 _ => None,
139 }
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct Flags {
146 pub frame_pointer: bool,
148 pub red_zone: bool,
150 pub stack_clash: bool,
152}
153
154impl Default for Flags {
155 fn default() -> Self {
159 Self { frame_pointer: false, red_zone: true, stack_clash: false }
160 }
161}
162
163pub fn compile(
182 source: &mut ir::Func,
183 names: &mut Interner,
184 machine: &Machine,
185 elsewhere: &Elsewhere,
186 flags: Flags,
187) -> Result<mir::Func, Unsupported> {
188 compile_recording(
189 source,
190 names,
191 machine,
192 elsewhere,
193 flags,
194 &mut Fired::new(),
195 &mut Pressure::new(),
196 )
197}
198
199pub fn compile_recording(
215 source: &mut ir::Func,
216 names: &mut Interner,
217 machine: &Machine,
218 elsewhere: &Elsewhere,
219 flags: Flags,
220 fired: &mut Fired,
221 pressure: &mut Pressure,
222) -> Result<mir::Func, Unsupported> {
223 switch::switches(source);
224 retry::loops(source);
229 expand::orderings(source, machine.conv.word);
232 widths::integers(source);
235 expand::bytes(source);
236 expand::counts(source);
237 expand::overflows(source);
238 expand::floats(source);
239 expand::bulk(source, names, machine.conv.word);
240 varargs::lists(source, machine.conv);
241 let lowered = lower::func(source, names, machine.conv, elsewhere)?;
242 fired.merge(&lowered.fired);
243 let lower::Lowered { mut func, stack, .. } = lowered;
244 let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
250 let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
251 let base = stack.layout(Layout::new(machine.conv, machine.file));
252 let layout = Layout {
253 frame_pointer: flags.frame_pointer,
254 red_zone: flags.red_zone,
255 protect: guard.is_some(),
256 leaf: base.leaf && guard.is_none(),
261 ..base
262 };
263
264 let waiting: HashSet<mir::Inst> = stack
270 .addresses
271 .iter()
272 .map(|&(inst, _)| inst)
273 .chain(stack.arguments.iter().map(|&(inst, _)| inst))
274 .collect();
275 fold::addresses(&mut func, machine.insts, names, &waiting);
276
277 let fusable = layout::fusable(&func, machine.branch, names);
282
283 split::critical(&mut func);
287 let called = names.resolve(func.name).to_owned();
288 let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
289 pressure.record(&called, Cost::of(&allocation));
290
291 let frame = Frame::of(&func, &allocation, &layout);
294 let scratch = machine.env.scratch(machine.conv.int_class);
295 let protect = guard.map(|guard| Protect {
296 guard,
297 branch: machine.branch,
298 scratch: [scratch[0], scratch[1]],
299 });
300 let probe = flags
304 .stack_clash
305 .then_some(machine.insts.probe.as_ref())
306 .flatten()
307 .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
308 let convention = Convention { protect, probe, ..Convention::new(machine.conv, machine.insts) };
309 finish(&mut func, &allocation, &frame, &stack, convention, names);
310
311 layout::blocks(&mut func, machine.branch, names, &fusable);
314 Ok(func)
315}
316
317#[cfg(test)]
318mod tests {
319 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
320 use rucc_target::x86_64::{REGS, SYSV, WIN64};
321
322 use super::*;
323
324 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
326 let mut names = Interner::new();
327 let mut func = Func::new(names.intern("f"), Signature::new());
328 let block = func.create_block();
329 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
330 (names, func, block, values)
331 }
332
333 #[test]
334 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
335 let i32 = Type::int(32);
336 let (mut names, mut source, block, args) = blank(&[i32, i32]);
337 let mut build = Builder::new(&mut source, block);
338 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
339 build.ret(&[sum]);
340
341 let machine = Machine::x86_64(&SYSV);
342 let out =
343 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
344 .expect("every instruction has a rule");
345
346 assert_eq!(
351 mir::print_func(&out, &names, ®S),
352 "mfunc @f {\n\
353 block0:\n \
354 $rdi($rdi) = x64.arg_val_32\n \
355 $rsi($rsi) = x64.arg_val_32\n \
356 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
357 $rax = x64.mov_rr_64 $rdi\n \
358 x64.ret_val_32 $rax($rax)\n \
359 x64.ret\n\
360 }\n"
361 );
362 }
363
364 #[test]
368 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
369 let i32 = Type::int(32);
370 let (mut names, mut source, block, args) = blank(&[i32, i32]);
371 let mut build = Builder::new(&mut source, block);
372 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
373 build.ret(&[sum]);
374
375 let machine = Machine::x86_64(&SYSV);
376 let mut fired = Fired::new();
377 compile_recording(
378 &mut source,
379 &mut names,
380 &machine,
381 &Elsewhere::default(),
382 Flags::default(),
383 &mut fired,
384 &mut Pressure::new(),
385 )
386 .expect("every instruction has a rule");
387 let one = fired.count();
388 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
389
390 let listing = fired.listing(&crate::select::x86_64::TABLE);
391 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
392 assert!(
393 listing.contains(&format!("{one} of ")),
394 "{}",
395 listing.lines().next().unwrap_or("")
396 );
397
398 let (mut names, mut source, block, args) = blank(&[i32, i32]);
400 let mut build = Builder::new(&mut source, block);
401 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
402 build.ret(&[difference]);
403 compile_recording(
404 &mut source,
405 &mut names,
406 &machine,
407 &Elsewhere::default(),
408 Flags::default(),
409 &mut fired,
410 &mut Pressure::new(),
411 )
412 .expect("every instruction has a rule");
413 assert!(fired.count() > one, "a subtraction is not an addition");
414 }
415
416 #[test]
417 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
418 let i32 = Type::int(32);
419 let (mut names, mut source, block, args) = blank(&[i32]);
420 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
421 let callee = names.intern("g");
422 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
423 let got = source[call].first_result.expect("an integer comes back");
424 let mut build = Builder::new(&mut source, block);
425 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
426 build.ret(&[sum]);
427
428 let machine = Machine::x86_64(&SYSV);
429 let out =
430 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
431 .expect("every instruction has a rule");
432
433 let text = mir::print_func(&out, &names, ®S);
436 assert!(text.contains("x64.push_64 $rbx"), "{text}");
437 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
438 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
439 assert!(!text.contains('%'), "{text}");
440 }
441
442 #[test]
443 fn the_other_convention_is_the_same_function_somewhere_else() {
444 let i32 = Type::int(32);
445 let (mut names, mut source, block, args) = blank(&[i32, i32]);
446 let mut build = Builder::new(&mut source, block);
447 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
448 build.ret(&[sum]);
449
450 let machine = Machine::x86_64(&WIN64);
451 let out =
452 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
453 .expect("every instruction has a rule");
454
455 let text = mir::print_func(&out, &names, ®S);
458 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
459 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
460 assert!(!text.contains("$rdi"), "{text}");
461 }
462
463 #[test]
464 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
465 let i32 = Type::int(32);
466 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
467 let then = source.create_block();
468 let join = source.create_block();
469 let got = source.append_param(join, i32);
470 let mut build = Builder::new(&mut source, entry);
471 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
472 build.br_if(cond, then, &[], join, &[args[1]]);
473 Builder::new(&mut source, then).jump(join, &[args[0]]);
474 Builder::new(&mut source, join).ret(&[got]);
475
476 let machine = Machine::x86_64(&SYSV);
477 let out =
478 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
479 .expect("every instruction has a rule");
480
481 assert_eq!(out.block_count(), 4);
485
486 let text = mir::print_func(&out, &names, ®S);
495 assert_eq!(
496 text,
497 "mfunc @f {\n\
498 block0:\n \
499 $rdi($rdi) = x64.arg_val_32\n \
500 $rsi($rsi) = x64.arg_val_32\n \
501 x64.cmp_rr_32 $rdi, $rsi\n \
502 x64.jcc_ge block2, block1\n\
503 \nblock1:\n \
504 $rax = x64.mov_rr_64 $rdi\n \
505 x64.jmp block3\n\
506 \nblock2:\n \
507 $rax = x64.mov_rr_64 $rsi, block3\n\
508 \nblock3:\n \
509 x64.ret_val_32 $rax($rax)\n \
510 x64.ret\n\
511 }\n"
512 );
513 }
514
515 #[test]
521 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
522 let i32 = Type::int(32);
523 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
524 let head = source.create_block();
525 let body = source.create_block();
526 let exit = source.create_block();
527 let left = source.append_param(head, i32);
528 let right = source.append_param(head, i32);
529 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
530 let mut build = Builder::new(&mut source, head);
531 let zero = build.iconst(i32, 0);
532 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
533 build.br_if(more, body, &[], exit, &[left]);
534 let mut build = Builder::new(&mut source, body);
535 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
536 build.jump(head, &[right, rest]);
537 let result = source.append_param(exit, i32);
538 Builder::new(&mut source, exit).ret(&[result]);
539
540 let machine = Machine::x86_64(&SYSV);
541 let out =
542 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
543 .expect("every instruction has a rule");
544
545 assert_eq!(
561 mir::print_func(&out, &names, ®S),
562 "mfunc @f {\n\
563 block0:\n \
564 $rdi($rdi) = x64.arg_val_32\n \
565 $rsi($rsi) = x64.arg_val_32\n \
566 $rcx = x64.mov_rr_64 $rdi, block1\n\
567 \nblock1:\n \
568 x64.cmp_ri_32 $rsi, 0\n \
569 x64.jcc_e block3, block2\n\
570 \nblock2:\n \
571 $rax = x64.mov_rr_64 $rcx\n \
572 $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
573 $rdi = x64.mov_rr_64 $rax\n \
574 $rcx = x64.mov_rr_64 $rsi\n \
575 $rsi = x64.mov_rr_64 $rdx\n \
576 x64.jmp block1\n\
577 \nblock3:\n \
578 $rax = x64.mov_rr_64 $rcx\n \
579 x64.ret_val_32 $rax($rax)\n \
580 x64.ret\n\
581 }\n"
582 );
583 }
584
585 #[test]
590 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
591 let i32 = Type::int(32);
592 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
593 let then = source.create_block();
594 let join = source.create_block();
595 let got = source.append_param(join, i32);
596 let mut build = Builder::new(&mut source, entry);
597 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
598 build.br_if(cond, then, &[], join, &[args[1]]);
599 Builder::new(&mut source, then).jump(join, &[args[0]]);
600 Builder::new(&mut source, join).ret(&[got]);
601
602 let machine = Machine::x86_64(&SYSV);
603 let out =
604 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
605 .expect("every instruction has a rule");
606
607 let text = mir::print_func(&out, &names, ®S);
608 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
609 assert_eq!(mir::print(&read, &names, ®S), text);
610 }
611
612 #[test]
613 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
614 let f80 = Type::float(rucc_ir::Float::F80);
615 let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
616 Builder::new(&mut source, block).ret(&args);
617
618 let machine = Machine::x86_64(&SYSV);
622 let failed =
623 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
624 .expect_err("a long double cannot come back beside another value");
625 assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
626 }
627
628 #[test]
636 fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
637 let f80 = Type::float(rucc_ir::Float::F80);
638 let (mut names, mut source, block, args) = blank(&[f80, f80]);
639 let mut build = Builder::new(&mut source, block);
640 let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
641 build.ret(&[sum]);
642
643 let machine = Machine::x86_64(&SYSV);
644 let out =
645 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
646 .expect("every instruction has a rule");
647
648 let text = mir::print_func(&out, &names, ®S);
649 assert!(text.contains("x64.lea_64 [$rsp + 32]"), "{text}");
652 assert!(text.contains("x64.lea_64 [$rsp + 48]"), "{text}");
653 assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
654 let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
657 assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rax]"], "{text}");
658 }
659
660 #[test]
664 fn a_float_is_added_in_the_register_file_it_arrives_in() {
665 let f32 = Type::float(rucc_ir::Float::F32);
666 let (mut names, mut source, block, args) = blank(&[f32, f32]);
667 let mut build = Builder::new(&mut source, block);
668 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
669 build.ret(&[sum]);
670
671 let machine = Machine::x86_64(&SYSV);
672 let out =
673 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
674 .expect("every instruction has a rule");
675
676 let text = mir::print_func(&out, &names, ®S);
677 assert!(text.contains("x64.addss_rr"), "{text}");
678 assert!(text.contains("$xmm0"), "{text}");
679 assert!(!text.contains("$rax"), "{text}");
680 }
681
682 #[test]
685 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
686 let f64 = Type::float(rucc_ir::Float::F64);
687 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
688 let mut build = Builder::new(&mut source, block);
689 let info = rucc_ir::MemInfo {
690 size: 8,
691 align: 8,
692 order: rucc_ir::MemOrder::NotAtomic,
693 tbaa: None,
694 restrict: Restrict::NONE,
695 };
696 let read = build.load(f64, args[0], info, ir::Flags::default());
697 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
698 build.store(sum, args[0], info, ir::Flags::default());
699 build.ret(&[sum]);
700
701 let machine = Machine::x86_64(&SYSV);
702 let out =
703 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
704 .expect("every instruction has a rule");
705
706 let text = mir::print_func(&out, &names, ®S);
707 assert!(text.contains("x64.movsd_rm"), "{text}");
708 assert!(text.contains("x64.movsd_mr"), "{text}");
709 assert!(!text.contains("x64.movaps_rm"), "{text}");
712 assert!(!text.contains("x64.movaps_mr"), "{text}");
713 }
714
715 #[test]
723 fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
724 let f80 = Type::float(rucc_ir::Float::F80);
725 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
726 let mut build = Builder::new(&mut source, block);
727 let info = rucc_ir::MemInfo {
728 size: 16,
729 align: 16,
730 order: rucc_ir::MemOrder::NotAtomic,
731 tbaa: None,
732 restrict: Restrict::NONE,
733 };
734 let wide = build.unary(Opcode::UIToFP, args[1], f80);
735 build.store(wide, args[0], info, ir::Flags::default());
736 let read = build.load(f80, args[0], info, ir::Flags::default());
737 let back = build.unary(Opcode::FPToUI, read, Type::int(64));
738 build.ret(&[back]);
739
740 let machine = Machine::x86_64(&SYSV);
741 let out =
742 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
743 .expect("every instruction has a rule");
744
745 let text = mir::print_func(&out, &names, ®S);
746 assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
749 assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
750 assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
751 assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
752 assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
753 assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
754 }
755
756 #[test]
761 fn a_conversion_carries_the_value_into_the_other_register_file() {
762 let f64 = Type::float(rucc_ir::Float::F64);
763 let (mut names, mut source, block, args) = blank(&[f64]);
764 let mut build = Builder::new(&mut source, block);
765 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
766 let back = build.unary(Opcode::SIToFP, whole, f64);
767 build.ret(&[back]);
768
769 let machine = Machine::x86_64(&SYSV);
770 let out =
771 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
772 .expect("every instruction has a rule");
773
774 let text = mir::print_func(&out, &names, ®S);
777 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
778 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
779 assert!(text.contains("$xmm0"), "{text}");
780 }
781
782 #[test]
785 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
786 let f64 = Type::float(rucc_ir::Float::F64);
787 let (mut names, mut source, block, args) = blank(&[f64]);
788 let mut build = Builder::new(&mut source, block);
789 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
790 build.ret(&[bits]);
791
792 let machine = Machine::x86_64(&SYSV);
793 let out =
794 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
795 .expect("every instruction has a rule");
796
797 let text = mir::print_func(&out, &names, ®S);
798 assert!(text.contains("x64.movq_from_xmm"), "{text}");
799 assert!(!text.contains("cvt"), "{text}");
800 }
801
802 #[test]
804 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
805 let f64 = Type::float(rucc_ir::Float::F64);
806 let (mut names, mut source, block, args) = blank(&[f64, f64]);
807 let mut build = Builder::new(&mut source, block);
808 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
809 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
810 build.ret(&[wide]);
811
812 let machine = Machine::x86_64(&SYSV);
813 let out =
814 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
815 .expect("every instruction has a rule");
816
817 let text = mir::print_func(&out, &names, ®S);
820 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
821 }
822
823 #[test]
828 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
829 let f64 = Type::float(rucc_ir::Float::F64);
830 let (mut names, mut source, block, args) = blank(&[f64, f64]);
831 let mut build = Builder::new(&mut source, block);
832 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
833 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
834 build.ret(&[wide]);
835
836 let machine = Machine::x86_64(&SYSV);
837 let out =
838 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
839 .expect("every instruction has a rule");
840
841 let text = mir::print_func(&out, &names, ®S);
842 let line = text
843 .lines()
844 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
845 .expect("the rule for an ordered equality fired");
846 let written: Vec<&str> = line
847 .split_once('=')
848 .expect("the instruction writes something")
849 .0
850 .split(',')
851 .map(str::trim)
852 .collect();
853 assert_eq!(written.len(), 2, "{line}");
854 assert_ne!(written[0], written[1], "{line}");
855 }
856
857 #[test]
861 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
862 let f64 = Type::float(rucc_ir::Float::F64);
863 let (mut names, mut source, block, _) = blank(&[]);
864 let mut build = Builder::new(&mut source, block);
865 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
866 build.ret(&[half]);
867
868 let machine = Machine::x86_64(&SYSV);
869 let out =
870 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
871 .expect("every instruction has a rule");
872
873 let text = mir::print_func(&out, &names, ®S);
874 assert!(text.contains("x64.mov_ri_64"), "{text}");
875 assert!(text.contains("x64.movq_to_xmm"), "{text}");
876 }
877
878 #[test]
881 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
882 let f64 = Type::float(rucc_ir::Float::F64);
883 let (mut names, mut source, block, args) = blank(&[f64]);
884 let mut build = Builder::new(&mut source, block);
885 let less = build.unary(Opcode::FNeg, args[0], f64);
886 build.ret(&[less]);
887
888 let machine = Machine::x86_64(&SYSV);
889 let out =
890 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
891 .expect("every instruction has a rule");
892
893 let text = mir::print_func(&out, &names, ®S);
894 assert!(text.contains("x64.xor_rr_64"), "{text}");
895 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
896 }
897
898 #[test]
899 fn the_flags_reach_the_frame() {
900 let i32 = Type::int(32);
901 let (mut names, mut source, block, args) = blank(&[i32]);
902 Builder::new(&mut source, block).ret(&[args[0]]);
903
904 let machine = Machine::x86_64(&SYSV);
905 let flags = Flags { frame_pointer: true, red_zone: true, stack_clash: false };
906 let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
907 .expect("every instruction has a rule");
908
909 let text = mir::print_func(&out, &names, ®S);
912 assert!(text.contains("x64.push_64 $rbp"), "{text}");
913 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
914 }
915
916 #[test]
917 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
918 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
919 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
920 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
921 assert!(std::ptr::eq(machine.conv, &SYSV));
922
923 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
924 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
925 assert!(std::ptr::eq(machine.conv, &WIN64));
926
927 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
930 assert!(Machine::for_target(&info).is_none());
931 }
932}