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.
246///
247/// It also only holds when the value being written begins at that instruction. The start above was
248/// already pulled back to the reuse point, so one still earlier is a value that was already live on
249/// the way in, which is what a loop carrying its own answer round looks like: written at the bottom
250/// and read by the next turn. Such a value is wanted where the instruction reads as well as after
251/// it, so it is genuinely on top of the one it reuses and no excuse at the one instruction they
252/// share makes them fit in a single register.
253fn coalesced(first: Value, second: Value, reuses: &[Option<Reuse>], live: &Live) -> bool {
254    let pair = |source: Value, dest: Value| {
255        let Some(reuse) = reuses[index(dest.reg)] else { return false };
256        reuse.source == source.reg
257            && dest.range.start == reuse.at
258            && live.range(source.reg).is_some_and(|r| r.end == reuse.at)
259    };
260    pair(first, second) || pair(second, first)
261}
262
263/// Looks for a value in a register an instruction wants, and for a value that had to be in memory
264/// and is not.
265fn instructions(
266    func: &Func,
267    order: &Order,
268    assignment: &Assignment,
269    values: &[Value],
270    reuses: &[Option<Reuse>],
271    problems: &mut Vec<Problem>,
272) {
273    for block in func.blocks() {
274        for inst in func.insts(block) {
275            for operand in &func[func[inst].operands] {
276                if operand.constraint == Constraint::Stack
277                    && matches!(assignment.place(operand.reg), Some(Place::Reg(_)))
278                {
279                    problems.push(Problem::NotOnTheStack { reg: operand.reg, inst });
280                }
281                // A physical register an operand names outright is claimed exactly as firmly as
282                // one a constraint asks for, since nothing before allocation writes one except an
283                // instruction that has no choice.
284                let at = match operand.constraint {
285                    Constraint::Fixed(at) => Some(at),
286                    _ => operand.reg.phys(),
287                };
288                let Some(at) = at else { continue };
289                let early = order.early(inst);
290                let point = if operand.role == Role::Def { order.late(inst) } else { early };
291                for value in values {
292                    let mine = value.reg == operand.reg
293                        || reuses[index(value.reg)].is_some_and(|reuse| {
294                            reuse.source == operand.reg
295                                && reuse.at == early
296                                && value.place == Place::Reg(at)
297                        });
298                    if mine || value.class != operand.class {
299                        continue;
300                    }
301                    if value.place == Place::Reg(at) && value.range.covers(point) {
302                        problems.push(Problem::InTheWay { reg: value.reg, at, inst });
303                    }
304                }
305            }
306        }
307    }
308}
309
310/// The value each two address instruction reuses, by the virtual register it writes.
311fn reuses(func: &Func, order: &Order) -> Vec<Option<Reuse>> {
312    let mut reuses = vec![None; func.vregs()];
313    for block in func.blocks() {
314        for inst in func.insts(block) {
315            let operands = &func[func[inst].operands];
316            for operand in operands {
317                let Constraint::Reuse(other) = operand.constraint else { continue };
318                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
319                let Some(number) = number else { continue };
320                let source = operands[usize::from(other)].reg;
321                reuses[number] = Some(Reuse { source, at: order.early(inst) });
322            }
323        }
324    }
325    reuses
326}
327
328/// A virtual register's number as a table index, and zero for a physical one, which never has an
329/// entry of its own and is never what a reuse writes.
330fn index(reg: Reg) -> usize {
331    reg.number().and_then(|number| usize::try_from(number).ok()).unwrap_or(0)
332}
333
334/// What a value is called in a report.
335fn name(reg: Reg) -> String {
336    match reg.number() {
337        Some(number) => format!("%{number}"),
338        None => format!("register {}", reg.phys().expect("a physical register").number()),
339    }
340}
341
342/// What a place is called in a report, without the target's name for it, since this crate holds
343/// nothing of any target.
344fn place_name(place: Place) -> String {
345    match place {
346        Place::Reg(at) => format!("register {}", at.number()),
347        Place::Slot(slot) => format!("slot {slot}"),
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use rucc_base::Interner;
354    use rucc_mir::{BlockCall, Opcode, Operand};
355    use rucc_target::x86_64::{GPR, RAX, RCX, SYSV};
356
357    use super::*;
358    use crate::assign::{Env, assign};
359
360    /// The x86-64 environment, with the last three of the allocation order held back as scratch.
361    fn env() -> Env {
362        let (order, scratch) = SYSV.int_order.split_at(SYSV.int_order.len() - 3);
363        Env::new().with(GPR, order, scratch)
364    }
365
366    /// What the checker says about the allocation the single pass allocator works out, which is
367    /// supposed to be nothing at all.
368    fn allocated(func: &Func) -> Vec<String> {
369        let order = Order::of(func);
370        let live = Live::of(func, &order);
371        let assignment = assign(func, &order, &live, &env());
372        said(func, &order, &live, &assignment)
373    }
374
375    /// What the checker says about an allocation somebody wrote by hand.
376    fn said(func: &Func, order: &Order, live: &Live, assignment: &Assignment) -> Vec<String> {
377        check(func, order, live, assignment).iter().map(ToString::to_string).collect()
378    }
379
380    /// The order and the liveness of a function, which every hand written case needs both of.
381    fn read(func: &Func) -> (Order, Live) {
382        let order = Order::of(func);
383        let live = Live::of(func, &order);
384        (order, live)
385    }
386
387    #[test]
388    fn an_allocation_the_allocator_worked_out_has_nothing_wrong_with_it() {
389        let mut names = Interner::new();
390        let mut func = Func::new(names.intern("f"));
391        let opcode = Opcode::new(names.intern("x64.nop"));
392        let block = func.create_block();
393        let first = func.new_vreg(GPR);
394        let second = func.new_vreg(GPR);
395        func.build(block, opcode).def(first, GPR).finish();
396        func.build(block, opcode).def(second, GPR).finish();
397        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
398
399        assert_eq!(allocated(&func), Vec::<String>::new());
400    }
401
402    #[test]
403    fn a_value_with_nowhere_to_live_is_found() {
404        let mut names = Interner::new();
405        let mut func = Func::new(names.intern("f"));
406        let opcode = Opcode::new(names.intern("x64.nop"));
407        let block = func.create_block();
408        let only = func.new_vreg(GPR);
409        func.build(block, opcode).def(only, GPR).finish();
410        func.build(block, opcode).uses(only, GPR).finish();
411
412        let (order, live) = read(&func);
413        let assignment = Assignment::empty(func.vregs());
414
415        assert_eq!(said(&func, &order, &live, &assignment), ["%0 has nowhere to live"]);
416    }
417
418    #[test]
419    fn a_value_read_before_anything_writes_it_is_found() {
420        let mut names = Interner::new();
421        let mut func = Func::new(names.intern("f"));
422        let opcode = Opcode::new(names.intern("x64.nop"));
423        let block = func.create_block();
424        let never = func.new_vreg(GPR);
425        func.build(block, opcode).uses(never, GPR).finish();
426
427        let (order, live) = read(&func);
428        let mut assignment = Assignment::empty(func.vregs());
429        assignment.put(never, Place::Reg(RAX));
430
431        assert_eq!(
432            said(&func, &order, &live, &assignment),
433            ["%0 is read before anything writes it"]
434        );
435    }
436
437    #[test]
438    fn two_values_that_are_both_wanted_and_share_a_register_are_found() {
439        let mut names = Interner::new();
440        let mut func = Func::new(names.intern("f"));
441        let opcode = Opcode::new(names.intern("x64.nop"));
442        let block = func.create_block();
443        let first = func.new_vreg(GPR);
444        let second = func.new_vreg(GPR);
445        func.build(block, opcode).def(first, GPR).finish();
446        func.build(block, opcode).def(second, GPR).finish();
447        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
448
449        let (order, live) = read(&func);
450        let mut assignment = Assignment::empty(func.vregs());
451        assignment.put(first, Place::Reg(RAX));
452        assignment.put(second, Place::Reg(RAX));
453
454        let said = said(&func, &order, &live, &assignment);
455        assert_eq!(said, ["%0 and %1 are both live and both in register 0"]);
456    }
457
458    #[test]
459    fn two_values_that_are_both_wanted_and_share_a_slot_are_found() {
460        let mut names = Interner::new();
461        let mut func = Func::new(names.intern("f"));
462        let opcode = Opcode::new(names.intern("x64.nop"));
463        let block = func.create_block();
464        let first = func.new_vreg(GPR);
465        let second = func.new_vreg(GPR);
466        func.build(block, opcode).def(first, GPR).finish();
467        func.build(block, opcode).def(second, GPR).finish();
468        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
469
470        let (order, live) = read(&func);
471        let mut assignment = Assignment::empty(func.vregs());
472        let slot = assignment.take_slot(GPR);
473        assignment.put(first, Place::Slot(slot));
474        assignment.put(second, Place::Slot(slot));
475
476        let said = said(&func, &order, &live, &assignment);
477        assert_eq!(said, ["%0 and %1 are both live and both in slot 0"]);
478    }
479
480    #[test]
481    fn two_values_that_are_never_both_wanted_may_share_anything() {
482        let mut names = Interner::new();
483        let mut func = Func::new(names.intern("f"));
484        let opcode = Opcode::new(names.intern("x64.nop"));
485        let block = func.create_block();
486        let first = func.new_vreg(GPR);
487        let second = func.new_vreg(GPR);
488        func.build(block, opcode).def(first, GPR).finish();
489        func.build(block, opcode).uses(first, GPR).finish();
490        func.build(block, opcode).def(second, GPR).finish();
491        func.build(block, opcode).uses(second, GPR).finish();
492
493        let (order, live) = read(&func);
494        let mut assignment = Assignment::empty(func.vregs());
495        assignment.put(first, Place::Reg(RAX));
496        assignment.put(second, Place::Reg(RAX));
497
498        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
499    }
500
501    #[test]
502    fn a_value_left_in_a_register_an_instruction_wants_is_found() {
503        let mut names = Interner::new();
504        let mut func = Func::new(names.intern("f"));
505        let nop = Opcode::new(names.intern("x64.nop"));
506        let divide = Opcode::new(names.intern("x64.idiv"));
507        let block = func.create_block();
508        let held = func.new_vreg(GPR);
509        let dividend = func.new_vreg(GPR);
510        func.build(block, nop).def(held, GPR).finish();
511        func.build(block, nop).def(dividend, GPR).finish();
512        // The division reads its dividend out of one register and no other, so anything still
513        // wanted afterwards has to be somewhere else while it runs.
514        func.build(block, divide)
515            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
516            .finish();
517        func.build(block, nop).uses(held, GPR).finish();
518
519        let (order, live) = read(&func);
520        let mut assignment = Assignment::empty(func.vregs());
521        assignment.put(held, Place::Reg(RAX));
522        assignment.put(dividend, Place::Reg(RCX));
523
524        let said = said(&func, &order, &live, &assignment);
525        assert_eq!(said, ["%0 is in register 0, which instruction 2 wants"]);
526    }
527
528    #[test]
529    fn the_value_an_instruction_wants_a_register_for_may_be_in_it_already() {
530        let mut names = Interner::new();
531        let mut func = Func::new(names.intern("f"));
532        let nop = Opcode::new(names.intern("x64.nop"));
533        let divide = Opcode::new(names.intern("x64.idiv"));
534        let block = func.create_block();
535        let dividend = func.new_vreg(GPR);
536        func.build(block, nop).def(dividend, GPR).finish();
537        func.build(block, divide)
538            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
539            .finish();
540
541        let (order, live) = read(&func);
542        let mut assignment = Assignment::empty(func.vregs());
543        assignment.put(dividend, Place::Reg(RAX));
544
545        // Being in the register the instruction wanted is the best answer, not a problem, and the
546        // rewrite writes no move at all for it.
547        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
548    }
549
550    #[test]
551    fn a_value_that_can_only_be_read_from_memory_and_is_in_a_register_is_found() {
552        let mut names = Interner::new();
553        let mut func = Func::new(names.intern("f"));
554        let nop = Opcode::new(names.intern("x64.nop"));
555        let wide = Opcode::new(names.intern("x64.wide"));
556        let block = func.create_block();
557        let only = func.new_vreg(GPR);
558        func.build(block, nop).def(only, GPR).finish();
559        func.build(block, wide).operand(Operand::read(only, GPR).with(Constraint::Stack)).finish();
560
561        let (order, live) = read(&func);
562        let mut assignment = Assignment::empty(func.vregs());
563        assignment.put(only, Place::Reg(RAX));
564
565        let said = said(&func, &order, &live, &assignment);
566        assert_eq!(said, ["%0 is not on the stack, and instruction 1 needs it"]);
567    }
568
569    #[test]
570    fn a_two_address_instruction_may_write_the_register_it_read_a_finished_value_from() {
571        let mut names = Interner::new();
572        let mut func = Func::new(names.intern("f"));
573        let nop = Opcode::new(names.intern("x64.nop"));
574        let add = Opcode::new(names.intern("x64.add"));
575        let block = func.create_block();
576        let left = func.new_vreg(GPR);
577        let right = func.new_vreg(GPR);
578        let sum = func.new_vreg(GPR);
579        func.build(block, nop).def(left, GPR).finish();
580        func.build(block, nop).def(right, GPR).finish();
581        func.build(block, add)
582            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
583            .uses(left, GPR)
584            .uses(right, GPR)
585            .finish();
586        func.build(block, nop).uses(sum, GPR).finish();
587
588        let (order, live) = read(&func);
589        let mut assignment = Assignment::empty(func.vregs());
590        assignment.put(left, Place::Reg(RAX));
591        assignment.put(right, Place::Reg(RCX));
592        assignment.put(sum, Place::Reg(RAX));
593
594        // The left operand is finished with at the addition, so the sum takes its register and
595        // the addition is the one instruction rather than a move and an instruction.
596        assert_eq!(said(&func, &order, &live, &assignment), Vec::<String>::new());
597    }
598
599    #[test]
600    fn a_two_address_instruction_may_not_write_over_a_value_wanted_afterwards() {
601        let mut names = Interner::new();
602        let mut func = Func::new(names.intern("f"));
603        let nop = Opcode::new(names.intern("x64.nop"));
604        let add = Opcode::new(names.intern("x64.add"));
605        let block = func.create_block();
606        let left = func.new_vreg(GPR);
607        let right = func.new_vreg(GPR);
608        let sum = func.new_vreg(GPR);
609        func.build(block, nop).def(left, GPR).finish();
610        func.build(block, nop).def(right, GPR).finish();
611        func.build(block, add)
612            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
613            .uses(left, GPR)
614            .uses(right, GPR)
615            .finish();
616        func.build(block, nop).uses(sum, GPR).uses(left, GPR).finish();
617
618        let (order, live) = read(&func);
619        let mut assignment = Assignment::empty(func.vregs());
620        assignment.put(left, Place::Reg(RAX));
621        assignment.put(right, Place::Reg(RCX));
622        assignment.put(sum, Place::Reg(RAX));
623
624        // The left operand is read again after the addition, so the addition may not have its
625        // register even though it is the one the addition reads.
626        let said = said(&func, &order, &live, &assignment);
627        assert_eq!(said, ["%0 and %2 are both live and both in register 0"]);
628    }
629
630    #[test]
631    fn a_two_address_instruction_may_not_write_the_register_it_reads_its_other_operand_from() {
632        let mut names = Interner::new();
633        let mut func = Func::new(names.intern("f"));
634        let nop = Opcode::new(names.intern("x64.nop"));
635        let add = Opcode::new(names.intern("x64.add"));
636        let block = func.create_block();
637        let left = func.new_vreg(GPR);
638        let right = func.new_vreg(GPR);
639        let sum = func.new_vreg(GPR);
640        func.build(block, nop).def(left, GPR).finish();
641        func.build(block, nop).def(right, GPR).finish();
642        func.build(block, add)
643            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
644            .uses(left, GPR)
645            .uses(right, GPR)
646            .finish();
647        func.build(block, nop).uses(sum, GPR).finish();
648
649        let (order, live) = read(&func);
650        let mut assignment = Assignment::empty(func.vregs());
651        assignment.put(left, Place::Reg(RAX));
652        assignment.put(right, Place::Reg(RCX));
653        assignment.put(sum, Place::Reg(RCX));
654
655        // Copying the left operand into the sum's register would destroy the right operand before
656        // the addition has read it, even though both are finished with at the addition.
657        let said = said(&func, &order, &live, &assignment);
658        assert_eq!(said, ["%1 and %2 are both live and both in register 1"]);
659    }
660
661    #[test]
662    fn a_two_address_instruction_may_not_write_the_register_it_read_over_its_own_last_answer() {
663        let mut names = Interner::new();
664        let mut func = Func::new(names.intern("f"));
665        let nop = Opcode::new(names.intern("x64.nop"));
666        let add = Opcode::new(names.intern("x64.add"));
667        let head = func.create_block();
668        let latch = func.create_block();
669        let out = func.create_block();
670        let source = func.new_vreg(GPR);
671        let carried = func.new_vreg(GPR);
672        func.build(head, nop).def(source, GPR).finish();
673        func.build(head, nop).def(carried, GPR).finish();
674        *func.succs_mut(head) = vec![BlockCall::to(latch)];
675        func.build(latch, add)
676            .operand(Operand::write(carried, GPR).with(Constraint::Reuse(1)))
677            .uses(source, GPR)
678            .uses(carried, GPR)
679            .finish();
680        *func.succs_mut(latch) = vec![BlockCall::to(head), BlockCall::to(out)];
681        func.build(out, nop).uses(carried, GPR).finish();
682
683        let (order, live) = read(&func);
684        let mut assignment = Assignment::empty(func.vregs());
685        assignment.put(source, Place::Reg(RAX));
686        assignment.put(carried, Place::Reg(RAX));
687
688        // The source is finished with at the addition, which is what would normally let the answer
689        // have its register. It does not here, because the answer is the one the last turn round
690        // the loop wrote and the addition reads it too, so both are wanted where it reads.
691        let said = said(&func, &order, &live, &assignment);
692        assert_eq!(said, ["%0 and %1 are both live and both in register 0"]);
693    }
694
695    #[test]
696    fn a_report_names_every_problem() {
697        let mut names = Interner::new();
698        let mut func = Func::new(names.intern("f"));
699        let opcode = Opcode::new(names.intern("x64.nop"));
700        let block = func.create_block();
701        let first = func.new_vreg(GPR);
702        let second = func.new_vreg(GPR);
703        func.build(block, opcode).def(first, GPR).finish();
704        func.build(block, opcode).def(second, GPR).finish();
705        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
706
707        let (order, live) = read(&func);
708        let mut assignment = Assignment::empty(func.vregs());
709        assignment.put(first, Place::Reg(RAX));
710        assignment.put(second, Place::Reg(RAX));
711
712        let problems = check(&func, &order, &live, &assignment);
713        assert_eq!(
714            report(&problems),
715            "the allocation is wrong in 1 place\n  %0 and %1 are both live and both in register 0"
716        );
717        assert_eq!(report(&[]), "the allocation is wrong in 0 places");
718    }
719}