rucc_codegen/compare.rs
1//! Taking out a comparison the machine has already made.
2//!
3//! Design: `spec/optimizer/37-machine-level-optimization.md` section 37.4.
4//!
5//! A comparison produces no value. It sets a few bits nobody named and the instruction behind it
6//! reads them, so a comparison that sets the bits that are already there is one nothing could tell
7//! had run. There are two ways for that to happen, and both of them are about an instruction a
8//! little way in front rather than about a dataflow the whole function takes part in.
9//!
10//! The same comparison twice. `if (x == y) ... else if (x != y)` and every expression that asks a
11//! question and then asks its negation come out as two comparisons of the same two registers with
12//! nothing between them but the bytes each one kept. The second asks what the first asked and the
13//! answer has not moved.
14//!
15//! A comparison against zero of something arithmetic has just worked out. `if (a & MASK)` is an
16//! `and` and then a comparison of its result against zero, and the `and` set the bits that
17//! comparison would have set on its way past. This is the common one by a long way: at `-O2` over
18//! the SQLite amalgamation there are 2250 of these and 0 of the other shape.
19//!
20//! # Why it runs after the layout rather than before
21//!
22//! Because this is the second pass to work on a pair of instructions whose middle has to stay
23//! empty, and the first is the block layout. A branch on a comparison is written there as the
24//! comparison with its byte taken off and a jump that reads the condition state, and what is
25//! between those two is live and is not a register, so anything that ran afterwards and put an
26//! instruction between them would be wrong. Running last is the whole of what makes this safe,
27//! which is the sentence section 37.4 uses about the layout itself.
28//!
29//! It also makes the two shapes one shape. A comparison the layout folded a branch into is a
30//! comparison that keeps nothing, one whose byte something else wanted is a comparison that keeps
31//! a byte, and after the layout both are sitting in a block to be looked at the same way. Before
32//! the layout the first kind does not exist yet, so a pass that ran earlier would have to either
33//! leave every branch alone or undo the fusion to get at one.
34//!
35//! # How the rewrite is made
36//!
37//! Through [`crate::changes`], one comparison at a time, because one comparison is all a change
38//! here is: a comparison that is already made is already made whatever happened to the one in
39//! front of it, so there is nothing to be all of or none of.
40//!
41//! What the framework is for here is the other half of it, which is the shape. What is left of a
42//! comparison is a different instruction with a different name and one operand rather than three,
43//! and that it is an instruction this machine has is now asked rather than believed. The condition
44//! state is the half nothing can check, because it is not a register and is in no operand vector,
45//! and the argument that the bits are already the bits stays the walk's own.
46//!
47//! # What a block boundary is
48//!
49//! The end of everything this knows. The state a comparison leaves is not a register and nothing
50//! in this back end carries one from a block to its successors: the layout writes the jump that
51//! reads a comparison into the same block as the comparison, which is the only place one is read
52//! at all. So the walk starts each block knowing nothing, which is what makes it a walk rather
53//! than a dataflow.
54//!
55//! # What it will not do
56//!
57//! A comparison with anything between it and the instruction that already made it that writes the
58//! condition state. The target says which instructions those are and says it about every name it
59//! does not recognise, so an opcode added to a rule set and not to that description makes this
60//! find less rather than making it wrong.
61//!
62//! A comparison of a register something wrote in between. The bits are still the bits the earlier
63//! instruction left, but they are about what the register held then and the comparison is about
64//! what it holds now. Every definition between the two is checked against the registers the
65//! earlier one was about, which are physical by the time this runs and so are the ones the machine
66//! will really read.
67//!
68//! A comparison against zero after arithmetic whose condition reads a part of the condition state
69//! the arithmetic did not leave the way a comparison would have. `subl` says whether its answer
70//! was zero and a comparison of that answer against zero would agree, and it says whether the
71//! subtraction overflowed where the comparison would have said it did not, so a signed `<` after
72//! one reads a sign and an overflow that no longer belong together. [`rucc_target::Zeroing`] is
73//! where each instruction says which conditions it is good for, and every condition that ends up
74//! reading what the arithmetic left has to be one of them, including the ones behind the
75//! comparison rather than on it.
76//!
77//! A comparison against zero after arithmetic that wrote a different number of bits. `andl` leaves
78//! a statement about thirty two bits and `cmpq $0` asks about sixty four, and on this machine the
79//! upper half is then zero and the two disagree about the sign.
80//!
81//! A comparison against zero after arithmetic whose condition state nothing is found to read. That
82//! is a comparison that is dead rather than redundant, and taking a dead one out is a different
83//! question: it needs no earlier instruction at all, so answering it here would mean answering it
84//! only where an earlier instruction happened to be.
85
86use std::collections::HashMap;
87
88use rucc_base::Interner;
89use rucc_mir::{self as mir, Role};
90use rucc_target::{Compare, FlagInsts, MachineInsts, Reads, RegClass, Zeroing};
91
92use crate::changes::{self, Changes, Plan};
93
94/// A register, and the file it is drawn from.
95///
96/// The class as well as the number, because the two files number from zero and `xmm0` is not
97/// `rax`. The width is deliberately not here: `%al` and `%eax` are one register, so a write of
98/// either is a write of the other and a statement about what the other held is a statement about
99/// a value that has moved.
100type Place = (RegClass, mir::Reg);
101
102/// Takes out every comparison whose condition state the instruction in front of it already left.
103///
104/// Gives back how many went, which the tests read and nothing else does.
105pub fn redundant(
106 func: &mut mir::Func,
107 insts: &FlagInsts,
108 machine: &MachineInsts,
109 names: &mut Interner,
110) -> usize {
111 // Every name the rewrite could want, before the walk rather than inside it. The walk holds a
112 // name it read out of the interner while it edits the function, and interning a new one there
113 // would be the same interner borrowed twice.
114 let opcodes: HashMap<&str, mir::Opcode> = insts
115 .compares
116 .iter()
117 .filter_map(|entry| entry.kept)
118 .map(|kept| (kept, mir::Opcode::new(names.intern(&format!("{}{kept}", insts.prefix)))))
119 .collect();
120 let names = &*names;
121 let mut counts = changes::Reads::of(func);
122 let mut gone = 0;
123 let mut seen = HashMap::new();
124 for block in func.blocks().collect::<Vec<_>>() {
125 let sequence: Vec<mir::Inst> = func.insts(block).collect();
126 let mut left: Option<Left> = None;
127 for at in 0..sequence.len() {
128 let inst = sequence[at];
129 let does = *seen
130 .entry(func[inst].opcode)
131 .or_insert_with(|| Does::of(insts, opcode(func, insts, names, inst)));
132 left = match does {
133 Does::Unknown => None,
134 Does::Compares(entry) => {
135 let already = left
136 .as_ref()
137 .is_some_and(|had| had.answers(func, insts, names, &sequence, at, entry));
138 // What the earlier instruction left comes to this one's answer, and it is
139 // worked out here rather than after the rewrite because one of the answers to
140 // what is left of an instruction is that there is nothing left of it.
141 let after = stale(func, inst, left);
142 if already && took(func, &opcodes, &mut counts, machine, names, inst, entry) {
143 gone += 1;
144 after
145 } else {
146 // Either the comparison is one nothing has made yet or it is one the
147 // target would not have what is left of, and both of those are a
148 // comparison that runs and leaves its own answer behind.
149 stale(func, inst, Some(Left::made(func, entry, inst)))
150 }
151 }
152 Does::Zeroes(name, zeroing) => Left::zeroed(func, insts, name, zeroing, inst),
153 Does::Writes => None,
154 Does::Neither => stale(func, inst, left),
155 };
156 }
157 }
158 gone
159}
160
161/// What the description says an opcode does to the condition state.
162///
163/// Asked once for each opcode a function has rather than once for each instruction, since each
164/// question is a walk down one of the target's tables comparing names and nearly every answer is
165/// no. A function has a few hundred opcodes at most, so the walk asks about each the first time it
166/// turns up and reads the answer back after that.
167#[derive(Debug, Clone, Copy)]
168enum Does<'a> {
169 /// The description does not cover it, so it may have done anything.
170 Unknown,
171 /// It makes a comparison.
172 Compares(&'static Compare),
173 /// It is arithmetic that leaves the comparison of what it wrote against zero. Asked before
174 /// whether it writes the condition state, because every one of these does and this is what it
175 /// wrote there.
176 Zeroes(&'a str, &'static Zeroing),
177 /// It writes the condition state with nothing this pass can use.
178 Writes,
179 /// It leaves the condition state alone.
180 Neither,
181}
182
183impl<'a> Does<'a> {
184 fn of(insts: &FlagInsts, name: Option<&'a str>) -> Self {
185 let Some(name) = name else { return Self::Unknown };
186 if let Some(entry) = insts.compare(name) {
187 Self::Compares(entry)
188 } else if let Some(zeroing) = insts.zeroed(name) {
189 Self::Zeroes(name, zeroing)
190 } else if (insts.writes)(name) {
191 Self::Writes
192 } else {
193 Self::Neither
194 }
195 }
196}
197
198/// What the condition state holds, and which registers it is a statement about.
199struct Left {
200 /// Which of the two ways it got there.
201 how: How,
202 /// The registers the statement is about, which anything writing one of makes it stale.
203 about: Vec<Place>,
204}
205
206/// The two ways the condition state comes to hold something this pass can use.
207enum How {
208 /// A comparison made it, and this is the question it asked.
209 Made {
210 /// The name of the comparison that keeps nothing, which is what says two are the same.
211 asks: &'static str,
212 /// What it compared, in the order it read them.
213 read: Vec<Place>,
214 /// The constant it compared against, if it compared against one.
215 imm: Option<i64>,
216 },
217 /// Arithmetic left it, and this is what a comparison against zero has to look like to be one
218 /// the arithmetic already made.
219 Zeroed {
220 /// How wide the value it wrote is.
221 width: u32,
222 /// Which conditions may read what it left.
223 covers: Zeroing,
224 },
225}
226
227impl Left {
228 /// What a comparison leaves behind.
229 fn made(func: &mir::Func, entry: &Compare, inst: mir::Inst) -> Self {
230 let read: Vec<Place> = reads(func, inst).into_iter().map(|(_, place)| place).collect();
231 Self {
232 how: How::Made {
233 asks: entry.asks,
234 read: read.clone(),
235 imm: func[inst].imm.map(|at| func[at].0),
236 },
237 about: read,
238 }
239 }
240
241 /// What arithmetic leaves behind, when what it wrote is one register of a width the
242 /// description names.
243 ///
244 /// The statement is about the register it wrote rather than about the ones it read, which is
245 /// what makes its own definition not something that makes it stale: what it wrote is the value
246 /// the comparison it stands in for is about.
247 fn zeroed(
248 func: &mir::Func,
249 insts: &FlagInsts,
250 name: &str,
251 zeroing: &Zeroing,
252 inst: mir::Inst,
253 ) -> Option<Self> {
254 let written = writes(func, inst);
255 let [(at, def)] = written[..] else { return None };
256 let width = (insts.width)(name, at)?;
257 Some(Self { how: How::Zeroed { width, covers: *zeroing }, about: vec![def] })
258 }
259
260 /// Whether this comparison is one the condition state already answers.
261 fn answers(
262 &self,
263 func: &mir::Func,
264 insts: &FlagInsts,
265 names: &Interner,
266 sequence: &[mir::Inst],
267 at: usize,
268 entry: &Compare,
269 ) -> bool {
270 let inst = sequence[at];
271 let asked: Vec<Place> = reads(func, inst).into_iter().map(|(_, place)| place).collect();
272 let against = func[inst].imm.map(|at| func[at].0);
273 match &self.how {
274 // The same question about the same values, so every bit of the answer is the bit that
275 // is already there and what reads it is not something anyone has to ask.
276 How::Made { asks, read, imm } => {
277 *asks == entry.asks && *read == asked && *imm == against
278 }
279 How::Zeroed { width, covers } => {
280 if against != Some(0) || self.about != asked {
281 return false;
282 }
283 let [(index, _)] = reads(func, inst)[..] else { return false };
284 let Some(name) = opcode(func, insts, names, inst) else { return false };
285 if (insts.width)(name, index) != Some(*width) {
286 return false;
287 }
288 let conditions = conditions(func, insts, names, sequence, at);
289 !conditions.is_empty() && conditions.iter().all(|&reads| covers.covers(reads))
290 }
291 }
292 }
293}
294
295/// The conditions that read what an instruction leaves in the condition state.
296///
297/// Its own first, which is where a comparison that keeps a byte carries the condition it is about,
298/// and then the ones behind it as far as whatever writes the condition state next. Both halves
299/// matter and for one reason: the rewrite leaves the readers where they are and takes the
300/// comparison out from under them, so each of them ends up reading what the instruction further
301/// back left instead.
302fn conditions(
303 func: &mir::Func,
304 insts: &FlagInsts,
305 names: &Interner,
306 sequence: &[mir::Inst],
307 at: usize,
308) -> Vec<Reads> {
309 let mut found = Vec::new();
310 let Some(name) = opcode(func, insts, names, sequence[at]) else { return found };
311 found.extend(insts.reads(name));
312 for &inst in &sequence[at + 1..] {
313 let Some(name) = opcode(func, insts, names, inst) else { break };
314 // What it reads before whether it writes, because an instruction can do both and the read
315 // it does is a read of what is there now. An add with carry is the one that does, and
316 // asking the questions the other way round would count it as the end of the walk and never
317 // count the carry it took off the comparison this is about to remove.
318 found.extend(insts.reads(name));
319 if (insts.writes)(name) {
320 break;
321 }
322 }
323 found
324}
325
326/// The same state, unless the instruction wrote a register it was a statement about.
327fn stale(func: &mir::Func, inst: mir::Inst, left: Option<Left>) -> Option<Left> {
328 let left = left?;
329 let touched = writes(func, inst).iter().any(|&(_, place)| left.about.contains(&place));
330 (!touched).then_some(left)
331}
332
333/// The registers an instruction reads, each with the index it reads it at.
334fn reads(func: &mir::Func, inst: mir::Inst) -> Vec<(u8, Place)> {
335 picked(func, inst, Role::Use)
336}
337
338/// The registers an instruction writes, each with the index it writes it at.
339fn writes(func: &mir::Func, inst: mir::Inst) -> Vec<(u8, Place)> {
340 let mut found = picked(func, inst, Role::Def);
341 found.extend(picked(func, inst, Role::EarlyDef));
342 found
343}
344
345/// The operands in that role, each with the index it is at.
346fn picked(func: &mir::Func, inst: mir::Inst, role: Role) -> Vec<(u8, Place)> {
347 func[func[inst].operands]
348 .iter()
349 .enumerate()
350 .filter(|(_, operand)| operand.role == role)
351 .filter_map(|(at, operand)| Some((u8::try_from(at).ok()?, (operand.class, operand.reg))))
352 .collect()
353}
354
355/// Turns a comparison into what is left of it, which is a byte or nothing at all, and says whether
356/// that was a change the target had.
357///
358/// The byte keeps the register it was going to and the constant goes, because what the constant
359/// was for was the comparison and the comparison is the part that is not happening. Nothing else
360/// about the instruction moves, which is what keeps this a rewrite of one instruction rather than
361/// a rewrite of the block around it.
362///
363/// One change is one set, since a comparison that is already made is already made whatever the one
364/// before it came to. What the set is for here is the other half of [`crate::changes`], which is
365/// the shape: the instruction the byte is left as is one this target has to have, and this is where
366/// that is asked rather than believed.
367fn took(
368 func: &mut mir::Func,
369 opcodes: &HashMap<&str, mir::Opcode>,
370 counts: &mut changes::Reads,
371 machine: &MachineInsts,
372 names: &Interner,
373 inst: mir::Inst,
374 entry: &Compare,
375) -> bool {
376 let mut set = Changes::new();
377 match entry.kept {
378 None => set.remove(inst),
379 Some(kept) => {
380 let Some(&opcode) = opcodes.get(kept) else { return false };
381 let byte: Vec<mir::Operand> = func[func[inst].operands]
382 .iter()
383 .filter(|operand| operand.role != Role::Use)
384 .copied()
385 .collect();
386 set.rewrite(inst, Plan { opcode, operands: byte, imm: None, ..Plan::of(func, inst) });
387 }
388 }
389 set.commit(func, counts, names, machine).is_ok()
390}
391
392/// The name this target knows an instruction by, for an instruction that is one of this target's.
393///
394/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
395/// compiled holds instructions of one machine and the prefix is what says which. Anything without
396/// it is not something this description covers, and the rest of the pass treats that as knowing
397/// nothing rather than as knowing it is safe.
398fn opcode<'a>(
399 func: &mir::Func,
400 insts: &FlagInsts,
401 names: &'a Interner,
402 inst: mir::Inst,
403) -> Option<&'a str> {
404 names.resolve(func[inst].opcode.name()).strip_prefix(insts.prefix)
405}
406
407#[cfg(test)]
408mod tests {
409 use rucc_target::x86_64::{FLAGS, GPR, MACHINE};
410
411 use super::*;
412
413 /// A function with one block, and the names it was built with.
414 fn empty() -> (Interner, mir::Func, mir::Block) {
415 let mut names = Interner::new();
416 let mut func = mir::Func::new(names.intern("f"));
417 let block = func.create_block();
418 (names, func, block)
419 }
420
421 /// The opcode of that name on this target.
422 fn op(names: &mut Interner, name: &str) -> mir::Opcode {
423 mir::Opcode::new(names.intern(&format!("{}{name}", FLAGS.prefix)))
424 }
425
426 /// The pass, over the machine this crate has a backend for.
427 fn takes(func: &mut mir::Func, names: &mut Interner) -> usize {
428 redundant(func, &FLAGS, &MACHINE, names)
429 }
430
431 /// What every instruction in a block came to, as opcodes with the target's prefix taken off.
432 fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
433 func.insts(block)
434 .map(|inst| {
435 names
436 .resolve(func[inst].opcode.name())
437 .strip_prefix(FLAGS.prefix)
438 .unwrap_or("")
439 .to_owned()
440 })
441 .collect()
442 }
443
444 /// The shape the issue is named after: the same comparison made twice with nothing between the
445 /// two but the byte the first one kept. The second asks what the first asked, so what is left
446 /// of it is the byte alone.
447 #[test]
448 fn the_same_comparison_twice_leaves_one_comparison_and_two_bytes() {
449 let (mut names, mut func, block) = empty();
450 let value = func.new_vreg(GPR);
451 let first = func.new_vreg(GPR);
452 let second = func.new_vreg(GPR);
453 let ne = op(&mut names, "cmp_set_ne_ri_32");
454 let e = op(&mut names, "cmp_set_e_ri_32");
455 func.build(block, ne).def(first, GPR).uses(value, GPR).imm(0).finish();
456 func.build(block, e).def(second, GPR).uses(value, GPR).imm(0).finish();
457
458 assert_eq!(takes(&mut func, &mut names), 1);
459 assert_eq!(shape(&func, &names, block), ["cmp_set_ne_ri_32", "set_e"]);
460 }
461
462 /// The same two comparisons with something writing the compared register in between. The bits
463 /// are the bits the first one left and they are about a value that has moved on.
464 #[test]
465 fn a_comparison_of_a_register_something_wrote_in_between_stays() {
466 let (mut names, mut func, block) = empty();
467 let value = func.new_vreg(GPR);
468 let other = func.new_vreg(GPR);
469 let first = func.new_vreg(GPR);
470 let second = func.new_vreg(GPR);
471 let ne = op(&mut names, "cmp_set_ne_ri_32");
472 let e = op(&mut names, "cmp_set_e_ri_32");
473 let copy = op(&mut names, "mov_rr_64");
474 func.build(block, ne).def(first, GPR).uses(value, GPR).imm(0).finish();
475 func.build(block, copy).def(value, GPR).uses(other, GPR).finish();
476 func.build(block, e).def(second, GPR).uses(value, GPR).imm(0).finish();
477
478 assert_eq!(takes(&mut func, &mut names), 0);
479 assert_eq!(shape(&func, &names, block).len(), 3);
480 }
481
482 /// The common shape, which is `if (a & MASK)`. The `and` clears the carry and the overflow and
483 /// sets the zero and the sign from what it wrote, which is every bit the comparison would have
484 /// set and the same values, so every condition may read it.
485 #[test]
486 fn a_comparison_against_zero_after_a_bitwise_operation_goes() {
487 for condition in ["e", "l", "b"] {
488 let (mut names, mut func, block) = empty();
489 let value = func.new_vreg(GPR);
490 let byte = func.new_vreg(GPR);
491 let and = op(&mut names, "and_ri_32");
492 let cmp = op(&mut names, &format!("cmp_set_{condition}_ri_32"));
493 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
494 func.build(block, cmp).def(byte, GPR).uses(value, GPR).imm(0).finish();
495
496 assert_eq!(takes(&mut func, &mut names), 1, "set{condition}");
497 assert_eq!(
498 shape(&func, &names, block),
499 ["and_ri_32".to_owned(), format!("set_{condition}")]
500 );
501 }
502 }
503
504 /// The same after a subtraction, which is the one that is only half true. The zero bit is what
505 /// a comparison of the answer against zero would have set it to, and the overflow is not, so
506 /// the conditions built out of the sign and the overflow together have to stay.
507 #[test]
508 fn a_comparison_against_zero_after_a_subtraction_goes_only_for_the_zero_conditions() {
509 for (condition, left) in [("e", 1), ("ne", 1), ("l", 0), ("ge", 0), ("a", 0)] {
510 let (mut names, mut func, block) = empty();
511 let value = func.new_vreg(GPR);
512 let other = func.new_vreg(GPR);
513 let byte = func.new_vreg(GPR);
514 let sub = op(&mut names, "sub_rr_32");
515 let cmp = op(&mut names, &format!("cmp_set_{condition}_ri_32"));
516 func.build(block, sub).def(value, GPR).uses(value, GPR).uses(other, GPR).finish();
517 func.build(block, cmp).def(byte, GPR).uses(value, GPR).imm(0).finish();
518
519 assert_eq!(takes(&mut func, &mut names), left, "set{condition}");
520 }
521 }
522
523 /// A comparison the layout already folded a branch into, which keeps no byte at all. There is
524 /// nothing left of one of those, and the jump behind it reads what the `and` left.
525 #[test]
526 fn a_comparison_that_keeps_nothing_is_taken_out_and_the_jump_reads_what_is_there() {
527 let (mut names, mut func, block) = empty();
528 let value = func.new_vreg(GPR);
529 let and = op(&mut names, "and_ri_32");
530 let cmp = op(&mut names, "cmp_ri_32");
531 let jump = op(&mut names, "jcc_l");
532 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
533 func.build(block, cmp).uses(value, GPR).imm(0).finish();
534 func.build(block, jump).finish();
535
536 assert_eq!(takes(&mut func, &mut names), 1);
537 assert_eq!(shape(&func, &names, block), ["and_ri_32", "jcc_l"]);
538 }
539
540 /// The same three instructions with a subtraction in front. The condition is behind the
541 /// comparison rather than on it, so finding it means looking at what reads what the comparison
542 /// would have left, and a signed `<` is not something a subtraction answers.
543 #[test]
544 fn a_comparison_that_keeps_nothing_is_refused_on_the_condition_behind_it() {
545 let (mut names, mut func, block) = empty();
546 let value = func.new_vreg(GPR);
547 let other = func.new_vreg(GPR);
548 let sub = op(&mut names, "sub_rr_32");
549 let cmp = op(&mut names, "cmp_ri_32");
550 let jump = op(&mut names, "jcc_l");
551 func.build(block, sub).def(value, GPR).uses(value, GPR).uses(other, GPR).finish();
552 func.build(block, cmp).uses(value, GPR).imm(0).finish();
553 func.build(block, jump).finish();
554
555 assert_eq!(takes(&mut func, &mut names), 0);
556 assert_eq!(shape(&func, &names, block).len(), 3);
557 }
558
559 /// Arithmetic that wrote half of what the comparison is asking about. The upper half is zero
560 /// because this machine writes it that way, so the two agree about whether the value is zero
561 /// and disagree about its sign, and the description has no way to say half of one condition.
562 #[test]
563 fn a_comparison_wider_than_the_arithmetic_in_front_of_it_stays() {
564 let (mut names, mut func, block) = empty();
565 let value = func.new_vreg(GPR);
566 let byte = func.new_vreg(GPR);
567 let and = op(&mut names, "and_ri_32");
568 let cmp = op(&mut names, "cmp_set_e_ri_64");
569 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
570 func.build(block, cmp).def(byte, GPR).uses(value, GPR).imm(0).finish();
571
572 assert_eq!(takes(&mut func, &mut names), 0);
573 assert_eq!(shape(&func, &names, block).len(), 2);
574 }
575
576 /// Something between the two that writes the condition state. A multiply is not in the
577 /// description's list because this machine leaves the zero bit undefined after one, so what it
578 /// left is not something to read and not something to reason from either.
579 #[test]
580 fn anything_that_writes_the_condition_state_in_between_makes_the_comparison_stay() {
581 let (mut names, mut func, block) = empty();
582 let value = func.new_vreg(GPR);
583 let other = func.new_vreg(GPR);
584 let byte = func.new_vreg(GPR);
585 let and = op(&mut names, "and_ri_32");
586 let mul = op(&mut names, "imul_rr_32");
587 let cmp = op(&mut names, "cmp_set_e_ri_32");
588 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
589 func.build(block, mul).def(other, GPR).uses(other, GPR).uses(other, GPR).finish();
590 func.build(block, cmp).def(byte, GPR).uses(value, GPR).imm(0).finish();
591
592 assert_eq!(takes(&mut func, &mut names), 0);
593 assert_eq!(shape(&func, &names, block).len(), 3);
594 }
595
596 /// A comparison that keeps nothing and whose condition state nothing is found to read. It is
597 /// dead rather than redundant, and this pass is not the one that answers that.
598 #[test]
599 fn a_comparison_nothing_is_found_to_read_stays() {
600 let (mut names, mut func, block) = empty();
601 let value = func.new_vreg(GPR);
602 let and = op(&mut names, "and_ri_32");
603 let cmp = op(&mut names, "cmp_ri_32");
604 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
605 func.build(block, cmp).uses(value, GPR).imm(0).finish();
606
607 assert_eq!(takes(&mut func, &mut names), 0);
608 assert_eq!(shape(&func, &names, block).len(), 2);
609 }
610
611 /// The condition state does not cross a block boundary, and neither does this.
612 #[test]
613 fn a_comparison_in_another_block_is_not_one_the_arithmetic_answers() {
614 let (mut names, mut func, block) = empty();
615 let next = func.create_block();
616 let value = func.new_vreg(GPR);
617 let byte = func.new_vreg(GPR);
618 let and = op(&mut names, "and_ri_32");
619 let cmp = op(&mut names, "cmp_set_e_ri_32");
620 func.build(block, and).def(value, GPR).uses(value, GPR).imm(255).finish();
621 *func.succs_mut(block) = vec![mir::BlockCall::to(next)];
622 func.build(next, cmp).def(byte, GPR).uses(value, GPR).imm(0).finish();
623
624 assert_eq!(takes(&mut func, &mut names), 0);
625 assert_eq!(shape(&func, &names, next).len(), 1);
626 }
627}