Skip to main content

rucc_regalloc/
spill.rs

1//! Which values go to memory before any register is handed out.
2//!
3//! Design: `spec/optimizer/39-register-allocation.md` section 39.7, and tamnd/rucc#1177.
4//!
5//! [`crate::pressure`] finds the points where more values are live than there are registers. At
6//! each of those some of the values live there have to be in memory, and this picks which: the
7//! lightest first, by the weight [`crate::backtrack`] places values by. That is how often a value
8//! is read or written, each time counted by how often its block runs, over how much of the
9//! function it is live across. A value read in a loop is heavy for the loop's sake, so what goes
10//! is one read outside it, and a value live over a long stretch and rarely read is light, since
11//! sending it to memory frees a register over the most points for the fewest loads.
12//!
13//! The points are taken in order along the line, and at each one values go until no more are
14//! over the room. A value that goes is taken off every point it was live at, so one long light
15//! value can settle several points at once, and a later point may already be settled by the time
16//! it is reached.
17//!
18//! # What it promises
19//!
20//! It takes off each point no more values than the pressure model says have to go, and that
21//! number is a floor, so every value picked here is standing in for one that some value at that
22//! point had to be. It does not promise that the rest then fit. A register a fixed operand claims
23//! for one value, the answer of a two address instruction live where its source is read, and a
24//! value wanted across a call in one of the registers the call keeps are all left to the
25//! assignment, which can still evict and spill after this the way it did before.
26
27use std::cmp::Reverse;
28use std::collections::BTreeMap;
29
30use rucc_mir::{Func, Reg};
31use rucc_target::RegClass;
32
33use crate::assign;
34use crate::backtrack;
35use crate::live::{Area, Live};
36use crate::pressure::Pressure;
37
38/// One value that could go to memory.
39#[derive(Debug, Clone, Copy)]
40struct Candidate<'a> {
41    reg: Reg,
42    area: Area<'a>,
43    weight: u128,
44    size: u32,
45}
46
47/// The values to send to memory before any register is handed out, lightest first at each point
48/// where more are live than there is room for.
49///
50/// # Panics
51///
52/// Panics on a function with more virtual registers than a `u32` can number, which is one no
53/// earlier pass could have built.
54#[must_use]
55pub fn choose(func: &Func, live: &Live, pressure: &Pressure) -> Vec<Reg> {
56    let costs = backtrack::costs(func);
57    let mut forced = vec![false; func.vregs()];
58    for reg in assign::forced(func) {
59        forced[index(reg)] = true;
60    }
61    let mut classes: BTreeMap<RegClass, Vec<Candidate<'_>>> = BTreeMap::new();
62    for (number, &forced) in forced.iter().enumerate() {
63        let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
64        let (Some(area), Some(class)) = (live.area(reg), func.class_of(reg)) else {
65            continue;
66        };
67        if forced {
68            continue;
69        }
70        let size = backtrack::size(area);
71        let weight = costs[number] * 1024 / u128::from(size + 8);
72        classes.entry(class).or_default().push(Candidate { reg, area, weight, size });
73    }
74
75    let mut pressure = pressure.clone();
76    let mut chosen = Vec::new();
77    for (class, mut candidates) in classes {
78        candidates.sort_by_key(|candidate| candidate.area.hull().start);
79        let over: Vec<_> = pressure.over(class).collect();
80        // The values whose hull has begun by the point being looked at, and which have not gone.
81        let mut open: Vec<usize> = Vec::new();
82        let mut next = 0;
83        for point in over {
84            while next < candidates.len() && candidates[next].area.hull().start <= point {
85                open.push(next);
86                next += 1;
87            }
88            open.retain(|&one| candidates[one].area.hull().end >= point);
89            while pressure.excess(class, point) > 0 {
90                let lightest = open
91                    .iter()
92                    .copied()
93                    .filter(|&one| candidates[one].area.covers(point))
94                    .min_by_key(|&one| {
95                        (candidates[one].weight, Reverse(candidates[one].size), one)
96                    });
97                let Some(one) = lightest else { break };
98                open.retain(|&other| other != one);
99                pressure.lift(class, candidates[one].area);
100                chosen.push(candidates[one].reg);
101            }
102        }
103    }
104    chosen
105}
106
107fn index(reg: Reg) -> usize {
108    usize::try_from(reg.number().expect("a virtual register")).expect("a register number")
109}
110
111#[cfg(test)]
112mod tests {
113    use rucc_base::Interner;
114    use rucc_mir::{BlockCall, Opcode, Weight};
115    use rucc_target::x86_64::{GPR, SYSV};
116
117    use super::*;
118    use crate::assign::Env;
119    use crate::order::Order;
120
121    fn narrow(count: usize) -> Env {
122        Env::new().with(GPR, &SYSV.int_order[..count], &SYSV.int_order[count..count + 1])
123    }
124
125    fn chosen(func: &Func, env: &Env) -> Vec<Reg> {
126        let order = Order::of(func);
127        let live = Live::of(func, &order);
128        let pressure = Pressure::of(func, &order, &live, env);
129        choose(func, &live, &pressure)
130    }
131
132    #[test]
133    fn nothing_goes_where_everything_fits() {
134        let mut names = Interner::new();
135        let mut func = Func::new(names.intern("f"));
136        let opcode = Opcode::new(names.intern("x64.nop"));
137        let block = func.create_block();
138        let first = func.new_vreg(GPR);
139        let second = func.new_vreg(GPR);
140        func.build(block, opcode).def(first, GPR).finish();
141        func.build(block, opcode).def(second, GPR).finish();
142        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
143
144        assert!(chosen(&func, &narrow(2)).is_empty());
145    }
146
147    #[test]
148    fn the_value_read_least_is_the_one_that_goes() {
149        let mut names = Interner::new();
150        let mut func = Func::new(names.intern("f"));
151        let opcode = Opcode::new(names.intern("x64.nop"));
152        let block = func.create_block();
153        let busy = func.new_vreg(GPR);
154        let once = func.new_vreg(GPR);
155        let other = func.new_vreg(GPR);
156        func.build(block, opcode).def(busy, GPR).finish();
157        func.build(block, opcode).def(once, GPR).finish();
158        func.build(block, opcode).def(other, GPR).finish();
159        for _ in 0..3 {
160            func.build(block, opcode).uses(busy, GPR).uses(other, GPR).finish();
161        }
162        func.build(block, opcode).uses(once, GPR).uses(busy, GPR).uses(other, GPR).finish();
163
164        assert_eq!(chosen(&func, &narrow(2)), [once]);
165    }
166
167    #[test]
168    fn a_value_read_in_a_loop_stays_and_one_read_outside_it_goes() {
169        let mut names = Interner::new();
170        let mut func = Func::new(names.intern("f"));
171        let opcode = Opcode::new(names.intern("x64.nop"));
172        let entry = func.create_block();
173        let body = func.create_block();
174        let out = func.create_block();
175        let step = func.new_vreg(GPR);
176        let cold = func.new_vreg(GPR);
177        func.build(entry, opcode).def(cold, GPR).finish();
178        func.build(entry, opcode).def(step, GPR).finish();
179        *func.succs_mut(entry) = vec![BlockCall::to(body)];
180        func.build(body, opcode).uses(step, GPR).finish();
181        *func.succs_mut(body) = vec![BlockCall::to(body), BlockCall::to(out)];
182        func.set_weight(body, Weight::parts(100 * Weight::SCALE));
183        func.build(out, opcode).uses(cold, GPR).finish();
184        func.build(out, opcode).uses(step, GPR).finish();
185
186        assert_eq!(chosen(&func, &narrow(1)), [cold]);
187    }
188
189    #[test]
190    fn one_long_light_value_settles_two_points_that_are_each_one_over() {
191        let mut names = Interner::new();
192        let mut func = Func::new(names.intern("f"));
193        let opcode = Opcode::new(names.intern("x64.nop"));
194        let block = func.create_block();
195        let long = func.new_vreg(GPR);
196        let first = func.new_vreg(GPR);
197        let second = func.new_vreg(GPR);
198        func.build(block, opcode).def(long, GPR).finish();
199        func.build(block, opcode).def(first, GPR).finish();
200        func.build(block, opcode).uses(first, GPR).finish();
201        for _ in 0..4 {
202            func.build(block, opcode).finish();
203        }
204        func.build(block, opcode).def(second, GPR).finish();
205        func.build(block, opcode).uses(second, GPR).finish();
206        func.build(block, opcode).uses(long, GPR).finish();
207
208        // Each short value meets the long one at a point with room for one. Sending the long one
209        // away settles both, where sending the short ones would take two.
210        assert_eq!(chosen(&func, &narrow(1)), [long]);
211    }
212}