Skip to main content

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