rucc_codegen/layout.rs
1//! Putting the blocks in an order, and turning the edges between them into jumps.
2//!
3//! Design: `spec/10-backend.md` section 10.6.
4//!
5//! Up to here a function is a set of blocks and a set of edges, and nothing has said which block
6//! comes first in memory. A machine has no such thing: it runs the instruction after the one it
7//! just ran, so an order is not a presentation detail but the last piece of what the function
8//! means. This is what chooses one, and then writes the jumps that make the edges the order did
9//! not put next to each other still go where they went.
10//!
11//! # What the order is
12//!
13//! Two orders, and which one is used is what `-freorder-blocks` asks about.
14//!
15//! At `-O0`, reverse postorder over the CFG, with each block's successors walked in reverse, and
16//! anything unreachable put at the end in block order. That is the order `spec/10-backend.md`
17//! section 10.3 asks for, and it is not arbitrary. Walking the successors in reverse is what
18//! makes the first arm of a branch come out first, because a depth-first walk finishes its last
19//! child first and reverse postorder then puts that child last. So an `if` with no `else` falls
20//! through into its body, and a loop comes out as its header, its body and then whatever follows
21//! it, which is the shape where the back edge is the only jump in it.
22//!
23//! Above it, traces: the software trace cache construction of
24//! `spec/optimizer/38-scheduling-and-layout.md` section 38.4, which is `traces` below.
25//!
26//! Unreachable blocks are laid out rather than deleted. Deleting one is a decision about what the
27//! program does and this pass has no business making it, and a block nothing reaches costs the
28//! bytes it occupies and nothing else.
29//!
30//! # What a block looks like afterwards
31//!
32//! A block still holds where it goes, and it still holds every arm, which is what keeps the
33//! control flow graph readable after this has run. What changes is that the order the arms are in
34//! now means something it did not mean before:
35//!
36//! ```text
37//! no arms it returns
38//! one arm it falls into that block if that block is next, and jumps to it if not
39//! two arms a test and a conditional jump to the first, and the second is always next
40//! ```
41//!
42//! So a jump target is a block without an instruction growing a field for one.
43//! `rucc_mir::InstData` is twenty eight bytes by assertion and a block reference does not fit in
44//! it, and every pass over the graph already reads the arms, so putting the target where the
45//! graph already is costs nothing and keeps the two from disagreeing.
46//!
47//! Which arm is which is no longer which way the condition went, because a block that falls into
48//! the arm the condition is true for is a block whose jump has to be taken when it is false. That
49//! is what the two conditional jumps in [`BranchInsts`] are for, and it is why the arms may come
50//! out swapped: what the condition meant is in the opcode afterwards, and what the arms mean is
51//! where the jump goes and what comes next.
52//!
53//! # The one block none of that is true of
54//!
55//! A block that ends in the jump through a register, which is what a computed `goto` is selected
56//! as. Where it goes is in the register, so the arms are the whole list of places it might arrive
57//! at and there may be any number of them. Nothing is written here for such a block: the jump is
58//! already in it, none of its arms is fallen into and none is jumped to from here, and a jump
59//! written behind that one would be a jump nothing reaches. The arms stay on the block for the
60//! reason they stay on every other one, which is that the liveness and this pass both read them.
61//!
62//! # The block a branch sometimes needs
63//!
64//! A branch whose second arm cannot be laid out next, because both its arms are blocks the walk
65//! has already been to, would need two jumps in one block. Rather than write one, this makes the
66//! block it needs: an empty one on the second edge, laid out immediately after the branch, that
67//! jumps where the edge went. That is exactly the critical edge splitting in [`crate::split`],
68//! done for a different reason, and it costs the same jump the second jump would have cost while
69//! leaving every block with at most one.
70//!
71//! # The test a comparison makes unnecessary
72//!
73//! Almost every branch a C program writes is on a comparison, and a comparison has already set
74//! the flags by the time the byte it wrote is tested against itself. So where the instruction in
75//! front of the branch is that comparison, and the branch is the whole of what reads its byte,
76//! the byte and the test both go and the jump names the condition the comparison was asked about
77//! instead of naming zero. Three instructions become two, and the two are what the machine has a
78//! comparison and a conditional jump for.
79//!
80//! This is where it happens rather than anywhere earlier because of what the flags are. Between
81//! the comparison and the jump they are live and they are not a register: no pass could be told
82//! about them, so no pass may put an instruction between the two. After this one there is no pass
83//! left, which is the whole of the argument, and it is the same argument
84//! `rucc_target::x86_64::Form::CmpSet` is one form rather than two under.
85//!
86//! What this cannot work out for itself is whether the byte has another reader. Every register is
87//! physical by the time this runs and a physical register is written many times in a function, so
88//! the question has to be asked while they are still virtual and written once. [`fusable`] is that
89//! question, asked before allocation, and its answer is one of the arguments to [`blocks`]. The
90//! same arrangement, and for the same reason, as the addresses [`crate::finish`] has still to
91//! write and [`crate::fold`] is handed.
92//!
93//! # Why it runs last
94//!
95//! [`crate::finish`] finds the blocks a function returns from by looking for the ones that go
96//! nowhere. Nothing here creates one of those, but everything here reads and writes the arms, and
97//! a pass that reorders them is one nothing before it should be looking at. Running the layout
98//! after the prologue and the epilogue are in is also what makes the epilogue something it can
99//! lay out around rather than something it has to leave room for.
100
101use std::cmp::Reverse;
102use std::collections::{BinaryHeap, HashMap, HashSet};
103
104use rucc_base::Interner;
105use rucc_mir as mir;
106use rucc_target::{BranchInsts, Fusion, Role};
107
108/// The scale a weight is in, which is what a share of a block is worked out against.
109const SCALE: u128 = mir::Weight::SCALE as u128;
110
111/// Puts a function's blocks in an order and writes the jumps that order needs.
112///
113/// Run last, after [`crate::finish`].
114///
115/// # Panics
116///
117/// Panics on a block with more than two successors that does not end in the jump through a
118/// register, which is the only thing that lowers to one, and on a block with two whose last
119/// instruction is not the conditional branch the target named. Both are a function that was built
120/// wrongly somewhere earlier, and both are worth finding here rather than as a jump to the wrong
121/// place.
122pub fn blocks(
123 func: &mut mir::Func,
124 insts: &BranchInsts,
125 names: &mut Interner,
126 fusable: &HashSet<mir::Inst>,
127 reorder: bool,
128) {
129 let table = table(insts, names);
130 let mut order = if reorder { traces(func) } else { order(func) };
131 let mut writer = Writer { func, insts, names, table, fusable };
132 let mut at = 0;
133 while at < order.len() {
134 // A branch that can fall into neither arm asks for a block to put the second jump in, and
135 // that block goes immediately after it, which is where the loop reaches it next.
136 if let Some(bridge) = writer.edges(order[at], order.get(at + 1).copied()) {
137 order.insert(at + 1, bridge);
138 }
139 at += 1;
140 }
141 func.set_block_order(&order);
142}
143
144/// The heads of the loops, which are the blocks a jump inside a loop runs backwards to, in the order
145/// they are laid out.
146///
147/// Read off the layout rather than off a loop tree, because what the padding is for is where the
148/// jump lands and the layout is what says that. A loop the layout rotated has its test at the
149/// bottom and its body at the top, and the top of the body is the head here, since it is where the
150/// back edge goes every time round. A block that jumps to itself is its own head.
151///
152/// A jump that runs backwards is not always a loop. The trace can lay a cold arm out after the
153/// block it rejoins, and the jump back from it runs once. What makes it a loop is that the block
154/// it lands on can get back to the jump, which is both ends being on one cycle of the graph.
155///
156/// Never the first block. The front of a function is already on the boundary a function is given,
157/// and anything put between the function's name and its first instruction would be in the room a
158/// patcher was promised or ahead of the landing pad an indirect call has to find first.
159///
160/// Nor a loop that hardly runs. `spec/optimizer/38-scheduling-and-layout.md` section 38.5 takes
161/// gcc's `align-threshold`: padding is size, so it goes in front of a head that runs at least a
162/// hundredth as often as the hottest block of the function and nowhere else. A function with no
163/// weights has every block at the same one, and then every loop is hot enough.
164///
165/// Run after [`blocks`], and after anything else that adds or takes out a block.
166#[must_use]
167pub fn heads(func: &mir::Func) -> Vec<mir::Block> {
168 let mut at = vec![usize::MAX; func.block_count()];
169 for (place, block) in func.blocks().enumerate() {
170 at[block.index()] = place;
171 }
172 let piece = cycles(func);
173 let mut back = vec![false; func.block_count()];
174 for block in func.blocks() {
175 for succ in &func[block].succs {
176 let to = succ.block.index();
177 if at[to] <= at[block.index()] && piece[to] == piece[block.index()] {
178 back[to] = true;
179 }
180 }
181 }
182 let hottest = func.blocks().map(|block| func[block].weight.raw()).max().unwrap_or(0);
183 let floor = hottest / ALIGN_THRESHOLD;
184 func.blocks()
185 .skip(1)
186 .filter(|block| back[block.index()] && func[*block].weight.raw() >= floor)
187 .collect()
188}
189
190/// How many times less often than the hottest block a loop may run and still be padded, which is
191/// gcc's `align-threshold` (`gcc/params.opt:29`). See [`heads`].
192const ALIGN_THRESHOLD: u64 = 100;
193
194/// Which piece of the graph each block is in, indexed by the block's own number, where two blocks
195/// are in the same piece when each can reach the other.
196///
197/// Kosaraju's two walks, both with a stack of their own rather than recursion, for the reason
198/// [`order`] gives: the first down the edges to find the order the blocks finish in, and the second
199/// up them from the last to finish, where everything one walk reaches is one piece.
200fn cycles(func: &mir::Func) -> Vec<usize> {
201 let count = func.block_count();
202 let mut preds = vec![Vec::new(); count];
203 for block in func.blocks() {
204 for succ in &func[block].succs {
205 preds[succ.block.index()].push(block.index());
206 }
207 }
208 let mut finished = Vec::with_capacity(count);
209 let mut seen = vec![false; count];
210 for block in func.blocks() {
211 if std::mem::replace(&mut seen[block.index()], true) {
212 continue;
213 }
214 let mut stack = vec![(block, 0usize)];
215 while let Some((block, next)) = stack.pop() {
216 let Some(succ) = func[block].succs.get(next) else {
217 finished.push(block.index());
218 continue;
219 };
220 stack.push((block, next + 1));
221 if !std::mem::replace(&mut seen[succ.block.index()], true) {
222 stack.push((succ.block, 0));
223 }
224 }
225 }
226 let mut piece = vec![usize::MAX; count];
227 for (number, &root) in finished.iter().rev().enumerate() {
228 if piece[root] != usize::MAX {
229 continue;
230 }
231 piece[root] = number;
232 let mut stack = vec![root];
233 while let Some(block) = stack.pop() {
234 for &pred in &preds[block] {
235 if piece[pred] == usize::MAX {
236 piece[pred] = number;
237 stack.push(pred);
238 }
239 }
240 }
241 }
242 piece
243}
244
245/// The order the blocks are laid out in, which is every block the function has exactly once.
246fn order(func: &mir::Func) -> Vec<mir::Block> {
247 let mut order = Vec::with_capacity(func.block_count());
248 let mut seen = vec![false; func.block_count()];
249 if let Some(entry) = func.entry() {
250 seen[entry.index()] = true;
251 // The walk is explicit rather than recursive because a function with a hundred thousand
252 // blocks in it is a function somebody generated, and it should compile rather than run out
253 // of stack. Each entry is a block and how many of its arms have been started.
254 let mut stack = vec![(entry, 0usize)];
255 while let Some((block, next)) = stack.pop() {
256 let succs = &func[block].succs;
257 let Some(arm) = succs.len().checked_sub(next + 1) else {
258 order.push(block);
259 continue;
260 };
261 stack.push((block, next + 1));
262 let to = succs[arm].block;
263 if !std::mem::replace(&mut seen[to.index()], true) {
264 stack.push((to, 0));
265 }
266 }
267 order.reverse();
268 }
269 // Whatever the walk did not reach, in the order the blocks were made, which is the only order
270 // there is anything to be said for when nothing goes to any of them.
271 order.extend(func.blocks().filter(|block| !seen[block.index()]));
272 order
273}
274
275/// The rounds the traces are built in, each asking for less than the one before it.
276///
277/// Design: `spec/optimizer/38-scheduling-and-layout.md` section 38.4, which quotes
278/// `gcc/bb-reorder.cc:32` on why there is more than one round: a first round that only follows
279/// the arms almost always taken builds the trunk of the function, and the rounds below it pick up
280/// what is left without being able to break the trunk apart. It costs one more pass over the
281/// blocks per round and it is the difference between "stc" and "simple".
282///
283/// A round is a pair. The first number is how likely an arm has to be for the trace to follow it,
284/// in parts of [`mir::Weight::SCALE`], which is GCC's branch threshold. The second is how often
285/// the block at the end of that arm has to run, in the same parts of how often the function is
286/// entered, which is GCC's exec threshold. The last round asks for nothing, which is what makes
287/// every block end up somewhere.
288///
289/// The eight numbers are GCC's own, out of `branch_threshold` and `exec_threshold` in
290/// `gcc/bb-reorder.cc`, in ten thousandths where GCC writes thousandths. Two things about them
291/// are worth saying out loud because both were got wrong here first.
292///
293/// The branch threshold is low. Two fifths, not nine tenths: an arm taken half the time is an arm
294/// the first round follows, and since one arm of a two way branch always is, the first round walks
295/// straight through an unpredicted function the way a depth first walk would. A high threshold
296/// stops the trace at every branch nothing predicted, which is most of them, and hands both arms
297/// back to the seed list to be laid out by weight, and weight is exactly what has nothing to say
298/// about them.
299///
300/// The exec threshold is against the entry and not against the hottest block. A block that runs
301/// once per call is a block in the trunk of the function, and measuring it against a loop that
302/// runs twenty times a call makes the whole trunk cold: the preheader of every loop lands at the
303/// end of the function behind a jump, which is the opposite of what this is for.
304const ROUNDS: [(u64, u64); 4] = [(4_000, 5_000), (2_000, 2_000), (1_000, 500), (0, 0)];
305
306/// The order the blocks are laid out in above `-O0`, which is traces grown from the hottest
307/// blocks outwards.
308///
309/// Design: `spec/optimizer/38-scheduling-and-layout.md` section 38.4.
310///
311/// A trace is a run of blocks that control is expected to walk straight through. It is grown from
312/// a seed by repeatedly taking the arm most likely to be the one taken, stopping when no arm is
313/// likely enough for the round or when the likeliest one leads somewhere the layout has already
314/// been. Every block is a seed in some round, the hotter ones first, and the traces come out in
315/// the order they were grown. So the function's trunk is laid out first and contiguously, its
316/// error paths end up behind it, and the branch that leaves the trunk is the one that costs a
317/// jump.
318///
319/// The entry is the first seed whatever its weight, because on this machine a function is entered
320/// at its first byte and the block laid out first is the block that runs first. A hotter block
321/// inside a loop would otherwise take the seat.
322///
323/// The traces are then run together by [`connect`], which is what keeps a run of blocks the rounds
324/// cut in half from coming out in two places.
325///
326/// # Which block the next trace starts at
327///
328/// Not simply the hottest one left. A block something already laid out goes to comes first, and
329/// among those the one with the hottest edge into it, which is [`Seed`] and which is GCC's
330/// `bb_to_key` in `gcc/bb-reorder.cc`. The reason is the whole of what a layout costs: a block laid
331/// out in front of everything that reaches it pays a jump on every one of those paths and saves
332/// nothing, and a block laid out behind the trace that reaches it pays nothing on the path that
333/// falls into it. Seeding by weight alone gets this wrong on the commonest shape in C, which is two
334/// arms that both end at one block: the block both arms join at is the hottest of the three and
335/// goes first, and then both arms jump to it.
336///
337/// # Loop rotation, and where it comes from
338///
339/// Section 38.4 asks for the loop to be rotated so that its exit is the last block of the trace,
340/// and there is no step here that does it. It falls out of the walk instead: a trace that enters
341/// a loop header follows the body, reaches the latch, finds that the latch's likeliest arm is the
342/// header it has already laid out, and stops. The exit is then a seed of its own and comes next.
343/// That is the rotated order, back edge running backwards and exit falling through, arrived at
344/// from the greedy rule rather than from a rule about loops.
345///
346/// What that does not cover is a loop whose header is its exit test and whose body is cold, where
347/// GCC would duplicate the header. Section 38.4 says the first version should not copy code and
348/// this does not.
349fn traces(func: &mir::Func) -> Vec<mir::Block> {
350 // Where the shape of the graph would have put each block, which is what decides between two
351 // blocks that run equally often. Most branches in most functions have nothing to predict them
352 // by and come out even, so without this the seed order between them would be the order the
353 // blocks happen to have been made in, and a block that falls into the one after it under
354 // [`order`] would be laid out somewhere else for no reason and pay a jump for it.
355 let mut place = vec![usize::MAX; func.block_count()];
356 for (at, &block) in order(func).iter().enumerate() {
357 place[block.index()] = at;
358 }
359
360 let mut found: Vec<Vec<mir::Block>> = Vec::new();
361 let mut seen = vec![false; func.block_count()];
362 // How often the function is entered, which every exec threshold is a share of. A function
363 // whose entry says nothing is one nobody wrote a weight on, and then once is the right answer
364 // for every block in it and every round behaves the same.
365 let entered = func.entry().map_or(mir::Weight::ONCE, |entry| func[entry].weight).raw();
366 // The hottest edge into each block out of a block already laid out, which is what the queue is
367 // ordered by and what says whether an entry popped off it is out of date. It outlives the
368 // round it was written in on purpose: a trace that stops because the next block is below this
369 // round's exec threshold leaves that block remembered as reached, and the round that does take
370 // it starts its first trace there rather than wherever the weights happen to point. That is
371 // how a chain of comparisons whose tail cools off below the threshold stays a straight line.
372 let mut reached = vec![0; func.block_count()];
373
374 for (likely, often) in ROUNDS {
375 // The exec threshold as a number rather than a fraction. In a hundred and twenty eight
376 // bits because a weight saturates at the top of a sixty four bit one and a nest of loops
377 // gets there.
378 let floor =
379 u64::try_from(u128::from(entered) * u128::from(often) / SCALE).unwrap_or(u64::MAX);
380 // A round does not start a trace in a block colder than its exec threshold, which is what
381 // keeps an error path out of the middle of the trunk: it waits for a round that asks for
382 // less. The entry is the exception below, because the block laid out first is the block
383 // that runs first and that has to be the entry whatever it weighs.
384 let mut queue: BinaryHeap<Seed> = func
385 .blocks()
386 .filter(|&block| !seen[block.index()] && func[block].weight.raw() >= floor)
387 .map(|block| Seed {
388 reached: reached[block.index()],
389 weight: func[block].weight,
390 place: Reverse(place[block.index()]),
391 block,
392 })
393 .collect();
394 let mut start = func.entry().filter(|entry| !seen[entry.index()]);
395
396 while let Some(from) = start.take().or_else(|| next_seed(&mut queue, &seen, &reached)) {
397 let mut trace = Vec::new();
398 let mut block = from;
399 loop {
400 seen[block.index()] = true;
401 trace.push(block);
402 let next = along(func, block, &seen, likely, floor);
403 // Everything this block goes to and the trace does not, so that the next trace can
404 // start at one of them rather than wherever the weights point. A block too cold
405 // for this round is still written down as reached, because the round that is cold
406 // enough to take it wants to know it hangs off something already laid out.
407 for call in &func[block].succs {
408 let to = call.block;
409 if seen[to.index()]
410 || Some(to) == next
411 || call.weight.raw() <= reached[to.index()]
412 {
413 continue;
414 }
415 reached[to.index()] = call.weight.raw();
416 if func[to].weight.raw() >= floor {
417 queue.push(Seed {
418 reached: call.weight.raw(),
419 weight: func[to].weight,
420 place: Reverse(place[to.index()]),
421 block: to,
422 });
423 }
424 }
425 let Some(next) = next else { break };
426 block = next;
427 }
428 found.push(trace);
429 }
430 }
431 connect(func, found)
432}
433
434/// The traces run together into one order, each one followed where possible by the trace control
435/// leaves it for.
436///
437/// Design: `gcc/bb-reorder.cc`, `connect_traces`.
438///
439/// The rounds cut a straight run of blocks into pieces whenever the run cools below the round's
440/// exec threshold, and a chain of comparisons against a constant is exactly that: each comparison
441/// is reached only when every one before it failed, so the chain halves in weight at every step and
442/// the round that laid the head of it down will not touch the tail. Left alone, the pieces come out
443/// in round order with other traces between them, and every piece pays a jump to reach the next.
444///
445/// So the pieces are put back together. Each trace is followed by the unplaced trace its last block
446/// most often goes to, and that one by the trace its last block most often goes to, until there is
447/// none, and only then does the next trace in round order start a new run. The rounds still decide
448/// which trace is hot and comes first, and this decides what falls in behind it.
449fn connect(func: &mir::Func, traces: Vec<Vec<mir::Block>>) -> Vec<mir::Block> {
450 // Which trace each block starts, for the blocks that start one. A trace may only be joined at
451 // its first block, because joining it anywhere else would mean cutting it in half and the
452 // rounds put it together for a reason.
453 let mut head = vec![usize::MAX; func.block_count()];
454 for (at, trace) in traces.iter().enumerate() {
455 if let Some(&first) = trace.first() {
456 head[first.index()] = at;
457 }
458 }
459
460 let mut order = Vec::with_capacity(func.block_count());
461 let mut used = vec![false; traces.len()];
462 for from in 0..traces.len() {
463 if used[from] {
464 continue;
465 }
466 let mut at = from;
467 loop {
468 used[at] = true;
469 order.extend_from_slice(&traces[at]);
470 let Some(&last) = traces[at].last() else { break };
471 let mut best: Option<(u64, usize)> = None;
472 for call in &func[last].succs {
473 let to = head[call.block.index()];
474 if to == usize::MAX || used[to] {
475 continue;
476 }
477 let weight = call.weight.raw();
478 // Ties go to the trace found first, which is the hotter of the two, because the
479 // rounds laid the traces down hottest first.
480 if best.is_none_or(|(found, over)| weight > found || (weight == found && to < over))
481 {
482 best = Some((weight, to));
483 }
484 }
485 let Some((_, next)) = best else { break };
486 at = next;
487 }
488 }
489 order
490}
491
492/// A block a trace could start at, ordered so that the greatest is the one to start at next.
493///
494/// Design: `gcc/bb-reorder.cc`, `bb_to_key`, of which this is the same three answers in the order
495/// GCC asks them.
496#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
497struct Seed {
498 /// How often the hottest edge into this block out of a block already laid out is taken, and
499 /// zero while nothing laid out goes here. First, so that a block something reaches beats a
500 /// block nothing reaches however hot the second one is.
501 reached: u64,
502 /// How often the block runs, which decides between two blocks nothing laid out reaches.
503 weight: mir::Weight,
504 /// Where reverse postorder would have put it, which decides between two blocks that are equal
505 /// on both of the above, so that a function with no weights on it comes out in the order the
506 /// shape of its graph gives rather than in whatever order the queue settles.
507 place: Reverse<usize>,
508 /// The block, last, so that two blocks equal on everything else still come out in one order.
509 block: mir::Block,
510}
511
512/// The next block to start a trace at, out of the queue, or nothing when there is none left.
513///
514/// An entry whose block has been laid out since it was queued, or which was queued before a hotter
515/// edge into the same block was found, is thrown away here rather than found and updated in place
516/// when that happens. The queue is a heap and an entry in the middle of one cannot be reached, so
517/// the choice is between this and an index beside it, and a stale entry costs one pop.
518fn next_seed(queue: &mut BinaryHeap<Seed>, seen: &[bool], reached: &[u64]) -> Option<mir::Block> {
519 while let Some(seed) = queue.pop() {
520 if !seen[seed.block.index()] && seed.reached >= reached[seed.block.index()] {
521 return Some(seed.block);
522 }
523 }
524 None
525}
526
527/// The arm the trace follows out of a block, or nothing when no arm is worth following.
528///
529/// The likeliest arm that has not been laid out already, is taken at least as often as the
530/// round's floor, and takes at least the round's share of the times the block runs. Ties go to
531/// the arm written first, which is the arm a conditional branch takes when its condition holds,
532/// so a function with no weights on it at all comes out following the true arm.
533fn along(
534 func: &mir::Func,
535 block: mir::Block,
536 seen: &[bool],
537 likely: u64,
538 floor: u64,
539) -> Option<mir::Block> {
540 let whole = func[block].weight;
541 let mut best: Option<&mir::BlockCall> = None;
542 for call in &func[block].succs {
543 if seen[call.block.index()]
544 || call.weight.raw() < floor
545 || call.weight.out_of(whole) < likely
546 {
547 continue;
548 }
549 if best.is_none_or(|found| call.weight > found.weight) {
550 best = Some(call);
551 }
552 }
553 best.map(|call| call.block)
554}
555
556/// The comparisons a branch may be folded into, which [`blocks`] can then find by opcode.
557///
558/// One entry per name the target's table holds, interned once for the function rather than once
559/// per block, since a block that ends in a branch is most of the blocks there are.
560fn table(insts: &BranchInsts, names: &mut Interner) -> HashMap<mir::Opcode, &'static Fusion> {
561 insts
562 .fused
563 .iter()
564 .map(|fusion| {
565 (mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, fusion.set))), fusion)
566 })
567 .collect()
568}
569
570/// The comparisons a branch on their answer is the whole of what reads, which [`blocks`] may fold
571/// the test out of.
572///
573/// Run before allocation, on the same function [`blocks`] is later given. What it answers is
574/// whether anything but the branch reads the byte a comparison wrote, and that is a question about
575/// a virtual register: a physical one is written many times in a function and counting its readers
576/// would mean asking which of the writes each reader belongs to. So it is asked here, where a
577/// register is written once, and the answer is carried to the pass that can use it.
578///
579/// Being on this list is necessary and not sufficient. Allocation may put a reload between the
580/// comparison and the branch, and a comparison that is no longer the instruction in front of the
581/// branch is not one the flags survive to, so [`blocks`] checks that again on what it finds.
582#[must_use]
583pub fn fusable(func: &mir::Func, insts: &BranchInsts, names: &mut Interner) -> HashSet<mir::Inst> {
584 let table = table(insts, names);
585 let branch = mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, insts.cond)));
586 let reads = crate::changes::Reads::of(func);
587 let mut found = HashSet::new();
588 for block in func.blocks() {
589 let insts: Vec<mir::Inst> = func.insts(block).collect();
590 let [.., compare, last] = insts[..] else { continue };
591 if func[last].opcode != branch || !table.contains_key(&func[compare].opcode) {
592 continue;
593 }
594 let operands = &func[func[compare].operands];
595 let Some(byte) = operands.first().filter(|operand| operand.role != Role::Use) else {
596 continue;
597 };
598 if !byte.reg.is_virtual() || reads.count(byte.reg) != 1 {
599 continue;
600 }
601 // And it is this branch that reads it rather than one in some other block, which the
602 // count alone does not say.
603 if func[func[last].operands].first().map(|operand| operand.reg) == Some(byte.reg) {
604 found.insert(compare);
605 }
606 }
607 found
608}
609
610/// The one thing that writes an instruction here, over the function it writes into.
611struct Writer<'a> {
612 func: &'a mut mir::Func,
613 insts: &'a BranchInsts,
614 names: &'a mut Interner,
615 table: HashMap<mir::Opcode, &'static Fusion>,
616 fusable: &'a HashSet<mir::Inst>,
617}
618
619impl Writer<'_> {
620 /// Writes the jumps one block needs, given the block laid out after it, and gives back the
621 /// block that has to go between the two when the branch needed one.
622 fn edges(&mut self, block: mir::Block, next: Option<mir::Block>) -> Option<mir::Block> {
623 // A block that already ends in the jump through a register wants nothing written, whatever
624 // its arms are. Where it goes is in the register, so none of its arms is fallen into and
625 // none of them is jumped to from here, and a jump written behind that one would be a jump
626 // nothing reaches.
627 if self.leaves_indirectly(block) {
628 return None;
629 }
630 match self.func[block].succs.len() {
631 0 => None,
632 1 => {
633 self.one(block, next);
634 None
635 }
636 2 => self.two(block, next),
637 arms => panic!("a block with {arms} arms, and nothing lowers to one"),
638 }
639 }
640
641 /// Whether the block ends in the jump through a register a computed `goto` is selected as.
642 fn leaves_indirectly(&mut self, block: mir::Block) -> bool {
643 let Some(last) = self.func.terminator(block) else { return false };
644 let indirect = self.opcode(self.insts.indirect);
645 self.func[last].opcode == indirect
646 }
647
648 /// Whether the block already ends in a jump on the condition state, which an `asm` template
649 /// wrote and this pass did not.
650 fn jumps_already(&mut self, block: mir::Block) -> bool {
651 let Some(last) = self.func.terminator(block) else { return false };
652 let opcode = self.func[last].opcode;
653 let conditional = self.insts.conditional;
654 conditional.iter().any(|name| self.opcode(name) == opcode)
655 }
656
657 /// A block that goes to one place, which either follows it or has to be jumped to.
658 fn one(&mut self, block: mir::Block, next: Option<mir::Block>) {
659 if Some(self.func[block].succs[0].block) == next {
660 return;
661 }
662 let opcode = self.opcode(self.insts.jump);
663 self.func.build(block, opcode).finish();
664 }
665
666 /// A block that goes to two places, which is a test and a jump to one of them.
667 ///
668 /// The condition is read off the branch the rules selected and the branch is taken out, so the
669 /// register the test reads is the one the branch read and no new value is made. That is what
670 /// makes this safe to run after allocation: it writes no register that was not already
671 /// written and it asks for none that was not already asked for.
672 fn two(&mut self, block: mir::Block, next: Option<mir::Block>) -> Option<mir::Block> {
673 // A block whose jump is already there, which is one an `asm` template wrote itself. Its
674 // arms are in the order the jump means, so all that is left is the block the second arm
675 // needs when it is not the one laid out next.
676 if self.jumps_already(block) {
677 let second = self.func[block].succs[1].block;
678 return (next != Some(second)).then(|| self.bridge(block));
679 }
680
681 // Asked before the branch is taken out, because what it looks at is the instruction in
682 // front of the branch and taking the branch out would make that the last one.
683 let fused = self.fused(block);
684 let condition = self.take(block);
685
686 // Whichever arm is laid out next is the one the block falls into, and the jump is then
687 // the one taken when the condition sends it the other way. Falling into the arm the
688 // condition is false for leaves the jump taken when it holds, and falling into the arm it
689 // is true for leaves the other jump and the arms the other way round.
690 let (if_true, if_false) = match fused {
691 Some((_, fusion)) => (fusion.if_true, fusion.if_false),
692 None => (self.insts.if_true, self.insts.if_false),
693 };
694 let arms: Vec<mir::Block> = self.func[block].succs.iter().map(|arm| arm.block).collect();
695 let (name, bridge) = if next == Some(arms[1]) {
696 (if_true, None)
697 } else if next == Some(arms[0]) {
698 self.func.succs_mut(block).swap(0, 1);
699 (if_false, None)
700 } else {
701 (if_true, Some(self.bridge(block)))
702 };
703
704 match fused {
705 Some((compare, fusion)) => self.keep_only_the_flags(compare, fusion),
706 None => {
707 let opcode = self.opcode(self.insts.test);
708 self.func.build(block, opcode).operand(condition).finish();
709 }
710 }
711 let opcode = self.opcode(name);
712 self.func.build(block, opcode).finish();
713 bridge
714 }
715
716 /// The comparison the block's branch can be folded into, when there is one.
717 ///
718 /// Three things have to hold and [`fusable`] has already answered the one that cannot be
719 /// answered here. What is left is that the comparison is still the instruction in front of the
720 /// branch, since allocation may have put a reload between them and the flags do not survive
721 /// one, and that the byte the branch reads is the byte that comparison wrote, since the
722 /// allocator has since given both of them a physical register and two registers that were
723 /// different could have become the same one.
724 fn fused(&self, block: mir::Block) -> Option<(mir::Inst, &'static Fusion)> {
725 let insts: Vec<mir::Inst> = self.func.insts(block).collect();
726 let [.., compare, last] = insts[..] else { return None };
727 if !self.fusable.contains(&compare) {
728 return None;
729 }
730 let fusion = *self.table.get(&self.func[compare].opcode)?;
731 let byte = self.func[self.func[compare].operands].first()?.reg;
732 (self.func[self.func[last].operands].first()?.reg == byte).then_some((compare, fusion))
733 }
734
735 /// Turns a comparison that wrote a byte into the same comparison that writes nothing.
736 ///
737 /// The instruction stays where it is and keeps its immediate, which is the point: what it does
738 /// to the flags is what it already did, and the jump written behind it reads those. Only the
739 /// operand at the front goes, which is the byte, and the opcode changes to the one that has no
740 /// operand there.
741 ///
742 /// An addressing mode comes with the rest of it and does not survive the move on its own. What
743 /// a mode holds is where in the operand vector its base and its index are, and every operand
744 /// has just come down one place, so the two positions come down with them. A comparison
745 /// against a register or a constant has no mode and nothing to do here, and a comparison
746 /// against memory is the one that does.
747 fn keep_only_the_flags(&mut self, compare: mir::Inst, fusion: &Fusion) {
748 let read: Vec<mir::Operand> =
749 self.func[self.func[compare].operands].iter().skip(1).copied().collect();
750 let operands = self.func.push_operands(&read);
751 self.func[compare].opcode = self.opcode(fusion.cmp);
752 self.func[compare].operands = operands;
753 if let Some(at) = self.func[compare].mem {
754 let mut amode = self.func[at];
755 amode.base = amode.base.map(|position| position - 1);
756 amode.index = amode.index.map(|position| position - 1);
757 self.func[compare].mem = Some(self.func.add_amode(amode));
758 }
759 }
760
761 /// Takes the conditional branch off the end of a block and gives back what it read.
762 fn take(&mut self, block: mir::Block) -> mir::Operand {
763 let branch = self.func.terminator(block).expect("a block with two arms has a branch");
764 let cond = self.opcode(self.insts.cond);
765 assert_eq!(
766 self.func[branch].opcode, cond,
767 "a block with two arms whose last instruction is not the branch"
768 );
769 let operands = self.func[branch].operands;
770 let condition = self.func[operands][0];
771 self.func.remove_inst(branch);
772 condition
773 }
774
775 /// Puts an empty block on a branch's second edge, so that the branch has something to fall
776 /// into and the jump the edge really needs is in a block of its own.
777 fn bridge(&mut self, block: mir::Block) -> mir::Block {
778 let bridge = self.func.create_block();
779 let edge = self.func[block].succs[1].clone();
780 let weight = edge.weight;
781 self.func.set_weight(bridge, weight);
782 *self.func.succs_mut(bridge) = vec![edge];
783 self.func.succs_mut(block)[1] = mir::BlockCall::to(bridge).taken(weight);
784 bridge
785 }
786
787 /// The opcode of that name on this target, which is the name with the target's prefix in
788 /// front of it.
789 fn opcode(&mut self, name: &str) -> mir::Opcode {
790 mir::Opcode::new(self.names.intern(&format!("{}{name}", self.insts.prefix)))
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use rucc_mir::{BlockCall, Mem, Opcode, Operand, Reg};
797 use rucc_target::x86_64::{BRANCH, GPR, RAX, RCX, REGS};
798
799 use super::*;
800
801 /// A function with that many blocks, none of which goes anywhere yet.
802 fn blank(count: usize) -> (Interner, mir::Func, Vec<mir::Block>) {
803 let mut names = Interner::new();
804 let mut func = mir::Func::new(names.intern("f"));
805 let blocks = (0..count).map(|_| func.create_block()).collect();
806 (names, func, blocks)
807 }
808
809 /// Puts a conditional branch at the end of a block, on a register that is already physical
810 /// the way one is by the time this pass runs.
811 fn branch(func: &mut mir::Func, names: &mut Interner, block: mir::Block, arms: &[mir::Block]) {
812 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
813 func.build(block, opcode).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
814 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
815 }
816
817 /// Laying the blocks out for the one machine this crate has, and the dump of what came out.
818 ///
819 /// The dump rather than the function, because where a jump goes is on the block and the dump
820 /// is the one place the instruction and the arm are put back together. A test that read the
821 /// two separately would pass on a function whose jump and whose edge disagreed, which is the
822 /// mistake this pass is most able to make.
823 ///
824 /// A block is named in the dump by where it is in the layout rather than by the number it was
825 /// made with, which is why every expectation below reads that way and why the order is worth
826 /// asserting on its own.
827 fn laid_out(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
828 // Both halves, in the order the pipeline runs them, so that a test which builds a
829 // comparison in front of its branch sees what a compiled function would see.
830 let fusable = fusable(func, &BRANCH, names);
831 blocks(func, &BRANCH, names, &fusable, false);
832 mir::print_func(func, names, ®S)
833 .lines()
834 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
835 .map(|line| line.trim().to_string())
836 .collect()
837 }
838
839 /// The blocks in layout order, by the number each was made with.
840 fn order_of(func: &mir::Func) -> Vec<usize> {
841 func.blocks().map(mir::Block::index).collect()
842 }
843
844 #[test]
845 fn a_block_that_falls_into_the_next_one_gets_no_jump_at_all() {
846 let (mut names, mut func, made) = blank(2);
847 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
848
849 let text = laid_out(&mut func, &mut names);
850
851 // The arm is still on the block, because the graph is still worth reading, and there is
852 // no instruction on it because the block it goes to is the one that runs next anyway.
853 assert_eq!(text, ["block0:", "block1", "block1:"]);
854 }
855
856 #[test]
857 fn a_block_that_goes_somewhere_that_is_not_next_gets_a_jump() {
858 let (mut names, mut func, made) = blank(2);
859 // A loop with nothing in it and no way out, which is the smallest function there is with
860 // an edge that runs backwards. Every layout puts the two blocks in this order, so the
861 // second one has nothing after it and its edge has to be a jump.
862 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
863 *func.succs_mut(made[1]) = vec![BlockCall::to(made[0])];
864
865 let text = laid_out(&mut func, &mut names);
866
867 assert_eq!(text, ["block0:", "block1", "block1:", "x64.jmp block0"]);
868 }
869
870 #[test]
871 fn a_branch_that_falls_into_its_false_arm_jumps_when_the_condition_holds() {
872 let (mut names, mut func, made) = blank(3);
873 // A loop whose body is the block it came from: the arm taken when the condition holds is
874 // a block the walk has already been to, so the other arm is what comes next.
875 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
876 branch(&mut func, &mut names, made[1], &[made[0], made[2]]);
877
878 let text = laid_out(&mut func, &mut names);
879
880 assert_eq!(order_of(&func), [0, 1, 2]);
881 assert_eq!(
882 text,
883 [
884 "block0:",
885 "block1",
886 "block1:",
887 "x64.test_rr_8 $rax",
888 "x64.jcc_ne block0, block2",
889 "block2:",
890 ]
891 );
892 }
893
894 #[test]
895 fn a_branch_that_falls_into_its_true_arm_jumps_when_the_condition_does_not_hold() {
896 let (mut names, mut func, made) = blank(3);
897 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
898
899 let text = laid_out(&mut func, &mut names);
900
901 // The arms come out swapped, because after this the first is where the jump goes and the
902 // second is what runs next, and the jump is the one taken when the condition failed.
903 assert_eq!(order_of(&func), [0, 1, 2]);
904 assert_eq!(
905 text,
906 ["block0:", "x64.test_rr_8 $rax", "x64.jcc_e block2, block1", "block1:", "block2:"]
907 );
908 }
909
910 #[test]
911 fn a_block_that_leaves_through_a_register_is_given_no_jump_and_keeps_every_arm() {
912 let (mut names, mut func, made) = blank(4);
913 let jump = Opcode::new(names.intern("x64.jmp_reg"));
914 func.build(made[0], jump).operand(Operand::read(Reg::physical(RAX), GPR)).finish();
915 *func.succs_mut(made[0]) = made[1..].iter().map(|&arm| BlockCall::to(arm)).collect();
916
917 let text = laid_out(&mut func, &mut names);
918
919 // Nothing written behind the jump that is already there, whatever the first arm is, since
920 // where this block goes is in the register. The arms stay on the block because they are
921 // how everything downstream finds out where control can go.
922 assert_eq!(
923 text,
924 [
925 "block0:",
926 "x64.jmp_reg $rax, block1, block2, block3",
927 "block1:",
928 "block2:",
929 "block3:"
930 ]
931 );
932 }
933
934 #[test]
935 fn a_branch_that_can_fall_into_neither_arm_is_given_a_block_to_jump_from() {
936 let (mut names, mut func, made) = blank(2);
937 // A loop that goes back to the top or round again, so both arms are blocks the walk has
938 // already been to and nothing is left to lay out after it.
939 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
940 branch(&mut func, &mut names, made[1], &[made[0], made[1]]);
941
942 let text = laid_out(&mut func, &mut names);
943
944 // Block two is the one this made. It is empty, it is laid out where the branch falls into
945 // it, and the jump the second arm needed is in it rather than being a second jump in the
946 // block above.
947 assert_eq!(order_of(&func), [0, 1, 2]);
948 assert_eq!(
949 text,
950 [
951 "block0:",
952 "block1",
953 "block1:",
954 "x64.test_rr_8 $rax",
955 "x64.jcc_ne block0, block2",
956 "block2:",
957 "x64.jmp block1",
958 ]
959 );
960 }
961
962 #[test]
963 fn the_test_reads_the_register_the_branch_read() {
964 let (mut names, mut func, made) = blank(3);
965 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
966
967 let fusable = fusable(&func, &BRANCH, &mut names);
968 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
969
970 let test = func.insts(made[0]).next().expect("a test");
971 let operands = func[test].operands;
972 assert_eq!(func[operands], [Operand::read(Reg::physical(RAX), GPR)]);
973 }
974
975 #[test]
976 fn a_block_nothing_reaches_is_laid_out_at_the_end_rather_than_deleted() {
977 let (mut names, mut func, made) = blank(4);
978 *func.succs_mut(made[0]) = vec![BlockCall::to(made[3])];
979
980 let fusable = fusable(&func, &BRANCH, &mut names);
981 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
982
983 // Blocks one and two are reached by nothing, so they go last, in the order they were
984 // made. Deleting one would be a decision about what the program does, and this pass has
985 // no business making it.
986 assert_eq!(order_of(&func), [0, 3, 1, 2]);
987 }
988
989 #[test]
990 fn a_function_with_no_blocks_is_left_alone() {
991 let mut names = Interner::new();
992 let mut func = mir::Func::new(names.intern("f"));
993
994 let fusable = fusable(&func, &BRANCH, &mut names);
995 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
996
997 assert_eq!(func.block_count(), 0);
998 }
999
1000 #[test]
1001 #[should_panic(expected = "a block with 3 arms")]
1002 fn a_block_with_three_arms_is_refused_rather_than_laid_out_wrongly() {
1003 let (mut names, mut func, made) = blank(4);
1004 branch(&mut func, &mut names, made[0], &[made[1], made[2], made[3]]);
1005
1006 let fusable = fusable(&func, &BRANCH, &mut names);
1007 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
1008 }
1009
1010 #[test]
1011 #[should_panic(expected = "whose last instruction is not the branch")]
1012 fn a_block_with_two_arms_and_no_branch_in_it_is_refused() {
1013 let (mut names, mut func, made) = blank(3);
1014 let opcode = Opcode::new(names.intern("x64.nop"));
1015 func.build(made[0], opcode).finish();
1016 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
1017
1018 let fusable = fusable(&func, &BRANCH, &mut names);
1019 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
1020 }
1021
1022 /// Puts a comparison and a branch on its answer at the end of a block.
1023 ///
1024 /// The byte is a virtual register, which is what it is when [`fusable`] is asked and is not
1025 /// what it is when [`blocks`] runs. Nothing in either half cares which it is except the
1026 /// counting, so a test that runs both over one function has to use the register the counting
1027 /// wants, and what it costs is that this is one thing the unit tests cannot check about the
1028 /// two halves running at different times. `crate::pipeline` runs them the real way round.
1029 fn compare(
1030 func: &mut mir::Func,
1031 names: &mut Interner,
1032 block: mir::Block,
1033 arms: &[mir::Block],
1034 ) -> Reg {
1035 let byte = func.new_vreg(GPR);
1036 let opcode = Opcode::new(names.intern("x64.cmp_set_l_32"));
1037 func.build(block, opcode)
1038 .def(byte, GPR)
1039 .operand(Operand::read(Reg::physical(RAX), GPR))
1040 .operand(Operand::read(Reg::physical(RCX), GPR))
1041 .finish();
1042 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
1043 func.build(block, opcode).operand(Operand::read(byte, GPR)).finish();
1044 *func.succs_mut(block) = arms.iter().map(|&arm| BlockCall::to(arm)).collect();
1045 byte
1046 }
1047
1048 /// A branch on a comparison is the comparison and a jump on what it found.
1049 ///
1050 /// Three instructions go in and two come out. The byte goes because nothing reads it, the test
1051 /// goes because the comparison set the flags the test was going to set, and the jump names the
1052 /// condition rather than naming zero. Which condition it names is the opposite of the one the
1053 /// comparison asked about, since the block falls into the arm the comparison is true for.
1054 #[test]
1055 fn a_branch_on_a_comparison_is_the_comparison_and_a_jump_on_what_it_found() {
1056 let (mut names, mut func, made) = blank(3);
1057 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
1058
1059 let text = laid_out(&mut func, &mut names);
1060
1061 assert_eq!(
1062 text,
1063 [
1064 "block0:",
1065 "x64.cmp_rr_32 $rax, $rcx",
1066 "x64.jcc_ge block2, block1",
1067 "block1:",
1068 "block2:",
1069 ]
1070 );
1071 }
1072
1073 /// The same thing for a comparison that reads memory, where the address has to come down with
1074 /// the operands.
1075 ///
1076 /// What an addressing mode holds is where its base register is in the operand vector, and
1077 /// taking the byte off the front moves every operand one place. A mode left pointing at where
1078 /// the base used to be would name the operand in front of it, which here is the value being
1079 /// compared, so the instruction would read an address it was never given. The count of the
1080 /// operands is checked as well as the position, since a mode that points past the end is the
1081 /// other way this goes wrong.
1082 #[test]
1083 fn a_folded_comparison_keeps_its_address_when_the_byte_comes_off_the_front() {
1084 let (mut names, mut func, made) = blank(3);
1085 let byte = func.new_vreg(GPR);
1086 let opcode = Opcode::new(names.intern("x64.cmp_set_l_rm_32"));
1087 func.build(made[0], opcode)
1088 .def(byte, GPR)
1089 .operand(Operand::read(Reg::physical(RAX), GPR))
1090 .mem(Mem { disp: 24, ..Mem::at(Operand::read(Reg::physical(RCX), GPR)) })
1091 .finish();
1092 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
1093 func.build(made[0], opcode).operand(Operand::read(byte, GPR)).finish();
1094 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
1095
1096 let text = laid_out(&mut func, &mut names);
1097
1098 assert_eq!(
1099 text,
1100 [
1101 "block0:",
1102 "x64.cmp_rm_32 $rax, [$rcx + 24]",
1103 "x64.jcc_ge block2, block1",
1104 "block1:",
1105 "block2:",
1106 ]
1107 );
1108 let compare = func.insts(made[0]).next().expect("the comparison");
1109 let mem = func[compare].mem.expect("it reads memory");
1110 assert_eq!(func[mem].base, Some(1), "the base came down with the operands");
1111 assert_eq!(func[func[compare].operands].len(), 2, "the value and the base of the address");
1112 }
1113
1114 /// The same thing again for a comparison of memory against a constant, which is the shape with
1115 /// the fewest operands there is.
1116 ///
1117 /// The byte is the only operand in front of the address here, so taking it off leaves the base
1118 /// at the very front and the instruction reading nothing but the address it was given. A mode
1119 /// that had not come down would be pointing one past the end of a vector with a single operand
1120 /// in it, which is the way this goes wrong on the narrowest shape rather than on the widest.
1121 #[test]
1122 fn a_comparison_of_memory_against_a_constant_keeps_its_address_when_the_byte_comes_off() {
1123 let (mut names, mut func, made) = blank(3);
1124 let byte = func.new_vreg(GPR);
1125 let opcode = Opcode::new(names.intern("x64.cmp_set_l_mi_32"));
1126 func.build(made[0], opcode)
1127 .def(byte, GPR)
1128 .mem(Mem { disp: 24, ..Mem::at(Operand::read(Reg::physical(RCX), GPR)) })
1129 .imm(7)
1130 .finish();
1131 let opcode = Opcode::new(names.intern("x64.br_cond_8"));
1132 func.build(made[0], opcode).operand(Operand::read(byte, GPR)).finish();
1133 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1]), BlockCall::to(made[2])];
1134
1135 let text = laid_out(&mut func, &mut names);
1136
1137 assert_eq!(
1138 text,
1139 [
1140 "block0:",
1141 "x64.cmp_mi_32 [$rcx + 24], 7",
1142 "x64.jcc_ge block2, block1",
1143 "block1:",
1144 "block2:",
1145 ]
1146 );
1147 let compare = func.insts(made[0]).next().expect("the comparison");
1148 let mem = func[compare].mem.expect("it reads memory");
1149 assert_eq!(func[mem].base, Some(0), "the base came down to the front");
1150 assert_eq!(func[func[compare].operands].len(), 1, "the base of the address on its own");
1151 }
1152
1153 /// The same comparison with something else reading its answer, which keeps everything.
1154 ///
1155 /// Folding the byte away when a second instruction wants it would be deleting a value the
1156 /// program computes. This is the whole of what [`fusable`] is asked before allocation, and the
1157 /// second reader here is in another block so that it is a question about the function rather
1158 /// than about the block the branch is in.
1159 #[test]
1160 fn a_comparison_whose_answer_something_else_reads_keeps_its_byte_and_its_test() {
1161 let (mut names, mut func, made) = blank(3);
1162 let byte = compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
1163 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
1164 func.build(made[1], opcode)
1165 .def(Reg::physical(RAX), GPR)
1166 .operand(Operand::read(byte, GPR))
1167 .finish();
1168
1169 let text = laid_out(&mut func, &mut names);
1170
1171 assert!(text.contains(&"x64.test_rr_8 %0".to_owned()), "{text:?}");
1172 assert!(text.contains(&"x64.jcc_e block2, block1".to_owned()), "{text:?}");
1173 }
1174
1175 /// A comparison allocation moved away from its branch, which keeps its test.
1176 ///
1177 /// [`fusable`] says the byte has one reader and says nothing about where the two instructions
1178 /// end up, because allocation runs between the two halves and may put a reload in front of the
1179 /// branch. The flags do not survive one, so the second half looks again, and this is the case
1180 /// where it finds something and refuses. The instruction is put in between the two calls
1181 /// because that is when allocation would have put it there.
1182 #[test]
1183 fn a_comparison_that_is_no_longer_in_front_of_its_branch_keeps_its_test() {
1184 let (mut names, mut func, made) = blank(3);
1185 compare(&mut func, &mut names, made[0], &[made[1], made[2]]);
1186 let fusable = fusable(&func, &BRANCH, &mut names);
1187 assert_eq!(fusable.len(), 1, "the comparison is one the byte's count allows");
1188
1189 let branch = func.terminator(made[0]).expect("a block with two arms has a branch");
1190 let opcode = Opcode::new(names.intern("x64.mov_rr_64"));
1191 let reload = func
1192 .build_loose(opcode)
1193 .def(Reg::physical(RCX), GPR)
1194 .operand(Operand::read(Reg::physical(RAX), GPR))
1195 .finish();
1196 func.insert_before(branch, reload);
1197 blocks(&mut func, &BRANCH, &mut names, &fusable, false);
1198 let text = mir::print_func(&func, &names, ®S);
1199
1200 assert!(text.contains("x64.cmp_set_l_32"), "{text}");
1201 assert!(text.contains("x64.test_rr_8"), "{text}");
1202 assert!(!text.contains("x64.cmp_rr_32"), "{text}");
1203 }
1204
1205 /// Laying the blocks out along the traces the weights say, which is what every level above
1206 /// `-O0` asks for.
1207 fn traced(func: &mut mir::Func, names: &mut Interner) -> Vec<String> {
1208 let fusable = fusable(func, &BRANCH, names);
1209 blocks(func, &BRANCH, names, &fusable, true);
1210 mir::print_func(func, names, ®S)
1211 .lines()
1212 .filter(|line| !line.trim().is_empty() && !line.starts_with("mfunc") && *line != "}")
1213 .map(|line| line.trim().to_string())
1214 .collect()
1215 }
1216
1217 /// Says how often a block runs and how often each of its arms is taken, in parts of ten
1218 /// thousand, the way `crate::weights` would have.
1219 fn runs(func: &mut mir::Func, block: mir::Block, weight: u64, arms: &[u64]) {
1220 func.set_weight(block, mir::Weight::parts(weight));
1221 for (index, &taken) in arms.iter().enumerate() {
1222 func.succs_mut(block)[index].weight = mir::Weight::parts(taken);
1223 }
1224 }
1225
1226 /// The arm almost always taken is the one laid out next, whichever of the two it is.
1227 ///
1228 /// Same function twice, with the two arms weighted the two ways round. At `-O0` the order is
1229 /// the shape of the graph and the first arm always comes next; here it is the weights, so the
1230 /// block that hardly ever runs goes behind the one that nearly always does and the jump is
1231 /// spent on it rather than on the common path.
1232 #[test]
1233 fn the_arm_that_is_nearly_always_taken_is_the_one_laid_out_next() {
1234 let (mut names, mut func, made) = blank(3);
1235 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1236 runs(&mut func, made[0], 10_000, &[200, 9_800]);
1237 runs(&mut func, made[1], 200, &[]);
1238 runs(&mut func, made[2], 9_800, &[]);
1239
1240 traced(&mut func, &mut names);
1241
1242 assert_eq!(order_of(&func), [0, 2, 1]);
1243
1244 let (mut names, mut func, made) = blank(3);
1245 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1246 runs(&mut func, made[0], 10_000, &[9_800, 200]);
1247 runs(&mut func, made[1], 9_800, &[]);
1248 runs(&mut func, made[2], 200, &[]);
1249
1250 traced(&mut func, &mut names);
1251
1252 assert_eq!(order_of(&func), [0, 1, 2]);
1253 }
1254
1255 /// A loop comes out as its header, its body and then its exit, with the back edge backwards.
1256 ///
1257 /// Nothing here rotates anything. The trace walks out of the header into the body because the
1258 /// body is where the header nearly always goes, stops at the latch because the header it
1259 /// wants next is already laid out, and the exit is picked up as the next seed. That is the
1260 /// order a branch predictor's static guess expects and it is what the greedy rule gives.
1261 #[test]
1262 fn a_loop_is_laid_out_with_its_exit_behind_it_and_its_back_edge_running_backwards() {
1263 let (mut names, mut func, made) = blank(4);
1264 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1265 branch(&mut func, &mut names, made[1], &[made[2], made[3]]);
1266 *func.succs_mut(made[2]) = vec![BlockCall::to(made[1])];
1267 runs(&mut func, made[0], 10_000, &[10_000]);
1268 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1269 runs(&mut func, made[2], 90_000, &[90_000]);
1270 runs(&mut func, made[3], 10_000, &[]);
1271
1272 let text = traced(&mut func, &mut names);
1273
1274 assert_eq!(order_of(&func), [0, 1, 2, 3]);
1275 assert_eq!(
1276 text,
1277 [
1278 "block0:",
1279 "block1",
1280 "block1:",
1281 "x64.test_rr_8 $rax",
1282 "x64.jcc_e block3, block2",
1283 "block2:",
1284 "x64.jmp block1",
1285 "block3:",
1286 ]
1287 );
1288 }
1289
1290 /// A block reached only from the cold arm is laid out behind everything the trunk reaches.
1291 ///
1292 /// The shape is `if (unlikely) handle(); rest();`, where the handler and the rest of the
1293 /// function are both reached from the branch. Reverse postorder puts the handler between the
1294 /// branch and the rest of the function; the trace puts the rest of the function next, because
1295 /// that is where the branch nearly always goes, and the handler ends up last.
1296 #[test]
1297 fn a_block_only_the_cold_arm_reaches_goes_behind_the_rest_of_the_function() {
1298 let (mut names, mut func, made) = blank(4);
1299 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1300 *func.succs_mut(made[1]) = vec![BlockCall::to(made[2])];
1301 *func.succs_mut(made[2]) = vec![BlockCall::to(made[3])];
1302 runs(&mut func, made[0], 10_000, &[100, 9_900]);
1303 runs(&mut func, made[1], 100, &[100]);
1304 runs(&mut func, made[2], 10_000, &[10_000]);
1305 runs(&mut func, made[3], 10_000, &[]);
1306
1307 assert_eq!(order(&func), [made[0], made[1], made[2], made[3]]);
1308
1309 traced(&mut func, &mut names);
1310
1311 assert_eq!(order_of(&func), [0, 2, 3, 1]);
1312 }
1313
1314 /// A block nothing reaches is still laid out, since the last round asks for nothing.
1315 #[test]
1316 fn the_last_round_picks_up_a_block_nothing_reaches() {
1317 let (mut names, mut func, made) = blank(3);
1318 *func.succs_mut(made[0]) = vec![BlockCall::to(made[2])];
1319 runs(&mut func, made[0], 10_000, &[10_000]);
1320 runs(&mut func, made[1], 0, &[]);
1321 runs(&mut func, made[2], 10_000, &[]);
1322
1323 traced(&mut func, &mut names);
1324
1325 assert_eq!(order_of(&func), [0, 2, 1]);
1326 }
1327
1328 /// The entry is laid out first however cold it is against the rest of the function.
1329 ///
1330 /// A function is entered at its first byte, so the block that runs first has to be the block
1331 /// that is written first, and the seed order is what makes that true rather than any check
1332 /// afterwards. Here the loop body runs ten times for every call and would otherwise have been
1333 /// the first seed.
1334 #[test]
1335 fn the_entry_is_the_first_seed_even_when_something_else_runs_more_often() {
1336 let (mut names, mut func, made) = blank(3);
1337 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1338 branch(&mut func, &mut names, made[1], &[made[1], made[2]]);
1339 runs(&mut func, made[0], 10_000, &[10_000]);
1340 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1341 runs(&mut func, made[2], 10_000, &[]);
1342
1343 traced(&mut func, &mut names);
1344
1345 assert_eq!(func.blocks().next().map(mir::Block::index), Some(0));
1346 }
1347
1348 /// A branch whose arms are even still falls into one of them rather than jumping to both.
1349 ///
1350 /// Nothing predicts a range check, so both arms come out at half, and half is under every
1351 /// branch threshold above the last round. The trace therefore ends at the branch, and what
1352 /// decides the layout is where the next one starts: at the likeliest arm out of the block the
1353 /// trace stopped in, which is a fall-through, and not at whichever of the two blocks was made
1354 /// first, which would have cost a jump on both paths out of an even branch.
1355 #[test]
1356 fn a_branch_whose_arms_are_even_is_still_laid_out_next_to_one_of_them() {
1357 let (mut names, mut func, made) = blank(3);
1358 // The second arm is the block made first, so a layout that fell back to the seed list
1359 // would lay that one out next and leave the arm written first to be jumped to.
1360 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1361 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1362 runs(&mut func, made[1], 5_000, &[]);
1363 runs(&mut func, made[2], 5_000, &[]);
1364
1365 traced(&mut func, &mut names);
1366
1367 assert_eq!(order_of(&func), [0, 2, 1]);
1368 }
1369
1370 /// A run of blocks the rounds cut in half comes back out in one piece.
1371 ///
1372 /// Two comparisons against a constant, one behind the other, which is what a switch over
1373 /// scattered labels is lowered to. The second comparison is only reached when the first one
1374 /// failed, so it runs half as often as the function is entered and the first round will not
1375 /// touch it: the trace stops at the first comparison and the block that was about to fall
1376 /// through it is left for a later round. What puts it back is [`connect`], and without it the
1377 /// body of the first case would sit between the two comparisons and both would pay a jump.
1378 #[test]
1379 fn a_chain_the_rounds_cut_in_half_is_run_back_together() {
1380 let (mut names, mut func, made) = blank(5);
1381 branch(&mut func, &mut names, made[0], &[made[2], made[1]]);
1382 branch(&mut func, &mut names, made[2], &[made[4], made[3]]);
1383 runs(&mut func, made[0], 10_000, &[5_000, 5_000]);
1384 runs(&mut func, made[1], 5_000, &[]);
1385 runs(&mut func, made[2], 5_000, &[3_000, 2_000]);
1386 runs(&mut func, made[3], 2_000, &[]);
1387 runs(&mut func, made[4], 3_000, &[]);
1388
1389 traced(&mut func, &mut names);
1390
1391 assert_eq!(order_of(&func), [0, 2, 4, 1, 3]);
1392 }
1393
1394 /// The head of a loop is the block its back edge runs to, and a function with no loop has none.
1395 #[test]
1396 fn the_head_of_a_loop_is_where_its_back_edge_lands() {
1397 let (mut names, mut func, made) = blank(4);
1398 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1399 branch(&mut func, &mut names, made[1], &[made[2], made[3]]);
1400 *func.succs_mut(made[2]) = vec![BlockCall::to(made[1])];
1401 runs(&mut func, made[0], 10_000, &[10_000]);
1402 runs(&mut func, made[1], 100_000, &[90_000, 10_000]);
1403 runs(&mut func, made[2], 90_000, &[90_000]);
1404 runs(&mut func, made[3], 10_000, &[]);
1405 traced(&mut func, &mut names);
1406 assert_eq!(heads(&func), [made[1]]);
1407
1408 let (mut names, mut func, made) = blank(4);
1409 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1410 *func.succs_mut(made[1]) = vec![BlockCall::to(made[2])];
1411 *func.succs_mut(made[2]) = vec![BlockCall::to(made[3])];
1412 traced(&mut func, &mut names);
1413 assert_eq!(heads(&func), [], "nothing runs backwards");
1414 }
1415
1416 /// A loop that runs less than a hundredth as often as the hottest block is left unpadded.
1417 #[test]
1418 fn a_loop_that_hardly_runs_is_not_padded() {
1419 let (mut names, mut func, made) = blank(5);
1420 branch(&mut func, &mut names, made[0], &[made[1], made[3]]);
1421 branch(&mut func, &mut names, made[1], &[made[1], made[2]]);
1422 branch(&mut func, &mut names, made[3], &[made[3], made[4]]);
1423 *func.succs_mut(made[2]) = vec![BlockCall::to(made[4])];
1424 runs(&mut func, made[0], 10_000, &[10, 9_990]);
1425 runs(&mut func, made[1], 900, &[890, 10]);
1426 runs(&mut func, made[2], 10, &[10]);
1427 runs(&mut func, made[3], 100_000, &[90_010, 9_990]);
1428 runs(&mut func, made[4], 10_000, &[]);
1429 traced(&mut func, &mut names);
1430 assert_eq!(heads(&func), [made[3]], "the cold loop runs 900 times to the hot one's 100000");
1431 }
1432
1433 /// A jump back to a block that cannot get back to the jump is the end of a cold arm rather
1434 /// than a loop, however the layout ordered the two.
1435 #[test]
1436 fn a_jump_backwards_out_of_a_cold_arm_is_not_a_loop() {
1437 let (mut names, mut func, made) = blank(4);
1438 branch(&mut func, &mut names, made[0], &[made[1], made[2]]);
1439 *func.succs_mut(made[1]) = vec![BlockCall::to(made[3])];
1440 *func.succs_mut(made[2]) = vec![BlockCall::to(made[3])];
1441 runs(&mut func, made[0], 10_000, &[9_990, 10]);
1442 runs(&mut func, made[1], 9_990, &[9_990]);
1443 runs(&mut func, made[2], 10, &[10]);
1444 runs(&mut func, made[3], 10_000, &[]);
1445 traced(&mut func, &mut names);
1446 let at = |block| func.blocks().position(|laid| laid == block);
1447 assert!(at(made[2]) > at(made[3]), "the cold arm is laid out behind where it rejoins");
1448 assert_eq!(heads(&func), []);
1449 }
1450
1451 /// A block that jumps to itself is a loop, and the first block is never padded even when a
1452 /// jump runs back to it.
1453 #[test]
1454 fn a_block_that_goes_round_itself_is_a_head_and_the_first_block_is_not() {
1455 let (mut names, mut func, made) = blank(3);
1456 *func.succs_mut(made[0]) = vec![BlockCall::to(made[1])];
1457 branch(&mut func, &mut names, made[1], &[made[1], made[2]]);
1458 branch(&mut func, &mut names, made[2], &[made[0], made[2]]);
1459 laid_out(&mut func, &mut names);
1460 assert_eq!(heads(&func), [made[1], made[2]]);
1461 }
1462}