Skip to main content

rucc_codegen/
shorten.rs

1//! Writing the same answer in fewer bytes, once the registers are the real ones.
2//!
3//! Design: `spec/optimizer/37-machine-level-optimization.md` section 37.4, which calls these the
4//! size directed peepholes and puts them after register allocation. tamnd/rucc#741 is the issue
5//! about the back end never learning what it is compiling for, and names three of these as free
6//! before any of that is settled and one as waiting for it.
7//!
8//! Five rewrites. A move of zero into a register becomes an exclusive or of the register with
9//! itself: `movl $0, %eax` spells the zero out in four bytes of zero bits and is five bytes, `xorl
10//! %eax, %eax` says it without spelling it and is two. The processor knows the idiom, so the
11//! shorter one is no slower, and this is not a trade of speed for size and does not wait for a size
12//! goal to arrive.
13//!
14//! And a move of a number into a sixty-four bit register becomes the thirty-two bit move where the
15//! number is one that fits, because the narrow instruction clears the half of the register it does
16//! not write rather than leaving it alone. `movq $7, %rax` is seven bytes and `movl $7, %eax` is
17//! five, and for a number above two to the thirty-first it is ten against five, since the wide move
18//! cannot reach one by sign extending and writes all eight bytes of it out.
19//!
20//! The two meet on a zero, and the order they are asked in is the order they are worth: a zero
21//! whose condition state is free becomes the exclusive or, and a zero whose state is not becomes
22//! the narrow move, which is two bytes off rather than five but costs nothing to say.
23//!
24//! And a comparison of a register against zero becomes a test of the register against itself.
25//! `cmpl $0, %eax` is three bytes and `testl %eax, %eax` is two, the byte being the zero the first
26//! one writes out. That one is asked of every instruction whatever the walk has seen, because the
27//! test writes the condition state exactly as the comparison does: both leave the sign, the zero
28//! and the parity of what is in the register and both clear the carry and the overflow, so every
29//! condition this machine jumps on reads the same answer behind either of them.
30//!
31//! And an addition of one to a register becomes the instruction that adds one and says so in its
32//! opcode. `addl $1, %eax` is three bytes, one for the opcode, one saying which register and one
33//! for the number, and `incl %eax` is two. A subtraction of one becomes the instruction that takes
34//! one away, and each of the two is also what the other one written against minus one becomes.
35//!
36//! And an address computation whose address is a register becomes a move of that register. `leaq
37//! (%rsp), %rax` works out an address that is a base and nothing else, which is what is already in
38//! the base, and `movq %rsp, %rax` puts the same number in the same place in three bytes rather than
39//! four. The byte is the one an address counted from the stack pointer has to spend saying it has no
40//! index, and the stack pointer is the register this turns up on, because what makes it is taking
41//! the address of whichever local sits at the bottom of the frame.
42//!
43//! That fifth one is the only one here worth taking for something other than bytes. A move between
44//! registers is a thing the machine can do by renaming, so it is off the critical path, and an
45//! address computation is an addition however small the numbers in it are. gcc writes no address
46//! computation of that shape anywhere in the SQLite amalgamation and rucc wrote 444 of them.
47//!
48//! That fourth one is the only one here that is not free, and it is the only one that reads the
49//! goal. An addition writes the carry and an increment leaves the carry as it found it, so the
50//! machine has to merge what was left with what the next instruction writes, which costs a little
51//! where the code is hot and is worth a byte where the goal is size. gcc writes the addition at
52//! `-O2` and the increment at `-Os`, and so does this. The goal arriving here at all is the first
53//! half of tamnd/rucc#741: before it, `-Os` was a shorter list of middle end passes and the back
54//! end compiled what came out of it exactly as `-O2` would have.
55//!
56//! The numbers over the corpus at `-Os` before this pass existed: rucc wrote a move of zero into a
57//! register 21,304 times and GCC 16 wrote it 9 times, and GCC wrote the exclusive or 23,729 times
58//! against rucc's 965. So this is not a case the selector catches most of and misses at the edges.
59//! It is one it does not do. Afterwards rucc writes the move 1,232 times and the exclusive or
60//! 21,037, and the two moved by the same number, which is what says every one that went became one
61//! of these and none of them came from anywhere else.
62//!
63//! # Why it is not something the encoder does
64//!
65//! Because the two are not the same instruction. The exclusive or writes the condition state and
66//! the move does not, so an encoder that quietly swapped one for the other would change what the
67//! instruction behind it reads. Whether anything reads it is a question about the instructions that
68//! follow rather than about this one, which is what makes this a pass. [`rucc_target::FlagInsts`]
69//! is where the answer comes from, the same description [`crate::compare`] asks, and it answers
70//! that a name it does not know writes the state, so an opcode added to a rule set and not to that
71//! table makes this find less rather than making it wrong.
72//!
73//! The narrower move and the test are a different answer to the same question. Those two an encoder
74//! could do without asking anything, since the narrower move leaves the same number in the same
75//! register and the test leaves the same condition state the comparison left. They are not done
76//! there because an encoder handed a sixty-four bit move and writing the bytes of a thirty-two bit
77//! one would be writing bytes the listing beside them does not say, and the listing and the bytes
78//! agreeing is worth more than the two bytes. Choosing the instruction is this pass and spelling
79//! the one it chose is the encoder.
80//!
81//! # Why it runs last
82//!
83//! After [`crate::compare`], because that pass takes comparisons out and a comparison that is gone
84//! is one whose write of the condition state is gone with it. Running before it would see a state
85//! written where the output has none and would refuse rewrites that are allowed. After the layout
86//! for the reason `compare` is: the layout writes the jump that reads a comparison into the same
87//! block as the comparison, and this is the other pass that has to see that pair whole.
88//!
89//! Nothing here moves an instruction, removes one or changes a block, so running after the freeze
90//! costs nothing. The rewrite is one instruction becoming one instruction in the same place.
91//!
92//! # What a block boundary is
93//!
94//! The end of everything this knows, which is the same sentence [`crate::compare`] uses and the
95//! same reason: the condition state is not a register, nothing in this back end carries one from a
96//! block to its successors, and the only place a comparison is read is the block it was made in.
97//!
98//! That is an invariant of the passes in front rather than of this one, so it is checked instead of
99//! believed. `carried` walks every block and asks whether any of them reads the condition state
100//! before writing it, which is what a block reading a predecessor's state would look like from
101//! here, and one that does turns the whole function down. What it buys is that if some later pass
102//! starts writing that shape, this pass stops rather than starts being wrong.
103//!
104//! Reads it rather than mentions it. A comparison that keeps a byte makes the comparison and reads
105//! the answer in the one instruction, so a block opening with one is not a block reading anything a
106//! predecessor left, and the description is asked which of the two kinds of read it is rather than
107//! being taken at the word. tamnd/rucc#1432 is what that cost before it was asked: 456 functions in
108//! the SQLite amalgamation were turned down and every one of them was turned down by this, which is
109//! most of the functions in it that have anything for this pass to do.
110//!
111//! Down for the exclusive or and the increment. The narrower move reads no condition state and
112//! writes none, the test writes the same state the comparison it replaces wrote, and neither an
113//! address computation nor a move touches any state at all, so where a state is alive is not a
114//! question those three have to ask, and a function this turns down still gets all of them.
115//!
116//! What the walk carries for the increment is a second answer beside the first, which is whether
117//! anything behind reads the carry rather than whether anything behind reads the state. The two are
118//! not the same question and neither implies the other: a jump on whether a value was zero reads the
119//! state and not the carry, and an increment already in the code writes the state and not the carry
120//! and so ends the life of neither. That last case is the reason the walk and the check above both
121//! ask the target which instructions leave the carry alone rather than stopping at the flag saying
122//! the state was written.
123//!
124//! # A template a program wrote
125//!
126//! An `asm` statement is not opaque to this. `rucc_target::x86_64::read` turns the text of a
127//! template into the opcodes this back end already has, so by the time this runs a template is
128//! ordinary instructions carrying ordinary names, and the ones in it that read the condition state
129//! are seen the same way any other instruction's read is. A move of zero in front of a template is
130//! rewritten when nothing in that template reads a state it did not write itself, which is the same
131//! rule as everywhere else and not a rule about templates.
132//!
133//! Nothing weaker is being assumed there than what a program could already rely on. On this machine
134//! GCC has every `asm` clobber the condition state whether the statement said so or not, so a
135//! template reading one set before it was never something to hold on to.
136//!
137//! # What it will not do
138//!
139//! Turn a move into the exclusive or when anything reads its condition state before anything
140//! writes. That is the rule and what it costs is now a small number: the zero going into a register
141//! right before a comparison of something else stays a move, and the most the other rewrite can do
142//! for it is make it a narrower one. Of the 215 moves of zero left over the corpus at `-Os`, 146
143//! are this and the other 69 are the eight bit rule below. Not one of them is sixty-four bits wide.
144//!
145//! It was 1,232 until the whole function check stopped counting a comparison that keeps a byte as a
146//! state read from in front of it, which is tamnd/rucc#1432 and was most of what this pass was
147//! leaving alone rather than anything about the instructions it was looking at.
148//!
149//! Eight bits. `movb $0, %al` and `xorb %al, %al` are both two bytes, so the exchange buys nothing
150//! and would spend the condition state on it. The target's table is where that is written down.
151//!
152//! Write an increment at a level that asked for fast code. That is the goal doing its job rather
153//! than a limit, and it is why the same corpus compiled at `-O2` and at `-Os` now differs by
154//! something other than which middle end passes ran.
155//!
156//! Add or take away anything but one. The machine has an opcode for one and for nothing else, so a
157//! constant of two is already as short as it is going to be written.
158//!
159//! Turn an address computation into a move when the address is anything more than a register. An
160//! index is a multiplication, a constant is an addition and a symbol is an address the assembler
161//! fills in, and a move does none of those. That is what most address computations are for, so this
162//! last rewrite is about the ones that were not computing anything rather than about address
163//! computation in general.
164
165use rucc_base::Interner;
166use rucc_cost::Goal;
167use rucc_mir::{self as mir, Role};
168use rucc_target::{FlagInsts, MachineInsts, Reads, ShortInsts};
169
170use crate::changes::{self, Changes, Plan};
171
172/// Rewrites every instruction that has a shorter spelling nothing would notice.
173///
174/// Gives back how many were rewritten, which the tests read and nothing else does.
175pub fn shorter(
176    func: &mut mir::Func,
177    short: &ShortInsts,
178    flags: &FlagInsts,
179    machine: &MachineInsts,
180    names: &mut Interner,
181    goal: Goal,
182) -> usize {
183    // Every name a rewrite could want, before the walk rather than inside it, because the walk
184    // holds a name it read out of the interner while it edits the function and interning a new one
185    // there would be the same interner borrowed twice. The same reason [`crate::compare`] has.
186    let wanted = short.zeroing.iter().map(|entry| entry.into);
187    let wanted = wanted.chain(short.narrowing.iter().map(|entry| entry.into));
188    let wanted = wanted.chain(short.testing.iter().map(|entry| entry.into));
189    let wanted = wanted.chain(short.stepping.iter().map(|entry| entry.into));
190    let wanted = wanted.chain(short.copying.iter().map(|entry| entry.into));
191    let opcodes: Vec<(&'static str, mir::Opcode)> = wanted
192        .map(|into| (into, mir::Opcode::new(names.intern(&format!("{}{into}", short.prefix)))))
193        .collect();
194    let names = &*names;
195    let mut counts = changes::Reads::of(func);
196    let mut took = 0;
197    // Whether the rewrite that spends the condition state may be asked for at all. The narrower
198    // instruction neither reads the state nor writes it, so it is not asked this and a function
199    // this turns down still gets that one.
200    let free = !carried(func, short, flags, names);
201    // Whether the rewrite that trades the carry for a byte may be asked for. It is the one thing
202    // here that is not free, so it waits for a level that said it wanted small code.
203    let small = free && goal == Goal::Size;
204    for block in func.blocks().collect::<Vec<_>>() {
205        // Backwards, because the question each instruction asks is about the ones behind it. The
206        // state is dead at the end of a block, which is the invariant [`carried`] has just held the
207        // function to.
208        let mut live = false;
209        // The same question about the carry alone, which is the part of the state the shorter
210        // addition does not write. It starts false for the reason `live` does and moves separately,
211        // because an instruction that writes the whole state ends the life of both and one that
212        // writes everything but the carry ends the life of neither.
213        let mut carry = false;
214        for inst in func.insts(block).collect::<Vec<_>>().into_iter().rev() {
215            if free && !live {
216                let into = shorter_form(func, short, names, &opcodes, inst);
217                if into.is_some_and(|op| zeroed(func, &mut counts, machine, names, inst, op)) {
218                    took += 1;
219                    // What stands there now writes the state, and the state was already dead, so
220                    // nothing about what the instructions in front of it may do has changed.
221                    continue;
222                }
223            }
224            // The zero that could not become an exclusive or can still be written in fewer bytes,
225            // which is why this is asked after that one and not instead of it.
226            let into = narrower_form(func, short, names, &opcodes, inst);
227            if into.is_some_and(|op| narrowed(func, &mut counts, machine, names, inst, op)) {
228                took += 1;
229                // What stands there now is the same instruction at half the width, which is a
230                // move either way, so what it does to the state is what it did before: nothing.
231            }
232            // A comparison against zero asked of the register alone. Nothing about where the state
233            // is live comes into it, because the shorter instruction writes the same five bits of
234            // state the comparison wrote, so this is asked of every instruction whatever the walk
235            // has seen behind it.
236            let into = tested_form(func, short, names, &opcodes, inst);
237            if into.is_some_and(|op| tested(func, &mut counts, machine, names, inst, op)) {
238                took += 1;
239            }
240            // An address that is a register, written as the move it is. Nothing about the condition
241            // state comes into it either, since neither instruction writes any, so this is asked of
242            // every instruction the same way the narrower move is.
243            let into = copied_form(func, short, names, &opcodes, inst);
244            if into.is_some_and(|op| copied(func, &mut counts, machine, names, inst, op)) {
245                took += 1;
246            }
247            // Adding one with the one in the opcode, which is the only rewrite here that is a
248            // trade. It needs the carry to be dead rather than the whole state, since that is the
249            // only part of the state the shorter instruction leaves behind, and it needs the level
250            // to have asked for small code.
251            if small && !carry {
252                let into = stepped_form(func, short, names, &opcodes, inst);
253                if into.is_some_and(|op| stepped(func, &mut counts, machine, names, inst, op)) {
254                    took += 1;
255                    // What stands there now writes everything but the carry, and the carry was
256                    // already dead, so both answers below are the ones they already are and the
257                    // walk past it is the walk it would have taken anyway.
258                }
259            }
260            let Some(name) = opcode(func, flags, names, inst) else {
261                // A name the description does not cover may have read the state and may have
262                // written it, and the answer that finds fewer rewrites is that it read it.
263                live = true;
264                carry = true;
265                continue;
266            };
267            // What it reads before whether it writes, because an instruction can do both and the
268            // read it does is a read of what is there now. An add with carry is the one that does,
269            // and asking the other way round would call it the end of the state's life and let a
270            // rewrite in front of it take the carry away.
271            //
272            // Unless what it reads is what it wrote itself. A comparison that keeps a byte makes
273            // the comparison and reads the answer in the one instruction, so the state it was
274            // handed is state it wrote over before anything looked at it, and it ends a life rather
275            // than extending one. Asking the description which kind it is rather than stopping at
276            // the word read is most of what this pass gets to do in real code, since a C function
277            // of any size has one of these in it.
278            if flags.asks_what_it_reads(name) {
279                live = false;
280                carry = false;
281            } else if let Some(reads) = flags.reads(name) {
282                live = true;
283                // Which part of the state the condition on it is about. A condition that asks where
284                // a value sits as an unsigned number reads the carry, and so does an instruction
285                // that is adding a carry on rather than asking a question about one.
286                if matches!(reads, Reads::Unsigned | Reads::Carry) {
287                    carry = true;
288                }
289            } else if (flags.writes)(name) && !short.steps(name) {
290                // An instruction that writes the state ends the life of everything in it. One that
291                // writes all of it but the carry ends the life of none of it, which is the second
292                // half of the sentence and is why this asks the description rather than stopping at
293                // the flag. That answer is about `live` as much as about `carry`: a rewrite in front
294                // that spends the state would be spending a carry this instruction was going to
295                // leave for something behind it.
296                live = false;
297                carry = false;
298            }
299        }
300    }
301    took
302}
303
304/// Whether any block reads the condition state before writing it, which is what a state carried in
305/// from a predecessor would look like from inside this pass.
306///
307/// The passes in front are the ones that promise this does not happen and the promise is theirs to
308/// keep, so what this does is hold them to it rather than restate it. A function where it is broken
309/// gets no rewrites at all, which is the answer that is wrong about nothing.
310///
311/// An instruction that leaves the carry alone does not count as having written the state here, for
312/// the same reason it does not count as having written it in the walk. A block opening with one and
313/// reading a carry afterwards is reading a carry a predecessor left, which is exactly the shape this
314/// is looking for, and stopping at it would be calling that block clean.
315///
316/// An instruction that reads what it wrote itself does not count as having read the state, for the
317/// same reason it does not in the walk. A block opening with a comparison that keeps a byte opens
318/// with a comparison, and what the comparison found is not what anything in front of it left.
319/// Counting it as a read is the difference between this turning down a few functions and turning
320/// down most of them, because a comparison that keeps a byte is what every `!` and every `==` in a
321/// value position comes out as.
322fn carried(func: &mir::Func, short: &ShortInsts, flags: &FlagInsts, names: &Interner) -> bool {
323    func.blocks().any(|block| {
324        for inst in func.insts(block) {
325            let Some(name) = opcode(func, flags, names, inst) else { return true };
326            if flags.reads(name).is_some() && !flags.asks_what_it_reads(name) {
327                return true;
328            }
329            if (flags.writes)(name) && !short.steps(name) {
330                return false;
331            }
332        }
333        false
334    })
335}
336
337/// The shorter instruction this one has, when it has one and the constant it carries is the one
338/// that instruction writes.
339///
340/// The name says which instruction it is and the description says which names have a shorter
341/// spelling, and neither of them says what number this one holds. That is the half that decides
342/// whether the shorter spelling says the same thing, since the short way of writing zero is only
343/// the short way of writing zero.
344fn shorter_form(
345    func: &mir::Func,
346    short: &ShortInsts,
347    names: &Interner,
348    opcodes: &[(&'static str, mir::Opcode)],
349    inst: mir::Inst,
350) -> Option<mir::Opcode> {
351    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
352    let into = short.zeroed(name)?;
353    if func[inst].imm.map(|at| func[at].0) != Some(0) {
354        return None;
355    }
356    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
357}
358
359/// The narrower instruction this one has, when it has one and the number it carries is one that
360/// instruction holds.
361///
362/// A number the narrower instruction cannot hold is every negative one and everything above what
363/// fits in the bits it writes, since what it does to the rest of the register is clear it. So the
364/// question is not whether the number fits in that many bits the way the program meant it, which is
365/// a question about a type, but whether the bits the wide instruction would leave in the register
366/// are the bits the narrow one leaves there, which is a question about the number.
367fn narrower_form(
368    func: &mir::Func,
369    short: &ShortInsts,
370    names: &Interner,
371    opcodes: &[(&'static str, mir::Opcode)],
372    inst: mir::Inst,
373) -> Option<mir::Opcode> {
374    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
375    let narrow = short.narrowed(name)?;
376    let held = u64::try_from(func[func[inst].imm?].0).ok()?;
377    if narrow.writes >= u64::BITS || held >= 1u64 << narrow.writes {
378        return None;
379    }
380    opcodes.iter().find(|&&(at, _)| at == narrow.into).map(|&(_, opcode)| opcode)
381}
382
383/// Rewrites the move into the narrower move, which is the same instruction with a different name.
384///
385/// So the operands are the ones it had, where the exclusive or below needs its own built: the two
386/// moves take a register they write and a number, and the number is the one that was already there.
387/// A description where that is not so is one [`Changes`] turns down, and a rewrite it turns down is
388/// one this reports as not taken rather than one that goes in anyway.
389fn narrowed(
390    func: &mut mir::Func,
391    counts: &mut changes::Reads,
392    machine: &MachineInsts,
393    names: &Interner,
394    inst: mir::Inst,
395    opcode: mir::Opcode,
396) -> bool {
397    let mut set = Changes::new();
398    set.rewrite(inst, Plan { opcode, ..Plan::of(func, inst) });
399    set.commit(func, counts, names, machine).is_ok()
400}
401
402/// The shorter comparison this one has, when it has one and the constant it carries is zero.
403///
404/// Zero is the whole of it. A comparison of a register against itself asks whether the register is
405/// zero and nothing else, so the description's entry says what to write instead of a comparison
406/// against zero and says nothing about a comparison against anything, and an instruction carrying
407/// any other number is one this walks past.
408fn tested_form(
409    func: &mir::Func,
410    short: &ShortInsts,
411    names: &Interner,
412    opcodes: &[(&'static str, mir::Opcode)],
413    inst: mir::Inst,
414) -> Option<mir::Opcode> {
415    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
416    let into = short.tested(name)?;
417    if func[inst].imm.map(|at| func[at].0) != Some(0) {
418        return None;
419    }
420    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
421}
422
423/// Rewrites the comparison into the test, which reads the register the comparison read and drops
424/// the constant.
425///
426/// The operands are the ones it had, for the reason [`narrowed`] keeps them: both instructions name
427/// one register and read it, and what changes is the number, which the shorter one does not carry.
428/// So the constant goes and nothing else does. A description where the two are not that shape is one
429/// [`Changes`] turns down, and this reports a rewrite it turned down as not taken.
430fn tested(
431    func: &mut mir::Func,
432    counts: &mut changes::Reads,
433    machine: &MachineInsts,
434    names: &Interner,
435    inst: mir::Inst,
436    opcode: mir::Opcode,
437) -> bool {
438    let mut set = Changes::new();
439    set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
440    set.commit(func, counts, names, machine).is_ok()
441}
442
443/// The move this address computation is, when the address it works out is a register.
444///
445/// Which is an addressing mode naming a base and nothing else. An index is a multiplication and an
446/// addition, a constant is an addition, and a symbol or a label is an address the assembler fills in
447/// later, so any of those is work the move does not do. What is left is a mode that says to take
448/// what is in one register, and taking what is in one register is the move.
449///
450/// The width is not asked about, unlike the narrower move above. An address on this machine is
451/// sixty four bits wide whatever is at it, so an address computation that keeps its answer keeps all
452/// of it, and the move the description names beside it is the move of that width.
453fn copied_form(
454    func: &mir::Func,
455    short: &ShortInsts,
456    names: &Interner,
457    opcodes: &[(&'static str, mir::Opcode)],
458    inst: mir::Inst,
459) -> Option<mir::Opcode> {
460    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
461    let into = short.copied(name)?;
462    let amode = func[inst].mem.map(|at| func[at])?;
463    if amode.base.is_none() || amode.index.is_some() || amode.disp != 0 {
464        return None;
465    }
466    if amode.symbol.is_some() || amode.block.is_some() || amode.table.is_some() {
467        return None;
468    }
469    if amode.segment.is_some() {
470        return None;
471    }
472    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
473}
474
475/// Rewrites the address computation into the move, which keeps the operands and drops the mode.
476///
477/// The operands are already the move's. An instruction with an addressing mode carries the registers
478/// that mode names in its operand vector, behind the ones it writes, so an address computation whose
479/// mode is one base is an instruction that writes one register and reads one register, in that
480/// order, which is the move's shape. What goes is the mode itself, since the move has none.
481///
482/// A description where those two are not the same shape is one [`Changes`] turns down, and this
483/// reports a rewrite it turned down as not taken, which is how an address computation with more in
484/// its operand vector than the mode accounted for is left alone rather than guessed at.
485fn copied(
486    func: &mut mir::Func,
487    counts: &mut changes::Reads,
488    machine: &MachineInsts,
489    names: &Interner,
490    inst: mir::Inst,
491    opcode: mir::Opcode,
492) -> bool {
493    let mut set = Changes::new();
494    set.rewrite(inst, Plan { opcode, amode: None, ..Plan::of(func, inst) });
495    set.commit(func, counts, names, machine).is_ok()
496}
497
498/// Rewrites the move into the exclusive or, which names the one register the move wrote in every
499/// operand it has.
500///
501/// The shapes come from the description rather than from the move, since the shorter instruction is
502/// not the shape the longer one was: the exclusive or writes a register it also reads, which on this
503/// machine is an operand constrained to the same place as one of the reads, and a plan whose
504/// operands do not say so is one [`Changes`] turns down. So each operand is built to what the
505/// description asks for and the register in it is the one the move wrote, which after allocation is
506/// a physical register and so is a register every operand can name without anything being arranged.
507/// The constant goes with the move, the shorter instruction being the one that carries none.
508///
509/// A description whose operands are not all of the register's class, or which writes more than the
510/// one register or none, is a description this does not fit, and the answer there is to leave the
511/// instruction alone rather than to guess.
512fn zeroed(
513    func: &mut mir::Func,
514    counts: &mut changes::Reads,
515    machine: &MachineInsts,
516    names: &Interner,
517    inst: mir::Inst,
518    opcode: mir::Opcode,
519) -> bool {
520    let written: Vec<mir::Operand> = func[func[inst].operands]
521        .iter()
522        .filter(|operand| operand.role != Role::Use)
523        .copied()
524        .collect();
525    let [def] = written[..] else { return false };
526    let bare = machine.bare(names.resolve(opcode.name()));
527    let Some(desc) = (machine.operands)(bare) else { return false };
528    if desc.iter().any(|want| want.class != def.class) {
529        return false;
530    }
531    if desc.iter().filter(|want| want.role != Role::Use).count() != 1 {
532        return false;
533    }
534    let operands = desc
535        .iter()
536        .map(|want| mir::Operand {
537            reg: def.reg,
538            class: want.class,
539            role: want.role,
540            constraint: want.constraint,
541        })
542        .collect();
543    let mut set = Changes::new();
544    set.rewrite(inst, Plan { opcode, operands, imm: None, ..Plan::of(func, inst) });
545    set.commit(func, counts, names, machine).is_ok()
546}
547
548/// The shorter addition this one has, when it has one and the number it carries is the number that
549/// shorter instruction is about.
550///
551/// Both halves again, and the second one is doing more work here than anywhere else in this pass.
552/// One addition has two shorter instructions, one for each of the two numbers a machine has an
553/// opcode for, and a subtraction has the same two the other way round, so the number is what says
554/// which of the two is meant rather than only whether either is.
555fn stepped_form(
556    func: &mir::Func,
557    short: &ShortInsts,
558    names: &Interner,
559    opcodes: &[(&'static str, mir::Opcode)],
560    inst: mir::Inst,
561) -> Option<mir::Opcode> {
562    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
563    let into = short.stepped(name, func[func[inst].imm?].0)?;
564    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
565}
566
567/// Rewrites the addition into the one that carries its number in its opcode.
568///
569/// The operands are the ones it had, for the reason [`tested`] keeps them: both instructions write
570/// one register and read that same register, and what changes is the number, which the shorter one
571/// does not carry. So the constant goes and nothing else does.
572fn stepped(
573    func: &mut mir::Func,
574    counts: &mut changes::Reads,
575    machine: &MachineInsts,
576    names: &Interner,
577    inst: mir::Inst,
578    opcode: mir::Opcode,
579) -> bool {
580    let mut set = Changes::new();
581    set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
582    set.commit(func, counts, names, machine).is_ok()
583}
584
585/// The name this target knows an instruction by, for an instruction that is one of this target's.
586///
587/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
588/// compiled holds instructions of one machine and the prefix is what says which. Anything without
589/// it is not something this description covers, and the walk treats that as knowing nothing rather
590/// than as knowing it is safe.
591fn opcode<'a>(
592    func: &mir::Func,
593    flags: &FlagInsts,
594    names: &'a Interner,
595    inst: mir::Inst,
596) -> Option<&'a str> {
597    names.resolve(func[inst].opcode.name()).strip_prefix(flags.prefix)
598}
599
600#[cfg(test)]
601mod tests {
602    use rucc_target::x86_64::{FLAGS, GPR, MACHINE, SHORT};
603
604    use super::*;
605
606    /// A function with one block, and the names it was built with.
607    fn empty() -> (Interner, mir::Func, mir::Block) {
608        let mut names = Interner::new();
609        let mut func = mir::Func::new(names.intern("f"));
610        let block = func.create_block();
611        (names, func, block)
612    }
613
614    /// The opcode of that name on this target.
615    fn op(names: &mut Interner, name: &str) -> mir::Opcode {
616        mir::Opcode::new(names.intern(&format!("{}{name}", SHORT.prefix)))
617    }
618
619    /// The pass, over the machine this crate has a backend for, at a level that wanted fast code.
620    fn takes(func: &mut mir::Func, names: &mut Interner) -> usize {
621        shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Speed)
622    }
623
624    /// The same pass at a level that wanted small code, which is the only one that steps.
625    fn small(func: &mut mir::Func, names: &mut Interner) -> usize {
626        shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Size)
627    }
628
629    /// What every instruction in a block came to, as opcodes with the target's prefix taken off.
630    fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
631        func.insts(block)
632            .map(|inst| {
633                names
634                    .resolve(func[inst].opcode.name())
635                    .strip_prefix(SHORT.prefix)
636                    .unwrap_or("")
637                    .to_owned()
638            })
639            .collect()
640    }
641
642    /// The destination of a two-address instruction, which the description constrains to the same
643    /// register as the first source. The builder's own `def` leaves the constraint off, and the
644    /// change framework holds a rewrite to the shape the target asks for, so a test that built one
645    /// without it would be a test of a function the allocator could not have produced.
646    fn reuse(reg: mir::Reg) -> mir::Operand {
647        mir::Operand {
648            reg,
649            class: GPR,
650            role: Role::Def,
651            constraint: rucc_mir::Constraint::Reuse(1),
652        }
653    }
654
655    /// The registers an instruction names, in the order its operands do.
656    fn regs(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
657        func[func[inst].operands].iter().map(|operand| operand.reg).collect()
658    }
659
660    /// The number an instruction carries, for an instruction that carries one.
661    fn imm(func: &mir::Func, inst: mir::Inst) -> Option<i64> {
662        func[inst].imm.map(|at| func[at].0)
663    }
664
665    /// The shape the pass is for: a move of zero with nothing reading the condition state after it
666    /// becomes the exclusive or, which names the register it writes in all three of its operands and
667    /// carries no constant.
668    #[test]
669    fn a_move_of_zero_becomes_an_exclusive_or() {
670        let (mut names, mut func, block) = empty();
671        let into = func.new_vreg(GPR);
672        let zero = op(&mut names, "mov_ri_32");
673        let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
674
675        assert_eq!(takes(&mut func, &mut names), 1);
676        assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
677        assert_eq!(regs(&func, inst), [into, into, into]);
678        assert!(func[inst].imm.is_none());
679    }
680
681    /// Sixty-four bits is the same rewrite and the biggest one, since the long way of writing a zero
682    /// there is seven bytes. The instruction it becomes is the thirty-two bit one, which clears the
683    /// half of the register it does not write and so leaves the same sixty-four bit zero in one
684    /// byte less.
685    #[test]
686    fn sixty_four_bits_is_the_same_rewrite_at_half_the_width() {
687        let (mut names, mut func, block) = empty();
688        let into = func.new_vreg(GPR);
689        let zero = op(&mut names, "mov_ri_64");
690        func.build(block, zero).def(into, GPR).imm(0).finish();
691
692        assert_eq!(takes(&mut func, &mut names), 1);
693        assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
694    }
695
696    /// The other rewrite. A number that is not zero has nothing shorter than a move, and the move
697    /// that writes half the register is shorter than the one that writes all of it.
698    #[test]
699    fn a_number_a_narrower_move_holds_is_written_by_the_narrower_move() {
700        for value in [1, 7, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff] {
701            let (mut names, mut func, block) = empty();
702            let into = func.new_vreg(GPR);
703            let wide = op(&mut names, "mov_ri_64");
704            let inst = func.build(block, wide).def(into, GPR).imm(value).finish();
705
706            assert_eq!(takes(&mut func, &mut names), 1, "{value}");
707            assert_eq!(shape(&func, &names, block), ["mov_ri_32"], "{value}");
708            assert_eq!(imm(&func, inst), Some(value), "{value}");
709            assert_eq!(regs(&func, inst), [into], "{value}");
710        }
711    }
712
713    /// A number the narrower move does not hold, which is everything above what fits in the bits it
714    /// writes and every negative number, since what it does to the rest of the register is clear it
715    /// rather than fill it with the sign.
716    #[test]
717    fn a_number_the_narrower_move_does_not_hold_stays_wide() {
718        for value in [-1, -7, 0x1_0000_0000, i64::MIN, i64::MAX] {
719            let (mut names, mut func, block) = empty();
720            let into = func.new_vreg(GPR);
721            let wide = op(&mut names, "mov_ri_64");
722            func.build(block, wide).def(into, GPR).imm(value).finish();
723
724            assert_eq!(takes(&mut func, &mut names), 0, "{value}");
725            assert_eq!(shape(&func, &names, block), ["mov_ri_64"], "{value}");
726        }
727    }
728
729    /// A zero the condition state is not free for, which the first rewrite has to leave alone. The
730    /// second one has nothing to do with the state and takes it, so the instruction that stays is
731    /// five bytes rather than seven.
732    #[test]
733    fn a_zero_the_state_is_not_free_for_is_narrowed_instead() {
734        let (mut names, mut func, block) = empty();
735        let left = func.new_vreg(GPR);
736        let right = func.new_vreg(GPR);
737        let into = func.new_vreg(GPR);
738        let byte = func.new_vreg(GPR);
739        let cmp = op(&mut names, "cmp_rr_32");
740        let zero = op(&mut names, "mov_ri_64");
741        let set = op(&mut names, "set_e");
742        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
743        let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
744        func.build(block, set).def(byte, GPR).finish();
745
746        assert_eq!(takes(&mut func, &mut names), 1);
747        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
748        assert_eq!(imm(&func, inst), Some(0));
749    }
750
751    /// A function the state carried across an edge turns down, which is the first rewrite's rule
752    /// and not the second one's. The narrower move writes no state and reads none, so a function
753    /// that rule turns down still gets it.
754    #[test]
755    fn a_function_the_carried_state_turns_down_is_still_narrowed() {
756        let (mut names, mut func, first) = empty();
757        let second = func.create_block();
758        let into = func.new_vreg(GPR);
759        let byte = func.new_vreg(GPR);
760        let wide = op(&mut names, "mov_ri_64");
761        let set = op(&mut names, "set_e");
762        func.build(first, wide).def(into, GPR).imm(7).finish();
763        func.build(second, set).def(byte, GPR).finish();
764
765        assert_eq!(takes(&mut func, &mut names), 1);
766        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
767    }
768
769    /// A move of anything else. The shorter instruction writes zero, so it says the same thing only
770    /// where the longer one said zero.
771    #[test]
772    fn a_move_of_a_number_that_is_not_zero_stays() {
773        let (mut names, mut func, block) = empty();
774        let into = func.new_vreg(GPR);
775        let one = op(&mut names, "mov_ri_32");
776        func.build(block, one).def(into, GPR).imm(1).finish();
777
778        assert_eq!(takes(&mut func, &mut names), 0);
779        assert_eq!(shape(&func, &names, block), ["mov_ri_32"]);
780    }
781
782    /// Eight bits, where both spellings are two bytes. The target's table leaves it out and the pass
783    /// has nothing to look up, so the move stays and the condition state stays with it.
784    #[test]
785    fn eight_bits_buys_nothing_and_is_left_alone() {
786        let (mut names, mut func, block) = empty();
787        let into = func.new_vreg(GPR);
788        let zero = op(&mut names, "mov_ri_8");
789        func.build(block, zero).def(into, GPR).imm(0).finish();
790
791        assert_eq!(takes(&mut func, &mut names), 0);
792        assert_eq!(shape(&func, &names, block), ["mov_ri_8"]);
793    }
794
795    /// The cost of the rewrite, which is the zero going into a register in front of something that
796    /// reads a comparison of something else. The exclusive or would write over the answer the byte
797    /// is about, so the move stays.
798    #[test]
799    fn a_move_a_condition_reads_the_state_after_stays() {
800        let (mut names, mut func, block) = empty();
801        let left = func.new_vreg(GPR);
802        let right = func.new_vreg(GPR);
803        let into = func.new_vreg(GPR);
804        let byte = func.new_vreg(GPR);
805        let cmp = op(&mut names, "cmp_rr_32");
806        let zero = op(&mut names, "mov_ri_32");
807        let set = op(&mut names, "set_e");
808        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
809        func.build(block, zero).def(into, GPR).imm(0).finish();
810        func.build(block, set).def(byte, GPR).finish();
811
812        assert_eq!(takes(&mut func, &mut names), 0);
813        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
814    }
815
816    /// The same three instructions with something writing the condition state in between. What the
817    /// byte reads is what the addition left, so the state the move would write is one nothing was
818    /// going to read and the rewrite is back on.
819    #[test]
820    fn a_state_something_else_writes_first_lets_the_rewrite_back_in() {
821        let (mut names, mut func, block) = empty();
822        let left = func.new_vreg(GPR);
823        let right = func.new_vreg(GPR);
824        let sum = func.new_vreg(GPR);
825        let into = func.new_vreg(GPR);
826        let byte = func.new_vreg(GPR);
827        let zero = op(&mut names, "mov_ri_32");
828        let add = op(&mut names, "add_rr_32");
829        let set = op(&mut names, "set_e");
830        func.build(block, zero).def(into, GPR).imm(0).finish();
831        func.build(block, add).def(sum, GPR).uses(left, GPR).uses(right, GPR).finish();
832        func.build(block, set).def(byte, GPR).finish();
833
834        assert_eq!(takes(&mut func, &mut names), 1);
835        assert_eq!(shape(&func, &names, block), ["xor_rr_32", "add_rr_32", "set_e"]);
836    }
837
838    /// A function where a block reads the condition state before it writes one, which is what a
839    /// state carried across an edge looks like from here. The passes in front say that does not
840    /// happen and this is where that is held to rather than believed, so the whole function is
841    /// turned down and the move in the other block stays as well.
842    #[test]
843    fn a_state_carried_into_a_block_turns_the_whole_function_down() {
844        let (mut names, mut func, first) = empty();
845        let second = func.create_block();
846        let into = func.new_vreg(GPR);
847        let byte = func.new_vreg(GPR);
848        let zero = op(&mut names, "mov_ri_32");
849        let set = op(&mut names, "set_e");
850        func.build(first, zero).def(into, GPR).imm(0).finish();
851        func.build(second, set).def(byte, GPR).finish();
852
853        assert_eq!(takes(&mut func, &mut names), 0);
854        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
855    }
856
857    /// The third rewrite. A comparison of a register against zero asks whether the register is
858    /// zero, and so does a test of the register against itself, which says it without a number on
859    /// the instruction.
860    #[test]
861    fn a_comparison_against_zero_becomes_a_test_of_the_register_against_itself() {
862        for (wide, narrow) in [
863            ("cmp_ri_8", "test_rr_8"),
864            ("cmp_ri_16", "test_rr_16"),
865            ("cmp_ri_32", "test_rr_32"),
866            ("cmp_ri_64", "test_rr_64"),
867        ] {
868            let (mut names, mut func, block) = empty();
869            let value = func.new_vreg(GPR);
870            let byte = func.new_vreg(GPR);
871            let cmp = op(&mut names, wide);
872            let set = op(&mut names, "set_e");
873            let inst = func.build(block, cmp).uses(value, GPR).imm(0).finish();
874            func.build(block, set).def(byte, GPR).finish();
875
876            assert_eq!(takes(&mut func, &mut names), 1, "{wide}");
877            assert_eq!(shape(&func, &names, block), [narrow, "set_e"], "{wide}");
878            assert_eq!(regs(&func, inst), [value], "{wide}");
879            assert_eq!(imm(&func, inst), None, "{wide}");
880        }
881    }
882
883    /// A comparison against anything else, which the test cannot ask. What a test leaves is the
884    /// bits of the register it was given, so it answers one question and the question is zero.
885    #[test]
886    fn a_comparison_against_a_number_that_is_not_zero_is_left_alone() {
887        for value in [1, -1, 7, 255, i64::from(i32::MIN)] {
888            let (mut names, mut func, block) = empty();
889            let held = func.new_vreg(GPR);
890            let byte = func.new_vreg(GPR);
891            let cmp = op(&mut names, "cmp_ri_32");
892            let set = op(&mut names, "set_e");
893            let inst = func.build(block, cmp).uses(held, GPR).imm(value).finish();
894            func.build(block, set).def(byte, GPR).finish();
895
896            assert_eq!(takes(&mut func, &mut names), 0, "{value}");
897            assert_eq!(shape(&func, &names, block), ["cmp_ri_32", "set_e"], "{value}");
898            assert_eq!(imm(&func, inst), Some(value), "{value}");
899        }
900    }
901
902    /// The condition state is not a question this rewrite asks. The comparison writes the state and
903    /// the test writes the same state, so a comparison whose answer something reads right behind it
904    /// is rewritten exactly as one whose answer nothing wants is, and a function the carried state
905    /// rule turns down gets it too.
906    #[test]
907    fn a_comparison_is_tested_whatever_the_condition_state_is_doing() {
908        let (mut names, mut func, first) = empty();
909        let second = func.create_block();
910        let value = func.new_vreg(GPR);
911        let byte = func.new_vreg(GPR);
912        let cmp = op(&mut names, "cmp_ri_32");
913        let set = op(&mut names, "set_e");
914        func.build(first, cmp).uses(value, GPR).imm(0).finish();
915        // A block that reads the state before writing it, which is what `carried` turns a function
916        // down for and what the first rewrite is the only one to need.
917        func.build(second, set).def(byte, GPR).finish();
918
919        assert_eq!(takes(&mut func, &mut names), 1);
920        assert_eq!(shape(&func, &names, first), ["test_rr_32"]);
921        assert_eq!(shape(&func, &names, second), ["set_e"]);
922    }
923
924    /// The fourth rewrite, at every width and in both directions. An addition of one and a
925    /// subtraction of minus one are the instruction that adds one, and the other two are the one
926    /// that takes one away. The register is the one it had and the number is gone, the shorter
927    /// instruction being the one that carries the number in its opcode.
928    #[test]
929    fn adding_or_taking_away_one_becomes_the_instruction_that_says_so_in_its_opcode() {
930        for (name, by, into) in [
931            ("add_ri_8", 1, "inc_r_8"),
932            ("add_ri_16", 1, "inc_r_16"),
933            ("add_ri_32", 1, "inc_r_32"),
934            ("add_ri_64", 1, "inc_r_64"),
935            ("add_ri_8", -1, "dec_r_8"),
936            ("add_ri_16", -1, "dec_r_16"),
937            ("add_ri_32", -1, "dec_r_32"),
938            ("add_ri_64", -1, "dec_r_64"),
939            ("sub_ri_8", 1, "dec_r_8"),
940            ("sub_ri_16", 1, "dec_r_16"),
941            ("sub_ri_32", 1, "dec_r_32"),
942            ("sub_ri_64", 1, "dec_r_64"),
943            ("sub_ri_8", -1, "inc_r_8"),
944            ("sub_ri_16", -1, "inc_r_16"),
945            ("sub_ri_32", -1, "inc_r_32"),
946            ("sub_ri_64", -1, "inc_r_64"),
947        ] {
948            let (mut names, mut func, block) = empty();
949            let value = func.new_vreg(GPR);
950            let add = op(&mut names, name);
951            let inst =
952                func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
953
954            assert_eq!(small(&mut func, &mut names), 1, "{name} {by}");
955            assert_eq!(shape(&func, &names, block), [into], "{name} {by}");
956            assert_eq!(regs(&func, inst), [value, value], "{name} {by}");
957            assert_eq!(imm(&func, inst), None, "{name} {by}");
958        }
959    }
960
961    /// The same function at a level that asked for fast code, which is the goal doing its job. This
962    /// is the only rewrite in the pass that asks it, and it is the only one that is a trade.
963    #[test]
964    fn a_level_that_wanted_fast_code_keeps_the_addition() {
965        let (mut names, mut func, block) = empty();
966        let value = func.new_vreg(GPR);
967        let add = op(&mut names, "add_ri_32");
968        let inst = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
969
970        assert_eq!(takes(&mut func, &mut names), 0);
971        assert_eq!(shape(&func, &names, block), ["add_ri_32"]);
972        assert_eq!(imm(&func, inst), Some(1));
973    }
974
975    /// Any other number. The machine has an opcode that means one and none that means anything
976    /// else, so the constant is written out either way and the addition is already as short as it
977    /// gets.
978    #[test]
979    fn adding_anything_but_one_stays_an_addition() {
980        for by in [0, 2, -2, 7, 255, i64::from(i32::MIN)] {
981            let (mut names, mut func, block) = empty();
982            let value = func.new_vreg(GPR);
983            let add = op(&mut names, "add_ri_32");
984            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
985
986            assert_eq!(small(&mut func, &mut names), 0, "{by}");
987            assert_eq!(shape(&func, &names, block), ["add_ri_32"], "{by}");
988        }
989    }
990
991    /// What the rewrite is really conditional on. Something behind it reading where the value sits
992    /// as an unsigned number is something reading the carry, and the carry is the one part of the
993    /// condition state the shorter instruction does not write.
994    #[test]
995    fn an_addition_whose_carry_something_reads_stays_an_addition() {
996        for reader in ["set_b", "set_be", "set_a", "set_ae", "adc_ri_32"] {
997            let (mut names, mut func, block) = empty();
998            let value = func.new_vreg(GPR);
999            let byte = func.new_vreg(GPR);
1000            let add = op(&mut names, "add_ri_32");
1001            let reads = op(&mut names, reader);
1002            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1003            func.build(block, reads).def(byte, GPR).finish();
1004
1005            assert_eq!(small(&mut func, &mut names), 0, "{reader}");
1006            assert_eq!(shape(&func, &names, block), ["add_ri_32", reader], "{reader}");
1007        }
1008    }
1009
1010    /// A reader of any other part of the state, which the shorter instruction writes exactly as the
1011    /// addition did. So the rewrite is not about whether the state is read, it is about which part.
1012    #[test]
1013    fn an_addition_whose_zero_or_sign_something_reads_still_steps() {
1014        for reader in ["set_e", "set_ne", "set_l", "set_le", "set_g", "set_ge"] {
1015            let (mut names, mut func, block) = empty();
1016            let value = func.new_vreg(GPR);
1017            let byte = func.new_vreg(GPR);
1018            let add = op(&mut names, "add_ri_32");
1019            let reads = op(&mut names, reader);
1020            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1021            func.build(block, reads).def(byte, GPR).finish();
1022
1023            assert_eq!(small(&mut func, &mut names), 1, "{reader}");
1024            assert_eq!(shape(&func, &names, block), ["inc_r_32", reader], "{reader}");
1025        }
1026    }
1027
1028    /// The carry read behind an instruction that writes the rest of the state, which is what the
1029    /// walk asking the description rather than the flag is for. The addition in front of the
1030    /// comparison stays, because the comparison writes the carry the reader wants and the addition
1031    /// would not have to, and the addition behind it goes, because nothing reads a carry after it.
1032    #[test]
1033    fn a_write_of_the_state_ends_the_life_of_the_carry_and_a_step_does_not() {
1034        let (mut names, mut func, block) = empty();
1035        let value = func.new_vreg(GPR);
1036        let byte = func.new_vreg(GPR);
1037        let add = op(&mut names, "add_ri_32");
1038        let cmp = op(&mut names, "cmp_rr_32");
1039        let below = op(&mut names, "set_b");
1040        let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1041        func.build(block, cmp).uses(value, GPR).uses(value, GPR).finish();
1042        func.build(block, below).def(byte, GPR).finish();
1043
1044        assert_eq!(small(&mut func, &mut names), 1);
1045        assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_rr_32", "set_b"]);
1046        assert_eq!(imm(&func, first), None);
1047    }
1048
1049    /// An instruction that leaves the carry alone is not a write of the condition state as far as
1050    /// the walk is concerned, which is what stops one of them from hiding a carry read behind it.
1051    /// The increment here is one a program wrote in a template rather than one this put there, and
1052    /// the addition in front of it is the only thing that sets the carry the reader wants, so the
1053    /// addition stays.
1054    #[test]
1055    fn a_step_does_not_hide_the_carry_read_behind_it() {
1056        let (mut names, mut func, block) = empty();
1057        let value = func.new_vreg(GPR);
1058        let byte = func.new_vreg(GPR);
1059        let add = op(&mut names, "add_ri_32");
1060        let step = op(&mut names, "inc_r_32");
1061        let below = op(&mut names, "set_b");
1062        let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1063        func.build(block, step).operand(reuse(value)).uses(value, GPR).finish();
1064        func.build(block, below).def(byte, GPR).finish();
1065
1066        assert_eq!(small(&mut func, &mut names), 0);
1067        assert_eq!(shape(&func, &names, block), ["add_ri_32", "inc_r_32", "set_b"]);
1068        assert_eq!(imm(&func, first), Some(1));
1069    }
1070
1071    /// Two additions in a row with a carry read behind them. The second one sets the carry the
1072    /// reader wants and stays, and the first one goes, because whatever the first leaves the second
1073    /// writes over. That is the same walk as the test above arriving at the other answer, and it is
1074    /// what says the rule is about the carry rather than about the addition.
1075    #[test]
1076    fn an_addition_the_next_addition_writes_over_still_steps() {
1077        let (mut names, mut func, block) = empty();
1078        let value = func.new_vreg(GPR);
1079        let byte = func.new_vreg(GPR);
1080        let add = op(&mut names, "add_ri_32");
1081        let below = op(&mut names, "set_b");
1082        func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1083        let second = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1084        func.build(block, below).def(byte, GPR).finish();
1085
1086        assert_eq!(small(&mut func, &mut names), 1);
1087        assert_eq!(shape(&func, &names, block), ["inc_r_32", "add_ri_32", "set_b"]);
1088        assert_eq!(imm(&func, second), Some(1));
1089    }
1090
1091    /// The instruction the whole function check used to stop at. A comparison that keeps a byte
1092    /// reads the condition state and the state it reads is the one it wrote itself a moment
1093    /// earlier, so a block opening with one is not a block reading what a predecessor left, and the
1094    /// move in the other block is rewritten.
1095    #[test]
1096    fn a_block_opening_with_a_comparison_that_keeps_a_byte_is_not_a_carried_state() {
1097        let (mut names, mut func, first) = empty();
1098        let second = func.create_block();
1099        let into = func.new_vreg(GPR);
1100        let byte = func.new_vreg(GPR);
1101        let value = func.new_vreg(GPR);
1102        let zero = op(&mut names, "mov_ri_32");
1103        let fused = op(&mut names, "cmp_set_e_32");
1104        func.build(first, zero).def(into, GPR).imm(0).finish();
1105        func.build(second, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1106
1107        assert_eq!(takes(&mut func, &mut names), 1);
1108        assert_eq!(shape(&func, &names, first), ["xor_rr_32"]);
1109    }
1110
1111    /// The same with the comparison's operand in memory, which is the shape a loop reading an array
1112    /// and counting with tier six's `setcc` and `movzbl` comes out as. The comparison table leaves
1113    /// these out, and before the description named them apart this turned the function down.
1114    #[test]
1115    fn a_block_opening_with_a_comparison_against_memory_is_not_a_carried_state() {
1116        let (mut names, mut func, first) = empty();
1117        let second = func.create_block();
1118        let into = func.new_vreg(GPR);
1119        let byte = func.new_vreg(GPR);
1120        let value = func.new_vreg(GPR);
1121        let base = func.new_vreg(GPR);
1122        let zero = op(&mut names, "mov_ri_32");
1123        let fused = op(&mut names, "cmp_set_g_rm_32");
1124        func.build(first, zero).def(into, GPR).imm(0).finish();
1125        func.build(second, fused).def(byte, GPR).uses(value, GPR).uses(base, GPR).finish();
1126
1127        assert_eq!(takes(&mut func, &mut names), 1);
1128        assert_eq!(shape(&func, &names, first), ["xor_rr_32"]);
1129    }
1130
1131    /// The same sentence inside a block. What the comparison reads is what it wrote, so what it was
1132    /// handed is written over before anything looks at it, and the move in front of it may spend a
1133    /// state nothing wants.
1134    #[test]
1135    fn a_comparison_that_keeps_a_byte_ends_the_life_of_the_state() {
1136        let (mut names, mut func, block) = empty();
1137        let into = func.new_vreg(GPR);
1138        let byte = func.new_vreg(GPR);
1139        let value = func.new_vreg(GPR);
1140        let zero = op(&mut names, "mov_ri_32");
1141        let fused = op(&mut names, "cmp_set_e_32");
1142        func.build(block, zero).def(into, GPR).imm(0).finish();
1143        func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1144
1145        assert_eq!(takes(&mut func, &mut names), 1);
1146        assert_eq!(shape(&func, &names, block), ["xor_rr_32", "cmp_set_e_32"]);
1147    }
1148
1149    /// And the carry with it. A comparison that keeps a byte and asks where a value sits as an
1150    /// unsigned number reads the carry, and it is the carry it set itself, so the addition in front
1151    /// of it is free to become the instruction that leaves the carry alone.
1152    #[test]
1153    fn a_comparison_that_keeps_a_byte_does_not_keep_the_carry_alive() {
1154        let (mut names, mut func, block) = empty();
1155        let value = func.new_vreg(GPR);
1156        let byte = func.new_vreg(GPR);
1157        let add = op(&mut names, "add_ri_32");
1158        let fused = op(&mut names, "cmp_set_b_32");
1159        func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1160        func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1161
1162        assert_eq!(small(&mut func, &mut names), 1);
1163        assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_set_b_32"]);
1164    }
1165
1166    /// The other kind of read, which is the one this must go on stopping at. An add with carry is
1167    /// reading the bit the instruction in front of it left rather than one it wrote itself, and it
1168    /// makes no comparison, which is how the description tells the two apart.
1169    #[test]
1170    fn an_add_with_carry_opening_a_block_is_still_a_carried_state() {
1171        let (mut names, mut func, first) = empty();
1172        let second = func.create_block();
1173        let into = func.new_vreg(GPR);
1174        let value = func.new_vreg(GPR);
1175        let zero = op(&mut names, "mov_ri_32");
1176        let adc = op(&mut names, "adc_ri_32");
1177        func.build(first, zero).def(into, GPR).imm(0).finish();
1178        func.build(second, adc).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1179
1180        assert_eq!(takes(&mut func, &mut names), 0);
1181        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
1182    }
1183
1184    /// A name the description does not cover, which is anything without this target's prefix. It
1185    /// may read the condition state and it may write one, and the answer that is wrong about
1186    /// nothing is that it read it, so the move in front of it stays.
1187    #[test]
1188    fn a_name_this_target_does_not_know_stops_the_walk() {
1189        let (mut names, mut func, block) = empty();
1190        let left = func.new_vreg(GPR);
1191        let right = func.new_vreg(GPR);
1192        let into = func.new_vreg(GPR);
1193        let cmp = op(&mut names, "cmp_rr_32");
1194        let zero = op(&mut names, "mov_ri_32");
1195        let strange = mir::Opcode::new(names.intern("nowhere.thing"));
1196        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1197        func.build(block, zero).def(into, GPR).imm(0).finish();
1198        func.build(block, strange).finish();
1199
1200        assert_eq!(takes(&mut func, &mut names), 0);
1201        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", ""]);
1202    }
1203
1204    /// The fifth rewrite. An address that is a base register and nothing else is that register, so
1205    /// the instruction that works it out and keeps it is the move, which keeps both registers in the
1206    /// order it had them and drops the addressing mode it no longer has a place for.
1207    #[test]
1208    fn an_address_that_is_a_register_becomes_a_move() {
1209        let (mut names, mut func, block) = empty();
1210        let base = func.new_vreg(GPR);
1211        let into = func.new_vreg(GPR);
1212        let lea = op(&mut names, "lea_64");
1213        let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1214        let inst = func.build(block, lea).def(into, GPR).mem(mem).finish();
1215
1216        assert_eq!(takes(&mut func, &mut names), 1);
1217        assert_eq!(shape(&func, &names, block), ["mov_rr_64"]);
1218        assert_eq!(regs(&func, inst), [into, base]);
1219        assert!(func[inst].mem.is_none());
1220    }
1221
1222    /// A constant added to the address, which is the shape most address computations have. The move
1223    /// adds nothing, so there is nothing here for it to say.
1224    #[test]
1225    fn an_address_with_a_constant_added_stays() {
1226        let (mut names, mut func, block) = empty();
1227        let base = func.new_vreg(GPR);
1228        let into = func.new_vreg(GPR);
1229        let lea = op(&mut names, "lea_64");
1230        let mem = mir::Mem { disp: 8, ..mir::Mem::at(mir::Operand::read(base, GPR)) };
1231        func.build(block, lea).def(into, GPR).mem(mem).finish();
1232
1233        assert_eq!(takes(&mut func, &mut names), 0);
1234        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1235    }
1236
1237    /// An index, which is the other half of what an address computation is for. It is a
1238    /// multiplication and an addition and the move is neither.
1239    #[test]
1240    fn an_address_with_an_index_stays() {
1241        let (mut names, mut func, block) = empty();
1242        let base = func.new_vreg(GPR);
1243        let index = func.new_vreg(GPR);
1244        let into = func.new_vreg(GPR);
1245        let lea = op(&mut names, "lea_64");
1246        let mem = mir::Mem {
1247            index: Some(mir::Operand::read(index, GPR)),
1248            scale: 4,
1249            ..mir::Mem::at(mir::Operand::read(base, GPR))
1250        };
1251        func.build(block, lea).def(into, GPR).mem(mem).finish();
1252
1253        assert_eq!(takes(&mut func, &mut names), 0);
1254        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1255    }
1256
1257    /// The address of a global, which names no register at all. What it works out is a number the
1258    /// assembler fills in rather than a number that is already somewhere, so there is nothing for a
1259    /// move to move.
1260    #[test]
1261    fn an_address_of_a_symbol_stays() {
1262        let (mut names, mut func, block) = empty();
1263        let into = func.new_vreg(GPR);
1264        let lea = op(&mut names, "lea_64");
1265        let mem = mir::Mem::of(names.intern("table"));
1266        func.build(block, lea).def(into, GPR).mem(mem).finish();
1267
1268        assert_eq!(takes(&mut func, &mut names), 0);
1269        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1270    }
1271
1272    /// And it does not wait on the condition state. Neither the address computation nor the move
1273    /// writes any, so a byte reading a comparison from in front of it reads the same comparison
1274    /// afterwards, and the rewrite is taken in the one function the first rewrite has to turn down.
1275    #[test]
1276    fn an_address_is_copied_whatever_the_state_behind_it_is() {
1277        let (mut names, mut func, block) = empty();
1278        let left = func.new_vreg(GPR);
1279        let right = func.new_vreg(GPR);
1280        let base = func.new_vreg(GPR);
1281        let into = func.new_vreg(GPR);
1282        let byte = func.new_vreg(GPR);
1283        let cmp = op(&mut names, "cmp_rr_32");
1284        let lea = op(&mut names, "lea_64");
1285        let set = op(&mut names, "set_e");
1286        let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1287        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1288        func.build(block, lea).def(into, GPR).mem(mem).finish();
1289        func.build(block, set).def(byte, GPR).finish();
1290
1291        assert_eq!(takes(&mut func, &mut names), 1);
1292        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_rr_64", "set_e"]);
1293    }
1294}