Skip to main content

rucc_regalloc/
assign.rs

1//! Which register each value lives in, and which values live on the stack instead.
2//!
3//! Design: `spec/10-backend.md` section 10.4.
4//!
5//! This is the `-O0` allocator's decision and nothing else. It is linear scan over the line
6//! [`crate::order`] lays the function out in: the values are taken in the order they are written,
7//! each is given a register that nothing else live at the same time is in, and when there is no
8//! such register one of the values in flight goes to the stack instead. There is no splitting and
9//! no coalescing, so a value gets one place for the whole of its range and keeps it. That produces
10//! mediocre code quickly, which is what `-O0` is for, and the allocator that produces good code
11//! slowly is a separate one, in M4.
12//!
13//! Which value is sent to the stack is the one whose range ends last, counting the value being
14//! placed among the candidates. A value wanted for a long time is the cheapest to spill per
15//! instruction it frees a register over, and it is the only heuristic here.
16//!
17//! # What it does with a register an instruction insists on
18//!
19//! Two things. It stays out of that register for everybody else, and it tries that register first
20//! for the value the operand names. A division wants its dividend in `rax`, so `rax` is
21//! unavailable to every other value that is live where the division reads, and it is the first
22//! register offered to the dividend itself. When the dividend gets it there is no move on the way
23//! in, and when it does not the rewrite writes one and nothing else changes.
24//!
25//! That second half is the hint, and without it the register an instruction insists on is the one
26//! register the value in it can never have, since the value's own operand is what makes the
27//! register look busy. The effect is largest on returns, because a function that gives a value
28//! back has an operand fixed to `rax` at the end of it and most functions give a value back.
29//!
30//! What makes the hint safe is asking about the register at each of the instruction's two points
31//! rather than across the whole of it. An instruction reads at the first and writes at the second,
32//! so a register it insists on is one value's at the first, another value's at the second, and
33//! nobody else's at either. A division reads its dividend from `rax` and writes its quotient to
34//! `rax`, and those are different values that can both live there. A value passed to a call in
35//! `rdi` and wanted again afterwards cannot, because nothing writes `rdi` at the second point and
36//! a register the call does not write is a register the call is assumed to destroy.
37//!
38//! An operand that has to be in memory is the other way round. The value it names goes on the
39//! stack whatever else is true of it, because that is the only place the instruction could read it
40//! from.
41//!
42//! # What it does with a two address instruction
43//!
44//! An `add` on x86-64 writes one of the registers it reads, which the operand says as a reuse of
45//! another operand. The rewrite can always make that true by copying the source into the
46//! destination first, but only if the destination is a register the instruction does not otherwise
47//! read, so a value written by a reuse is treated here as live from where the instruction reads
48//! rather than from where it writes. Then the copy is always safe.
49//!
50//! The copy is also usually unnecessary, and the one place this looks past the interval it is
51//! placing is to see that: if the value being reused is read here for the last time, the value
52//! being written may have its register, and the instruction is already two address without
53//! anything being moved anywhere. That is the whole of the coalescing this allocator does, and it
54//! is worth the dozen lines, because otherwise every piece of arithmetic in the output carries a
55//! move in front of it.
56//!
57//! # What it does not do
58//!
59//! It does not touch the function. What comes out is a table saying where each value went, and the
60//! pass that rewrites the operands and writes the moves reads it. Keeping the decision and the
61//! rewrite apart is what lets the decision be checked by looking at it, and it is the shape
62//! `spec/10-backend.md` section 10.4 asks for: an allocator is a function from a program to an
63//! assignment and the moves that make it true.
64
65use rucc_mir::{Constraint, Func, Operand, Reg, Role};
66use rucc_target::{PhysReg, RegClass};
67
68use crate::live::{Live, Range};
69use crate::order::{Order, Point};
70
71/// Where a value lives.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Place {
74    /// In a register, for the whole of its range.
75    Reg(PhysReg),
76    /// In a slot of the frame, which is what a value the allocator ran out of registers for gets,
77    /// and what a value an instruction can only read from memory gets.
78    Slot(u32),
79}
80
81/// What the allocator is allowed to use.
82///
83/// The order is the calling convention's, because which register to hand out first follows from
84/// which ones a call destroys, and `rucc-target` is where a convention says so. The scratch
85/// registers are held back out of the order and are what a spilled value is read into at each
86/// instruction that wants it, so a class needs as many of them as one of its instructions has
87/// register operands. Nothing here uses them, since a spilled value is only read once the rewrite
88/// is writing the instruction that reads it, but they are held back here because this is what
89/// decides what everything else may have.
90#[derive(Debug, Clone, Default)]
91pub struct Env {
92    classes: Vec<Class>,
93}
94
95/// What one class of registers offers.
96#[derive(Debug, Clone, Default)]
97struct Class {
98    order: Vec<PhysReg>,
99    scratch: Vec<PhysReg>,
100}
101
102impl Env {
103    /// An environment offering nothing, which is what a target that has said nothing offers.
104    #[must_use]
105    pub fn new() -> Self {
106        Self::default()
107    }
108
109    /// The same environment, with that class described.
110    #[must_use]
111    pub fn with(mut self, class: RegClass, order: &[PhysReg], scratch: &[PhysReg]) -> Self {
112        let index = usize::from(class.number());
113        if self.classes.len() <= index {
114            self.classes.resize(index + 1, Class::default());
115        }
116        self.classes[index] = Class { order: order.to_vec(), scratch: scratch.to_vec() };
117        self
118    }
119
120    /// The registers it may hand out in a class, in the order it prefers them.
121    #[must_use]
122    pub fn order(&self, class: RegClass) -> &[PhysReg] {
123        self.classes.get(usize::from(class.number())).map_or(&[], |class| &class.order)
124    }
125
126    /// The registers held back in a class for reading a spilled value into.
127    #[must_use]
128    pub fn scratch(&self, class: RegClass) -> &[PhysReg] {
129        self.classes.get(usize::from(class.number())).map_or(&[], |class| &class.scratch)
130    }
131}
132
133/// Where every value in a function went.
134#[derive(Debug, Clone)]
135pub struct Assignment {
136    places: Vec<Option<Place>>,
137    slots: Vec<RegClass>,
138}
139
140impl Assignment {
141    /// An assignment that says nothing yet about a function with that many values.
142    ///
143    /// This and [`Assignment::put`] and [`Assignment::take_slot`] are how an allocator says what
144    /// it decided. There will be a second one in M4 and it will not reach its answer this way, so
145    /// what an assignment is has to be separable from how this file arrives at one, and the
146    /// checker in [`crate::check`] reads an assignment without caring which allocator wrote it.
147    #[must_use]
148    pub fn empty(vregs: usize) -> Self {
149        Self { places: vec![None; vregs], slots: Vec::new() }
150    }
151
152    /// Records where a value went.
153    ///
154    /// # Panics
155    ///
156    /// Panics on a physical register, which is somewhere already, and on a virtual one the
157    /// function never handed out.
158    pub fn put(&mut self, reg: Reg, place: Place) {
159        self.places[index(reg)] = Some(place);
160    }
161
162    /// Takes a slot of the frame, of that class, and gives back which one it is.
163    ///
164    /// # Panics
165    ///
166    /// Panics past four billion slots, which is a frame no machine has room for.
167    pub fn take_slot(&mut self, class: RegClass) -> u32 {
168        let slot = u32::try_from(self.slots.len()).expect("too many spilled values");
169        self.slots.push(class);
170        slot
171    }
172
173    /// Where a value lives, or `None` for a virtual register this function never mentions and for
174    /// a physical one, which is already where it is.
175    #[must_use]
176    pub fn place(&self, reg: Reg) -> Option<Place> {
177        self.places.get(usize::try_from(reg.number()?).ok()?).copied().flatten()
178    }
179
180    /// The class of each slot of the frame, which is what says how wide it has to be.
181    #[must_use]
182    pub fn slots(&self) -> &[RegClass] {
183        &self.slots
184    }
185
186    /// How many values went to the stack.
187    #[must_use]
188    pub fn spilled(&self) -> usize {
189        self.slots.len()
190    }
191
192    /// Puts a value on the stack, in a slot of its own.
193    fn spill(&mut self, reg: Reg, class: RegClass) {
194        let slot = self.take_slot(class);
195        self.put(reg, Place::Slot(slot));
196    }
197}
198
199/// One value waiting for a place.
200#[derive(Debug, Clone, Copy)]
201struct Interval {
202    reg: Reg,
203    class: RegClass,
204    range: Range,
205}
206
207/// One value that has a register, for as long as it still wants it.
208#[derive(Debug, Clone, Copy)]
209struct Held {
210    reg: Reg,
211    class: RegClass,
212    range: Range,
213    at: PhysReg,
214}
215
216/// A register an instruction insists on, and where it insists on it.
217#[derive(Debug, Clone, Copy)]
218struct Blocked {
219    class: RegClass,
220    at: PhysReg,
221    /// One of the instruction's two points. Every register an instruction insists on has an entry
222    /// at each of them, because a register held at one of the two is a register nothing else may
223    /// be in across the instruction.
224    point: Point,
225    /// The one value that may be in it there, which is the value of an operand the instruction
226    /// reads at that point or writes at it. `None` means nothing may: an operand naming a physical
227    /// register outright claims it against everything, and a point no operand covers is a point
228    /// the instruction has the register to itself at.
229    by: Option<Reg>,
230}
231
232/// A value written into the register another operand of the same instruction was read from.
233#[derive(Debug, Clone, Copy)]
234struct Reuse {
235    /// The value being read, which is the one whose register would do.
236    source: Reg,
237    /// Where the instruction reads it.
238    at: Point,
239}
240
241/// Decides where every value in a function lives.
242///
243/// # Panics
244///
245/// Panics if a class has no registers to hand out and something in the function is in that class,
246/// since that is a target description that does not describe the target the function is for.
247#[must_use]
248pub fn assign(func: &Func, order: &Order, live: &Live, env: &Env) -> Assignment {
249    let blocked = blocked(func, order);
250    let forced = forced(func);
251    let reuses = reuses(func, order);
252    let hints = hints(func);
253
254    let mut intervals = Vec::with_capacity(func.vregs());
255    for (number, reuse) in reuses.iter().enumerate() {
256        let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
257        let (Some(mut range), Some(class)) = (live.range(reg), func.class_of(reg)) else {
258            continue;
259        };
260        if let Some(reuse) = reuse {
261            range.start = range.start.min(reuse.at);
262        }
263        intervals.push(Interval { reg, class, range });
264    }
265    intervals.sort_by_key(|interval| (interval.range.start, interval.reg));
266
267    let mut assignment = Assignment::empty(func.vregs());
268    let mut active: Vec<Held> = Vec::new();
269    for interval in intervals {
270        active.retain(|held| held.range.end >= interval.range.start);
271        if forced.contains(&interval.reg) {
272            assignment.spill(interval.reg, interval.class);
273            continue;
274        }
275        assert!(
276            !env.order(interval.class).is_empty(),
277            "a value in a class the target hands out no registers from"
278        );
279        let two_address = reuses[index(interval.reg)]
280            .and_then(|reuse| coalesce(&assignment, &active, &blocked, interval, reuse));
281        // The reuse comes first, because a two address instruction that has to copy its left
282        // operand in pays for the copy whatever the hint says, and taking the hint here would buy
283        // one move at the cost of another.
284        let hinted = hints[index(interval.reg)].filter(|&at| {
285            env.order(interval.class).contains(&at)
286                && available(&active, &blocked, interval, at, None)
287        });
288        let chosen = two_address.or(hinted).or_else(|| {
289            env.order(interval.class)
290                .iter()
291                .copied()
292                .find(|&at| available(&active, &blocked, interval, at, None))
293        });
294        match chosen {
295            Some(at) => {
296                assignment.places[index(interval.reg)] = Some(Place::Reg(at));
297                let reg = interval.reg;
298                active.push(Held { reg, class: interval.class, range: interval.range, at });
299            }
300            None => spill_one(&mut assignment, &mut active, &blocked, interval),
301        }
302    }
303    assignment
304}
305
306/// Whether a register is one this interval could have.
307///
308/// The exception is the value a reuse is coalescing with, which holds the register right up to the
309/// point the new value takes it over and is the one thing that may overlap.
310fn available(
311    active: &[Held],
312    blocked: &[Blocked],
313    interval: Interval,
314    at: PhysReg,
315    except: Option<Reg>,
316) -> bool {
317    let taken = active
318        .iter()
319        .any(|held| held.at == at && held.class == interval.class && Some(held.reg) != except);
320    let insisted = blocked.iter().any(|one| {
321        one.at == at
322            && one.class == interval.class
323            && one.by != Some(interval.reg)
324            && interval.range.covers(one.point)
325    });
326    !taken && !insisted
327}
328
329/// The register the value being reused is in, when this instruction is the last thing that reads
330/// it and the register is otherwise free.
331fn coalesce(
332    assignment: &Assignment,
333    active: &[Held],
334    blocked: &[Blocked],
335    interval: Interval,
336    reuse: Reuse,
337) -> Option<PhysReg> {
338    let Some(Place::Reg(at)) = assignment.place(reuse.source) else { return None };
339    let source = active.iter().find(|held| held.reg == reuse.source)?;
340    // A value read again later needs its register after this instruction would have overwritten
341    // it, so the two really do have to be different and the rewrite really does have to copy.
342    let dies = source.range.end == reuse.at;
343    (dies && available(active, blocked, interval, at, Some(reuse.source))).then_some(at)
344}
345
346/// Sends one value to the stack: the one wanted for longest, since its register pays for itself
347/// over the most instructions.
348fn spill_one(
349    assignment: &mut Assignment,
350    active: &mut Vec<Held>,
351    blocked: &[Blocked],
352    interval: Interval,
353) {
354    // A value whose register the instructions in the way insist on for themselves is no use as a
355    // victim, because taking it over would put this value in a register it may not have.
356    let victim = active
357        .iter()
358        .enumerate()
359        .filter(|(_, held)| held.class == interval.class)
360        .filter(|(_, held)| available(&[], blocked, interval, held.at, None))
361        .max_by_key(|(_, held)| held.range.end)
362        .map(|(at, held)| (at, held.at, held.range.end));
363    match victim {
364        Some((victim, at, end)) if end > interval.range.end => {
365            let held = active.remove(victim);
366            assignment.spill(held.reg, held.class);
367            assignment.places[index(interval.reg)] = Some(Place::Reg(at));
368            let reg = interval.reg;
369            active.push(Held { reg, class: interval.class, range: interval.range, at });
370        }
371        _ => assignment.spill(interval.reg, interval.class),
372    }
373}
374
375/// The registers the instructions insist on, and where.
376///
377/// A physical register an operand names outright counts the same way. Nothing before allocation
378/// writes one except an instruction that has to, and it has to for the length of that one
379/// instruction, which is the same statement a fixed constraint makes.
380fn blocked(func: &Func, order: &Order) -> Vec<Blocked> {
381    let mut blocked = Vec::new();
382    let mut claimed: Vec<(RegClass, PhysReg)> = Vec::new();
383    for block in func.blocks() {
384        for inst in func.insts(block) {
385            let operands = &func[func[inst].operands];
386            claimed.clear();
387            for operand in operands {
388                if let Some(at) = insisted(operand) {
389                    let key = (operand.class, at);
390                    if !claimed.contains(&key) {
391                        claimed.push(key);
392                    }
393                }
394            }
395            for &(class, at) in &claimed {
396                // Both points, whether or not an operand is at them. A register an instruction
397                // reads and does not write is destroyed by the time the instruction is done as far
398                // as anything here knows, which is what stops the value a call is passed in `rdi`
399                // from staying in `rdi` over the call.
400                for (point, role) in [(order.early(inst), Role::Use), (order.late(inst), Role::Def)]
401                {
402                    let mut named = false;
403                    for operand in operands {
404                        let mine = insisted(operand) == Some(at) && operand.class == class;
405                        if !mine || !(operand.role == role || operand.role == Role::EarlyDef) {
406                            continue;
407                        }
408                        named = true;
409                        let by = operand.reg.is_virtual().then_some(operand.reg);
410                        blocked.push(Blocked { class, at, point, by });
411                    }
412                    if !named {
413                        blocked.push(Blocked { class, at, point, by: None });
414                    }
415                }
416            }
417        }
418    }
419    blocked
420}
421
422/// The register an operand has to be in, which is the one a constraint asks for or the one the
423/// operand names outright.
424fn insisted(operand: &Operand) -> Option<PhysReg> {
425    match operand.constraint {
426        Constraint::Fixed(at) => Some(at),
427        _ => operand.reg.phys(),
428    }
429}
430
431/// The register each value would rather be in, which is the one an operand naming it insists on.
432///
433/// A value with two of them keeps the first the function writes down, which is the definition when
434/// there is one, since a value written into a fixed register and then moved somewhere else pays
435/// for the move at the top of its life rather than at the bottom. Two different fixed registers on
436/// one value is rare enough that the second is not worth carrying a list for.
437fn hints(func: &Func) -> Vec<Option<PhysReg>> {
438    let mut hints = vec![None; func.vregs()];
439    for block in func.blocks() {
440        for inst in func.insts(block) {
441            for operand in &func[func[inst].operands] {
442                let Constraint::Fixed(at) = operand.constraint else { continue };
443                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
444                let Some(number) = number else { continue };
445                if func.class_of(operand.reg) == Some(operand.class) && hints[number].is_none() {
446                    hints[number] = Some(at);
447                }
448            }
449        }
450    }
451    hints
452}
453
454/// The values that have to be on the stack whatever else is true of them.
455fn forced(func: &Func) -> Vec<Reg> {
456    let mut forced = Vec::new();
457    for block in func.blocks() {
458        for inst in func.insts(block) {
459            for operand in &func[func[inst].operands] {
460                if operand.constraint == Constraint::Stack
461                    && operand.reg.is_virtual()
462                    && !forced.contains(&operand.reg)
463                {
464                    forced.push(operand.reg);
465                }
466            }
467        }
468    }
469    forced
470}
471
472/// The value each two address instruction reuses, by the virtual register it writes.
473fn reuses(func: &Func, order: &Order) -> Vec<Option<Reuse>> {
474    let mut reuses = vec![None; func.vregs()];
475    for block in func.blocks() {
476        for inst in func.insts(block) {
477            let operands = &func[func[inst].operands];
478            for operand in operands {
479                let Constraint::Reuse(other) = operand.constraint else { continue };
480                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
481                let Some(number) = number else { continue };
482                let source = operands[usize::from(other)].reg;
483                reuses[number] = Some(Reuse { source, at: order.early(inst) });
484            }
485        }
486    }
487    reuses
488}
489
490/// A virtual register's number as a table index.
491fn index(reg: Reg) -> usize {
492    usize::try_from(reg.number().expect("a virtual register")).expect("a register number")
493}
494
495#[cfg(test)]
496mod tests {
497    use rucc_base::Interner;
498    use rucc_mir::{BlockCall, Opcode, Operand};
499    use rucc_target::x86_64::{GPR, R13, R14, R15, RAX, RCX, RDX, REGS, SYSV};
500
501    use super::*;
502
503    /// The x86-64 environment, with the last three of the allocation order held back as scratch.
504    fn env() -> Env {
505        let (order, scratch) = SYSV.int_order.split_at(SYSV.int_order.len() - 3);
506        Env::new().with(GPR, order, scratch)
507    }
508
509    /// An environment with that many general purpose registers, for putting a function under
510    /// pressure without writing a hundred instructions.
511    fn narrow(count: usize) -> Env {
512        Env::new().with(GPR, &SYSV.int_order[..count], &SYSV.int_order[count..count + 1])
513    }
514
515    /// What a place is called, which is what an assertion reads.
516    fn named(place: Option<Place>) -> String {
517        match place {
518            Some(Place::Reg(reg)) => REGS.name(GPR, reg).expect("a register").to_string(),
519            Some(Place::Slot(slot)) => format!("slot {slot}"),
520            None => "nowhere".to_string(),
521        }
522    }
523
524    /// Where every value in a function went.
525    fn places(func: &Func, env: &Env) -> Vec<String> {
526        let order = Order::of(func);
527        let live = Live::of(func, &order);
528        let assignment = assign(func, &order, &live, env);
529        (0..func.vregs())
530            .map(|number| {
531                let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
532                named(assignment.place(reg))
533            })
534            .collect()
535    }
536
537    #[test]
538    fn two_values_that_are_never_both_wanted_share_a_register() {
539        let mut names = Interner::new();
540        let mut func = Func::new(names.intern("f"));
541        let opcode = Opcode::new(names.intern("x64.nop"));
542        let block = func.create_block();
543        let first = func.new_vreg(GPR);
544        let second = func.new_vreg(GPR);
545        func.build(block, opcode).def(first, GPR).finish();
546        func.build(block, opcode).uses(first, GPR).finish();
547        func.build(block, opcode).def(second, GPR).finish();
548        func.build(block, opcode).uses(second, GPR).finish();
549
550        // The first register in the order, twice, because the first value is finished with before
551        // the second one is written.
552        assert_eq!(places(&func, &env()), ["rax", "rax"]);
553    }
554
555    #[test]
556    fn two_values_that_are_both_wanted_do_not() {
557        let mut names = Interner::new();
558        let mut func = Func::new(names.intern("f"));
559        let opcode = Opcode::new(names.intern("x64.nop"));
560        let block = func.create_block();
561        let first = func.new_vreg(GPR);
562        let second = func.new_vreg(GPR);
563        func.build(block, opcode).def(first, GPR).finish();
564        func.build(block, opcode).def(second, GPR).finish();
565        func.build(block, opcode).uses(first, GPR).finish();
566        func.build(block, opcode).uses(second, GPR).finish();
567
568        assert_eq!(places(&func, &env()), ["rax", "rcx"]);
569    }
570
571    #[test]
572    fn a_value_written_early_that_nothing_reads_still_holds_its_register() {
573        let mut names = Interner::new();
574        let mut func = Func::new(names.intern("f"));
575        let opcode = Opcode::new(names.intern("x64.nop"));
576        let block = func.create_block();
577        let wanted = func.new_vreg(GPR);
578        let spare = func.new_vreg(GPR);
579        // A division: a remainder somebody wants, and a quotient nobody does. Both are written by
580        // the one instruction and the quotient is written before the operands have been read.
581        func.build(block, opcode)
582            .def(wanted, GPR)
583            .operand(Operand::write_early(spare, GPR))
584            .finish();
585        func.build(block, opcode).uses(wanted, GPR).finish();
586
587        // Two registers, not one. A value nothing reads is still somewhere, and the instruction
588        // that wrote it wrote the other one too, so the two cannot be the same place. Handing them
589        // the same register loses the remainder, because the copy that takes the quotient out of
590        // the register the machine insisted on goes on top of it. The quotient gets the first
591        // register because it is written first, which is the whole of what early means.
592        assert_eq!(places(&func, &env()), ["rcx", "rax"]);
593    }
594
595    #[test]
596    fn the_value_wanted_longest_is_the_one_that_goes_to_the_stack() {
597        let mut names = Interner::new();
598        let mut func = Func::new(names.intern("f"));
599        let opcode = Opcode::new(names.intern("x64.nop"));
600        let block = func.create_block();
601        let long = func.new_vreg(GPR);
602        let short = func.new_vreg(GPR);
603        let third = func.new_vreg(GPR);
604        func.build(block, opcode).def(long, GPR).finish();
605        func.build(block, opcode).def(short, GPR).finish();
606        func.build(block, opcode).def(third, GPR).finish();
607        func.build(block, opcode).uses(short, GPR).finish();
608        func.build(block, opcode).uses(third, GPR).finish();
609        func.build(block, opcode).uses(long, GPR).finish();
610
611        // Two registers between three values. The one still wanted at the end of the function is
612        // the one whose register is worth the most to everybody else, so it is the one that goes.
613        assert_eq!(places(&func, &narrow(2)), ["slot 0", "rcx", "rax"]);
614    }
615
616    #[test]
617    fn a_register_an_instruction_insists_on_goes_to_the_values_that_asked_for_it() {
618        let mut names = Interner::new();
619        let mut func = Func::new(names.intern("f"));
620        let opcode = Opcode::new(names.intern("x64.nop"));
621        let block = func.create_block();
622        let across = func.new_vreg(GPR);
623        let dividend = func.new_vreg(GPR);
624        let quotient = func.new_vreg(GPR);
625        let remainder = func.new_vreg(GPR);
626        func.build(block, opcode).def(across, GPR).finish();
627        func.build(block, opcode).def(dividend, GPR).finish();
628        func.build(block, opcode)
629            .operand(Operand::write(quotient, GPR).with(Constraint::Fixed(RAX)))
630            .operand(Operand::write_early(remainder, GPR).with(Constraint::Fixed(RDX)))
631            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
632            .finish();
633        func.build(block, opcode).uses(across, GPR).finish();
634
635        // The value that has to be across the division is nowhere near `rax` or `rdx`, and each of
636        // the three the division names is in the register the division asked for it in. The
637        // dividend and the quotient share `rax` because the first is read where the second is
638        // written, which is what a division does.
639        assert_eq!(places(&func, &env()), ["rcx", "rax", "rax", "rdx"]);
640    }
641
642    #[test]
643    fn a_value_wanted_after_the_instruction_that_insists_does_not_get_that_register() {
644        let mut names = Interner::new();
645        let mut func = Func::new(names.intern("f"));
646        let opcode = Opcode::new(names.intern("x64.nop"));
647        let block = func.create_block();
648        let dividend = func.new_vreg(GPR);
649        let quotient = func.new_vreg(GPR);
650        func.build(block, opcode).def(dividend, GPR).finish();
651        func.build(block, opcode)
652            .operand(Operand::write(quotient, GPR).with(Constraint::Fixed(RAX)))
653            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
654            .finish();
655        func.build(block, opcode).uses(dividend, GPR).finish();
656
657        // The hint is a preference and not a claim. The dividend would rather be in `rax` and
658        // cannot be, because the division writes `rax` and the dividend is wanted afterwards, so
659        // it takes the next register and the quotient keeps the one it was promised.
660        assert_eq!(places(&func, &env()), ["rcx", "rax"]);
661    }
662
663    #[test]
664    fn a_value_an_instruction_can_only_read_from_memory_is_on_the_stack() {
665        let mut names = Interner::new();
666        let mut func = Func::new(names.intern("f"));
667        let opcode = Opcode::new(names.intern("x64.nop"));
668        let block = func.create_block();
669        let value = func.new_vreg(GPR);
670        func.build(block, opcode).def(value, GPR).finish();
671        func.build(block, opcode)
672            .operand(Operand::read(value, GPR).with(Constraint::Stack))
673            .finish();
674
675        assert_eq!(places(&func, &env()), ["slot 0"]);
676    }
677
678    #[test]
679    fn a_two_address_instruction_writes_the_register_it_read_when_it_can() {
680        let mut names = Interner::new();
681        let mut func = Func::new(names.intern("f"));
682        let opcode = Opcode::new(names.intern("x64.nop"));
683        let block = func.create_block();
684        let left = func.new_vreg(GPR);
685        let right = func.new_vreg(GPR);
686        let sum = func.new_vreg(GPR);
687        func.build(block, opcode).def(left, GPR).finish();
688        func.build(block, opcode).def(right, GPR).finish();
689        func.build(block, opcode)
690            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
691            .uses(left, GPR)
692            .uses(right, GPR)
693            .finish();
694        func.build(block, opcode).uses(right, GPR).finish();
695
696        // The addition reads the left value for the last time, so the answer goes where that was
697        // and the instruction is two address without a move in front of it.
698        assert_eq!(places(&func, &env()), ["rax", "rcx", "rax"]);
699    }
700
701    #[test]
702    fn a_two_address_instruction_that_cannot_gets_a_register_nothing_it_reads_is_in() {
703        let mut names = Interner::new();
704        let mut func = Func::new(names.intern("f"));
705        let opcode = Opcode::new(names.intern("x64.nop"));
706        let block = func.create_block();
707        let left = func.new_vreg(GPR);
708        let right = func.new_vreg(GPR);
709        let sum = func.new_vreg(GPR);
710        func.build(block, opcode).def(left, GPR).finish();
711        func.build(block, opcode).def(right, GPR).finish();
712        func.build(block, opcode)
713            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
714            .uses(left, GPR)
715            .uses(right, GPR)
716            .finish();
717        func.build(block, opcode).uses(left, GPR).finish();
718
719        // The left value is wanted afterwards, so the answer cannot have its register. It cannot
720        // have the right one's either, because the rewrite is about to write a move into it before
721        // the addition has read anything.
722        assert_eq!(places(&func, &env()), ["rax", "rcx", "rdx"]);
723    }
724
725    #[test]
726    fn a_value_live_across_a_whole_loop_holds_its_register_over_all_of_it() {
727        let mut names = Interner::new();
728        let mut func = Func::new(names.intern("f"));
729        let opcode = Opcode::new(names.intern("x64.nop"));
730        let head = func.create_block();
731        let body = func.create_block();
732        let carried = func.new_vreg(GPR);
733        let inside = func.new_vreg(GPR);
734        func.build(head, opcode).def(carried, GPR).finish();
735        *func.succs_mut(head) = vec![BlockCall::to(body)];
736        func.build(body, opcode).def(inside, GPR).finish();
737        func.build(body, opcode).uses(inside, GPR).uses(carried, GPR).finish();
738        *func.succs_mut(body) = vec![BlockCall::to(body)];
739
740        // The value inside the loop cannot have the carried one's register, even though nothing
741        // between the two definitions says so.
742        assert_eq!(places(&func, &env()), ["rax", "rcx"]);
743    }
744
745    #[test]
746    fn a_frame_says_what_each_of_its_slots_is_for() {
747        let mut names = Interner::new();
748        let mut func = Func::new(names.intern("f"));
749        let opcode = Opcode::new(names.intern("x64.nop"));
750        let block = func.create_block();
751        let first = func.new_vreg(GPR);
752        let second = func.new_vreg(GPR);
753        func.build(block, opcode).def(first, GPR).finish();
754        func.build(block, opcode).def(second, GPR).finish();
755        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
756
757        let order = Order::of(&func);
758        let live = Live::of(&func, &order);
759        let assignment = assign(&func, &order, &live, &narrow(1));
760        assert_eq!(assignment.spilled(), 1);
761        assert_eq!(assignment.slots(), [GPR]);
762        // A register that is already a register is where it is, and this has nothing to say about
763        // it.
764        assert_eq!(assignment.place(Reg::physical(RCX)), None);
765        assert_eq!(env().scratch(GPR), [R13, R14, R15]);
766    }
767}