Skip to main content

rucc_regalloc/
lib.rs

1//! Both register allocators and the allocation checker.
2//!
3//! Design: `spec/10-backend.md`. Layer rank 11, see `spec/18-package-layout.md`.
4//!
5//! # Status
6//!
7//! Liveness is here, which is the question both allocators ask first: [`order`] lays a function
8//! out in the line the encoder will emit it in, and [`live`] says where in that line each value
9//! is wanted. So is [`moves`], which puts the moves an edge turns into in an order they can be
10//! made in one at a time. The single pass allocator's decision is in [`assign`]: where every value
11//! of a function goes, in one linear scan, which is what `-O0` asks for. The rewrite that makes
12//! that decision true in the function is in [`rewrite`], and [`run`] is the two of them together,
13//! which is the whole of the `-O0` allocator. [`check`] reads an assignment back and says whether
14//! it is one the machine can run, which [`run`] asserts on in debug and CI builds and which the
15//! backtracking allocator is held to the same way. [`trace`] asks the other half of the question,
16//! which is whether the rewrite wrote that decision down without losing a value on the way: it
17//! follows every value from the instruction that wrote it to the instructions that read it,
18//! through the moves, and [`run`] asserts on it in the same builds.
19//!
20//! The allocator the optimizer uses is in [`backtrack`]. [`pressure`] counts, at every point, the
21//! values that want a register against the registers there are, and [`spill`] reads that to pick
22//! which values go to memory before [`backtrack`] places the rest.
23//!
24//! Every crate in the workspace is published, and publishing implies a promise. This one is
25//! tier 3: its Rust API is explicitly unstable and will change without a major version bump.
26//! Depend on the `rucc` binary's behaviour, not on this.
27
28#![doc(html_root_url = "https://docs.rs/rucc-regalloc/0.12.2")]
29
30pub mod assign;
31pub mod backtrack;
32pub mod check;
33pub mod live;
34pub mod moves;
35pub mod order;
36pub mod pressure;
37pub mod rewrite;
38pub mod spill;
39pub mod trace;
40
41/// What allocating a function produced.
42///
43/// The moves are handed back rather than written into the function because a move is an
44/// instruction and an instruction belongs to a target, which `spec/10-backend.md` section 10.8
45/// says this crate holds nothing of. The consumer turns each one into whatever its target moves a
46/// register with.
47#[derive(Debug, Clone)]
48pub struct Allocation {
49    /// Where every value of the function went, which is what the frame layout reads.
50    pub assignment: assign::Assignment,
51    /// The moves the places do not already make true, in the order they have to be made in.
52    pub edits: Vec<rewrite::Edit>,
53    /// The line the function was laid out in while it was allocated, which the liveness below is
54    /// counted along.
55    pub order: order::Order,
56    /// Where every value was live.
57    ///
58    /// Handed back rather than dropped because the stack slot allocator shares one run of bytes
59    /// between two things that are never both wanted, and the only liveness that knows where a
60    /// spilled value is wanted is the one the spilling was decided from. Working a second one out
61    /// afterwards would cost a pass and would be free to disagree with this one.
62    /// `spec/optimizer/36-lowering-and-isel.md` section 36.7 asks for the one answer.
63    pub live: live::Live,
64}
65
66/// Allocates registers for a function the way `-O0` asks for, rewriting it as it goes.
67///
68/// This is the shape `spec/10-backend.md` section 10.4 gives an allocator: a function and the
69/// registers it may use in, an assignment and the moves that make it true out. The backtracking
70/// allocator will answer the same question the same way.
71///
72/// # Panics
73///
74/// Panics on a function the caller was told not to hand it, which is one with a critical edge or
75/// one whose entry block has parameters. See [`rewrite::rewrite`].
76///
77/// It also panics on an assignment [`check`] finds a problem with, which is a bug in this crate or
78/// in whatever produced the function rather than anything the caller did. `spec/10-backend.md`
79/// section 10.4 asks for that check in debug and CI builds, and it runs before the rewrite because
80/// the assignment is the decision and the rewrite only writes it down.
81///
82/// It panics on a rewrite [`trace`] finds a value missing from as well. That one runs afterwards,
83/// since a transcription can only be read once it has been made, and it is the check
84/// `spec/optimizer/39-register-allocation.md` section 39.6 asks for.
85///
86/// `verify` is what turns both of those on in a build that has assertions compiled out. A debug
87/// build runs them whatever it says, since that is where a broken pass should be caught, and a
88/// release build runs them when the caller asks, which is what `-Zverify-each` is for and what
89/// section 10.4 means by a CI build. It is a parameter rather than a `cfg!` because the thing
90/// worth catching is a pass that writes a function nothing defines a register in, the gate
91/// compiles release, and a check the gate never runs is a check that finds the bug after the merge
92/// rather than on the pull request. tamnd/rucc#1411.
93///
94/// `called` is what to call the function in that message. It is passed in rather than read off the
95/// function because the name there is a symbol and resolving one wants the interner, which this
96/// crate has no reason to be handed otherwise. Without it the message is a pair of register numbers
97/// and nothing that says where, and finding the function it was about in a file the size of the
98/// SQLite amalgamation means bisecting by hand.
99pub fn run(func: &mut rucc_mir::Func, env: &assign::Env, called: &str, verify: bool) -> Allocation {
100    run_with(func, env, called, verify, Allocator::Single)
101}
102
103/// Which of the two allocators decides where the values go.
104///
105/// The rewrite, the checks and the moves are the same for both, since each hands back an
106/// [`assign::Assignment`] and nothing after the decision asks which one made it.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
108pub enum Allocator {
109    /// The single pass of [`assign`], which is what `-O0` asks for.
110    #[default]
111    Single,
112    /// The allocator of [`backtrack`], which weighs what each value costs to keep in memory.
113    Backtracking,
114}
115
116/// Allocates registers for a function with the allocator asked for, rewriting it as it goes.
117///
118/// # Panics
119///
120/// As [`run`].
121pub fn run_with(
122    func: &mut rucc_mir::Func,
123    env: &assign::Env,
124    called: &str,
125    verify: bool,
126    allocator: Allocator,
127) -> Allocation {
128    let checking = verify || cfg!(debug_assertions);
129    let order = order::Order::of(func);
130    let live = live::Live::of(func, &order);
131    let mut assignment = match allocator {
132        Allocator::Single => assign::assign(func, &order, &live, env),
133        Allocator::Backtracking => backtrack::assign(func, &order, &live, env),
134    };
135    // An answer that went over the second source of an instruction that reads its sources either
136    // way round. Swapping them makes it an ordinary reuse of the first, so the checker, the trace
137    // and the rewrite read it as one. Liveness does not care which way round two uses are.
138    for &inst in assignment.commuted() {
139        let list = func[inst].operands;
140        func[list].swap(1, 2);
141    }
142    if checking {
143        let problems = check::check(func, &order, &live, &assignment);
144        assert!(problems.is_empty(), "in '{called}': {}", check::report(&problems));
145    }
146    // What the rewrite is about to lose, taken while it is still there. Only in a build that is
147    // going to read it, since the snapshot is a copy of every operand list in the function.
148    let shape = checking.then(|| trace::shape(func));
149    let edits = rewrite::rewrite(func, &mut assignment, env);
150    if let Some(shape) = shape {
151        let faults = trace::trace(func, &shape, &assignment, &edits);
152        assert!(faults.is_empty(), "in '{called}': {}", trace::report(&faults));
153    }
154    Allocation { assignment, edits, order, live }
155}
156
157/// The milestone in `spec/17-milestones.md` that fills this crate in.
158pub const MILESTONE: &str = "M3";
159
160#[cfg(test)]
161mod tests {
162    use rucc_base::Interner;
163    use rucc_mir::{Func, Opcode};
164    use rucc_target::x86_64::{GPR, SYSV};
165
166    use super::*;
167
168    #[test]
169    fn milestone_is_recorded() {
170        assert!(MILESTONE.starts_with('M'));
171    }
172
173    #[test]
174    fn allocating_a_function_places_every_value_and_hands_back_the_moves_it_needs() {
175        let mut names = Interner::new();
176        let mut func = Func::new(names.intern("f"));
177        let opcode = Opcode::new(names.intern("x64.nop"));
178        let block = func.create_block();
179        let first = func.new_vreg(GPR);
180        let second = func.new_vreg(GPR);
181        let third = func.new_vreg(GPR);
182        func.build(block, opcode).def(first, GPR).finish();
183        func.build(block, opcode).def(second, GPR).finish();
184        func.build(block, opcode).def(third, GPR).finish();
185        func.build(block, opcode).uses(first, GPR).uses(second, GPR).uses(third, GPR).finish();
186
187        // Two registers to hand out and three values that are all wanted at once, so one of them
188        // goes to the stack and the instruction that reads it gets a reload. This is also where
189        // the checker runs, since a debug build asserts on what it says.
190        let env = assign::Env::new().with(GPR, &SYSV.int_order[..2], &SYSV.int_order[2..5]);
191        let allocation = run(&mut func, &env, "test", true);
192
193        assert_eq!(allocation.assignment.spilled(), 1);
194        assert_eq!(allocation.edits.len(), 2);
195    }
196}