Skip to main content

rucc_codegen/
fold.rs

1//! Folding an address computation into the memory operand of whatever reads it.
2//!
3//! Design: `spec/10-backend.md` section 10.9, and `spec/optimizer/37-machine-level-optimization.md`
4//! section 37.4.
5//!
6//! The selector matches one instruction at a time and offers it its operands' operands, which is
7//! two levels of term and is exactly what an address needs to become a `lea`: `a + i * 4` is an
8//! add at the root with a multiply under it. Put that same address under a load and everything
9//! moves down a level, the multiply is at level two, and no plan the selector has reaches it. So
10//! an array read comes out of selection as two instructions, the `lea` that works the address out
11//! and the `mov` that reads through it, and the second one's addressing mode holds nothing but a
12//! base.
13//!
14//! Which is a pair a peephole can see. When an instruction reads the register a `lea` wrote as the
15//! base of its memory operand, the two addresses compose: the reader's displacement is a constant
16//! added to an address the `lea` already worked out, so adding the two displacements together gives
17//! the address the reader wanted in the mode the `lea` was using.
18//!
19//! The question is asked of the readers together rather than one at a time, which is what section
20//! 37.4 says the pass is really for. One address read at several offsets is what a structure
21//! written field by field comes out as, and what a loop the unroller took apart comes out as, and
22//! in neither of those does any one reader own the address. If every reader can take it then
23//! nothing reads the `lea` any more and it goes, and the arithmetic moved into addressing modes
24//! that were doing an addition anyway. If one reader cannot, folding into the rest buys nothing:
25//! the `lea` stays where it is for the one that refused, the address is worked out twice rather
26//! than once, and the registers it reads are now live across every reader as well. So it is all of
27//! them or none of them, and that is a property of the set rather than of a pair.
28//!
29//! # What it will not do
30//!
31//! A set with a reader in it that cannot take the address. Each of the refusals below is one
32//! reader's, and any one of them turns down the whole set it belongs to.
33//!
34//! An address relative to a symbol, with more than one reader. A reader that reads through a
35//! register has room in it for a register and a displacement, and an address made of registers and
36//! a displacement goes into that room whoever takes it. A symbol does not: the reader has to name
37//! the symbol, which is a whole address word rather than a register number, so each reader that
38//! takes one grows by the difference and several readers pay it several times while the `lea` is
39//! saved once. Taking those as well loses 2643 bytes over the corpus at -O2 and gains 386, and the
40//! loss is almost all soft float and bit counting expansions, which read one global thirty or
41//! forty times each. One reader keeps the old answer, since there the address word is written once
42//! either way and what goes is the whole `lea`.
43//!
44//! Two indexes. An address and the reader that takes it each having an index means the composed
45//! address wants two scaled registers and this machine, like every machine, has one. Nothing looks
46//! for a way to put them together because there is not one. One index between the two is a
47//! different answer and is folded, whichever of them it came from, since the composed address then
48//! wants exactly the one place the machine has. That is the shape of an array inside something
49//! whose own address had to be worked out, `s.items[i]` on a local and `a[i][j]` on a row, where
50//! the `lea` is a base and a displacement and the reader is what scales the subscript.
51//!
52//! A symbol, where the reader has an index. An address relative to a symbol has the symbol in the
53//! place a base register would go, so what the composed address would be is a symbol and a scaled
54//! register with nothing to be relative to. The one reader rule below still takes those when the
55//! reader is reading a flat address.
56//!
57//! # The sum of two registers
58//!
59//! `p[i]` on a `char` is an address with an index and no scale, and the selector writes that as
60//! the addition it is rather than as a `lea`, since the rules that make a `lea` are the ones with a
61//! multiply in them. So a byte array read came out as a copy, an add and a load through the result,
62//! which is the pair above with the address written as arithmetic. An add of two registers at the
63//! width of an address is read here as the address a base, an index and a scale of one make, and it
64//! goes into its readers under exactly the rules a `lea` does. The flags the add writes are nothing
65//! to lose, since this runs straight after selection and the selector never reads the flags of an
66//! addition, it compares.
67//!
68//! The stack pointer cannot be an index on this machine, so a sum with it in the second place has
69//! the two swapped, and a sum of two registers neither of which can be an index is left alone.
70//!
71//! A displacement that does not fit. The two are added as `i64` and the answer has to be an `i32`,
72//! which is what the field holds. It is not a case that comes up in a program anybody wrote, and
73//! the check is there because the alternative to checking is wrapping.
74//!
75//! A reader in another block. Folding moves the work from where the `lea` is to where the reader
76//! is, and across a block boundary that can mean moving it into a loop. The same rule and the same
77//! reason as `crate::lower::Lowering::foldable`, which is the selector's version of this question.
78//!
79//! A register that something writes between the address and the last of its readers. Machine IR is
80//! in SSA form until the allocator has run, so a virtual register cannot be, but a physical one
81//! can: the frame pointer and the stack pointer are already physical here, and a call in between
82//! writes every register it is allowed to. Rather than ask which registers are the exceptions, the
83//! walk below drops a candidate the moment anything writes a register its address reads. The last
84//! reader rather than the first is what makes this the set's question too, since a write after the
85//! first reader and before the second is a write the one at a time version would never have seen.
86//!
87//! # The addresses into the frame
88//!
89//! A local's place in the frame and an argument's place in the caller's area is a distance from the
90//! stack pointer, and there is no frame until the allocator has finished, so [`crate::lower`]
91//! leaves those instructions with a zero in the displacement and [`crate::finish`] writes the
92//! number in later against a list of which instruction is which.
93//!
94//! This used to refuse them for that reason, and refusing was expensive: it is the shape of every
95//! access to a local that has to go through its address, and of every argument that arrives in the
96//! caller's area. What it takes to fold one is that the entry moves. The instruction the list names
97//! goes away and the ones that took the
98//! address arrive, so [`Pending`] rewrites the list as the fold is applied, and `finish` adds the
99//! frame's offset to the displacement rather than assigning it, because the reader brought a
100//! displacement of its own and the field it is reading is some way past where the object starts.
101//! tamnd/rucc#784.
102//!
103//! What they do not get is the whole of the set rule above. An address into the frame is off the
104//! stack pointer and a memory operand based on the stack pointer needs an index byte on this
105//! machine whether or not anything is indexed, so a reader that takes one grows by more than a
106//! reader that takes an address in an ordinary register does. Past three of them the bytes the
107//! readers put on are more than the whole `lea` was, which is the same arithmetic as the symbol
108//! above and comes out at a different number. `FRAME_READERS` below has the measurement.
109//!
110//! # Where it runs
111//!
112//! After selection and before the allocator, which is the one window where both instructions
113//! exist and the registers are still virtual. Running it after allocation would work on the
114//! arithmetic and would be reading a register file where the reader's base may have been reused
115//! for something else in between.
116
117use std::collections::HashMap;
118
119use rucc_base::Interner;
120use rucc_mir as mir;
121use rucc_target::{FrameInsts, MachineInsts, Role};
122
123use crate::changes::{Changes, Plan, Reads};
124
125/// The addresses [`crate::finish`] has still to write a displacement into.
126///
127/// Three lists, because the frame holds three kinds of place this pass runs before the layout of:
128/// a local's address is an offset into this function's own objects, a stack argument's is an offset
129/// into the caller's area, and a variable length array's is an offset above wherever the stack
130/// pointer ended up. What they have in common is the shape, a `lea` off the stack pointer with the
131/// displacement left at zero, and what this type is for is that folding one of those away has to
132/// move the entry rather than lose it.
133///
134/// This used to be a set of instructions the pass refused to touch, and refusing was expensive.
135/// Every access to a local through its address was a `lea` and then a memory instruction reading
136/// through the register it wrote, which is one instruction more than it needs, on the shape any
137/// function whose locals have their address taken is full of. tamnd/rucc#784.
138#[derive(Debug)]
139pub struct Pending<'a> {
140    /// Which instruction carries the address of which of this function's stack objects.
141    pub addresses: &'a mut Vec<(mir::Inst, usize)>,
142    /// Which instruction reads which of the arguments the caller passed on the stack.
143    pub arguments: &'a mut Vec<(mir::Inst, u32)>,
144    /// Which instructions carry the address of a local whose size the program worked out.
145    ///
146    /// There is no number beside one of these, because where a variable length array starts is not
147    /// a place the frame layout hands back: the bytes are already off the stack pointer by the time
148    /// the address is taken, so what gets written in is how much of the bottom of the frame the
149    /// arguments of a call keep, which is the same for all of them.
150    pub dynamic: &'a mut Vec<mir::Inst>,
151}
152
153impl Pending<'_> {
154    /// Moves an entry from an address that has gone to the instructions that took it.
155    ///
156    /// One entry becomes as many as there were readers, because an address every reader has room
157    /// for is handed to all of them, and each of those now carries a displacement of its own that
158    /// the frame layout has still to be added to.
159    ///
160    /// No readers at all takes the entry off the list, which is what a caller that joined a run
161    /// into one instruction wants when the instruction it kept is already waiting on the same
162    /// entry. Handing it the same offset twice would put the local at twice its distance.
163    ///
164    /// An address on any of the lists reads the stack pointer and nothing else, so it never reads a
165    /// register another one of them wrote, which is what makes it impossible for a reader to end up
166    /// on a list twice and be given two offsets.
167    pub(crate) fn moved(&mut self, from: mir::Inst, into: &[mir::Inst]) {
168        move_entries(self.addresses, from, into);
169        move_entries(self.arguments, from, into);
170        if let Some(at) = self.dynamic.iter().position(|&inst| inst == from) {
171            self.dynamic.splice(at..=at, into.iter().copied());
172        }
173    }
174
175    /// Whether these two instructions are waiting on the same thing.
176    ///
177    /// Asked by a pass that has found two addressing modes that read alike and is about to treat
178    /// them as the same place. Reading alike is not enough on its own once the frame is involved:
179    /// the address of a local is a displacement this list has still to add an offset to, and two
180    /// locals whose displacements are both zero so far are the same three registers and the same
181    /// number and are two different places. What tells them apart is which entry each instruction
182    /// is waiting on, which is this.
183    pub(crate) fn alike(&self, one: mir::Inst, other: mir::Inst) -> bool {
184        let address = |inst| self.addresses.iter().find(|&&(at, _)| at == inst).map(|&(_, of)| of);
185        let argument = |inst| self.arguments.iter().find(|&&(at, _)| at == inst).map(|&(_, of)| of);
186        let dynamic = |inst| self.dynamic.contains(&inst);
187        address(one) == address(other)
188            && argument(one) == argument(other)
189            && dynamic(one) == dynamic(other)
190    }
191
192    /// Whether this instruction is on one of the lists, which is how many readers it may go to.
193    fn holds(&self, inst: mir::Inst) -> bool {
194        let named = self.addresses.iter().map(|&(at, _)| at);
195        let listed = named.chain(self.arguments.iter().map(|&(at, _)| at));
196        listed.chain(self.dynamic.iter().copied()).any(|at| at == inst)
197    }
198}
199
200/// How many readers an address into the frame may be handed to.
201///
202/// There is a limit at all for the same reason a symbol has one, in the list above. An address into
203/// the frame is off the stack pointer, and a memory operand whose base is the stack pointer needs
204/// an index byte on this machine whether or not anything is indexed, so every reader that takes one
205/// grows by that byte and by the displacement while the `lea` is saved once. Reading through a
206/// register the `lea` wrote is three or four bytes and reading the same place off the stack pointer
207/// is five or eight, against the five or eight the `lea` itself costs, so the readers are ahead of
208/// it while there are few of them and behind it once there are enough.
209///
210/// Three is where they turn, measured. Over the 1838 corpus programs that come out of both
211/// compilers at `-O2`, one reader is 757 bytes better than folding none of them, two is 806, three
212/// is 868, four is 848 and five is 520. Handing them to every reader with room, which is what every
213/// other address gets, is 528 bytes worse than folding none: 97 programs larger by 1117 bytes
214/// against 100 smaller by 589. Up to three, only two programs anywhere in the corpus are larger at
215/// all, by two bytes each.
216///
217/// 690 of the 868 are the ten `long-double` programs, which is the shape this is about at its
218/// plainest. A `long double` argument arrives in the caller's area and the `fld` that reads it is
219/// its only reader, so the address goes and the read costs nothing more than it did.
220const FRAME_READERS: usize = 3;
221
222/// The half of [`Pending::moved`] that does not care what the entry says.
223fn move_entries<T: Copy>(list: &mut Vec<(mir::Inst, T)>, from: mir::Inst, into: &[mir::Inst]) {
224    let Some(at) = list.iter().position(|&(inst, _)| inst == from) else { return };
225    let (_, what) = list[at];
226    list.splice(at..=at, into.iter().map(|&inst| (inst, what)));
227}
228
229/// Folds every address computation that one memory operand reads, and gives back how many.
230///
231/// `pending` is the addresses [`crate::finish`] has still to write a displacement into, and folding
232/// one moves its entry to the instruction that took it. The displacement composed in by the fold
233/// stays where it is and the frame's offset is added to it later, which is why that write is an
234/// addition rather than an assignment.
235///
236/// Run after lowering and before allocation, and run once. Running it twice can find more than
237/// running it once in principle: folding a `lea` into a second `lea` leaves that second one foldable
238/// in turn, and the walk below takes those in the one pass since it goes forwards, but it does not
239/// take the other order, where the second `lea` has a reader of its own and goes before the first
240/// one's set is complete, and that is a set a second run would find whole.
241///
242/// Measured, it finds nothing. Running this to a fixed point is the same instruction count over the
243/// corpus at every level and one instruction more over the SQLite amalgamation, which is the
244/// allocator taking a different tie break somewhere rather than a fold. So the pipeline runs it once
245/// and this note is here so the next person to notice the same thing does not have to build it to
246/// find out.
247pub fn addresses(
248    func: &mut mir::Func,
249    insts: &FrameInsts,
250    machine: &MachineInsts,
251    names: &mut Interner,
252    pending: &mut Pending<'_>,
253) -> usize {
254    let lea = mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, insts.lea)));
255    let sum = mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, insts.sum)));
256    let mut reads = Reads::of(func);
257    let mut folded = 0;
258    for block in func.blocks().collect::<Vec<_>>() {
259        // One `lea` per register it wrote, along with the folds its readers so far have agreed to.
260        // A register leaves the table the moment the set can no longer be all of them: anything
261        // writes what the address reads, or a reader turns up that cannot take it.
262        let mut open: HashMap<mir::Reg, Open> = HashMap::new();
263        for inst in func.insts(block).collect::<Vec<_>>() {
264            if let Some(ready) = offer(func, &mut open, inst) {
265                // The set is the whole of what this fold is: every reader takes the address and
266                // the address computation goes, and a set that is missing either half is one that
267                // works the address out twice. So it is proposed together and the target is asked
268                // about all of it at once.
269                let mut set = Changes::new();
270                for folding in &ready.folds {
271                    let plan = Plan {
272                        operands: folding.operands.clone(),
273                        amode: Some(folding.amode),
274                        ..Plan::of(func, folding.into)
275                    };
276                    set.rewrite(folding.into, plan);
277                }
278                set.remove(ready.from);
279                if set.commit(func, &mut reads, names, machine).is_ok() {
280                    folded += ready.folds.len();
281                    let took: Vec<mir::Inst> = ready.folds.iter().map(|fold| fold.into).collect();
282                    pending.moved(ready.from, &took);
283                    // Anything still open that was going to fold into the instruction just removed
284                    // is holding a plan for an instruction that is not there any more. That is a
285                    // chain whose middle went first, and the outer address waits for the next run
286                    // of the pass rather than being written into a gap.
287                    //
288                    // An address that has just taken another one into itself is the same problem
289                    // read from the other end. It is still there, but it is not the address it was:
290                    // the registers it names have changed, and so have the two things that decided
291                    // what its own set was allowed to be, which are whether it is relative to a
292                    // symbol and whether the frame still owes it an offset. Every plan its readers
293                    // have agreed to so far was worked out against the address it used to be, and a
294                    // plan naming a register whose `lea` has just gone is exactly the gap this is
295                    // here to keep shut. So the whole entry goes and the chain waits.
296                    open.retain(|_, held| {
297                        !took.contains(&held.from)
298                            && held.folds.iter().all(|fold| fold.into != ready.from)
299                    });
300                }
301            }
302            for written in written(func, inst) {
303                open.retain(|reg, held| *reg != written && !touches(func, held, written));
304            }
305            if func[inst].opcode == lea {
306                let room = if pending.holds(inst) { FRAME_READERS } else { usize::MAX };
307                let Some(address) = func[inst].mem.map(|mem| func[mem]) else { continue };
308                match folding_def(func, &reads, inst) {
309                    Some((reg, wanted))
310                        if wanted <= room && (wanted == 1 || fits_every_reader(address)) =>
311                    {
312                        open.insert(reg, Open { from: inst, address, wanted, folds: Vec::new() });
313                    }
314                    _ => {}
315                }
316            } else if func[inst].opcode == sum {
317                let Some(address) = summed(func, inst) else { continue };
318                if let Some((reg, wanted)) = folding_def(func, &reads, inst) {
319                    open.insert(reg, Open { from: inst, address, wanted, folds: Vec::new() });
320                }
321            }
322        }
323    }
324    folded
325}
326
327/// An address computation whose readers are still being counted.
328struct Open {
329    /// The address instruction, which goes once every one of its readers has taken it.
330    from: mir::Inst,
331    /// The address it works out, with its registers numbered as that instruction's operands.
332    ///
333    /// A `lea`'s own memory operand, or for a sum the base and the index it adds.
334    address: mir::Amode,
335    /// How many reads of the register it wrote there are in the whole function.
336    wanted: usize,
337    /// The folds agreed to so far, which are applied together or not at all.
338    folds: Vec<Folding>,
339}
340
341/// Offers an instruction the addresses that are open, and gives back the set that is now complete.
342///
343/// Every open register this instruction reads either takes the address into its own memory operand
344/// or ends the chance for the whole set. Reading it any other way is what makes it a reader nothing
345/// can fold into, and one of those is enough, so the register is dropped rather than the read being
346/// passed over. Reading it twice in the one instruction counts as that too, since only one of the
347/// two reads is the memory operand and the other would be left naming a register nothing writes.
348fn offer(func: &mir::Func, open: &mut HashMap<mir::Reg, Open>, inst: mir::Inst) -> Option<Open> {
349    let folding = candidate(func, open, inst);
350    let takes = |reg: mir::Reg| folding.as_ref().is_some_and(|fold| fold.base == reg);
351    let refused: Vec<mir::Reg> = open
352        .keys()
353        .copied()
354        .filter(|&reg| {
355            let times = times_read(func, inst, reg);
356            times > 0 && !(times == 1 && takes(reg))
357        })
358        .collect();
359    for reg in refused {
360        open.remove(&reg);
361    }
362    let folding = folding?;
363    let base = folding.base;
364    let held = open.get_mut(&base)?;
365    held.folds.push(folding);
366    if held.folds.len() < held.wanted {
367        return None;
368    }
369    open.remove(&base)
370}
371
372/// The address a sum of two registers is, as a base and an index at a scale of one.
373///
374/// The operands are the register written and then the two added, so the address names the second
375/// and the third. `None` when neither of the two can be an index, which on this machine is the
376/// stack pointer, the only register [`candidate`] could be handed that the encoding has no room
377/// for as one.
378fn summed(func: &mir::Func, inst: mir::Inst) -> Option<mir::Amode> {
379    let operands = &func[func[inst].operands];
380    let [_, left, right] = operands else { return None };
381    let (base, index) = if right.reg.is_virtual() {
382        (1, 2)
383    } else if left.reg.is_virtual() {
384        (2, 1)
385    } else {
386        return None;
387    };
388    Some(mir::Amode { base: Some(base), index: Some(index), ..mir::Amode::NOTHING })
389}
390
391/// Whether an address is one every reader can carry in the room it already has, which is what
392/// makes handing it to more than one of them free.
393///
394/// A reader that reads an address through a register has room in it for a register and for a
395/// displacement, and an address made of registers and a displacement fits in exactly that room
396/// however many readers take it. An address relative to a symbol does not. The reader was naming a
397/// register and now has to name the symbol, which is a whole address word rather than a register
398/// number, so each reader that takes it grows by the difference and several readers pay it several
399/// times over while the `lea` is only saved once.
400///
401/// The measurement is what settled the size of that: folding symbol relative addresses into every
402/// reader as well loses 2643 bytes over the corpus at -O2 against 386 gained, and the 2643 is
403/// almost all soft float and bit counting expansions, which read one global thirty or forty times
404/// each and are the longest runs of straight line code in the corpus.
405///
406/// One reader is a different question and keeps the old answer, since there the address word is
407/// written once either way and what goes is the whole `lea`.
408fn fits_every_reader(address: mir::Amode) -> bool {
409    address.symbol.is_none()
410}
411
412/// How many of an instruction's operands read that register.
413fn times_read(func: &mir::Func, inst: mir::Inst, reg: mir::Reg) -> usize {
414    func[func[inst].operands]
415        .iter()
416        .filter(|operand| operand.role == Role::Use && operand.reg == reg)
417        .count()
418}
419
420/// The one virtual register an instruction writes, and how many reads of it there are, when it
421/// writes exactly one and something reads it.
422///
423/// A `lea` is only worth folding when the instructions folding it are the whole of what reads the
424/// register, since folding does not delete the `lea` for anybody else and doing the address twice
425/// is not a saving. The count is what says when the set is complete, and it is taken over the whole
426/// function rather than over the block, so a read anywhere else is a set that never completes and
427/// an address that stays where it is.
428///
429/// A register nothing reads is left alone rather than folded into nothing, since an address whose
430/// answer is never wanted is dead code and belongs to the pass that removes dead code.
431fn folding_def(func: &mir::Func, reads: &Reads, inst: mir::Inst) -> Option<(mir::Reg, usize)> {
432    let operands = &func[func[inst].operands];
433    let mut defs = operands.iter().filter(|operand| operand.role != Role::Use);
434    let def = defs.next()?;
435    if defs.next().is_some() || !def.reg.is_virtual() {
436        return None;
437    }
438    let wanted = reads.count(def.reg);
439    (wanted > 0).then_some((def.reg, wanted))
440}
441
442/// The registers an instruction writes.
443fn written(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
444    func[func[inst].operands]
445        .iter()
446        .filter(|operand| operand.role != Role::Use)
447        .map(|operand| operand.reg)
448        .collect()
449}
450
451/// Whether an address computation reads that register, which is what makes writing it the end of
452/// the chance to fold it.
453fn touches(func: &mir::Func, held: &Open, reg: mir::Reg) -> bool {
454    let amode = held.address;
455    let operands = &func[func[held.from].operands];
456    [amode.base, amode.index]
457        .into_iter()
458        .flatten()
459        .filter_map(|at| operands.get(usize::from(at)))
460        .any(|operand| operand.reg == reg)
461}
462
463/// The register an instruction's memory operand reads as its base, when the rest of that operand
464/// leaves the composed address somewhere to go.
465///
466/// A symbol of the reader's own means the two addresses do not compose, and this is where that is
467/// turned down, because the reader is then the half of the pair with no room left in it. An index
468/// of the reader's own is not turned down here, since whether there is room for it depends on the
469/// address as well, which is [`candidate`]'s question and not this one's.
470fn base_reg(func: &mir::Func, inst: mir::Inst) -> Option<mir::Reg> {
471    let amode = func[func[inst].mem?];
472    if amode.symbol.is_some() || amode.reach != mir::Reach::Itself {
473        return None;
474    }
475    Some(func[func[inst].operands].get(usize::from(amode.base?))?.reg)
476}
477
478/// A fold that has been checked and not yet done.
479///
480/// Everything the rewrite needs is worked out here rather than after the decision, so that the
481/// decision is the last thing that can go either way and the rewrite itself is three assignments
482/// that cannot fail.
483struct Folding {
484    /// The reader this rewrites, which is not always the instruction being looked at, since the
485    /// set is applied when its last reader arrives rather than as each one agrees.
486    into: mir::Inst,
487    /// The register the address instruction wrote, which is what ties this to its set.
488    base: mir::Reg,
489    /// What the reader's operands become.
490    operands: Vec<mir::Operand>,
491    /// What the reader's addressing mode becomes.
492    amode: mir::Amode,
493}
494
495/// The `lea` whose address this instruction should read directly, and what reading it directly
496/// makes of the instruction.
497///
498/// The operand vector is rebuilt rather than edited because the registers a memory operand names
499/// come last in it, base and then index, which is the invariant [`mir::InstBuilder::mem`] keeps and
500/// the printer and the allocator both read. Dropping the ones the reader's own address named and
501/// putting the composed address's on the end keeps it, and the indices in the new addressing mode
502/// are worked out from the length rather than carried over.
503fn candidate(func: &mir::Func, open: &HashMap<mir::Reg, Open>, inst: mir::Inst) -> Option<Folding> {
504    let base = base_reg(func, inst)?;
505    let held = open.get(&base)?;
506    let (from, address) = (held.from, held.address);
507    let reading = func[func[inst].mem?];
508    let taken = &func[func[from].operands];
509    let reader = &func[func[inst].operands];
510    // The machine scales one register and the two addresses between them can want two, so this is
511    // where the second one is turned down. Whichever side the index came from decides what it is
512    // multiplied by, so the operand and the scale are carried together.
513    let scaled = match (address.index, reading.index) {
514        (Some(_), Some(_)) => return None,
515        (None, Some(_)) if address.symbol.is_some() => return None,
516        (Some(at), None) => Some((*taken.get(usize::from(at))?, address.scale)),
517        (None, Some(at)) => Some((*reader.get(usize::from(at))?, reading.scale)),
518        (None, None) => None,
519    };
520    // The composed address is the `lea`'s with the reader's displacement added and whichever index
521    // there is, and the only thing that can go wrong is the width of the field the displacement
522    // goes in. [`offer`] is what checks that nothing else in the reader names the base.
523    let disp = i64::from(address.disp) + i64::from(reading.disp);
524    let mut amode = mir::Amode {
525        disp: i32::try_from(disp).ok()?,
526        base: None,
527        index: None,
528        scale: scaled.map_or(1, |(_, scale)| scale),
529        ..address
530    };
531
532    let named = 1 + usize::from(reading.index.is_some());
533    let keeping = reader.len().checked_sub(named)?;
534    // The invariant read out loud, because dropping the wrong operands here would build an address
535    // out of whatever the reader was carrying for its own reasons.
536    if usize::from(reading.base?) != keeping {
537        return None;
538    }
539    let mut operands = reader.get(..keeping)?.to_vec();
540    if let Some(at) = address.base {
541        operands.push(*taken.get(usize::from(at))?);
542        amode.base = Some(u8::try_from(operands.len() - 1).ok()?);
543    }
544    if let Some((operand, _)) = scaled {
545        operands.push(operand);
546        amode.index = Some(u8::try_from(operands.len() - 1).ok()?);
547    }
548    Some(Folding { into: inst, base, operands, amode })
549}
550
551#[cfg(test)]
552mod tests {
553    use rucc_target::x86_64::{FRAME, GPR, MACHINE, RDI, RSP};
554
555    use super::*;
556
557    /// A function with one block, and the names it was built with.
558    fn empty() -> (Interner, mir::Func, mir::Block) {
559        let mut names = Interner::new();
560        let mut func = mir::Func::new(names.intern("f"));
561        let block = func.create_block();
562        (names, func, block)
563    }
564
565    /// The pass, run over a function with nothing owed a frame offset, which is most of these.
566    ///
567    /// The lists are still there because the pass rewrites them, and a test that is about what it
568    /// wrote in them builds its own rather than calling this.
569    fn folds(func: &mut mir::Func, names: &mut Interner) -> usize {
570        let (mut locals, mut arguments, mut growable) = (Vec::new(), Vec::new(), Vec::new());
571        addresses(
572            func,
573            &FRAME,
574            &MACHINE,
575            names,
576            &mut Pending {
577                addresses: &mut locals,
578                arguments: &mut arguments,
579                dynamic: &mut growable,
580            },
581        )
582    }
583
584    /// The opcode of that name on this target.
585    fn op(names: &mut Interner, name: &str) -> mir::Opcode {
586        mir::Opcode::new(names.intern(&format!("{}{name}", FRAME.prefix)))
587    }
588
589    /// What every instruction in a block came to, as opcodes and addressing modes.
590    fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<(String, mir::Amode)> {
591        func.insts(block)
592            .map(|inst| {
593                let amode = func[inst].mem.map_or(mir::Amode::NOTHING, |mem| func[mem]);
594                (names.resolve(func[inst].opcode.name()).to_owned(), amode)
595            })
596            .collect()
597    }
598
599    /// The registers a memory operand names, in the order the addressing mode names them.
600    fn address_regs(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
601        let amode = func[func[inst].mem.expect("a memory operand")];
602        let operands = &func[func[inst].operands];
603        [amode.base, amode.index]
604            .into_iter()
605            .flatten()
606            .map(|at| operands[usize::from(at)].reg)
607            .collect()
608    }
609
610    /// An array read as selection leaves it: a `lea` that scales the index and adds the base, and
611    /// a `mov` that reads through the register it wrote.
612    #[test]
613    fn an_address_a_load_reads_once_becomes_the_load_s_own_addressing_mode() {
614        let (mut names, mut func, block) = empty();
615        let array = func.new_vreg(GPR);
616        let index = func.new_vreg(GPR);
617        let address = func.new_vreg(GPR);
618        let value = func.new_vreg(GPR);
619        let lea = op(&mut names, FRAME.lea);
620        let load = op(&mut names, "mov_rm_32");
621        func.build(block, lea)
622            .def(address, GPR)
623            .mem(
624                mir::Mem::at(mir::Operand::read(array, GPR))
625                    .indexed(mir::Operand::read(index, GPR), 4),
626            )
627            .finish();
628        func.build(block, load)
629            .def(value, GPR)
630            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
631            .finish();
632
633        assert_eq!(folds(&mut func, &mut names), 1);
634
635        let left = shape(&func, &names, block);
636        assert_eq!(left.len(), 1, "the address is worked out twice: {left:?}");
637        assert_eq!(left[0].0, format!("{}mov_rm_32", FRAME.prefix));
638        assert_eq!(left[0].1.scale, 4);
639        assert_eq!(left[0].1.disp, 0);
640        let inst = func.insts(block).next().expect("the load is still there");
641        assert_eq!(address_regs(&func, inst), vec![array, index], "the load reads the wrong pair");
642    }
643
644    /// The two displacements are added, which is the whole of what composing them takes when one
645    /// of the two addresses has room for an index and the other has none.
646    #[test]
647    fn the_displacements_of_the_two_addresses_are_added() {
648        let (mut names, mut func, block) = empty();
649        let array = func.new_vreg(GPR);
650        let address = func.new_vreg(GPR);
651        let value = func.new_vreg(GPR);
652        let lea = op(&mut names, FRAME.lea);
653        let load = op(&mut names, "mov_rm_32");
654        func.build(block, lea)
655            .def(address, GPR)
656            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
657            .finish();
658        func.build(block, load)
659            .def(value, GPR)
660            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(8))
661            .finish();
662
663        assert_eq!(folds(&mut func, &mut names), 1);
664
665        let left = shape(&func, &names, block);
666        assert_eq!(left.len(), 1);
667        assert_eq!(left[0].1.disp, 24, "the field is at the sum of the two offsets or nowhere");
668    }
669
670    /// A store keeps the value it writes, which is the operand the address does not name, and the
671    /// rebuilt operand vector has to hold on to it.
672    #[test]
673    fn a_store_keeps_the_value_it_is_storing() {
674        let (mut names, mut func, block) = empty();
675        let array = func.new_vreg(GPR);
676        let index = func.new_vreg(GPR);
677        let address = func.new_vreg(GPR);
678        let value = func.new_vreg(GPR);
679        let lea = op(&mut names, FRAME.lea);
680        let store = op(&mut names, "mov_mr_32");
681        func.build(block, lea)
682            .def(address, GPR)
683            .mem(
684                mir::Mem::at(mir::Operand::read(array, GPR))
685                    .indexed(mir::Operand::read(index, GPR), 8),
686            )
687            .finish();
688        func.build(block, store)
689            .uses(value, GPR)
690            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
691            .finish();
692
693        assert_eq!(folds(&mut func, &mut names), 1);
694
695        let inst = func.insts(block).next().expect("the store is still there");
696        let regs: Vec<mir::Reg> = func[func[inst].operands].iter().map(|op| op.reg).collect();
697        assert_eq!(regs, vec![value, array, index], "the value the store writes went missing");
698        assert_eq!(func[func[inst].mem.expect("a memory operand")].scale, 8);
699    }
700
701    /// One address at three offsets, which is what a structure written field by field comes out
702    /// as. Every reader can carry the whole of it in its own mode, so all three take it and the
703    /// `lea` has nothing left reading it. This is the case section 37.4 says the pass is for.
704    #[test]
705    fn an_address_every_reader_can_take_is_folded_into_all_of_them() {
706        let (mut names, mut func, block) = empty();
707        let array = func.new_vreg(GPR);
708        let address = func.new_vreg(GPR);
709        let value = func.new_vreg(GPR);
710        let lea = op(&mut names, FRAME.lea);
711        let store = op(&mut names, "mov_mr_32");
712        func.build(block, lea)
713            .def(address, GPR)
714            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
715            .finish();
716        for offset in [0, 12, 28] {
717            func.build(block, store)
718                .uses(value, GPR)
719                .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
720                .finish();
721        }
722
723        assert_eq!(folds(&mut func, &mut names), 3);
724
725        let left = shape(&func, &names, block);
726        assert_eq!(left.len(), 3, "the address is still worked out on its own: {left:?}");
727        let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
728        assert_eq!(disps, vec![16, 28, 44], "each store is at its own offset from the address");
729        for inst in func.insts(block).collect::<Vec<_>>() {
730            assert_eq!(address_regs(&func, inst), vec![array]);
731        }
732    }
733
734    /// Three readers of an indexed address and the middle one has an index of its own, which is the
735    /// pairing there is no room for. Folding into the other two would leave the `lea` where it is
736    /// for the third, so the address would be worked out twice rather than once and the two folds
737    /// would have bought nothing but a longer live range for what it reads. All or nothing over the
738    /// set means none of them.
739    #[test]
740    fn an_address_one_reader_cannot_take_is_folded_into_none_of_them() {
741        let (mut names, mut func, block) = empty();
742        let array = func.new_vreg(GPR);
743        let index = func.new_vreg(GPR);
744        let address = func.new_vreg(GPR);
745        let lea = op(&mut names, FRAME.lea);
746        let load = op(&mut names, "mov_rm_32");
747        func.build(block, lea)
748            .def(address, GPR)
749            .mem(
750                mir::Mem::at(mir::Operand::read(array, GPR))
751                    .indexed(mir::Operand::read(index, GPR), 8)
752                    .plus(16),
753            )
754            .finish();
755        for at in 0..3 {
756            let value = func.new_vreg(GPR);
757            let mem = mir::Mem::at(mir::Operand::read(address, GPR));
758            let mem = if at == 1 { mem.indexed(mir::Operand::read(index, GPR), 4) } else { mem };
759            func.build(block, load).def(value, GPR).mem(mem).finish();
760        }
761
762        assert_eq!(folds(&mut func, &mut names), 0);
763        assert_eq!(shape(&func, &names, block).len(), 4);
764    }
765
766    /// An address whose own set completes after one of its readers has already collected a plan of
767    /// its own, which is `int *q = &tmp[i]; *q = 0; ... tmp[j] = 39; ... return *q;` and is the
768    /// shape that miscompiled.
769    ///
770    /// The outer `lea` writes where the array starts, two inner `lea`s scale a subscript onto it,
771    /// and each inner one has readers of its own. The first reader of the first inner `lea` agrees
772    /// to a plan naming the outer register, since that is what the address it is taking reads at
773    /// the time. Then the second inner `lea` arrives, the outer set is complete, both inner ones
774    /// take the outer address into themselves and the outer `lea` goes. The agreed plan now names a
775    /// register nothing writes, and committing it would put that register in a load.
776    ///
777    /// So the entry goes when the address under it is rewritten. What is left works every address
778    /// out from something that is written, which is the whole of what this checks.
779    #[test]
780    fn a_plan_against_an_address_that_has_since_moved_is_not_committed() {
781        let (mut names, mut func, block) = empty();
782        let array = func.new_vreg(GPR);
783        let outer = func.new_vreg(GPR);
784        let lea = op(&mut names, FRAME.lea);
785        let load = op(&mut names, "mov_rm_32");
786        func.build(block, lea)
787            .def(outer, GPR)
788            .mem(mir::Mem::at(mir::Operand::read(array, GPR)))
789            .finish();
790
791        let mut inner = Vec::new();
792        let mut given = vec![array];
793        for _ in 0..2 {
794            let index = func.new_vreg(GPR);
795            let address = func.new_vreg(GPR);
796            given.push(index);
797            func.build(block, lea)
798                .def(address, GPR)
799                .mem(
800                    mir::Mem::at(mir::Operand::read(outer, GPR))
801                        .indexed(mir::Operand::read(index, GPR), 4),
802                )
803                .finish();
804            let value = func.new_vreg(GPR);
805            func.build(block, load)
806                .def(value, GPR)
807                .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
808                .finish();
809            inner.push(address);
810        }
811        // The second reader of the first inner address, which is what makes its set complete after
812        // that address has already been rewritten.
813        let value = func.new_vreg(GPR);
814        func.build(block, load)
815            .def(value, GPR)
816            .mem(mir::Mem::at(mir::Operand::read(inner[0], GPR)).plus(4))
817            .finish();
818
819        assert_eq!(folds(&mut func, &mut names), 3);
820
821        // Every register an address is left naming either comes into the block or is written in
822        // it, and the one that is gone is the outer `lea`'s, which is the register the stale plan
823        // named.
824        let written: Vec<mir::Reg> =
825            func.insts(block).flat_map(|inst| written(&func, inst)).collect();
826        for inst in func.insts(block).collect::<Vec<_>>() {
827            for reg in address_regs(&func, inst) {
828                assert!(
829                    given.contains(&reg) || written.contains(&reg),
830                    "an address reads {reg:?} and nothing writes it"
831                );
832            }
833        }
834        assert!(!written.contains(&outer), "the outer address is still there");
835    }
836
837    /// An indexed address with two readers, which both of them can take. The index goes into the
838    /// room the reader already has for one, the same as the base does, so this is the ordinary
839    /// case rather than a special one.
840    #[test]
841    fn an_indexed_address_every_reader_can_take_is_folded_into_all_of_them() {
842        let (mut names, mut func, block) = empty();
843        let array = func.new_vreg(GPR);
844        let index = func.new_vreg(GPR);
845        let address = func.new_vreg(GPR);
846        let lea = op(&mut names, FRAME.lea);
847        let load = op(&mut names, "mov_rm_32");
848        func.build(block, lea)
849            .def(address, GPR)
850            .mem(
851                mir::Mem::at(mir::Operand::read(array, GPR))
852                    .indexed(mir::Operand::read(index, GPR), 4),
853            )
854            .finish();
855        for offset in [0, 8] {
856            let value = func.new_vreg(GPR);
857            func.build(block, load)
858                .def(value, GPR)
859                .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
860                .finish();
861        }
862
863        assert_eq!(folds(&mut func, &mut names), 2);
864
865        let left = shape(&func, &names, block);
866        assert_eq!(left.len(), 2, "the address is gone and both loads carry it: {left:?}");
867        let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
868        assert_eq!(disps, vec![0, 8], "each load is at its own offset from the address");
869        for inst in func.insts(block).collect::<Vec<_>>() {
870            assert_eq!(address_regs(&func, inst), vec![array, index]);
871        }
872    }
873
874    /// A symbol relative address with two readers, which both of them could take and which is left
875    /// alone anyway. Each reader would have to name the symbol where it names a register now, and
876    /// a symbol is a whole address word, so two readers write that word twice to save one `lea`
877    /// that wrote it once. The corpus says that is a loss well before the reader count gets large.
878    #[test]
879    fn a_symbol_address_with_more_than_one_reader_is_left_where_it_is() {
880        let (mut names, mut func, block) = empty();
881        let address = func.new_vreg(GPR);
882        let lea = op(&mut names, FRAME.lea);
883        let load = op(&mut names, "mov_rm_32");
884        let cell = names.intern("cell");
885        func.build(block, lea).def(address, GPR).mem(mir::Mem::of(cell)).finish();
886        for offset in [0, 8] {
887            let value = func.new_vreg(GPR);
888            func.build(block, load)
889                .def(value, GPR)
890                .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
891                .finish();
892        }
893
894        assert_eq!(folds(&mut func, &mut names), 0);
895        assert_eq!(shape(&func, &names, block).len(), 3);
896    }
897
898    /// Two readers and one of them is in another block, which is the same refusal as the single
899    /// reader case and is caught by a different half of the pass. The count of reads is taken over
900    /// the whole function, so a set that leaves one out never becomes complete.
901    #[test]
902    fn an_address_read_outside_the_block_as_well_is_left_where_it_is() {
903        let (mut names, mut func, block) = empty();
904        let next = func.create_block();
905        let array = func.new_vreg(GPR);
906        let address = func.new_vreg(GPR);
907        let lea = op(&mut names, FRAME.lea);
908        let load = op(&mut names, "mov_rm_32");
909        func.build(block, lea)
910            .def(address, GPR)
911            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
912            .finish();
913        for at in [block, next] {
914            let value = func.new_vreg(GPR);
915            func.build(at, load)
916                .def(value, GPR)
917                .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
918                .finish();
919        }
920        *func.succs_mut(block) = vec![mir::BlockCall::to(next)];
921
922        assert_eq!(folds(&mut func, &mut names), 0);
923        assert_eq!(shape(&func, &names, block).len(), 2);
924    }
925
926    /// A register the address reads, written between the first reader and the second. This is the
927    /// one refusal the set adds that the pair version had no way to need, since a write after the
928    /// only reader is a write nobody was ever going to fold across.
929    #[test]
930    fn a_write_between_one_reader_and_the_next_ends_the_chance_for_the_set() {
931        let (mut names, mut func, block) = empty();
932        let array = mir::Reg::physical(RDI);
933        let address = func.new_vreg(GPR);
934        let first = func.new_vreg(GPR);
935        let second = func.new_vreg(GPR);
936        let lea = op(&mut names, FRAME.lea);
937        let load = op(&mut names, "mov_rm_32");
938        let put = op(&mut names, "mov_ri_64");
939        func.build(block, lea)
940            .def(address, GPR)
941            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
942            .finish();
943        func.build(block, load)
944            .def(first, GPR)
945            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
946            .finish();
947        func.build(block, put).def(array, GPR).imm(7).finish();
948        func.build(block, load)
949            .def(second, GPR)
950            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(4))
951            .finish();
952
953        assert_eq!(folds(&mut func, &mut names), 0);
954        assert_eq!(shape(&func, &names, block).len(), 4);
955    }
956
957    /// A reader that is not reading it as an address at all. There is nowhere in an ordinary
958    /// operand to put a base and an index and a displacement, so that read is one no fold can take
959    /// and it turns down the set the way any other refusal does.
960    #[test]
961    fn an_address_something_reads_as_a_plain_operand_is_left_where_it_is() {
962        let (mut names, mut func, block) = empty();
963        let array = func.new_vreg(GPR);
964        let address = func.new_vreg(GPR);
965        let value = func.new_vreg(GPR);
966        let sum = func.new_vreg(GPR);
967        let lea = op(&mut names, FRAME.lea);
968        let load = op(&mut names, "mov_rm_32");
969        let add = op(&mut names, "add_rr_64");
970        func.build(block, lea)
971            .def(address, GPR)
972            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
973            .finish();
974        func.build(block, load)
975            .def(value, GPR)
976            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
977            .finish();
978        func.build(block, add).def(sum, GPR).uses(address, GPR).finish();
979
980        assert_eq!(folds(&mut func, &mut names), 0);
981        assert_eq!(shape(&func, &names, block).len(), 3);
982    }
983
984    /// The one instruction reading the address twice, once as the value it stores and once as the
985    /// place it stores to. Only one of those two reads is the memory operand, so folding would
986    /// leave the other one naming a register nothing writes any more.
987    #[test]
988    fn an_address_the_one_instruction_reads_twice_is_left_where_it_is() {
989        let (mut names, mut func, block) = empty();
990        let array = func.new_vreg(GPR);
991        let address = func.new_vreg(GPR);
992        let lea = op(&mut names, FRAME.lea);
993        let store = op(&mut names, "mov_mr_64");
994        func.build(block, lea)
995            .def(address, GPR)
996            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
997            .finish();
998        func.build(block, store)
999            .uses(address, GPR)
1000            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
1001            .finish();
1002
1003        assert_eq!(folds(&mut func, &mut names), 0);
1004        assert_eq!(shape(&func, &names, block).len(), 2);
1005    }
1006
1007    /// A chain whose middle has a reader of its own, so the inner address is complete while the
1008    /// outer one is still waiting for its second reader. Folding the inner one away takes with it
1009    /// the instruction the outer one's plan was written for, and the outer one waits rather than
1010    /// being written into a gap. The second run is where it lands, which is the whole of what
1011    /// waiting costs.
1012    #[test]
1013    fn a_chain_whose_middle_goes_first_leaves_the_outer_address_for_the_next_run() {
1014        let (mut names, mut func, block) = empty();
1015        let array = func.new_vreg(GPR);
1016        let outer = func.new_vreg(GPR);
1017        let inner = func.new_vreg(GPR);
1018        let first = func.new_vreg(GPR);
1019        let second = func.new_vreg(GPR);
1020        let lea = op(&mut names, FRAME.lea);
1021        let load = op(&mut names, "mov_rm_32");
1022        func.build(block, lea)
1023            .def(outer, GPR)
1024            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1025            .finish();
1026        func.build(block, lea)
1027            .def(inner, GPR)
1028            .mem(mir::Mem::at(mir::Operand::read(outer, GPR)).plus(4))
1029            .finish();
1030        func.build(block, load)
1031            .def(first, GPR)
1032            .mem(mir::Mem::at(mir::Operand::read(inner, GPR)))
1033            .finish();
1034        func.build(block, load)
1035            .def(second, GPR)
1036            .mem(mir::Mem::at(mir::Operand::read(outer, GPR)).plus(8))
1037            .finish();
1038
1039        assert_eq!(folds(&mut func, &mut names), 1);
1040        assert_eq!(shape(&func, &names, block).len(), 3, "the inner address is still there");
1041
1042        assert_eq!(folds(&mut func, &mut names), 2);
1043        let left = shape(&func, &names, block);
1044        assert_eq!(left.len(), 2, "the outer address is still there: {left:?}");
1045        let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
1046        assert_eq!(disps, vec![20, 24], "the two loads are at the two composed offsets");
1047    }
1048
1049    /// Both of them having an index is the one shape that does not compose, since the answer would
1050    /// want two scaled registers.
1051    #[test]
1052    fn an_index_on_each_side_is_left_alone() {
1053        let (mut names, mut func, block) = empty();
1054        let array = func.new_vreg(GPR);
1055        let row = func.new_vreg(GPR);
1056        let index = func.new_vreg(GPR);
1057        let address = func.new_vreg(GPR);
1058        let value = func.new_vreg(GPR);
1059        let lea = op(&mut names, FRAME.lea);
1060        let load = op(&mut names, "mov_rm_32");
1061        func.build(block, lea)
1062            .def(address, GPR)
1063            .mem(
1064                mir::Mem::at(mir::Operand::read(array, GPR))
1065                    .indexed(mir::Operand::read(row, GPR), 8)
1066                    .plus(16),
1067            )
1068            .finish();
1069        func.build(block, load)
1070            .def(value, GPR)
1071            .mem(
1072                mir::Mem::at(mir::Operand::read(address, GPR))
1073                    .indexed(mir::Operand::read(index, GPR), 4),
1074            )
1075            .finish();
1076
1077        assert_eq!(folds(&mut func, &mut names), 0);
1078        assert_eq!(shape(&func, &names, block).len(), 2);
1079    }
1080
1081    /// The reader having the only index there is between the two, which is `s.items[i]` on a local:
1082    /// the `lea` works out where the object starts and the reader scales the subscript. The index
1083    /// stays where it is and the base and the displacement arrive from the address.
1084    #[test]
1085    fn the_reader_s_own_index_is_kept_when_the_address_has_none() {
1086        let (mut names, mut func, block) = empty();
1087        let array = func.new_vreg(GPR);
1088        let index = func.new_vreg(GPR);
1089        let address = func.new_vreg(GPR);
1090        let value = func.new_vreg(GPR);
1091        let lea = op(&mut names, FRAME.lea);
1092        let load = op(&mut names, "mov_rm_32");
1093        func.build(block, lea)
1094            .def(address, GPR)
1095            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1096            .finish();
1097        func.build(block, load)
1098            .def(value, GPR)
1099            .mem(
1100                mir::Mem::at(mir::Operand::read(address, GPR))
1101                    .indexed(mir::Operand::read(index, GPR), 4)
1102                    .plus(8),
1103            )
1104            .finish();
1105
1106        assert_eq!(folds(&mut func, &mut names), 1);
1107
1108        let left = shape(&func, &names, block);
1109        assert_eq!(left.len(), 1, "the address is worked out twice: {left:?}");
1110        assert_eq!(left[0].1.disp, 24, "the field is at the sum of the two offsets or nowhere");
1111        assert_eq!(
1112            left[0].1.scale, 4,
1113            "the scale is the reader's, since the index is the reader's"
1114        );
1115        let inst = func.insts(block).next().expect("the load is still there");
1116        assert_eq!(address_regs(&func, inst), vec![array, index], "the load reads the wrong pair");
1117    }
1118
1119    /// A store whose own address is indexed, which is the same composition with an operand in front
1120    /// of the address that the rebuilt vector has to hold on to.
1121    #[test]
1122    fn a_store_with_an_index_of_its_own_keeps_the_value_it_is_storing() {
1123        let (mut names, mut func, block) = empty();
1124        let array = func.new_vreg(GPR);
1125        let index = func.new_vreg(GPR);
1126        let address = func.new_vreg(GPR);
1127        let value = func.new_vreg(GPR);
1128        let lea = op(&mut names, FRAME.lea);
1129        let store = op(&mut names, "mov_mr_32");
1130        func.build(block, lea)
1131            .def(address, GPR)
1132            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(4))
1133            .finish();
1134        func.build(block, store)
1135            .uses(value, GPR)
1136            .mem(
1137                mir::Mem::at(mir::Operand::read(address, GPR))
1138                    .indexed(mir::Operand::read(index, GPR), 2),
1139            )
1140            .finish();
1141
1142        assert_eq!(folds(&mut func, &mut names), 1);
1143
1144        let inst = func.insts(block).next().expect("the store is still there");
1145        let regs: Vec<mir::Reg> = func[func[inst].operands].iter().map(|op| op.reg).collect();
1146        assert_eq!(regs, vec![value, array, index], "the value the store writes went missing");
1147        let amode = func[func[inst].mem.expect("a memory operand")];
1148        assert_eq!((amode.scale, amode.disp), (2, 4));
1149    }
1150
1151    /// An address relative to a symbol, read by an instruction with an index of its own. The symbol
1152    /// is in the place the base would go, so the composed address would be a symbol and a scaled
1153    /// register with nothing to be relative to, and there is no such address.
1154    #[test]
1155    fn a_symbol_is_not_composed_with_a_reader_s_index() {
1156        let (mut names, mut func, block) = empty();
1157        let index = func.new_vreg(GPR);
1158        let address = func.new_vreg(GPR);
1159        let value = func.new_vreg(GPR);
1160        let lea = op(&mut names, FRAME.lea);
1161        let load = op(&mut names, "mov_rm_32");
1162        func.build(block, lea).def(address, GPR).mem(mir::Mem::of(names.intern("table"))).finish();
1163        func.build(block, load)
1164            .def(value, GPR)
1165            .mem(
1166                mir::Mem::at(mir::Operand::read(address, GPR))
1167                    .indexed(mir::Operand::read(index, GPR), 4),
1168            )
1169            .finish();
1170
1171        assert_eq!(folds(&mut func, &mut names), 0);
1172        assert_eq!(shape(&func, &names, block).len(), 2);
1173    }
1174
1175    /// The two displacements add up to more than the field holds, so the pair stays a pair. The
1176    /// program that does this is one nobody wrote, and the point of the test is that the answer is
1177    /// a refusal rather than a wrap.
1178    #[test]
1179    fn two_displacements_that_do_not_fit_together_are_not_put_together() {
1180        let (mut names, mut func, block) = empty();
1181        let array = func.new_vreg(GPR);
1182        let address = func.new_vreg(GPR);
1183        let value = func.new_vreg(GPR);
1184        let lea = op(&mut names, FRAME.lea);
1185        let load = op(&mut names, "mov_rm_32");
1186        func.build(block, lea)
1187            .def(address, GPR)
1188            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(i32::MAX))
1189            .finish();
1190        func.build(block, load)
1191            .def(value, GPR)
1192            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(1))
1193            .finish();
1194
1195        assert_eq!(folds(&mut func, &mut names), 0);
1196        assert_eq!(shape(&func, &names, block).len(), 2);
1197    }
1198
1199    /// A physical register the address reads, written between the two. Machine IR is in SSA form
1200    /// here so a virtual register cannot be, and this is why the walk asks anyway.
1201    #[test]
1202    fn a_register_the_address_reads_being_written_in_between_ends_the_chance() {
1203        let (mut names, mut func, block) = empty();
1204        let array = mir::Reg::physical(RDI);
1205        let address = func.new_vreg(GPR);
1206        let value = func.new_vreg(GPR);
1207        let lea = op(&mut names, FRAME.lea);
1208        let load = op(&mut names, "mov_rm_32");
1209        let put = op(&mut names, "mov_ri_64");
1210        func.build(block, lea)
1211            .def(address, GPR)
1212            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1213            .finish();
1214        func.build(block, put).def(array, GPR).imm(7).finish();
1215        func.build(block, load)
1216            .def(value, GPR)
1217            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
1218            .finish();
1219
1220        assert_eq!(folds(&mut func, &mut names), 0);
1221        assert_eq!(shape(&func, &names, block).len(), 3);
1222    }
1223
1224    /// A reader in another block. Folding would move the address to wherever that block is, and
1225    /// this pass has no way to know whether that is somewhere it runs more often.
1226    #[test]
1227    fn a_reader_in_another_block_is_not_one_this_folds_into() {
1228        let (mut names, mut func, block) = empty();
1229        let next = func.create_block();
1230        let array = func.new_vreg(GPR);
1231        let address = func.new_vreg(GPR);
1232        let value = func.new_vreg(GPR);
1233        let lea = op(&mut names, FRAME.lea);
1234        let load = op(&mut names, "mov_rm_32");
1235        func.build(block, lea)
1236            .def(address, GPR)
1237            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1238            .finish();
1239        *func.succs_mut(block) = vec![mir::BlockCall::to(next)];
1240        func.build(next, load)
1241            .def(value, GPR)
1242            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
1243            .finish();
1244
1245        assert_eq!(folds(&mut func, &mut names), 0);
1246    }
1247
1248    /// A chain of two, which is what an address of a field of an element of an array comes out as.
1249    /// The walk goes forwards, so the second `lea` is folded into the load and then the first is
1250    /// folded into what is left of the second, both in the one pass.
1251    #[test]
1252    fn a_chain_of_two_addresses_is_folded_the_whole_way_in_one_pass() {
1253        let (mut names, mut func, block) = empty();
1254        let array = func.new_vreg(GPR);
1255        let index = func.new_vreg(GPR);
1256        let element = func.new_vreg(GPR);
1257        let field = func.new_vreg(GPR);
1258        let value = func.new_vreg(GPR);
1259        let lea = op(&mut names, FRAME.lea);
1260        let load = op(&mut names, "mov_rm_32");
1261        func.build(block, lea)
1262            .def(element, GPR)
1263            .mem(
1264                mir::Mem::at(mir::Operand::read(array, GPR))
1265                    .indexed(mir::Operand::read(index, GPR), 8),
1266            )
1267            .finish();
1268        func.build(block, lea)
1269            .def(field, GPR)
1270            .mem(mir::Mem::at(mir::Operand::read(element, GPR)).plus(4))
1271            .finish();
1272        func.build(block, load)
1273            .def(value, GPR)
1274            .mem(mir::Mem::at(mir::Operand::read(field, GPR)))
1275            .finish();
1276
1277        assert_eq!(folds(&mut func, &mut names), 2);
1278
1279        let left = shape(&func, &names, block);
1280        assert_eq!(left.len(), 1, "one of the two addresses is still its own instruction");
1281        assert_eq!(left[0].1.scale, 8);
1282        assert_eq!(left[0].1.disp, 4);
1283        let inst = func.insts(block).next().expect("the load is still there");
1284        assert_eq!(address_regs(&func, inst), vec![array, index]);
1285    }
1286
1287    /// An address of a global, which the `lea` holds as a symbol rather than as a register. It
1288    /// composes the same way and the reader ends up naming the symbol itself, which is one
1289    /// instruction rather than two for every read of a global with a constant subscript.
1290    #[test]
1291    fn an_address_of_a_global_folds_into_the_reader_symbol_and_all() {
1292        let (mut names, mut func, block) = empty();
1293        let global = names.intern("counters");
1294        let address = func.new_vreg(GPR);
1295        let value = func.new_vreg(GPR);
1296        let lea = op(&mut names, FRAME.lea);
1297        let load = op(&mut names, "mov_rm_32");
1298        func.build(block, lea).def(address, GPR).mem(mir::Mem::of(global)).finish();
1299        func.build(block, load)
1300            .def(value, GPR)
1301            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(12))
1302            .finish();
1303
1304        assert_eq!(folds(&mut func, &mut names), 1);
1305
1306        let left = shape(&func, &names, block);
1307        assert_eq!(left.len(), 1);
1308        assert_eq!(left[0].1.symbol, Some(global));
1309        assert_eq!(left[0].1.disp, 12);
1310    }
1311
1312    /// An address into the frame, which reads as an address of nothing until `finish` writes the
1313    /// distance in. It folds like any other and the entry moves to the instruction that took it, so
1314    /// the distance is still written into something that runs, and into the reader's own
1315    /// displacement rather than over it.
1316    #[test]
1317    fn an_address_whose_displacement_is_still_to_be_written_folds_and_takes_its_entry_with_it() {
1318        let (mut names, mut func, block) = empty();
1319        let sp = mir::Reg::physical(RDI);
1320        let address = func.new_vreg(GPR);
1321        let value = func.new_vreg(GPR);
1322        let lea = op(&mut names, FRAME.lea);
1323        let load = op(&mut names, "mov_rm_32");
1324        let local = func
1325            .build(block, lea)
1326            .def(address, GPR)
1327            .mem(mir::Mem::at(mir::Operand::read(sp, GPR)))
1328            .finish();
1329        func.build(block, load)
1330            .def(value, GPR)
1331            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(8))
1332            .finish();
1333
1334        let (mut locals, mut arguments, mut growable) = (vec![(local, 3)], Vec::new(), Vec::new());
1335        let mut pending =
1336            Pending { addresses: &mut locals, arguments: &mut arguments, dynamic: &mut growable };
1337        assert_eq!(addresses(&mut func, &FRAME, &MACHINE, &mut names, &mut pending), 1);
1338
1339        let left = shape(&func, &names, block);
1340        assert_eq!(left.len(), 1, "the address is worked out twice: {left:?}");
1341        assert_eq!(left[0].1.disp, 8, "the field's offset is what finish adds the frame's to");
1342        let reader = func.insts(block).next().expect("the load is still there");
1343        assert_eq!(locals, vec![(reader, 3)], "the offset is owed to whoever took the address");
1344    }
1345
1346    /// One address into the frame read at that many offsets, which is a structure written field by
1347    /// field. Gives back how many folded, which instructions are in the block afterwards, and what
1348    /// the caller is still owed an offset into.
1349    fn a_frame_address(readers: u32) -> (usize, Vec<mir::Inst>, Vec<(mir::Inst, u32)>) {
1350        let (mut names, mut func, block) = empty();
1351        let sp = mir::Reg::physical(RDI);
1352        let address = func.new_vreg(GPR);
1353        let lea = op(&mut names, FRAME.lea);
1354        let load = op(&mut names, "mov_rm_32");
1355        let local = func
1356            .build(block, lea)
1357            .def(address, GPR)
1358            .mem(mir::Mem::at(mir::Operand::read(sp, GPR)))
1359            .finish();
1360        for at in 0..readers {
1361            let value = func.new_vreg(GPR);
1362            func.build(block, load)
1363                .def(value, GPR)
1364                .mem(
1365                    mir::Mem::at(mir::Operand::read(address, GPR))
1366                        .plus(i32::try_from(at).unwrap_or(0) * 4),
1367                )
1368                .finish();
1369        }
1370
1371        let (mut locals, mut arguments, mut growable) = (Vec::new(), vec![(local, 7)], Vec::new());
1372        let mut pending =
1373            Pending { addresses: &mut locals, arguments: &mut arguments, dynamic: &mut growable };
1374        let folded = addresses(&mut func, &FRAME, &MACHINE, &mut names, &mut pending);
1375        assert!(locals.is_empty(), "an argument is owed off the other list");
1376        (folded, func.insts(block).collect(), arguments)
1377    }
1378
1379    /// One entry on the list becomes one per reader, since each of them now carries a displacement
1380    /// the frame's offset has to be added to and there is no instruction left to add it to instead.
1381    #[test]
1382    fn an_address_into_the_frame_that_three_readers_take_is_owed_to_all_of_them() {
1383        let (folded, left, owed) = a_frame_address(3);
1384        assert_eq!(folded, 3);
1385        assert_eq!(left.len(), 3, "the address is not its own instruction any more");
1386        assert_eq!(owed, vec![(left[0], 7), (left[1], 7), (left[2], 7)]);
1387    }
1388
1389    /// And the reader after that is one too many, so none of them takes it. What each of them would
1390    /// put on is more than what the whole address instruction costs, which is [`FRAME_READERS`].
1391    #[test]
1392    fn an_address_into_the_frame_a_fourth_reader_wants_is_left_where_it_is() {
1393        let (folded, left, owed) = a_frame_address(4);
1394        assert_eq!(folded, 0);
1395        assert_eq!(left.len(), 5, "the address and its four readers");
1396        assert_eq!(owed, vec![(left[0], 7)], "the offset is still owed to the address itself");
1397    }
1398
1399    /// An instruction that is not the target's address instruction, writing a register a load
1400    /// reads. A load through the result of a load is two loads and folding one into the other
1401    /// would read the wrong memory, so the opcode is checked rather than the shape.
1402    #[test]
1403    fn only_the_target_s_address_instruction_is_one_this_folds() {
1404        let (mut names, mut func, block) = empty();
1405        let array = func.new_vreg(GPR);
1406        let address = func.new_vreg(GPR);
1407        let value = func.new_vreg(GPR);
1408        let load = op(&mut names, "mov_rm_64");
1409        let read = op(&mut names, "mov_rm_32");
1410        func.build(block, load)
1411            .def(address, GPR)
1412            .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1413            .finish();
1414        func.build(block, read)
1415            .def(value, GPR)
1416            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
1417            .finish();
1418
1419        assert_eq!(folds(&mut func, &mut names), 0);
1420        assert_eq!(shape(&func, &names, block).len(), 2);
1421    }
1422
1423    /// A byte array read as selection leaves it, the sum of two registers and a load three bytes
1424    /// past it, and the register the sum wrote.
1425    fn a_sum_and_a_load(
1426        func: &mut mir::Func,
1427        names: &mut Interner,
1428        block: mir::Block,
1429        added: [mir::Reg; 2],
1430    ) -> mir::Reg {
1431        let address = func.new_vreg(GPR);
1432        let value = func.new_vreg(GPR);
1433        let sum = op(names, FRAME.sum);
1434        let load = op(names, "mov_rm_8");
1435        func.build(block, sum).def(address, GPR).uses(added[0], GPR).uses(added[1], GPR).finish();
1436        func.build(block, load)
1437            .def(value, GPR)
1438            .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(3))
1439            .finish();
1440        address
1441    }
1442
1443    /// `p[i + 3]` on a `char`, where there is no scale for a rule to make a `lea` out of.
1444    #[test]
1445    fn a_sum_of_two_registers_is_a_base_and_an_index_to_the_one_reading_through_it() {
1446        let (mut names, mut func, block) = empty();
1447        let array = func.new_vreg(GPR);
1448        let index = func.new_vreg(GPR);
1449        a_sum_and_a_load(&mut func, &mut names, block, [array, index]);
1450
1451        assert_eq!(folds(&mut func, &mut names), 1);
1452
1453        let left = shape(&func, &names, block);
1454        assert_eq!(left.len(), 1, "the sum is still there: {left:?}");
1455        assert_eq!(left[0].0, format!("{}mov_rm_8", FRAME.prefix));
1456        assert_eq!((left[0].1.scale, left[0].1.disp), (1, 3));
1457        let inst = func.insts(block).next().expect("the load is still there");
1458        assert_eq!(address_regs(&func, inst), vec![array, index]);
1459    }
1460
1461    /// The stack pointer has no encoding as an index, so a sum with it second reads it as the base.
1462    #[test]
1463    fn a_sum_with_the_stack_pointer_second_has_it_as_the_base() {
1464        let (mut names, mut func, block) = empty();
1465        let index = func.new_vreg(GPR);
1466        let sp = mir::Reg::physical(RSP);
1467        a_sum_and_a_load(&mut func, &mut names, block, [index, sp]);
1468
1469        assert_eq!(folds(&mut func, &mut names), 1);
1470
1471        let inst = func.insts(block).next().expect("the load is still there");
1472        assert_eq!(address_regs(&func, inst), vec![sp, index]);
1473    }
1474
1475    /// Two registers neither of which can be an index is a sum this leaves as a sum.
1476    #[test]
1477    fn a_sum_with_no_register_that_can_be_an_index_is_left_where_it_is() {
1478        let (mut names, mut func, block) = empty();
1479        let (sp, di) = (mir::Reg::physical(RSP), mir::Reg::physical(RDI));
1480        a_sum_and_a_load(&mut func, &mut names, block, [di, sp]);
1481
1482        assert_eq!(folds(&mut func, &mut names), 0);
1483        assert_eq!(shape(&func, &names, block).len(), 2);
1484    }
1485
1486    /// A sum anything reads as a number rather than as an address is arithmetic the program wants,
1487    /// and it stays, along with every reader that did want the address.
1488    #[test]
1489    fn a_sum_read_as_a_number_as_well_is_left_where_it_is() {
1490        let (mut names, mut func, block) = empty();
1491        let array = func.new_vreg(GPR);
1492        let index = func.new_vreg(GPR);
1493        let address = a_sum_and_a_load(&mut func, &mut names, block, [array, index]);
1494        let copy = func.new_vreg(GPR);
1495        let add = op(&mut names, "add_rr_64");
1496        func.build(block, add).def(copy, GPR).uses(address, GPR).uses(index, GPR).finish();
1497
1498        assert_eq!(folds(&mut func, &mut names), 0);
1499        assert_eq!(shape(&func, &names, block).len(), 3);
1500    }
1501}