Skip to main content

rucc_regalloc/
check.rs

1//! The allocation checker: whether an assignment is one the machine can actually run.
2//!
3//! Design: `spec/10-backend.md` section 10.4, which asks for this in debug and CI builds.
4//!
5//! A register allocator is the pass whose bugs are hardest to find from the outside. It does not
6//! change what a program means, so a wrong allocation compiles, links and runs, and then produces
7//! the wrong number in one function of one program under one register pressure. The stack trace
8//! points at the arithmetic, the arithmetic is right, and the value it read was overwritten four
9//! instructions earlier by something unrelated. A checker turns all of that into an assertion at
10//! the point the mistake was made, naming the two values and the register they were both put in.
11//!
12//! # What it asks
13//!
14//! Five questions, and they are the whole of what an assignment has to get right.
15//!
16//! Every value the function reads is written first, on every path that reaches the read. Every
17//! value the function uses has somewhere to live. Two values that are both wanted at the same
18//! point are not in the same register or the same slot. Nothing is sitting in a register that an
19//! instruction insists on for itself, because that register belongs to the instruction for as long
20//! as it runs. A value an instruction can only read from memory is in memory.
21//!
22//! The first of those is not about the allocation at all, since the value would be read before it
23//! was written whatever register it went to. It is asked here because this is where the answer is
24//! already computed: a value read before it is written is a value live on the way into the entry
25//! block, and the liveness the allocator needs anyway says which those are. A function that gets
26//! this wrong is one the allocator will happily place, and what comes out reads a stack slot
27//! nothing ever stored to.
28//!
29//! # What it does not ask
30//!
31//! Whether the allocation is any good. A function with every value on the stack passes, and so it
32//! should: it is slow and it is correct, and this is the thing that says which of the two a
33//! problem is. Quality is what the numbers in `spec/14-target-ladder.md` are for.
34//!
35//! It also does not read the rewrite. It runs on the assignment, before [`crate::rewrite`] has
36//! touched the function, because the assignment is the decision and the rewrite is a
37//! transcription of it. A rewrite that transcribes a good decision badly is a different bug and
38//! the tests in that file are what catch it.
39//!
40//! # Why it repeats work
41//!
42//! The two address instructions are worked out again here rather than borrowed from
43//! [`crate::assign`], and that is deliberate. A checker that shares its reasoning with the thing
44//! it checks agrees with it about everything, including the mistakes, and the one bug it can never
45//! find is the one in the code they share. Fifteen lines is a cheap price for a second opinion.
46//!
47//! It is also allowed to be slow. Looking for a value in a register an instruction wants is the
48//! plain product of the values and the constrained operands, with no index over either, because a
49//! checker runs in debug builds and in CI and the thing it is checking is the thing that has to be
50//! fast.
51
52use std::fmt;
53
54use rucc_mir::{Constraint, Func, Inst, Reg, Role};
55use rucc_target::{PhysReg, RegClass};
56
57use crate::assign::{Assignment, Place};
58use crate::live::{Live, Range};
59use crate::order::{Order, Point};
60
61/// One thing wrong with an allocation.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Problem {
64    /// A value the function reads or writes was given no place at all.
65    Nowhere {
66        /// The value with nowhere to be.
67        reg: Reg,
68    },
69    /// Two values that are both live somewhere were put in the same place, so whichever is written
70    /// second destroys the other.
71    Shared {
72        /// The value that was there first.
73        first: Reg,
74        /// The value that was put on top of it.
75        second: Reg,
76        /// The place they were both given.
77        place: Place,
78    },
79    /// A value was left in a register an instruction claims for itself, over the instruction that
80    /// claims it, so the moves around that instruction overwrite the value.
81    InTheWay {
82        /// The value in the way.
83        reg: Reg,
84        /// The register the instruction insists on.
85        at: PhysReg,
86        /// The instruction that insists on it.
87        inst: Inst,
88    },
89    /// A value an instruction can only read from memory was put in a register.
90    NotOnTheStack {
91        /// The value that has to be in memory.
92        reg: Reg,
93        /// The instruction that says so.
94        inst: Inst,
95    },
96    /// A value is read on some path from the entry block without anything on that path having
97    /// written it, so what the instruction reading it gets is whatever was left there.
98    NeverWritten {
99        /// The value nothing writes.
100        reg: Reg,
101    },
102}
103
104impl fmt::Display for Problem {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Problem::Nowhere { reg } => write!(f, "{} has nowhere to live", name(*reg)),
108            Problem::Shared { first, second, place } => {
109                let (first, second) = (name(*first), name(*second));
110                write!(f, "{first} and {second} are both live and both in {}", place_name(*place))
111            }
112            Problem::InTheWay { reg, at, inst } => {
113                let reg = name(*reg);
114                let inst = inst.index();
115                write!(f, "{reg} is in register {}, which instruction {inst} wants", at.number())
116            }
117            Problem::NotOnTheStack { reg, inst } => {
118                let reg = name(*reg);
119                write!(f, "{reg} is not on the stack, and instruction {} needs it", inst.index())
120            }
121            Problem::NeverWritten { reg } => {
122                write!(f, "{} is read before anything writes it", name(*reg))
123            }
124        }
125    }
126}
127
128/// Everything wrong with an allocation, in an order a person can read.
129///
130/// An empty answer is the one every allocation is supposed to give. Anything else is a compiler
131/// bug rather than a program the compiler cannot handle, which is why [`crate::run`] asserts on it
132/// instead of reporting it as a diagnostic.
133///
134/// # Panics
135///
136/// Panics on a function with two billion virtual registers in it, which is a function no machine
137/// has the memory to hold.
138#[must_use]
139pub fn check(func: &Func, order: &Order, live: &Live, assignment: &Assignment) -> Vec<Problem> {
140    let mut problems = Vec::new();
141    // What arrives live in the entry block is what the function reads without writing, since
142    // nothing runs in front of the entry block to have written it.
143    if let Some(entry) = func.entry() {
144        for reg in live.live_in(entry) {
145            problems.push(Problem::NeverWritten { reg });
146        }
147    }
148    let reuses = reuses(func, order);
149    let mut values = Vec::new();
150    for (number, reuse) in reuses.iter().enumerate() {
151        let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
152        let (Some(mut range), Some(class)) = (live.range(reg), func.class_of(reg)) else {
153            continue;
154        };
155        let Some(place) = assignment.place(reg) else {
156            problems.push(Problem::Nowhere { reg });
157            continue;
158        };
159        // A two address instruction writes its answer into a register it read, so the answer is
160        // really in that register from the moment the instruction starts and not from the moment
161        // it ends. Reading its range any other way lets it share the register with something the
162        // same instruction is still reading.
163        if let Some(reuse) = reuse {
164            range.start = range.start.min(reuse.at);
165        }
166        values.push(Value { reg, class, range, place });
167    }
168    overlaps(&values, &reuses, live, &mut problems);
169    instructions(func, order, assignment, &values, &reuses, &mut problems);
170    problems
171}
172
173/// Everything wrong with an allocation, as an assertion message.
174#[must_use]
175pub fn report(problems: &[Problem]) -> String {
176    let places = if problems.len() == 1 { "place" } else { "places" };
177    let mut report = format!("the allocation is wrong in {} {places}", problems.len());
178    for problem in problems {
179        report.push_str("\n  ");
180        report.push_str(&problem.to_string());
181    }
182    report
183}
184
185/// One value, where it is wanted and where it was put.
186#[derive(Debug, Clone, Copy)]
187struct Value {
188    reg: Reg,
189    class: RegClass,
190    range: Range,
191    place: Place,
192}
193
194/// A value written into the register another operand of the same instruction was read from.
195#[derive(Debug, Clone, Copy)]
196struct Reuse {
197    source: Reg,
198    at: Point,
199}
200
201/// Looks for two values that are both live somewhere and were put in the same place.
202///
203/// A sweep in the order the values start, holding the ones still live, so the pairs it compares
204/// are the pairs that can be wrong rather than all of them.
205fn overlaps(values: &[Value], reuses: &[Option<Reuse>], live: &Live, problems: &mut Vec<Problem>) {
206    let mut sorted = values.to_vec();
207    sorted.sort_by_key(|value| (value.range.start, value.reg));
208    let mut active: Vec<Value> = Vec::new();
209    for value in sorted {
210        active.retain(|held| held.range.end >= value.range.start);
211        for held in &active {
212            if !together(*held, value) || coalesced(*held, value, reuses, live) {
213                continue;
214            }
215            problems.push(Problem::Shared {
216                first: held.reg,
217                second: value.reg,
218                place: value.place,
219            });
220        }
221        active.push(value);
222    }
223}
224
225/// Whether two values were put in the same place.
226///
227/// Two registers of different classes are different registers even when they are the same number,
228/// which is what a class is. Two slots are the same slot whatever is in them, because a frame is
229/// one piece of memory.
230fn together(first: Value, second: Value) -> bool {
231    match (first.place, second.place) {
232        (Place::Reg(first_at), Place::Reg(second_at)) => {
233            first_at == second_at && first.class == second.class
234        }
235        (Place::Slot(first_slot), Place::Slot(second_slot)) => first_slot == second_slot,
236        _ => false,
237    }
238}
239
240/// Whether one of the two is the answer a two address instruction wrote into the register it read
241/// the other from, which is the one overlap that is not a mistake.
242///
243/// It only holds when the value being read is finished with at that instruction. A value read
244/// again afterwards needs its register afterwards, so writing over it is the plain bug this whole
245/// file exists to find.
246fn coalesced(first: Value, second: Value, reuses: &[Option<Reuse>], live: &Live) -> bool {
247    let pair = |source: Value, dest: Value| {
248        let Some(reuse) = reuses[index(dest.reg)] else { return false };
249        reuse.source == source.reg && live.range(source.reg).is_some_and(|r| r.end == reuse.at)
250    };
251    pair(first, second) || pair(second, first)
252}
253
254/// Looks for a value in a register an instruction wants, and for a value that had to be in memory
255/// and is not.
256fn instructions(
257    func: &Func,
258    order: &Order,
259    assignment: &Assignment,
260    values: &[Value],
261    reuses: &[Option<Reuse>],
262    problems: &mut Vec<Problem>,
263) {
264    for block in func.blocks() {
265        for inst in func.insts(block) {
266            for operand in &func[func[inst].operands] {
267                if operand.constraint == Constraint::Stack
268                    && matches!(assignment.place(operand.reg), Some(Place::Reg(_)))
269                {
270                    problems.push(Problem::NotOnTheStack { reg: operand.reg, inst });
271                }
272                // A physical register an operand names outright is claimed exactly as firmly as
273                // one a constraint asks for, since nothing before allocation writes one except an
274                // instruction that has no choice.
275                let at = match operand.constraint {
276                    Constraint::Fixed(at) => Some(at),
277                    _ => operand.reg.phys(),
278                };
279                let Some(at) = at else { continue };
280                let early = order.early(inst);
281                let point = if operand.role == Role::Def { order.late(inst) } else { early };
282                for value in values {
283                    let mine = value.reg == operand.reg
284                        || reuses[index(value.reg)].is_some_and(|reuse| {
285                            reuse.source == operand.reg
286                                && reuse.at == early
287                                && value.place == Place::Reg(at)
288                        });
289                    if mine || value.class != operand.class {
290                        continue;
291                    }
292                    if value.place == Place::Reg(at) && value.range.covers(point) {
293                        problems.push(Problem::InTheWay { reg: value.reg, at, inst });
294                    }
295                }
296            }
297        }
298    }
299}
300
301/// The value each two address instruction reuses, by the virtual register it writes.
302fn reuses(func: &Func, order: &Order) -> Vec<Option<Reuse>> {
303    let mut reuses = vec![None; func.vregs()];
304    for block in func.blocks() {
305        for inst in func.insts(block) {
306            let operands = &func[func[inst].operands];
307            for operand in operands {
308                let Constraint::Reuse(other) = operand.constraint else { continue };
309                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
310                let Some(number) = number else { continue };
311                let source = operands[usize::from(other)].reg;
312                reuses[number] = Some(Reuse { source, at: order.early(inst) });
313            }
314        }
315    }
316    reuses
317}
318
319/// A virtual register's number as a table index, and zero for a physical one, which never has an
320/// entry of its own and is never what a reuse writes.
321fn index(reg: Reg) -> usize {
322    reg.number().and_then(|number| usize::try_from(number).ok()).unwrap_or(0)
323}
324
325/// What a value is called in a report.
326fn name(reg: Reg) -> String {
327    match reg.number() {
328        Some(number) => format!("%{number}"),
329        None => format!("register {}", reg.phys().expect("a physical register").number()),
330    }
331}
332
333/// What a place is called in a report, without the target's name for it, since this crate holds
334/// nothing of any target.
335fn place_name(place: Place) -> String {
336    match place {
337        Place::Reg(at) => format!("register {}", at.number()),
338        Place::Slot(slot) => format!("slot {slot}"),
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use rucc_base::Interner;
345    use rucc_mir::{Opcode, Operand};
346    use rucc_target::x86_64::{GPR, RAX, RCX, SYSV};
347
348    use super::*;
349    use crate::assign::{Env, assign};
350
351    /// The x86-64 environment, with the last three of the allocation order held back as scratch.
352    fn env() -> Env {
353        let (order, scratch) = SYSV.int_order.split_at(SYSV.int_order.len() - 3);
354        Env::new().with(GPR, order, scratch)
355    }
356
357    /// What the checker says about the allocation the single pass allocator works out, which is
358    /// supposed to be nothing at all.
359    fn allocated(func: &Func) -> Vec<String> {
360        let order = Order::of(func);
361        let live = Live::of(func, &order);
362        let assignment = assign(func, &order, &live, &env());
363        said(func, &order, &live, &assignment)
364    }
365
366    /// What the checker says about an allocation somebody wrote by hand.
367    fn said(func: &Func, order: &Order, live: &Live, assignment: &Assignment) -> Vec<String> {
368        check(func, order, live, assignment).iter().map(ToString::to_string).collect()
369    }
370
371    /// The order and the liveness of a function, which every hand written case needs both of.
372    fn read(func: &Func) -> (Order, Live) {
373        let order = Order::of(func);
374        let live = Live::of(func, &order);
375        (order, live)
376    }
377
378    #[test]
379    fn an_allocation_the_allocator_worked_out_has_nothing_wrong_with_it() {
380        let mut names = Interner::new();
381        let mut func = Func::new(names.intern("f"));
382        let opcode = Opcode::new(names.intern("x64.nop"));
383        let block = func.create_block();
384        let first = func.new_vreg(GPR);
385        let second = func.new_vreg(GPR);
386        func.build(block, opcode).def(first, GPR).finish();
387        func.build(block, opcode).def(second, GPR).finish();
388        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
389
390        assert_eq!(allocated(&func), Vec::<String>::new());
391    }
392
393    #[test]
394    fn a_value_with_nowhere_to_live_is_found() {
395        let mut names = Interner::new();
396        let mut func = Func::new(names.intern("f"));
397        let opcode = Opcode::new(names.intern("x64.nop"));
398        let block = func.create_block();
399        let only = func.new_vreg(GPR);
400        func.build(block, opcode).def(only, GPR).finish();
401        func.build(block, opcode).uses(only, GPR).finish();
402
403        let (order, live) = read(&func);
404        let assignment = Assignment::empty(func.vregs());
405
406        assert_eq!(said(&func, &order, &live, &assignment), ["%0 has nowhere to live"]);
407    }
408
409    #[test]
410    fn a_value_read_before_anything_writes_it_is_found() {
411        let mut names = Interner::new();
412        let mut func = Func::new(names.intern("f"));
413        let opcode = Opcode::new(names.intern("x64.nop"));
414        let block = func.create_block();
415        let never = func.new_vreg(GPR);
416        func.build(block, opcode).uses(never, GPR).finish();
417
418        let (order, live) = read(&func);
419        let mut assignment = Assignment::empty(func.vregs());
420        assignment.put(never, Place::Reg(RAX));
421
422        assert_eq!(
423            said(&func, &order, &live, &assignment),
424            ["%0 is read before anything writes it"]
425        );
426    }
427
428    #[test]
429    fn two_values_that_are_both_wanted_and_share_a_register_are_found() {
430        let mut names = Interner::new();
431        let mut func = Func::new(names.intern("f"));
432        let opcode = Opcode::new(names.intern("x64.nop"));
433        let block = func.create_block();
434        let first = func.new_vreg(GPR);
435        let second = func.new_vreg(GPR);
436        func.build(block, opcode).def(first, GPR).finish();
437        func.build(block, opcode).def(second, GPR).finish();
438        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
439
440        let (order, live) = read(&func);
441        let mut assignment = Assignment::empty(func.vregs());
442        assignment.put(first, Place::Reg(RAX));
443        assignment.put(second, Place::Reg(RAX));
444
445        let said = said(&func, &order, &live, &assignment);
446        assert_eq!(said, ["%0 and %1 are both live and both in register 0"]);
447    }
448
449    #[test]
450    fn two_values_that_are_both_wanted_and_share_a_slot_are_found() {
451        let mut names = Interner::new();
452        let mut func = Func::new(names.intern("f"));
453        let opcode = Opcode::new(names.intern("x64.nop"));
454        let block = func.create_block();
455        let first = func.new_vreg(GPR);
456        let second = func.new_vreg(GPR);
457        func.build(block, opcode).def(first, GPR).finish();
458        func.build(block, opcode).def(second, GPR).finish();
459        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
460
461        let (order, live) = read(&func);
462        let mut assignment = Assignment::empty(func.vregs());
463        let slot = assignment.take_slot(GPR);
464        assignment.put(first, Place::Slot(slot));
465        assignment.put(second, Place::Slot(slot));
466
467        let said = said(&func, &order, &live, &assignment);
468        assert_eq!(said, ["%0 and %1 are both live and both in slot 0"]);
469    }
470
471    #[test]
472    fn two_values_that_are_never_both_wanted_may_share_anything() {
473        let mut names = Interner::new();
474        let mut func = Func::new(names.intern("f"));
475        let opcode = Opcode::new(names.intern("x64.nop"));
476        let block = func.create_block();
477        let first = func.new_vreg(GPR);
478        let second = func.new_vreg(GPR);
479        func.build(block, opcode).def(first, GPR).finish();
480        func.build(block, opcode).uses(first, GPR).finish();
481        func.build(block, opcode).def(second, GPR).finish();
482        func.build(block, opcode).uses(second, GPR).finish();
483
484        let (order, live) = read(&func);
485        let mut assignment = Assignment::empty(func.vregs());
486        assignment.put(first, Place::Reg(RAX));
487        assignment.put(second, Place::Reg(RAX));
488
489        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
490    }
491
492    #[test]
493    fn a_value_left_in_a_register_an_instruction_wants_is_found() {
494        let mut names = Interner::new();
495        let mut func = Func::new(names.intern("f"));
496        let nop = Opcode::new(names.intern("x64.nop"));
497        let divide = Opcode::new(names.intern("x64.idiv"));
498        let block = func.create_block();
499        let held = func.new_vreg(GPR);
500        let dividend = func.new_vreg(GPR);
501        func.build(block, nop).def(held, GPR).finish();
502        func.build(block, nop).def(dividend, GPR).finish();
503        // The division reads its dividend out of one register and no other, so anything still
504        // wanted afterwards has to be somewhere else while it runs.
505        func.build(block, divide)
506            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
507            .finish();
508        func.build(block, nop).uses(held, GPR).finish();
509
510        let (order, live) = read(&func);
511        let mut assignment = Assignment::empty(func.vregs());
512        assignment.put(held, Place::Reg(RAX));
513        assignment.put(dividend, Place::Reg(RCX));
514
515        let said = said(&func, &order, &live, &assignment);
516        assert_eq!(said, ["%0 is in register 0, which instruction 2 wants"]);
517    }
518
519    #[test]
520    fn the_value_an_instruction_wants_a_register_for_may_be_in_it_already() {
521        let mut names = Interner::new();
522        let mut func = Func::new(names.intern("f"));
523        let nop = Opcode::new(names.intern("x64.nop"));
524        let divide = Opcode::new(names.intern("x64.idiv"));
525        let block = func.create_block();
526        let dividend = func.new_vreg(GPR);
527        func.build(block, nop).def(dividend, GPR).finish();
528        func.build(block, divide)
529            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
530            .finish();
531
532        let (order, live) = read(&func);
533        let mut assignment = Assignment::empty(func.vregs());
534        assignment.put(dividend, Place::Reg(RAX));
535
536        // Being in the register the instruction wanted is the best answer, not a problem, and the
537        // rewrite writes no move at all for it.
538        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
539    }
540
541    #[test]
542    fn a_value_that_can_only_be_read_from_memory_and_is_in_a_register_is_found() {
543        let mut names = Interner::new();
544        let mut func = Func::new(names.intern("f"));
545        let nop = Opcode::new(names.intern("x64.nop"));
546        let wide = Opcode::new(names.intern("x64.wide"));
547        let block = func.create_block();
548        let only = func.new_vreg(GPR);
549        func.build(block, nop).def(only, GPR).finish();
550        func.build(block, wide).operand(Operand::read(only, GPR).with(Constraint::Stack)).finish();
551
552        let (order, live) = read(&func);
553        let mut assignment = Assignment::empty(func.vregs());
554        assignment.put(only, Place::Reg(RAX));
555
556        let said = said(&func, &order, &live, &assignment);
557        assert_eq!(said, ["%0 is not on the stack, and instruction 1 needs it"]);
558    }
559
560    #[test]
561    fn a_two_address_instruction_may_write_the_register_it_read_a_finished_value_from() {
562        let mut names = Interner::new();
563        let mut func = Func::new(names.intern("f"));
564        let nop = Opcode::new(names.intern("x64.nop"));
565        let add = Opcode::new(names.intern("x64.add"));
566        let block = func.create_block();
567        let left = func.new_vreg(GPR);
568        let right = func.new_vreg(GPR);
569        let sum = func.new_vreg(GPR);
570        func.build(block, nop).def(left, GPR).finish();
571        func.build(block, nop).def(right, GPR).finish();
572        func.build(block, add)
573            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
574            .uses(left, GPR)
575            .uses(right, GPR)
576            .finish();
577        func.build(block, nop).uses(sum, GPR).finish();
578
579        let (order, live) = read(&func);
580        let mut assignment = Assignment::empty(func.vregs());
581        assignment.put(left, Place::Reg(RAX));
582        assignment.put(right, Place::Reg(RCX));
583        assignment.put(sum, Place::Reg(RAX));
584
585        // The left operand is finished with at the addition, so the sum takes its register and
586        // the addition is the one instruction rather than a move and an instruction.
587        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
588    }
589
590    #[test]
591    fn a_two_address_instruction_may_not_write_over_a_value_wanted_afterwards() {
592        let mut names = Interner::new();
593        let mut func = Func::new(names.intern("f"));
594        let nop = Opcode::new(names.intern("x64.nop"));
595        let add = Opcode::new(names.intern("x64.add"));
596        let block = func.create_block();
597        let left = func.new_vreg(GPR);
598        let right = func.new_vreg(GPR);
599        let sum = func.new_vreg(GPR);
600        func.build(block, nop).def(left, GPR).finish();
601        func.build(block, nop).def(right, GPR).finish();
602        func.build(block, add)
603            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
604            .uses(left, GPR)
605            .uses(right, GPR)
606            .finish();
607        func.build(block, nop).uses(sum, GPR).uses(left, GPR).finish();
608
609        let (order, live) = read(&func);
610        let mut assignment = Assignment::empty(func.vregs());
611        assignment.put(left, Place::Reg(RAX));
612        assignment.put(right, Place::Reg(RCX));
613        assignment.put(sum, Place::Reg(RAX));
614
615        // The left operand is read again after the addition, so the addition may not have its
616        // register even though it is the one the addition reads.
617        let said = said(&func, &order, &live, &assignment);
618        assert_eq!(said, ["%0 and %2 are both live and both in register 0"]);
619    }
620
621    #[test]
622    fn a_two_address_instruction_may_not_write_the_register_it_reads_its_other_operand_from() {
623        let mut names = Interner::new();
624        let mut func = Func::new(names.intern("f"));
625        let nop = Opcode::new(names.intern("x64.nop"));
626        let add = Opcode::new(names.intern("x64.add"));
627        let block = func.create_block();
628        let left = func.new_vreg(GPR);
629        let right = func.new_vreg(GPR);
630        let sum = func.new_vreg(GPR);
631        func.build(block, nop).def(left, GPR).finish();
632        func.build(block, nop).def(right, GPR).finish();
633        func.build(block, add)
634            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
635            .uses(left, GPR)
636            .uses(right, GPR)
637            .finish();
638        func.build(block, nop).uses(sum, GPR).finish();
639
640        let (order, live) = read(&func);
641        let mut assignment = Assignment::empty(func.vregs());
642        assignment.put(left, Place::Reg(RAX));
643        assignment.put(right, Place::Reg(RCX));
644        assignment.put(sum, Place::Reg(RCX));
645
646        // Copying the left operand into the sum's register would destroy the right operand before
647        // the addition has read it, even though both are finished with at the addition.
648        let said = said(&func, &order, &live, &assignment);
649        assert_eq!(said, ["%1 and %2 are both live and both in register 1"]);
650    }
651
652    #[test]
653    fn a_report_names_every_problem() {
654        let mut names = Interner::new();
655        let mut func = Func::new(names.intern("f"));
656        let opcode = Opcode::new(names.intern("x64.nop"));
657        let block = func.create_block();
658        let first = func.new_vreg(GPR);
659        let second = func.new_vreg(GPR);
660        func.build(block, opcode).def(first, GPR).finish();
661        func.build(block, opcode).def(second, GPR).finish();
662        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
663
664        let (order, live) = read(&func);
665        let mut assignment = Assignment::empty(func.vregs());
666        assignment.put(first, Place::Reg(RAX));
667        assignment.put(second, Place::Reg(RAX));
668
669        let problems = check(&func, &order, &live, &assignment);
670        assert_eq!(
671            report(&problems),
672            "the allocation is wrong in 1 place\n  %0 and %1 are both live and both in register 0"
673        );
674        assert_eq!(report(&[]), "the allocation is wrong in 0 places");
675    }
676}