1use std::collections::{HashMap, HashSet};
91
92use rucc_base::Interner;
93use rucc_ir::{
94 Abi, Block, BlockCall, CallInfo, Def, Extra, Flags, Float, Func, Imm, Inst, InstData, IntPred,
95 MemInfo, MemOrder, Opcode, Param, Restrict, Signature, Type, Value,
96};
97use rucc_target::{AbiDescription, CallRegs, Places, Variadic, Where};
98
99use crate::capability;
100use crate::expand;
101
102const WIDE: u32 = 128;
104
105const MODE: &str = "i128";
107
108const HALF: u32 = 64;
110
111const STEP: u64 = 8;
113
114fn is_wide(ty: Type) -> bool {
116 ty.is_int() && ty.is_scalar() && ty.bits() == WIDE
117}
118
119fn half() -> Type {
121 Type::int(HALF)
122}
123
124pub fn halves(func: &mut Func, names: &mut Interner, conv: &CallRegs) -> bool {
135 if !func.values().any(|value| is_wide(func[value].ty)) {
136 return false;
137 }
138 let insts: Vec<Inst> =
139 walk(func).into_iter().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
140 let order: HashMap<Inst, usize> =
141 insts.iter().enumerate().map(|(at, &inst)| (inst, at)).collect();
142 if !insts.iter().enumerate().all(|(at, &inst)| can_split(func, conv, &order, at, inst)) {
143 return false;
144 }
145 let Some(arriving) = plan(func.signature(), conv) else { return false };
146 if !func.signatures().all(|signature| plan(signature, conv).is_some()) {
147 return false;
148 }
149
150 let mut halves: Halves = HashMap::new();
151 let mut forward: HashMap<Value, Value> = HashMap::new();
152 let entry = func.entry();
153 for block in func.blocks().collect::<Vec<_>>() {
154 if Some(block) == entry {
155 arrive(func, block, &arriving, &mut halves, &mut forward);
156 } else {
157 params(func, block, &mut halves, &mut forward);
158 }
159 }
160 for &inst in &insts {
161 rewrite(func, names, conv, &mut halves, &mut forward, inst);
162 }
163 substitute(func, &forward);
164 let signature = planned(func.signature(), &arriving);
165 func.set_signature(signature);
166 true
167}
168
169fn walk(func: &Func) -> Vec<Block> {
187 let Some(entry) = func.entry() else { return func.blocks().collect() };
188 let mut seen: HashSet<Block> = HashSet::new();
189 let mut order: Vec<Block> = Vec::new();
190 let mut stack: Vec<(Block, bool)> = vec![(entry, false)];
193 seen.insert(entry);
194 while let Some((block, done)) = stack.pop() {
195 if done {
196 order.push(block);
197 continue;
198 }
199 stack.push((block, true));
200 let Some(term) = func.terminator(block) else { continue };
201 for call in func.successors(term) {
202 if seen.insert(call.block) {
203 stack.push((call.block, false));
204 }
205 }
206 }
207 order.reverse();
208 order.extend(func.blocks().filter(|block| !seen.contains(block)));
209 order
210}
211
212type Halves = HashMap<Value, (Value, Value)>;
214
215fn understood(opcode: Opcode) -> bool {
226 matches!(
227 opcode,
228 Opcode::IConst
229 | Opcode::Load
230 | Opcode::Store
231 | Opcode::Add
232 | Opcode::Sub
233 | Opcode::Mul
234 | Opcode::UDiv
235 | Opcode::SDiv
236 | Opcode::URem
237 | Opcode::SRem
238 | Opcode::Shl
239 | Opcode::LShr
240 | Opcode::AShr
241 | Opcode::And
242 | Opcode::Or
243 | Opcode::Xor
244 | Opcode::ICmp
245 | Opcode::Select
246 | Opcode::SIToFP
247 | Opcode::UIToFP
248 | Opcode::FPToSI
249 | Opcode::FPToUI
250 | Opcode::Trunc
251 | Opcode::SExt
252 | Opcode::ZExt
253 | Opcode::Call
254 | Opcode::CallIndirect
255 | Opcode::Return
256 | Opcode::Jump
257 | Opcode::BrIf
258 )
259}
260
261fn can_split(
266 func: &Func,
267 conv: &CallRegs,
268 order: &HashMap<Inst, usize>,
269 at: usize,
270 inst: Inst,
271) -> bool {
272 let data = func[inst];
273 let reads = operands(func, inst);
274 let wide = |&value: &Value| is_wide(func[value].ty);
275 if !reads.iter().any(wide) && !data.results().any(|value| is_wide(func[value].ty)) {
276 return true;
277 }
278 if !understood(data.opcode) {
279 return false;
280 }
281 if func.carries_mem(inst) {
285 return false;
286 }
287 if data.opcode == Opcode::SExt && reads.iter().any(|&value| func[value].ty.bits() < 8) {
291 return false;
292 }
293 if matches!(data.opcode, Opcode::SIToFP | Opcode::UIToFP | Opcode::FPToSI | Opcode::FPToUI)
298 && converted(func, inst).is_none()
299 {
300 return false;
301 }
302 if matches!(data.opcode, Opcode::Call | Opcode::CallIndirect) {
309 let Some((site, variadic)) = site(func, inst) else { return false };
310 let in_memory = conv.abi.variadic == Variadic::AlwaysMemory;
311 if variadic && (conv.shared_positions || in_memory || plan(&site, conv).is_none()) {
312 return false;
313 }
314 }
315 reads.iter().filter(|value| wide(value)).all(|&value| match func[value].def {
319 Def::Result { inst, .. } => order.get(&inst).is_some_and(|&def| def < at),
320 Def::Param { .. } => true,
321 })
322}
323
324fn converted(func: &Func, inst: Inst) -> Option<Float> {
331 let data = func[inst];
332 let mut floats = func[data.args]
333 .iter()
334 .copied()
335 .chain(data.results())
336 .map(|value| func[value].ty)
337 .filter(|ty| ty.is_float());
338 let only = floats.next()?;
339 if floats.next().is_some() {
340 return None;
341 }
342 match only.format() {
343 Some(format @ (Float::F32 | Float::F64 | Float::F128)) => Some(format),
344 _ => None,
345 }
346}
347
348fn operands(func: &Func, inst: Inst) -> Vec<Value> {
354 let mut reads = func[func[inst].args].to_vec();
355 for call in func.successors(inst).collect::<Vec<_>>() {
356 reads.extend_from_slice(&func[call.args]);
357 }
358 reads
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363enum Slot {
364 Whole(usize),
366 Low(usize),
368 High(usize),
370 Filler(Type),
372}
373
374fn plan(signature: &Signature, conv: &CallRegs) -> Option<Vec<Slot>> {
400 let word = Param::new(half());
401 let mut places = Places::new(conv);
402 let mut meant: Vec<(Slot, Param, Where)> = Vec::new();
403 let mut moved = false;
404 for (index, ¶m) in signature.params.iter().enumerate() {
405 if !is_wide(param.ty) {
406 meant.push((Slot::Whole(index), param, place(&mut places, param, conv)));
407 continue;
408 }
409 let mut ahead = places.clone();
410 if let (low @ Where::Reg(_), high @ Where::Reg(_)) =
411 (ahead.integer(HALF / 8), ahead.integer(HALF / 8))
412 {
413 places = ahead;
414 meant.push((Slot::Low(index), word, low));
415 meant.push((Slot::High(index), word, high));
416 continue;
417 }
418 let Where::Stack(at) = places.on_stack(WIDE / 8, WIDE / 8) else { return None };
419 meant.push((Slot::Low(index), word, Where::Stack(at)));
420 meant.push((Slot::High(index), word, Where::Stack(at + HALF / 8)));
421 moved = true;
422 }
423 if !moved {
424 return Some(meant.into_iter().map(|(slot, _, _)| slot).collect());
425 }
426 if signature.variadic || conv.shared_positions {
427 return None;
428 }
429
430 let in_reg = |at: &Where| matches!(at, Where::Reg(_));
431 let mut stacked: Vec<&(Slot, Param, Where)> =
432 meant.iter().filter(|(_, _, at)| !in_reg(at)).collect();
433 stacked.sort_by_key(|(_, _, at)| match at {
434 Where::Stack(up) => *up,
435 Where::Reg(_) => 0,
436 });
437 let mut order: Vec<(Slot, Param, Option<Where>)> = Vec::new();
438 for float in [false, true] {
439 let kind = |param: &Param| scalar(*param) && param.ty.is_float() == float;
440 order.extend(
441 meant
442 .iter()
443 .filter(|(_, param, at)| kind(param) && in_reg(at))
444 .map(|&(slot, param, at)| (slot, param, Some(at))),
445 );
446 let (count, filler) = match float {
447 false => (conv.int_args.len(), word),
448 true => (conv.sse_args.len(), Param::new(Type::float(Float::F64))),
449 };
450 if stacked.iter().any(|(_, param, _)| kind(param)) {
451 let took = order.iter().filter(|(_, param, _)| kind(param)).count();
452 let padding = count.saturating_sub(took);
453 order.extend((0..padding).map(|_| (Slot::Filler(filler.ty), filler, None)));
454 }
455 }
456
457 let mut places = Places::new(conv);
458 let mut slots = Vec::with_capacity(order.len() + stacked.len());
459 for (slot, param, meant) in order {
460 let at = place(&mut places, param, conv);
461 if !in_reg(&at) || meant.is_some_and(|meant| meant != at) {
462 return None;
463 }
464 slots.push(slot);
465 }
466 for &&(slot, param, meant) in &stacked {
467 let Where::Stack(up) = meant else { return None };
468 while places.size() < up {
469 if in_reg(&place(&mut places, word, conv)) {
470 return None;
471 }
472 slots.push(Slot::Filler(word.ty));
473 }
474 if place(&mut places, param, conv) != meant {
475 return None;
476 }
477 slots.push(slot);
478 }
479 Some(slots)
480}
481
482fn place(places: &mut Places<'_>, param: Param, conv: &CallRegs) -> Where {
484 if let Abi::ByVal { size, align, drains } = param.abi {
488 let at = places.object(u32::try_from(size).unwrap_or(u32::MAX), align);
489 crate::abi::drain(places, drains);
490 at
491 } else if crate::abi::on_the_stack(param.ty) {
492 let (size, align) = crate::abi::X87_AREA;
493 places.on_stack(size, align)
494 } else if param.ty.is_float() {
495 places.float(crate::abi::float_bytes(param.ty))
496 } else {
497 places.integer(crate::abi::int_bytes(param.ty, conv))
498 }
499}
500
501fn scalar(param: Param) -> bool {
503 !matches!(param.abi, Abi::ByVal { .. }) && !crate::abi::on_the_stack(param.ty)
504}
505
506fn planned(signature: &Signature, slots: &[Slot]) -> Signature {
508 let params = slots
509 .iter()
510 .map(|&slot| match slot {
511 Slot::Whole(index) => signature.params[index],
512 Slot::Low(_) | Slot::High(_) => Param::new(half()),
513 Slot::Filler(ty) => Param::new(ty),
514 })
515 .collect();
516 Signature { params, ..split_signature(signature) }
517}
518
519fn params(func: &mut Func, block: Block, halves: &mut Halves, forward: &mut HashMap<Value, Value>) {
526 let old: Vec<Value> = func[block].params.clone();
527 if !old.iter().any(|&value| is_wide(func[value].ty)) {
528 return;
529 }
530 for &value in &old {
531 if is_wide(func[value].ty) {
532 let low = func.append_param(block, half());
533 let high = func.append_param(block, half());
534 halves.insert(value, (low, high));
535 } else {
536 let again = func.append_param(block, func[value].ty);
537 forward.insert(value, again);
538 }
539 }
540 func.retain_params(block, |value| !old.contains(&value));
541}
542
543fn arrive(
545 func: &mut Func,
546 block: Block,
547 slots: &[Slot],
548 halves: &mut Halves,
549 forward: &mut HashMap<Value, Value>,
550) {
551 let old: Vec<Value> = func[block].params.clone();
552 if !old.iter().any(|&value| is_wide(func[value].ty)) {
553 return;
554 }
555 let mut lows = HashMap::new();
556 for &slot in slots {
557 match slot {
558 Slot::Whole(index) => {
559 let again = func.append_param(block, func[old[index]].ty);
560 forward.insert(old[index], again);
561 }
562 Slot::Low(index) => {
563 lows.insert(index, func.append_param(block, half()));
564 }
565 Slot::High(index) => {
566 let high = func.append_param(block, half());
567 halves.insert(old[index], (lows[&index], high));
568 }
569 Slot::Filler(ty) => {
570 func.append_param(block, ty);
571 }
572 }
573 }
574 func.retain_params(block, |value| !old.contains(&value));
575}
576
577fn rewrite(
579 func: &mut Func,
580 names: &mut Interner,
581 conv: &CallRegs,
582 halves: &mut Halves,
583 forward: &mut HashMap<Value, Value>,
584 inst: Inst,
585) {
586 let abi = conv.abi;
587 let data = func[inst];
588 let produces = data.results().any(|value| is_wide(func[value].ty));
589 let takes = func[data.args].iter().any(|&value| is_wide(func[value].ty));
590 match data.opcode {
591 Opcode::IConst if produces => constant(func, halves, inst),
592 Opcode::Load if produces => load(func, halves, inst),
593 Opcode::Store if takes => store(func, halves, inst),
594 Opcode::Add | Opcode::Sub if produces => carried(func, halves, inst, data.opcode),
595 Opcode::Mul if produces => multiply(func, halves, inst),
596 Opcode::UDiv | Opcode::SDiv | Opcode::URem | Opcode::SRem if produces => {
597 divide(func, names, abi, halves, inst, data.opcode);
598 }
599 Opcode::Shl | Opcode::LShr | Opcode::AShr if produces => {
600 shifted(func, halves, inst, data.opcode);
601 }
602 Opcode::And | Opcode::Or | Opcode::Xor if produces => {
603 bitwise(func, halves, inst, data.opcode);
604 }
605 Opcode::SIToFP | Opcode::UIToFP if takes => {
606 to_float(func, names, abi, halves, forward, inst, data.opcode == Opcode::SIToFP);
607 }
608 Opcode::FPToSI | Opcode::FPToUI if produces => {
609 from_float(func, names, abi, halves, inst, data.opcode == Opcode::FPToSI);
610 }
611 Opcode::ICmp if takes => compare(func, halves, forward, inst),
612 Opcode::Select if produces => choose(func, halves, inst),
613 Opcode::Trunc if takes => truncate(func, halves, forward, inst),
614 Opcode::SExt | Opcode::ZExt if produces => {
615 extend(func, halves, inst, data.opcode == Opcode::SExt);
616 }
617 Opcode::Call | Opcode::CallIndirect if produces || takes => {
618 call(func, conv, halves, forward, inst);
619 }
620 Opcode::Return if takes => flatten(func, halves, inst),
621 Opcode::Jump | Opcode::BrIf => edges(func, halves, inst),
622 _ => {}
623 }
624}
625
626fn constant(func: &mut Func, halves: &mut Halves, inst: Inst) {
628 let Extra::Imm(imm) = func[inst].extra else { return };
629 let bits = func[imm].unsigned();
630 #[expect(clippy::cast_possible_truncation, reason = "the halves are what this is taking")]
631 let (low, high) = (bits as u64, (bits >> HALF) as u64);
632 let low = ahead_const(func, inst, i128::from(low));
633 let high = ahead_const(func, inst, i128::from(high));
634 replace(func, halves, inst, low, high);
635}
636
637fn load(func: &mut Func, halves: &mut Halves, inst: Inst) {
643 let data = func[inst];
644 let Extra::Mem(mem) = data.extra else { return };
645 let info = func[mem];
646 let Some(&from) = func[data.args].first() else { return };
647 let low = read(func, inst, from, word(info, 0), data.flags);
648 let up = stepped(func, inst, from);
649 let high = read(func, inst, up, word(info, STEP), data.flags);
650 replace(func, halves, inst, low, high);
651}
652
653fn store(func: &mut Func, halves: &mut Halves, inst: Inst) {
655 let data = func[inst];
656 let Extra::Mem(mem) = data.extra else { return };
657 let info = func[mem];
658 let args = func[data.args].to_vec();
659 let [value, into] = args[..] else { return };
660 let Some(&(low, high)) = halves.get(&value) else { return };
661 write(func, inst, low, into, word(info, 0), data.flags);
662 let up = stepped(func, inst, into);
663 write(func, inst, high, up, word(info, STEP), data.flags);
664 func.remove_inst(inst);
665}
666
667fn carried(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
677 let args = func[func[inst].args].to_vec();
678 let [a, b] = args[..] else { return };
679 let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
680 return;
681 };
682 let low = ahead(func, inst, opcode, &[a_low, b_low]);
683 let carried = if opcode == Opcode::Add {
684 compared(func, inst, IntPred::Ult, low, a_low)
685 } else {
686 compared(func, inst, IntPred::Ult, a_low, b_low)
687 };
688 let carry = ahead(func, inst, Opcode::ZExt, &[carried]);
689 let high = ahead(func, inst, opcode, &[a_high, b_high]);
690 let high = ahead(func, inst, opcode, &[high, carry]);
691 replace(func, halves, inst, low, high);
692}
693
694fn multiply(func: &mut Func, halves: &mut Halves, inst: Inst) {
714 let args = func[func[inst].args].to_vec();
715 let [a, b] = args[..] else { return };
716 let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
717 return;
718 };
719 let low = ahead(func, inst, Opcode::Mul, &[a_low, b_low]);
720 let carried = expand::high_half(func, inst, a_low, b_low, false, half());
721 let cross = ahead(func, inst, Opcode::Mul, &[a_low, b_high]);
722 let other = ahead(func, inst, Opcode::Mul, &[a_high, b_low]);
723 let high = ahead(func, inst, Opcode::Add, &[carried, cross]);
724 let high = ahead(func, inst, Opcode::Add, &[high, other]);
725 replace(func, halves, inst, low, high);
726}
727
728fn divide(
746 func: &mut Func,
747 names: &mut Interner,
748 abi: &'static AbiDescription,
749 halves: &mut Halves,
750 inst: Inst,
751 opcode: Opcode,
752) {
753 let args = func[func[inst].args].to_vec();
754 let [a, b] = args[..] else { return };
755 let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
756 return;
757 };
758 let Some(routine) = capability::libcall(opcode, MODE) else { return };
762 let args = [Operand::Split(a_low, a_high), Operand::Split(b_low, b_high)];
763 let made = runtime(func, names, abi, inst, routine, &args, &[half(), half()]);
764 let [low, high] = made[..] else { return };
765 replace(func, halves, inst, low, high);
766}
767
768fn to_float(
778 func: &mut Func,
779 names: &mut Interner,
780 abi: &'static AbiDescription,
781 halves: &Halves,
782 forward: &mut HashMap<Value, Value>,
783 inst: Inst,
784 signed: bool,
785) {
786 let Some(&arg) = func[func[inst].args].first() else { return };
787 let Some(&(low, high)) = halves.get(&arg) else { return };
788 let (Some(result), Some(format)) = (func[inst].first_result, converted(func, inst)) else {
789 return;
790 };
791 let routine = going_up(signed, format);
792 let args = [Operand::Split(low, high)];
793 let made = runtime(func, names, abi, inst, routine, &args, &[func[result].ty]);
794 if let [answer] = made[..] {
795 forward.insert(result, answer);
796 }
797 func.remove_inst(inst);
798}
799
800fn from_float(
810 func: &mut Func,
811 names: &mut Interner,
812 abi: &'static AbiDescription,
813 halves: &mut Halves,
814 inst: Inst,
815 signed: bool,
816) {
817 let Some(&arg) = func[func[inst].args].first() else { return };
818 let Some(format) = converted(func, inst) else { return };
819 let routine = coming_down(signed, format);
820 let args = [Operand::Whole(arg)];
821 let made = runtime(func, names, abi, inst, routine, &args, &[half(), half()]);
822 let [low, high] = made[..] else { return };
823 replace(func, halves, inst, low, high);
824}
825
826fn going_up(signed: bool, format: Float) -> &'static str {
832 let mode = match format {
833 Float::F32 => "i128.f32",
834 Float::F64 => "i128.f64",
835 _ => "i128.f128",
836 };
837 routine(if signed { Opcode::SIToFP } else { Opcode::UIToFP }, mode)
838}
839
840fn coming_down(signed: bool, format: Float) -> &'static str {
842 let mode = match format {
843 Float::F32 => "f32.i128",
844 Float::F64 => "f64.i128",
845 _ => "f128.i128",
846 };
847 routine(if signed { Opcode::FPToSI } else { Opcode::FPToUI }, mode)
848}
849
850fn routine(opcode: Opcode, mode: &str) -> &'static str {
855 capability::libcall(opcode, mode)
856 .unwrap_or_else(|| panic!("no routine for `{}` at `{mode}`", opcode.name()))
857}
858
859#[derive(Clone, Copy)]
865enum Operand {
866 Whole(Value),
868 Split(Value, Value),
870}
871
872fn runtime(
897 func: &mut Func,
898 names: &mut Interner,
899 abi: &'static AbiDescription,
900 inst: Inst,
901 routine: &str,
902 args: &[Operand],
903 results: &[Type],
904) -> Vec<Value> {
905 let mut params: Vec<Param> = Vec::new();
906 let mut values: Vec<Value> = Vec::new();
907 let mut answer = Answer::Registers;
908 match *results {
910 [ty] if abi.scalar_is_by_reference(bytes(ty)) => {
911 let size = bytes(ty);
912 let align = align(size);
913 let slot = room(func, inst, size, align);
914 params.push(Param::with_abi(Type::PTR, Abi::Sret { size, align }));
915 values.push(slot);
916 answer = Answer::Slot(slot, ty);
917 }
918 [low, high] if low == half() && high == half() => {
919 if let Some(format) = packed(abi) {
920 answer = Answer::Packed(format);
921 }
922 }
923 _ => {}
924 }
925 for &arg in args {
926 handed(func, abi, inst, arg, &mut params, &mut values);
927 }
928 let answers = match answer {
929 Answer::Registers => results.to_vec(),
930 Answer::Slot(..) => Vec::new(),
931 Answer::Packed(format) => vec![Type::float(format)],
932 };
933 let returns = answers.iter().map(|&ty| Param::new(ty)).collect();
934 let signature = func.add_signature(Signature { params, returns, variadic: false });
935 let callee = Some(names.intern(routine));
936 let varargs = func.push_abis(&[]);
937 let extra = Extra::Call(func.add_call(CallInfo { callee, signature, varargs }));
938 let pushed = func.push_values(&values);
939 let span = func.span(inst);
940 let data = InstData { args: pushed, extra, ..InstData::new(Opcode::Call) };
941 let made = func.create_inst(data, &answers, span);
942 func.insert_before(made, inst);
943 match answer {
944 Answer::Registers => func[made].results().collect(),
945 Answer::Slot(slot, ty) => {
946 let size = bytes(ty);
947 let info = whole(size, align(size));
948 let extra = Extra::Mem(func.add_mem(info));
949 let args = func.push_values(&[slot]);
950 let data = InstData { args, extra, ..InstData::new(Opcode::Load) };
951 vec![written(func, inst, data, ty)]
952 }
953 Answer::Packed(format) => unpacked(func, inst, made, format),
954 }
955}
956
957#[derive(Clone, Copy)]
959enum Answer {
960 Registers,
963 Slot(Value, Type),
966 Packed(Float),
968}
969
970fn packed(abi: &'static AbiDescription) -> Option<Float> {
977 let format = abi.wide_integer_returns_in(u64::from(WIDE / 8))?;
978 Float::from_bits(format.width())
979}
980
981fn unpacked(func: &mut Func, inst: Inst, call: Inst, format: Float) -> Vec<Value> {
989 let Some(value) = func[call].first_result else { return Vec::new() };
990 let size = bytes(Type::float(format));
991 let align = align(size);
992 let slot = room(func, inst, size, align);
993 let info = whole(size, align);
994 write(func, inst, value, slot, info, Flags::NONE);
995 let low = read(func, inst, slot, word(info, 0), Flags::NONE);
996 let up = stepped(func, inst, slot);
997 let high = read(func, inst, up, word(info, STEP), Flags::NONE);
998 vec![low, high]
999}
1000
1001fn handed(
1003 func: &mut Func,
1004 abi: &'static AbiDescription,
1005 inst: Inst,
1006 arg: Operand,
1007 params: &mut Vec<Param>,
1008 values: &mut Vec<Value>,
1009) {
1010 match arg {
1011 Operand::Whole(value) => {
1012 let ty = func[value].ty;
1013 let size = bytes(ty);
1014 if !abi.scalar_is_by_reference(size) {
1015 params.push(Param::new(ty));
1016 values.push(value);
1017 return;
1018 }
1019 let align = align(size);
1020 let slot = room(func, inst, size, align);
1021 write(func, inst, value, slot, whole(size, align), Flags::NONE);
1022 params.push(Param::new(Type::PTR));
1023 values.push(slot);
1024 }
1025 Operand::Split(low, high) => {
1026 let size = u64::from(WIDE / 8);
1027 if !abi.scalar_is_by_reference(size) {
1028 params.push(Param::new(half()));
1029 values.push(low);
1030 params.push(Param::new(half()));
1031 values.push(high);
1032 return;
1033 }
1034 let align = align(size);
1035 let slot = room(func, inst, size, align);
1036 let info = whole(size, align);
1037 write(func, inst, low, slot, word(info, 0), Flags::NONE);
1038 let up = stepped(func, inst, slot);
1039 write(func, inst, high, up, word(info, STEP), Flags::NONE);
1040 params.push(Param::new(Type::PTR));
1041 values.push(slot);
1042 }
1043 }
1044}
1045
1046fn bytes(ty: Type) -> u64 {
1048 u64::from(ty.bits().div_ceil(8))
1049}
1050
1051fn align(size: u64) -> u32 {
1053 u32::try_from(size).unwrap_or(u32::MAX)
1054}
1055
1056fn whole(size: u64, align: u32) -> MemInfo {
1058 MemInfo {
1059 size,
1060 align,
1061 order: MemOrder::NotAtomic,
1062 tbaa: None,
1063 owns: 0,
1064 restrict: Restrict::NONE,
1065 }
1066}
1067
1068fn room(func: &mut Func, inst: Inst, size: u64, align: u32) -> Value {
1070 let extra = Extra::Mem(func.add_mem(whole(size, align)));
1071 written(func, inst, InstData { extra, ..InstData::new(Opcode::Alloca) }, Type::PTR)
1072}
1073
1074fn shifted(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
1094 let args = func[func[inst].args].to_vec();
1095 let [a, b] = args[..] else { return };
1096 let (Some(&(a_low, a_high)), Some(&(count, _))) = (halves.get(&a), halves.get(&b)) else {
1097 return;
1098 };
1099 let top = ahead_const(func, inst, i128::from(HALF - 1));
1100 let places = ahead(func, inst, Opcode::And, &[count, top]);
1101 let back = ahead(func, inst, Opcode::Sub, &[top, places]);
1102 let one = ahead_const(func, inst, 1);
1103 let zero = ahead_const(func, inst, 0);
1104 let bit = ahead_const(func, inst, i128::from(HALF));
1105 let reach = ahead(func, inst, Opcode::And, &[count, bit]);
1106 let whole = compared(func, inst, IntPred::Ne, reach, zero);
1107
1108 let (low, high) = if opcode == Opcode::Shl {
1109 let moved = ahead(func, inst, Opcode::Shl, &[a_low, places]);
1110 let edge = ahead(func, inst, Opcode::LShr, &[a_low, one]);
1111 let across = ahead(func, inst, Opcode::LShr, &[edge, back]);
1112 let above = ahead(func, inst, Opcode::Shl, &[a_high, places]);
1113 let joined = ahead(func, inst, Opcode::Or, &[above, across]);
1114 let low = ahead(func, inst, Opcode::Select, &[whole, zero, moved]);
1115 let high = ahead(func, inst, Opcode::Select, &[whole, moved, joined]);
1116 (low, high)
1117 } else {
1118 let moved = ahead(func, inst, opcode, &[a_high, places]);
1119 let edge = ahead(func, inst, Opcode::Shl, &[a_high, one]);
1120 let across = ahead(func, inst, Opcode::Shl, &[edge, back]);
1121 let below = ahead(func, inst, Opcode::LShr, &[a_low, places]);
1122 let joined = ahead(func, inst, Opcode::Or, &[below, across]);
1123 let spent = if opcode == Opcode::AShr {
1126 ahead(func, inst, Opcode::AShr, &[a_high, top])
1127 } else {
1128 zero
1129 };
1130 let low = ahead(func, inst, Opcode::Select, &[whole, moved, joined]);
1131 let high = ahead(func, inst, Opcode::Select, &[whole, spent, moved]);
1132 (low, high)
1133 };
1134 replace(func, halves, inst, low, high);
1135}
1136
1137fn bitwise(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
1140 let args = func[func[inst].args].to_vec();
1141 let [a, b] = args[..] else { return };
1142 let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
1143 return;
1144 };
1145 let low = ahead(func, inst, opcode, &[a_low, b_low]);
1146 let high = ahead(func, inst, opcode, &[a_high, b_high]);
1147 replace(func, halves, inst, low, high);
1148}
1149
1150fn compare(func: &mut Func, halves: &Halves, forward: &mut HashMap<Value, Value>, inst: Inst) {
1165 let Extra::IntPred(pred) = func[inst].extra else { return };
1166 let args = func[func[inst].args].to_vec();
1167 let [a, b] = args[..] else { return };
1168 let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
1169 return;
1170 };
1171 let answer = if matches!(pred, IntPred::Eq | IntPred::Ne) {
1172 let low = ahead(func, inst, Opcode::Xor, &[a_low, b_low]);
1173 let high = ahead(func, inst, Opcode::Xor, &[a_high, b_high]);
1174 let both = ahead(func, inst, Opcode::Or, &[low, high]);
1175 let zero = ahead_const(func, inst, 0);
1176 compared(func, inst, pred, both, zero)
1177 } else {
1178 let above = compared(func, inst, strict(pred), a_high, b_high);
1179 let below = compared(func, inst, unsigned(pred), a_low, b_low);
1180 let same = compared(func, inst, IntPred::Eq, a_high, b_high);
1181 let tail = bit(func, inst, Opcode::And, same, below);
1182 bit(func, inst, Opcode::Or, above, tail)
1183 };
1184 if let Some(result) = func[inst].first_result {
1185 forward.insert(result, answer);
1186 }
1187 func.remove_inst(inst);
1188}
1189
1190fn strict(pred: IntPred) -> IntPred {
1192 match pred {
1193 IntPred::Sle => IntPred::Slt,
1194 IntPred::Sge => IntPred::Sgt,
1195 IntPred::Ule => IntPred::Ult,
1196 IntPred::Uge => IntPred::Ugt,
1197 other => other,
1198 }
1199}
1200
1201fn unsigned(pred: IntPred) -> IntPred {
1203 match pred {
1204 IntPred::Slt => IntPred::Ult,
1205 IntPred::Sle => IntPred::Ule,
1206 IntPred::Sgt => IntPred::Ugt,
1207 IntPred::Sge => IntPred::Uge,
1208 other => other,
1209 }
1210}
1211
1212fn choose(func: &mut Func, halves: &mut Halves, inst: Inst) {
1218 let args = func[func[inst].args].to_vec();
1219 let [cond, then, other] = args[..] else { return };
1220 let (Some(&(then_low, then_high)), Some(&(other_low, other_high))) =
1221 (halves.get(&then), halves.get(&other))
1222 else {
1223 return;
1224 };
1225 let low = ahead(func, inst, Opcode::Select, &[cond, then_low, other_low]);
1226 let high = ahead(func, inst, Opcode::Select, &[cond, then_high, other_high]);
1227 replace(func, halves, inst, low, high);
1228}
1229
1230fn truncate(func: &mut Func, halves: &Halves, forward: &mut HashMap<Value, Value>, inst: Inst) {
1236 let Some(&arg) = func[func[inst].args].first() else { return };
1237 let Some(&(low, _)) = halves.get(&arg) else { return };
1238 let Some(result) = func[inst].first_result else { return };
1239 if func[result].ty.bits() == HALF {
1240 forward.insert(result, low);
1241 func.remove_inst(inst);
1242 return;
1243 }
1244 becomes(func, inst, Opcode::Trunc, &[low]);
1245}
1246
1247fn extend(func: &mut Func, halves: &mut Halves, inst: Inst, signed: bool) {
1249 let Some(&arg) = func[func[inst].args].first() else { return };
1250 let low = if func[arg].ty.bits() == HALF {
1251 arg
1252 } else {
1253 let opcode = if signed { Opcode::SExt } else { Opcode::ZExt };
1254 ahead(func, inst, opcode, &[arg])
1255 };
1256 let high = if signed {
1257 let top = ahead_const(func, inst, i128::from(HALF - 1));
1258 ahead(func, inst, Opcode::AShr, &[low, top])
1259 } else {
1260 ahead_const(func, inst, 0)
1261 };
1262 replace(func, halves, inst, low, high);
1263}
1264
1265fn call(
1272 func: &mut Func,
1273 conv: &CallRegs,
1274 halves: &mut Halves,
1275 forward: &mut HashMap<Value, Value>,
1276 inst: Inst,
1277) {
1278 let data = func[inst];
1279 let Extra::Call(info) = data.extra else { return };
1280 let info = func[info];
1281 let Some((whole, variadic)) = site(func, inst) else { return };
1282 let old = func[data.args].to_vec();
1283 let skip = usize::from(data.opcode == Opcode::CallIndirect);
1285 let Some(slots) = plan(&whole, conv) else { return };
1286 let mut args = spread(&old[..skip], halves);
1287 for slot in slots.iter().copied() {
1288 let value = match slot {
1289 Slot::Whole(index) => old[skip + index],
1290 Slot::Low(index) => halves[&old[skip + index]].0,
1291 Slot::High(index) => halves[&old[skip + index]].1,
1292 Slot::Filler(ty) if ty.is_float() => {
1293 let extra = Extra::Imm(func.add_imm(Imm::from_bits(0)));
1294 written(func, inst, InstData { extra, ..InstData::new(Opcode::FConst) }, ty)
1295 }
1296 Slot::Filler(_) => ahead_const(func, inst, 0),
1297 };
1298 args.push(value);
1299 }
1300 let results: Vec<Type> = data
1301 .results()
1302 .map(|value| func[value].ty)
1303 .flat_map(|ty| if is_wide(ty) { vec![half(), half()] } else { vec![ty] })
1304 .collect();
1305 let signature = func.add_signature(planned(&Signature { variadic, ..whole }, &slots));
1306 let varargs = if variadic { func.push_abis(&[]) } else { info.varargs };
1309 let extra = Extra::Call(func.add_call(CallInfo { signature, varargs, ..info }));
1310 let args = func.push_values(&args);
1311 let span = func.span(inst);
1312 let made = func.create_inst(InstData { args, extra, ..data }, &results, span);
1313 func.insert_before(made, inst);
1314 let mut fresh = func[made].results();
1315 for old in data.results() {
1316 if is_wide(func[old].ty) {
1317 let (Some(low), Some(high)) = (fresh.next(), fresh.next()) else { return };
1318 halves.insert(old, (low, high));
1319 } else if let Some(again) = fresh.next() {
1320 forward.insert(old, again);
1321 }
1322 }
1323 func.remove_inst(inst);
1324}
1325
1326fn site(func: &Func, inst: Inst) -> Option<(Signature, bool)> {
1337 let data = func[inst];
1338 let Extra::Call(info) = data.extra else { return None };
1339 let info = func[info];
1340 let mut whole = func[info.signature].clone();
1341 let skip = usize::from(data.opcode == Opcode::CallIndirect);
1342 let args = &func[data.args];
1343 let named = skip + whole.params.len();
1344 if args.len() < named {
1345 return None;
1346 }
1347 let beyond = &func[info.varargs];
1348 for (index, &value) in args[named..].iter().enumerate() {
1349 let abi = beyond.get(index).copied().unwrap_or_default();
1350 whole.params.push(Param { ty: func[value].ty, abi });
1351 }
1352 let variadic = whole.variadic;
1353 whole.variadic = false;
1354 Some((whole, variadic))
1355}
1356
1357fn flatten(func: &mut Func, halves: &Halves, inst: Inst) {
1359 let args = spread(&func[func[inst].args], halves);
1360 func[inst].args = func.push_values(&args);
1361}
1362
1363fn edges(func: &mut Func, halves: &Halves, inst: Inst) {
1365 for at in func.target_list(inst).iter() {
1366 let call = func[at];
1367 let args = func[call.args].to_vec();
1368 if !args.iter().any(|value| halves.contains_key(value)) {
1369 continue;
1370 }
1371 let args = func.push_values(&spread(&args, halves));
1372 func.set_block_call(at, BlockCall { args, ..call });
1373 }
1374}
1375
1376fn spread(args: &[Value], halves: &Halves) -> Vec<Value> {
1378 args.iter()
1379 .flat_map(|value| match halves.get(value) {
1380 Some(&(low, high)) => vec![low, high],
1381 None => vec![*value],
1382 })
1383 .collect()
1384}
1385
1386fn split_signature(signature: &Signature) -> Signature {
1392 let split = |params: &[Param]| -> Vec<Param> {
1393 params
1394 .iter()
1395 .flat_map(|param| {
1396 if is_wide(param.ty) {
1397 vec![Param::new(half()), Param::new(half())]
1398 } else {
1399 vec![*param]
1400 }
1401 })
1402 .collect()
1403 };
1404 Signature {
1405 params: split(&signature.params),
1406 returns: split(&signature.returns),
1407 variadic: signature.variadic,
1408 }
1409}
1410
1411fn replace(func: &mut Func, halves: &mut Halves, inst: Inst, low: Value, high: Value) {
1413 if let Some(result) = func[inst].first_result {
1414 halves.insert(result, (low, high));
1415 }
1416 func.remove_inst(inst);
1417}
1418
1419fn substitute(func: &mut Func, forward: &HashMap<Value, Value>) {
1425 if forward.is_empty() {
1426 return;
1427 }
1428 let with = |value: Value| forward.get(&value).copied().unwrap_or(value);
1429 for block in func.blocks().collect::<Vec<_>>() {
1430 for inst in func.insts(block).collect::<Vec<Inst>>() {
1431 let args = func[inst].args;
1432 func.rewrite(args, with);
1433 for call in func.successors(inst).collect::<Vec<_>>() {
1434 func.rewrite(call.args, with);
1435 }
1436 }
1437 }
1438}
1439
1440fn word(info: MemInfo, at: u64) -> MemInfo {
1442 let align = if at == 0 { info.align } else { info.align.min(8) };
1443 MemInfo { size: STEP, align, ..info }
1444}
1445
1446fn stepped(func: &mut Func, inst: Inst, from: Value) -> Value {
1448 let step = ahead_const(func, inst, i128::from(STEP));
1449 let args = func.push_values(&[from, step]);
1450 written(func, inst, InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
1451}
1452
1453fn read(func: &mut Func, inst: Inst, from: Value, info: MemInfo, flags: Flags) -> Value {
1455 let extra = Extra::Mem(func.add_mem(info));
1456 let args = func.push_values(&[from]);
1457 let data = InstData { args, flags, extra, ..InstData::new(Opcode::Load) };
1458 written(func, inst, data, half())
1459}
1460
1461fn write(func: &mut Func, inst: Inst, value: Value, into: Value, info: MemInfo, flags: Flags) {
1463 let span = func.span(inst);
1464 let extra = Extra::Mem(func.add_mem(info));
1465 let args = func.push_values(&[value, into]);
1466 let data = InstData { args, flags, extra, ..InstData::new(Opcode::Store) };
1467 let made = func.create_inst(data, &[], span);
1468 func.insert_before(made, inst);
1469}
1470
1471fn compared(func: &mut Func, inst: Inst, pred: IntPred, lhs: Value, rhs: Value) -> Value {
1474 let args = func.push_values(&[lhs, rhs]);
1475 let extra = Extra::IntPred(pred);
1476 written(func, inst, InstData { args, extra, ..InstData::new(Opcode::ICmp) }, Type::I1)
1477}
1478
1479fn bit(func: &mut Func, inst: Inst, opcode: Opcode, lhs: Value, rhs: Value) -> Value {
1481 let args = func.push_values(&[lhs, rhs]);
1482 written(func, inst, InstData { args, ..InstData::new(opcode) }, Type::I1)
1483}
1484
1485fn ahead(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value]) -> Value {
1487 let args = func.push_values(args);
1488 written(func, inst, InstData { args, ..InstData::new(opcode) }, half())
1489}
1490
1491fn ahead_const(func: &mut Func, inst: Inst, value: i128) -> Value {
1493 let extra = Extra::Imm(func.add_imm(Imm::int(value, half())));
1494 written(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, half())
1495}
1496
1497fn written(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
1499 let span = func.span(inst);
1500 let made = func.create_inst(data, &[ty], span);
1501 func.insert_before(made, inst);
1502 func[made].first_result.expect("an instruction created with one result has one")
1503}
1504
1505fn becomes(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value]) {
1507 let args = func.push_values(args);
1508 let data = &mut func[inst];
1509 data.opcode = opcode;
1510 data.args = args;
1511 data.extra = Extra::None;
1512 data.flags = data.flags.intersection(Flags::legal_on(opcode));
1513}
1514
1515#[cfg(test)]
1516mod tests {
1517 use rucc_base::Interner;
1518 use rucc_ir::{
1519 Abi, Block, Builder, Flags, Float, Func, MemOrder, Module, Restrict, Signature, Type, Value,
1520 };
1521 use rucc_target::x86_64::{MINGW64, SYSV};
1522 use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
1523
1524 use super::{Def, Extra, HALF, IntPred, MemInfo, Opcode, halves};
1525
1526 fn wide() -> Type {
1528 Type::int(super::WIDE)
1529 }
1530
1531 fn target() -> TargetInfo {
1532 TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
1533 }
1534
1535 fn printed(func: &Func, names: &mut Interner) -> String {
1536 let module = Module::new(names.intern("w.c"), &target());
1537 rucc_ir::print_func(&module, func, names)
1538 }
1539
1540 fn shell(names: &mut Interner, params: &[Type], returns: &[Type]) -> (Func, Block, Vec<Value>) {
1542 let signature = Signature::new().with_params(params).with_returns(returns);
1543 let mut func = Func::new(names.intern("f"), signature);
1544 let entry = func.create_block();
1545 let values = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
1546 (func, entry, values)
1547 }
1548
1549 fn info(size: u64, align: u32) -> MemInfo {
1551 MemInfo {
1552 size,
1553 align,
1554 order: MemOrder::NotAtomic,
1555 tbaa: None,
1556 owns: 0,
1557 restrict: Restrict::NONE,
1558 }
1559 }
1560
1561 #[test]
1562 fn an_add_carries_from_the_low_half_into_the_high_one() {
1563 let mut names = Interner::new();
1564 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1565 let mut build = Builder::new(&mut func, entry);
1566 let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
1567 build.ret(&[sum]);
1568
1569 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1570 let text = printed(&func, &mut names);
1571 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1572 assert_eq!(text.matches(" = add ").count(), 3, "three adds: {text}");
1575 assert_eq!(text.matches("icmp ult").count(), 1, "one carry: {text}");
1576 assert_eq!(text.matches(" = zext.i64 ").count(), 1, "the carry as a number: {text}");
1577 }
1578
1579 #[test]
1580 fn a_subtract_borrows_the_other_way_round() {
1581 let mut names = Interner::new();
1582 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1583 let mut build = Builder::new(&mut func, entry);
1584 let difference = build.binary(Opcode::Sub, params[0], params[1], Flags::NONE);
1585 build.ret(&[difference]);
1586
1587 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1588 let text = printed(&func, &mut names);
1589 assert_eq!(text.matches(" = sub ").count(), 3, "three subtracts: {text}");
1590 assert!(text.contains("icmp ult %0, %2"), "the operands are compared: {text}");
1593 }
1594
1595 #[test]
1596 fn the_signature_and_the_entry_block_say_the_same_thing() {
1597 let mut names = Interner::new();
1598 let (mut func, entry, params) = shell(&mut names, &[Type::int(32), wide()], &[wide()]);
1599 let mut build = Builder::new(&mut func, entry);
1600 build.ret(&[params[1]]);
1601
1602 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1603 assert_eq!(
1604 func.signature().param_types().collect::<Vec<_>>(),
1605 [Type::int(32), Type::int(HALF), Type::int(HALF)],
1606 "the wide parameter became two where it stood"
1607 );
1608 assert_eq!(
1609 func.signature().return_types().collect::<Vec<_>>(),
1610 [Type::int(HALF), Type::int(HALF)],
1611 "and so did what comes back"
1612 );
1613 let text = printed(&func, &mut names);
1614 assert!(text.contains("block0(%0: i32, %1: i64, %2: i64)"), "the block agrees: {text}");
1615 assert!(text.contains("return %1, %2"), "both halves go back: {text}");
1616 let _ = entry;
1617 }
1618
1619 #[test]
1620 fn a_read_takes_the_high_word_a_word_above_the_low_one() {
1621 let mut names = Interner::new();
1622 let (mut func, entry, params) = shell(&mut names, &[Type::PTR], &[wide()]);
1623 let mut build = Builder::new(&mut func, entry);
1624 let value = build.load(wide(), params[0], info(16, 16), Flags::NONE);
1625 build.ret(&[value]);
1626
1627 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1628 let text = printed(&func, &mut names);
1629 assert_eq!(text.matches(" = load.i64 ").count(), 2, "two reads: {text}");
1630 assert!(text.contains("ptr_add"), "the high word is a word up: {text}");
1631 assert!(text.contains("align 16"), "the low word keeps what the object had: {text}");
1634 assert!(text.contains("align 8"), "the high word knows less: {text}");
1635 }
1636
1637 #[test]
1638 fn an_equality_asks_once_about_both_halves() {
1639 let mut names = Interner::new();
1640 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1641 let mut build = Builder::new(&mut func, entry);
1642 let same = build.icmp(IntPred::Eq, params[0], params[1]);
1643 let answer = build.unary(Opcode::ZExt, same, Type::int(32));
1644 build.ret(&[answer]);
1645
1646 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1647 let text = printed(&func, &mut names);
1648 assert_eq!(text.matches("icmp").count(), 1, "one comparison: {text}");
1649 assert_eq!(text.matches(" = xor ").count(), 2, "the halves differ or they do not: {text}");
1650 }
1651
1652 #[test]
1653 fn an_ordering_reads_the_low_halves_without_a_sign() {
1654 let mut names = Interner::new();
1655 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1656 let mut build = Builder::new(&mut func, entry);
1657 let below = build.icmp(IntPred::Slt, params[0], params[1]);
1658 let answer = build.unary(Opcode::ZExt, below, Type::int(32));
1659 build.ret(&[answer]);
1660
1661 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1662 let text = printed(&func, &mut names);
1663 assert!(text.contains("icmp slt"), "the high halves keep the sign: {text}");
1664 assert!(text.contains("icmp ult"), "the low halves have none: {text}");
1665 assert!(
1666 text.contains("icmp eq"),
1667 "and the low halves only matter when the high tie: {text}"
1668 );
1669 }
1670
1671 #[test]
1678 fn an_ordering_that_allows_equality_asks_the_high_halves_a_strict_question() {
1679 let mut names = Interner::new();
1680 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1681 let mut build = Builder::new(&mut func, entry);
1682 let at_least = build.icmp(IntPred::Sge, params[0], params[1]);
1683 let answer = build.unary(Opcode::ZExt, at_least, Type::int(32));
1684 build.ret(&[answer]);
1685
1686 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1687 let text = printed(&func, &mut names);
1688 assert!(text.contains("icmp sgt"), "the high halves settle it outright: {text}");
1689 assert!(!text.contains("icmp sge"), "a tie in the high halves settles nothing: {text}");
1690 assert!(text.contains("icmp uge"), "the low halves are the ones allowed to tie: {text}");
1691 }
1692
1693 #[test]
1694 fn a_widening_puts_the_sign_of_the_value_in_the_high_half() {
1695 let mut names = Interner::new();
1696 let (mut func, entry, params) = shell(&mut names, &[Type::int(32)], &[wide()]);
1697 let mut build = Builder::new(&mut func, entry);
1698 let value = build.unary(Opcode::SExt, params[0], wide());
1699 build.ret(&[value]);
1700
1701 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1702 let text = printed(&func, &mut names);
1703 assert!(text.contains("sext.i64"), "the value fills the low half: {text}");
1704 assert!(text.contains("ashr"), "and its sign fills the high one: {text}");
1705 }
1706
1707 #[test]
1708 fn a_block_parameter_becomes_two_and_every_branch_passes_two() {
1709 let mut names = Interner::new();
1710 let (mut func, entry, params) = shell(&mut names, &[wide(), Type::int(32)], &[wide()]);
1711 let tail = func.create_block();
1712 let carried = func.append_param(tail, wide());
1713 let mut build = Builder::new(&mut func, entry);
1714 let zero = build.iconst(Type::int(32), 0);
1715 let taken = build.icmp(IntPred::Ne, params[1], zero);
1716 let other = build.iconst(wide(), 7);
1717 build.br_if(taken, tail, &[params[0]], tail, &[other]);
1718 let mut build = Builder::new(&mut func, tail);
1719 build.ret(&[carried]);
1720
1721 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1722 let text = printed(&func, &mut names);
1723 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1724 assert!(text.contains("block1(%7: i64, %8: i64)"), "the block takes two: {text}");
1725 assert_eq!(text.matches("block1(").count(), 3, "and both edges pass two: {text}");
1726 }
1727
1728 #[test]
1735 fn a_multiply_is_three_multiplies_and_the_carry_out_of_the_low_ones() {
1736 let mut names = Interner::new();
1737 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1738 let mut build = Builder::new(&mut func, entry);
1739 let product = build.binary(Opcode::Mul, params[0], params[1], Flags::NONE);
1740 build.ret(&[product]);
1741
1742 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1743 let text = printed(&func, &mut names);
1744 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1745 assert_eq!(text.matches(" = mul ").count(), 7, "three and the carry's four: {text}");
1746 }
1747
1748 #[test]
1755 fn each_of_the_four_divisions_calls_the_routine_of_that_name() {
1756 for (opcode, routine) in [
1757 (Opcode::UDiv, "__udivti3"),
1758 (Opcode::SDiv, "__divti3"),
1759 (Opcode::URem, "__umodti3"),
1760 (Opcode::SRem, "__modti3"),
1761 ] {
1762 let mut names = Interner::new();
1763 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1764 let mut build = Builder::new(&mut func, entry);
1765 let answer = build.binary(opcode, params[0], params[1], Flags::NONE);
1766 build.ret(&[answer]);
1767
1768 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1769 let text = printed(&func, &mut names);
1770 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1771 assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1772 }
1773 }
1774
1775 #[test]
1781 fn a_divide_hands_over_four_halves_and_takes_two_back() {
1782 let mut names = Interner::new();
1783 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1784 let mut build = Builder::new(&mut func, entry);
1785 let quotient = build.binary(Opcode::UDiv, params[0], params[1], Flags::NONE);
1786 build.ret(&[quotient]);
1787
1788 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1789 let text = printed(&func, &mut names);
1790 assert!(text.contains("@__udivti3(%0, %1, %2, %3)"), "four halves go over: {text}");
1791 assert!(text.contains("return %4, %5"), "and two come back: {text}");
1792 }
1793
1794 #[test]
1800 fn a_divide_of_something_computed_calls_with_the_halves_of_it() {
1801 let mut names = Interner::new();
1802 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1803 let mut build = Builder::new(&mut func, entry);
1804 let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
1805 let quotient = build.binary(Opcode::SDiv, sum, params[1], Flags::NONE);
1806 build.ret(&[quotient]);
1807
1808 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1809 let text = printed(&func, &mut names);
1810 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1811 assert_eq!(text.matches(" = add ").count(), 3, "the sum is still a sum: {text}");
1812 assert_eq!(text.matches("call @__divti3").count(), 1, "one call: {text}");
1813 }
1814
1815 #[test]
1821 fn each_conversion_between_this_width_and_a_float_calls_the_routine_of_that_name() {
1822 let double = Type::float(Float::F64);
1823 let single = Type::float(Float::F32);
1824 let quad = Type::float(Float::F128);
1825 for (opcode, float, routine) in [
1826 (Opcode::SIToFP, double, "__floattidf"),
1827 (Opcode::SIToFP, single, "__floattisf"),
1828 (Opcode::UIToFP, double, "__floatuntidf"),
1829 (Opcode::UIToFP, single, "__floatuntisf"),
1830 (Opcode::SIToFP, quad, "__floattitf"),
1831 (Opcode::UIToFP, quad, "__floatuntitf"),
1832 ] {
1833 let mut names = Interner::new();
1834 let (mut func, entry, params) = shell(&mut names, &[wide()], &[float]);
1835 let mut build = Builder::new(&mut func, entry);
1836 let answer = build.unary(opcode, params[0], float);
1837 build.ret(&[answer]);
1838
1839 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1840 let text = printed(&func, &mut names);
1841 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1842 assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1843 }
1844 for (opcode, float, routine) in [
1845 (Opcode::FPToSI, double, "__fixdfti"),
1846 (Opcode::FPToSI, single, "__fixsfti"),
1847 (Opcode::FPToUI, double, "__fixunsdfti"),
1848 (Opcode::FPToUI, single, "__fixunssfti"),
1849 (Opcode::FPToSI, quad, "__fixtfti"),
1850 (Opcode::FPToUI, quad, "__fixunstfti"),
1851 ] {
1852 let mut names = Interner::new();
1853 let (mut func, entry, params) = shell(&mut names, &[float], &[wide()]);
1854 let mut build = Builder::new(&mut func, entry);
1855 let answer = build.unary(opcode, params[0], wide());
1856 build.ret(&[answer]);
1857
1858 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1859 let text = printed(&func, &mut names);
1860 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1861 assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1862 }
1863 }
1864
1865 #[test]
1871 fn a_conversion_hands_over_halves_one_way_and_takes_them_back_the_other() {
1872 let double = Type::float(Float::F64);
1873 let mut names = Interner::new();
1874 let (mut func, entry, params) = shell(&mut names, &[wide()], &[double]);
1875 let mut build = Builder::new(&mut func, entry);
1876 let answer = build.unary(Opcode::SIToFP, params[0], double);
1877 build.ret(&[answer]);
1878
1879 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1880 let text = printed(&func, &mut names);
1881 assert!(text.contains("@__floattidf(%0, %1)"), "two halves go over: {text}");
1882 assert!(text.contains("return %2"), "and one float comes back: {text}");
1883
1884 let mut names = Interner::new();
1885 let (mut func, entry, params) = shell(&mut names, &[double], &[wide()]);
1886 let mut build = Builder::new(&mut func, entry);
1887 let answer = build.unary(Opcode::FPToSI, params[0], wide());
1888 build.ret(&[answer]);
1889
1890 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1891 let text = printed(&func, &mut names);
1892 assert!(text.contains("@__fixdfti(%0)"), "the float goes over as it is: {text}");
1893 assert!(text.contains("return %1, %2"), "and two halves come back: {text}");
1894 }
1895
1896 #[test]
1903 fn a_conversion_against_a_quad_hands_over_the_pair_and_the_quad_whole() {
1904 let quad = Type::float(Float::F128);
1905 let mut names = Interner::new();
1906 let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
1907 let mut build = Builder::new(&mut func, entry);
1908 let answer = build.unary(Opcode::UIToFP, params[0], quad);
1909 build.ret(&[answer]);
1910
1911 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1912 let text = printed(&func, &mut names);
1913 assert!(text.contains("@__floatuntitf(%0, %1)"), "two halves go over: {text}");
1914 assert!(text.contains("return %2"), "and one quad comes back: {text}");
1915
1916 let mut names = Interner::new();
1917 let (mut func, entry, params) = shell(&mut names, &[quad], &[wide()]);
1918 let mut build = Builder::new(&mut func, entry);
1919 let answer = build.unary(Opcode::FPToSI, params[0], wide());
1920 build.ret(&[answer]);
1921
1922 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1923 let text = printed(&func, &mut names);
1924 assert!(text.contains("@__fixtfti(%0)"), "the quad goes over as it is: {text}");
1925 assert!(text.contains("return %1, %2"), "and two halves come back: {text}");
1926 }
1927
1928 #[test]
1935 fn a_conversion_at_a_width_the_runtime_has_no_routine_for_is_left_alone() {
1936 let long = Type::float(Float::F80);
1937 let mut names = Interner::new();
1938 let (mut func, entry, params) = shell(&mut names, &[wide()], &[long]);
1939 let mut build = Builder::new(&mut func, entry);
1940 let answer = build.unary(Opcode::SIToFP, params[0], long);
1941 build.ret(&[answer]);
1942
1943 assert!(!halves(&mut func, &mut names, &SYSV), "the pass does not understand this one");
1944 let text = printed(&func, &mut names);
1945 assert!(text.contains("i128"), "the width is still there: {text}");
1946 }
1947
1948 #[test]
1955 fn a_shift_left_chooses_between_a_count_that_crossed_a_half_and_one_that_did_not() {
1956 let mut names = Interner::new();
1957 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1958 let mut build = Builder::new(&mut func, entry);
1959 let moved = build.binary(Opcode::Shl, params[0], params[1], Flags::NONE);
1960 build.ret(&[moved]);
1961
1962 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1963 let text = printed(&func, &mut names);
1964 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1965 assert_eq!(
1966 text.matches(" = shl ").count(),
1967 2,
1968 "one per half, and the far case reuses one: {text}"
1969 );
1970 assert_eq!(text.matches(" = select.i64 ").count(), 2, "one choice per half: {text}");
1971 assert_eq!(text.matches(" = lshr ").count(), 2, "the crossing bits, in two steps: {text}");
1972 }
1973
1974 #[test]
1981 fn the_bits_that_cross_move_one_place_and_then_the_rest_of_the_way() {
1982 let mut names = Interner::new();
1983 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1984 let mut build = Builder::new(&mut func, entry);
1985 let moved = build.binary(Opcode::LShr, params[0], params[1], Flags::NONE);
1986 build.ret(&[moved]);
1987
1988 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1989 let text = printed(&func, &mut names);
1990 assert!(text.contains("iconst.i64 63"), "sixty three is the distance left: {text}");
1991 assert!(text.contains("iconst.i64 1"), "after the one place that comes first: {text}");
1992 assert!(text.contains(" = sub "), "the rest of the way is worked out: {text}");
1993 assert!(
1994 !text.contains("iconst.i64 127"),
1995 "and the count is not masked to the width: {text}"
1996 );
1997 }
1998
1999 #[test]
2005 fn an_arithmetic_shift_right_leaves_the_sign_bit_where_a_logical_one_leaves_zeroes() {
2006 let mut names = Interner::new();
2007 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2008 let mut build = Builder::new(&mut func, entry);
2009 let moved = build.binary(Opcode::AShr, params[0], params[1], Flags::NONE);
2010 build.ret(&[moved]);
2011
2012 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2013 let text = printed(&func, &mut names);
2014 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
2015 assert_eq!(text.matches(" = ashr ").count(), 2, "the count and the sign: {text}");
2017 assert_eq!(text.matches(" = lshr ").count(), 1, "the low half is not signed: {text}");
2018 assert_eq!(text.matches(" = select.i64 ").count(), 2, "one choice per half: {text}");
2019 }
2020
2021 fn arrived(params: &[Type], wide_at: usize) -> (Signature, usize) {
2027 let mut names = Interner::new();
2028 let word = Type::int(HALF);
2029 let (mut func, entry, values) = shell(&mut names, params, &[word]);
2030 let mut build = Builder::new(&mut func, entry);
2031 let low = build.unary(Opcode::Trunc, values[wide_at], word);
2032 build.ret(&[low]);
2033
2034 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2035 let ret = func.insts(entry).last().expect("the block ends in a return");
2036 let read = func[func[ret].args][0];
2037 let at = func[entry].params.iter().position(|&value| value == read);
2038 (func.signature().clone(), at.expect("the low half is a parameter"))
2039 }
2040
2041 fn types(signature: &Signature) -> Vec<Type> {
2042 signature.params.iter().map(|param| param.ty).collect()
2043 }
2044
2045 #[test]
2046 fn a_parameter_with_one_register_left_goes_in_memory_and_the_register_stays_empty() {
2047 let word = Type::int(HALF);
2048 let (signature, low) = arrived(&[word, word, word, word, word, wide()], 5);
2049 assert_eq!(types(&signature), vec![word; 8], "five, a filler and two halves");
2050 assert_eq!(low, 6, "the halves come after the register the value skipped");
2051 }
2052
2053 #[test]
2054 fn the_register_a_wide_parameter_skipped_goes_to_the_parameter_after_it() {
2055 let word = Type::int(HALF);
2056 let (signature, low) = arrived(&[word, word, word, word, word, wide(), word], 5);
2057 assert_eq!(types(&signature), vec![word; 8], "six registers and two words, no filler");
2058 assert_eq!(low, 6, "the word after the wide value took the sixth register");
2059 }
2060
2061 #[test]
2062 fn a_wide_parameter_in_memory_starts_on_a_sixteen_byte_boundary() {
2063 let word = Type::int(HALF);
2064 let params = [word, word, word, word, word, word, word, wide()];
2065 let (signature, low) = arrived(¶ms, 7);
2066 assert_eq!(types(&signature), vec![word; 10], "the seventh word, a filler, the halves");
2067 assert_eq!(low, 8, "the filler takes the word the alignment leaves empty");
2068 }
2069
2070 #[test]
2072 fn a_call_passes_a_wide_argument_in_memory_the_way_the_callee_reads_it() {
2073 let mut names = Interner::new();
2074 let word = Type::int(HALF);
2075 let (mut func, entry, _) = shell(&mut names, &[], &[]);
2076 let callee = names.intern("g");
2077 let params = [word, word, word, word, word, wide()];
2078 let signature = func.add_signature(Signature::new().with_params(¶ms));
2079 let mut build = Builder::new(&mut func, entry);
2080 let one = build.iconst(word, 1);
2081 let big = build.iconst(wide(), 4);
2082 build.call(callee, signature, &[one, one, one, one, one, big]);
2083 build.ret(&[]);
2084
2085 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2086 let call = func.insts(entry).find(|&inst| func[inst].opcode == Opcode::Call);
2087 let call = call.expect("the call is still there");
2088 let Extra::Call(info) = func[call].extra else { unreachable!("a call has call info") };
2089 let passed = func[func[call].args].to_vec();
2090 assert_eq!(types(&func[func[info].signature]), vec![word; 8], "as the callee has it");
2091 assert_eq!(passed.len(), 8, "one argument for each parameter");
2092 assert_eq!(passed[..5], [one; 5], "the words keep their registers");
2093 let constant = |value: Value| {
2094 let Def::Result { inst, .. } = func[value].def else { return None };
2095 let Extra::Imm(imm) = func[inst].extra else { return None };
2096 Some(func[imm].unsigned())
2097 };
2098 assert_eq!(constant(passed[6]), Some(4), "the low half is the first word in memory");
2099 assert_eq!(constant(passed[7]), Some(0), "and the high half the second");
2100 }
2101
2102 #[test]
2105 fn a_variadic_call_with_a_wide_argument_in_memory_leaves_the_function_alone() {
2106 let mut names = Interner::new();
2107 let word = Type::int(HALF);
2108 let (mut func, entry, _) = shell(&mut names, &[], &[]);
2109 let callee = names.intern("g");
2110 let params = [word, word, word, word, word, wide()];
2111 let signature = Signature { variadic: true, ..Signature::new().with_params(¶ms) };
2112 let signature = func.add_signature(signature);
2113 let mut build = Builder::new(&mut func, entry);
2114 let one = build.iconst(word, 1);
2115 let big = build.iconst(wide(), 4);
2116 build.call(callee, signature, &[one, one, one, one, one, big]);
2117 build.ret(&[]);
2118 let before = printed(&func, &mut names);
2119
2120 assert!(!halves(&mut func, &mut names, &SYSV), "the named parameters cannot move");
2121 assert_eq!(printed(&func, &mut names), before, "so nothing moved");
2122 }
2123
2124 #[test]
2128 fn a_wide_argument_past_the_dots_goes_where_a_named_one_would() {
2129 let mut names = Interner::new();
2130 let word = Type::int(HALF);
2131 let (mut func, entry, _) = shell(&mut names, &[], &[]);
2132 let callee = names.intern("g");
2133 let params = [word, word, word, word, word];
2134 let signature = Signature { variadic: true, ..Signature::new().with_params(¶ms) };
2135 let signature = func.add_signature(signature);
2136 let mut build = Builder::new(&mut func, entry);
2137 let one = build.iconst(word, 1);
2138 let big = build.iconst(wide(), 4);
2139 build.call_varargs(callee, signature, &[one, one, one, one, one, big], &[Abi::Plain]);
2140 build.ret(&[]);
2141
2142 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2143 let call = func.insts(entry).find(|&inst| func[inst].opcode == Opcode::Call);
2144 let call = call.expect("the call is still there");
2145 let Extra::Call(info) = func[call].extra else { unreachable!("a call has call info") };
2146 let made = &func[func[info].signature];
2147 assert!(made.variadic, "the callee is still variadic");
2148 assert_eq!(types(made), vec![word; 8], "five words, a filler and the two halves");
2149 assert!(func[func[info].varargs].is_empty(), "every argument is named now");
2150 assert_eq!(func[func[call].args].len(), 8, "one argument for each parameter");
2151 }
2152
2153 #[test]
2156 fn a_wide_argument_past_the_dots_on_windows_leaves_the_function_alone() {
2157 let mut names = Interner::new();
2158 let word = Type::int(HALF);
2159 let (mut func, entry, _) = shell(&mut names, &[], &[]);
2160 let callee = names.intern("g");
2161 let signature = Signature { variadic: true, ..Signature::new().with_params(&[word]) };
2162 let signature = func.add_signature(signature);
2163 let mut build = Builder::new(&mut func, entry);
2164 let one = build.iconst(word, 1);
2165 let big = build.iconst(wide(), 4);
2166 build.call_varargs(callee, signature, &[one, big], &[Abi::Plain]);
2167 build.ret(&[]);
2168
2169 assert!(!halves(&mut func, &mut names, &MINGW64), "the call is left for a refusal");
2170 }
2171
2172 #[test]
2181 fn a_block_made_after_the_one_it_runs_before_is_still_split() {
2182 let mut names = Interner::new();
2183 let (mut func, entry, params) = shell(&mut names, &[wide()], &[wide()]);
2184 let tail = func.create_block();
2185 let middle = func.create_block();
2186 let mut build = Builder::new(&mut func, entry);
2187 build.jump(middle, &[]);
2188 let mut build = Builder::new(&mut func, middle);
2189 let doubled = build.binary(Opcode::Add, params[0], params[0], Flags::NONE);
2190 build.jump(tail, &[]);
2191 let mut build = Builder::new(&mut func, tail);
2192 let again = build.binary(Opcode::Add, doubled, doubled, Flags::NONE);
2193 build.ret(&[again]);
2194
2195 assert!(
2196 halves(&mut func, &mut names, &SYSV),
2197 "the definition runs before the use whatever the list says"
2198 );
2199 let text = printed(&func, &mut names);
2200 assert!(!text.contains("i128"), "nothing that wide is left: {text}");
2201 }
2202
2203 #[test]
2204 fn a_function_with_nothing_that_wide_is_not_touched() {
2205 let mut names = Interner::new();
2206 let word = Type::int(HALF);
2207 let (mut func, entry, params) = shell(&mut names, &[word, word], &[word]);
2208 let mut build = Builder::new(&mut func, entry);
2209 let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
2210 build.ret(&[sum]);
2211
2212 assert!(!halves(&mut func, &mut names, &SYSV), "there is nothing to split");
2213 }
2214
2215 #[test]
2222 fn on_windows_a_wide_operand_goes_over_as_the_address_of_a_copy() {
2223 let mut names = Interner::new();
2224 let quad = Type::float(Float::F64);
2225 let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
2226 let mut build = Builder::new(&mut func, entry);
2227 let answer = build.unary(Opcode::SIToFP, params[0], quad);
2228 build.ret(&[answer]);
2229
2230 assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2231 let text = printed(&func, &mut names);
2232 assert!(text.contains("call @__floattidf"), "{text}");
2233 assert_eq!(text.matches("alloca").count(), 1, "one slot: {text}");
2235 assert_eq!(text.matches("store").count(), 2, "a half at a time: {text}");
2236 assert_eq!(text.matches("ptr_add").count(), 1, "the high half eight bytes up: {text}");
2237 assert!(!text.contains("__floattidf(%0, %1)"), "not the two halves: {text}");
2238 }
2239
2240 #[test]
2242 fn on_windows_a_wide_answer_at_this_format_comes_back_through_a_slot() {
2243 let mut names = Interner::new();
2244 let quad = Type::float(Float::F128);
2245 let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
2246 let mut build = Builder::new(&mut func, entry);
2247 let answer = build.unary(Opcode::SIToFP, params[0], quad);
2248 build.ret(&[answer]);
2249
2250 assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2251 let text = printed(&func, &mut names);
2252 assert!(text.contains("call @__floattitf"), "{text}");
2253 assert_eq!(text.matches("alloca").count(), 2, "two slots: {text}");
2255 assert_eq!(text.matches(" = call").count(), 0, "the call answers nothing: {text}");
2256 assert_eq!(text.matches(" = load").count(), 1, "the answer is the load after it: {text}");
2257 }
2258
2259 #[test]
2261 fn the_convention_with_registers_for_both_halves_puts_nothing_on_the_frame() {
2262 let mut names = Interner::new();
2263 let double = Type::float(Float::F64);
2264 let (mut func, entry, params) = shell(&mut names, &[wide()], &[double]);
2265 let mut build = Builder::new(&mut func, entry);
2266 let answer = build.unary(Opcode::SIToFP, params[0], double);
2267 build.ret(&[answer]);
2268
2269 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2270 let text = printed(&func, &mut names);
2271 assert!(text.contains("@__floattidf(%0, %1)"), "both halves in registers: {text}");
2272 assert!(!text.contains("alloca"), "nothing goes through the frame: {text}");
2273 }
2274
2275 #[test]
2278 fn on_windows_a_wide_answer_comes_back_in_one_register_and_is_split_on_the_frame() {
2279 let mut names = Interner::new();
2280 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2281 let mut build = Builder::new(&mut func, entry);
2282 let answer = build.binary(Opcode::SDiv, params[0], params[1], Flags::NONE);
2283 build.ret(&[answer]);
2284
2285 assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2286 let text = printed(&func, &mut names);
2287 assert!(text.contains("call @__divti3(%4, %7) : (ptr, ptr) -> f128"), "{text}");
2290 assert_eq!(text.matches(" = call").count(), 1, "one answer: {text}");
2291 assert_eq!(text.matches("alloca").count(), 3, "three slots: {text}");
2293 assert_eq!(text.matches(" = load").count(), 2, "the two halves: {text}");
2294 }
2295
2296 #[test]
2298 fn the_convention_with_registers_for_the_answer_reads_both_halves_out_of_them() {
2299 let mut names = Interner::new();
2300 let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2301 let mut build = Builder::new(&mut func, entry);
2302 let answer = build.binary(Opcode::SDiv, params[0], params[1], Flags::NONE);
2303 build.ret(&[answer]);
2304
2305 assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2306 let text = printed(&func, &mut names);
2307 assert!(text.contains("@__divti3(%0, %1, %2, %3)"), "four halves over: {text}");
2308 assert!(!text.contains("alloca"), "nothing goes through the frame: {text}");
2309 }
2310}