rucc_codegen/bits.rs
1//! Taking out a conversion whose bits nothing reads.
2//!
3//! Design: `spec/optimizer/37-machine-level-optimization.md` section 37.4.
4//!
5//! A register is one register at every width, and what says how much of it is in play is the
6//! instruction naming it. `movzbl %sil, %edi` writes thirty two bits of `rdi` and reads eight of
7//! `rsi`, and if the only thing that ever reads `rdi` is a `movb`, then the twenty four bits the
8//! widening worked out are bits nobody ever looks at. What is left of the widening once those bits
9//! are taken away is a copy of eight bits into a register, which is what the instruction after it
10//! was going to read anyway, so the widening goes and its readers read its source instead.
11//!
12//! That is the bit group liveness of `gcc/ext-dce.cc` at the width this compiler needs it at.
13//! Liveness answers whether a register is read at all, this answers how much of it is read, and
14//! the second question is the first one asked per group of bits rather than per register. Section
15//! 37.4 says to build this one of the two passes it offers, because it is more general than
16//! compare elimination and because the analysis is the liveness the allocator already computes
17//! with a number on it.
18//!
19//! # Where the conversions come from
20//!
21//! Not from code anybody wrote. C promotes nearly every operand of nearly every expression to
22//! `int` before doing anything with it, so a program that adds two `char`s widens both of them,
23//! adds at thirty two bits and stores eight, and the front end writes every one of those
24//! conversions out because each of them is in the language's own description of what the program
25//! means. `crate::widths` and tier four of the rewrite rules take the ones that are two
26//! instructions next to each other in the same block. What is left for this pass is the ones that
27//! are not: a conversion in one block whose readers are in another, and a conversion the selector
28//! itself wrote because the machine instruction it picked wanted its operand at a width the value
29//! did not arrive at.
30//!
31//! # What it finds, measured
32//!
33//! Both directions of conversion are in scope and only one of them turns up, which was not what
34//! was expected and is worth writing down rather than rounding off. Over the 1916 programs of
35//! tamnd/rucc-corpus at `-O2` this takes out 970 instructions and puts back 45, and not one of
36//! the 7040 widenings in that assembly is among them: the count of `movz` and `movs` is the same
37//! before and after. What goes is 469 `movl`, 259 `movw` and 242 `movb` between registers, which
38//! are the narrowings, and the 45 that come back are `movq`, which is the allocator wanting a
39//! plain copy where a narrowing had been doing that job as well as its own.
40//!
41//! That is tier four of the rewrite rules having already been through the corpus. A widening the
42//! rules could not reach is one whose upper bits some reader really does read, and there is
43//! nothing here for a bit counter to find in it. A narrowing is the other way round: the machine
44//! writes one where a value is put in a register at a width, and whether the bits above it matter
45//! is a question about every reader of the result rather than about the pair, which is the
46//! question only this pass asks.
47//!
48//! 2091 bytes of `.text` over the corpus, 76 programs smaller and two larger by a byte each, and
49//! 2048 bytes off SQLite's amalgamation at `-O2`. The two that grow are an eight bit division,
50//! where every narrowing that goes was also the move that got the answer out of the register the
51//! division fixes, so the allocator writes a full width copy of the same pair in its place. Nine
52//! of the ten are the same length either way and the tenth is `movb %dl, %bl` becoming
53//! `movq %rdx, %rbx`, which is the one byte: the byte names of those two registers need no prefix
54//! and the sixty four bit move needs the one that says so.
55//!
56//! # The analysis
57//!
58//! One number per register, which is how many of its low bits anything reads. It starts at none
59//! and grows, so a register nothing has been seen to read yet is one whose answer is still being
60//! worked out rather than one nothing reads.
61//!
62//! Three things raise it. An instruction reading a register raises it to the width that
63//! instruction names the operand at, which is [`rucc_target::BitInsts::width`] and is the target's
64//! answer rather than this pass's. An edge carrying a register into a block raises it to whatever
65//! the parameter it arrives as needs, which is what carries the answer across a block boundary and
66//! is the whole reason this finds anything the rules do not. And an instruction that copies the
67//! low bits of its source raises its source only as far as its own result is read, since the bits
68//! of the source above that are bits it puts nowhere anything reads.
69//!
70//! The last of those is what makes the answer a fixpoint rather than a walk: a chain of
71//! conversions passes the number back along itself, and how far it passes depends on a number the
72//! same pass is still working out. It only ever grows and it is bounded by the widest operand on
73//! the machine, so it settles.
74//!
75//! # What it will not do
76//!
77//! An operand the target's description does not name at a width. An address register, an operand
78//! of an opcode written as no instruction at all, and an opcode from somewhere other than this
79//! target all answer that they read everything, which is section 37.7's warning honoured by
80//! construction: a store reads every bit of the value it stores because the description says the
81//! operand is as wide as the store is, and anything the description is silent about is treated as
82//! reading the lot rather than as reading nothing.
83//!
84//! A physical register on either side. Machine IR is in SSA form until the allocator has run, so a
85//! virtual register is written once and the register a reader would be sent to instead still holds
86//! what it held. A physical one is not: the frame pointer and the stack pointer are already
87//! physical here and a call writes every register it is allowed to, so sending a reader to one of
88//! those would be sending it to whatever happened to be there.
89//!
90//! A conversion whose result is read as wide as it is written. That is a widening whose upper bits
91//! somebody does read, which is the whole instruction doing its job.
92//!
93//! A conversion whose result nothing reads at all. That is an instruction that computes something
94//! nobody wants, which is dead code rather than dead bits, and taking it out here would be this
95//! pass answering a question it was not asked and reporting a number that says it found widenings
96//! it had not. What this is about is a register something reads less of than was put in it.
97//!
98//! # How the rewrite is made
99//!
100//! One conversion at a time, as a set of changes [`crate::changes`] either takes or turns down.
101//! The set is the readers sent to the source and the conversion taken out, and those two are worth
102//! nothing apart: a reader left behind reads a register nothing writes any more. So the set is
103//! where the question is asked, and a reader this pass failed to find is a set that is refused
104//! rather than a function with a hole in it.
105//!
106//! The readers an edge holds are in the set the same way. A conversion in one block whose reader is
107//! in another is the case this pass is here for, and the argument the edge carries is how the value
108//! gets there, so sending it somewhere else is half of what taking the conversion out means.
109//!
110//! # Where it runs
111//!
112//! After selection and before allocation, which is the window where the machine instructions exist
113//! and the registers are still virtual. Section 37.6 puts it third in the group that runs there,
114//! after combining and if-conversion and before compare elimination and addressing-mode folding,
115//! and that is where `crate::pipeline` calls it.
116
117use std::collections::HashMap;
118
119use rucc_base::Interner;
120use rucc_mir as mir;
121use rucc_target::{BitInsts, Constraint, MachineInsts, Role};
122
123use crate::changes::{Changes, Reads};
124
125/// How much of a register a read that could be of any of it wants.
126///
127/// Every operand the target does not describe gets this, and no rewrite fires over a register that
128/// has it, since no instruction on any machine writes more bits than this many.
129const EVERYTHING: u32 = u32::MAX;
130
131/// Takes out every conversion whose result nothing reads above the width of its source, and gives
132/// back how many.
133///
134/// Each one that goes takes its readers with it: they are pointed at the source instead, which
135/// holds the same bits as the result did for as far as anything was looking.
136///
137/// One conversion is one set of changes, which is [`crate::changes`] asked the question this pass
138/// would otherwise be trusted about. Sending the readers of a register somewhere else and taking
139/// the instruction that wrote it out are worth nothing apart, and a reader this missed is a set
140/// the framework turns down rather than an instruction taken out from under something still
141/// reading it.
142///
143/// Run after lowering and before allocation. Running it once is enough, because the analysis is
144/// over the whole function at once and a chain of conversions is settled by the fixpoint rather
145/// than by a second run.
146pub fn dead(
147 func: &mut mir::Func,
148 insts: &BitInsts,
149 machine: &MachineInsts,
150 names: &Interner,
151) -> usize {
152 let wanted = demand(func, insts, names);
153 let mut sent: HashMap<mir::Reg, mir::Reg> = HashMap::new();
154 let mut gone: Vec<mir::Inst> = Vec::new();
155 for block in func.blocks() {
156 for inst in func.insts(block) {
157 let Some(name) = opcode(func, insts, names, inst) else { continue };
158 if !(insts.copies_low)(name) {
159 continue;
160 }
161 let Some((def, source)) = conversion(func, inst) else { continue };
162 let kept = (insts.width)(name, SOURCE).unwrap_or(EVERYTHING);
163 let read = wanted.get(&def).copied().unwrap_or(0);
164 if read == 0 || read > kept {
165 continue;
166 }
167 sent.insert(def, source);
168 gone.push(inst);
169 }
170 }
171 if gone.is_empty() {
172 return 0;
173 }
174 let sent = chased(&sent);
175 let readers = Readers::of(func, &sent);
176 let mut reads = Reads::of(func);
177 let mut taken = 0;
178 for inst in gone {
179 let Some((def, _)) = conversion(func, inst) else { continue };
180 let Some(&into) = sent.get(&def) else { continue };
181 let mut set = Changes::new();
182 for &reader in readers.insts.get(&def).into_iter().flatten() {
183 // A reader that has gone is one an earlier conversion in a chain took with it, and the
184 // read it was doing went with it.
185 if func.block_of(reader).is_some() {
186 set.rename(reader, def, into);
187 }
188 }
189 for &(from, at) in readers.edges.get(&def).into_iter().flatten() {
190 let args = func[from].succs[at]
191 .args
192 .iter()
193 .map(|&arg| if arg == def { into } else { arg })
194 .collect();
195 set.carry(from, at, args);
196 }
197 set.remove(inst);
198 if set.commit(func, &mut reads, names, machine).is_ok() {
199 taken += 1;
200 }
201 }
202 taken
203}
204
205/// Everything that reads each of the registers a conversion wrote.
206///
207/// Worked out in one walk rather than per conversion, because a function with a thousand of these
208/// in it would otherwise be walked a thousand times. It is the readers as they were when the walk
209/// ran, which is enough: a rename adds a read of the register it sends a reader to, and by the time
210/// that register's own conversion is the one being taken out the reader is found from the function
211/// rather than from here.
212#[derive(Debug, Default)]
213struct Readers {
214 /// The instructions that read it, each named once however many of its operands do.
215 insts: HashMap<mir::Reg, Vec<mir::Inst>>,
216 /// The edges that carry it, as the block each leaves and its position in that block's list.
217 edges: HashMap<mir::Reg, Vec<(mir::Block, usize)>>,
218}
219
220impl Readers {
221 /// Every read of every register in the map, which is the registers the conversions wrote.
222 fn of(func: &mir::Func, sent: &HashMap<mir::Reg, mir::Reg>) -> Self {
223 let mut found = Self::default();
224 for block in func.blocks() {
225 for inst in func.insts(block) {
226 for operand in &func[func[inst].operands] {
227 if operand.role != Role::Use || !sent.contains_key(&operand.reg) {
228 continue;
229 }
230 let readers = found.insts.entry(operand.reg).or_default();
231 if !readers.contains(&inst) {
232 readers.push(inst);
233 }
234 }
235 }
236 for (at, call) in func[block].succs.iter().enumerate() {
237 for arg in &call.args {
238 if !sent.contains_key(arg) {
239 continue;
240 }
241 let edges = found.edges.entry(*arg).or_default();
242 if !edges.contains(&(block, at)) {
243 edges.push((block, at));
244 }
245 }
246 }
247 }
248 found
249 }
250}
251
252/// Where a conversion holds the register it reads.
253///
254/// A conversion is one definition and one use in that order, which is what [`conversion`] checks
255/// rather than assumes, so the source is at one.
256const SOURCE: u8 = 1;
257
258/// How many low bits of each register something reads.
259///
260/// Absent means none, which is a register nothing has been seen to read. That is the right
261/// starting point rather than a wrong one to be corrected later: the answer only grows, so a
262/// register still absent when the walk settles is one nothing reads at all.
263fn demand(func: &mir::Func, insts: &BitInsts, names: &Interner) -> HashMap<mir::Reg, u32> {
264 let mut wanted: HashMap<mir::Reg, u32> = HashMap::new();
265 loop {
266 let mut moved = false;
267 for block in func.blocks() {
268 for inst in func.insts(block) {
269 let name = opcode(func, insts, names, inst);
270 // A conversion puts the low bits of its source in its result and nothing else, so
271 // the bits of the source above however much of the result is read are bits it
272 // takes nowhere. Anything else reads its operand at the width it names it at.
273 let copies = name.is_some_and(|name| (insts.copies_low)(name));
274 let through = conversion(func, inst)
275 .filter(|_| copies)
276 .map_or(EVERYTHING, |(def, _)| wanted.get(&def).copied().unwrap_or(0));
277 let operands = &func[func[inst].operands];
278 for (at, operand) in operands.iter().enumerate() {
279 if operand.role != Role::Use {
280 continue;
281 }
282 let Ok(at) = u8::try_from(at) else { continue };
283 let asked = read(name, insts, operands, at).min(through);
284 moved |= raise(&mut wanted, operand.reg, asked);
285 }
286 }
287 for call in &func[block].succs {
288 for (arg, param) in call.args.iter().zip(&func[call.block].params) {
289 let asked = wanted.get(¶m.reg).copied().unwrap_or(0);
290 moved |= raise(&mut wanted, *arg, asked);
291 }
292 }
293 }
294 if !moved {
295 return wanted;
296 }
297 }
298}
299
300/// Raises how much of a register is read, and says whether that changed anything.
301fn raise(wanted: &mut HashMap<mir::Reg, u32>, reg: mir::Reg, bits: u32) -> bool {
302 let had = wanted.entry(reg).or_insert(0);
303 if *had >= bits {
304 return false;
305 }
306 *had = bits;
307 true
308}
309
310/// How many bits of the operand at that index the instruction reads.
311///
312/// The target's description is asked first and is the answer whenever it has one. Where it has
313/// none the operand may still be a tied one, which is the operand an instruction of this shape
314/// reads and writes in the one place: the machine writes it once and the assembly names it once,
315/// so the description names the definition and says nothing about the use beside it. Those two
316/// are the same register at the same width by the time the allocator has finished, so the width
317/// of the definition is the width of the use.
318///
319/// Anything left over reads everything, which is what keeps an address register, an opcode written
320/// as no instruction and an opcode from another target from being believed to read nothing.
321fn read(name: Option<&str>, insts: &BitInsts, operands: &[mir::Operand], at: u8) -> u32 {
322 let Some(name) = name else { return EVERYTHING };
323 if let Some(bits) = (insts.width)(name, at) {
324 return bits;
325 }
326 for (index, operand) in operands.iter().enumerate() {
327 if operand.role == Role::Use || operand.constraint != Constraint::Reuse(at) {
328 continue;
329 }
330 let Ok(index) = u8::try_from(index) else { continue };
331 return (insts.width)(name, index).unwrap_or(EVERYTHING);
332 }
333 EVERYTHING
334}
335
336/// The name this target knows an instruction by, for an instruction that is one of this target's.
337///
338/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
339/// compiled holds instructions of one machine and the prefix is what says which. Anything without
340/// it is not something this description covers, and the rest of the pass treats that as knowing
341/// nothing rather than as knowing it is safe.
342fn opcode<'a>(
343 func: &mir::Func,
344 insts: &BitInsts,
345 names: &'a Interner,
346 inst: mir::Inst,
347) -> Option<&'a str> {
348 names.resolve(func[inst].opcode.name()).strip_prefix(insts.prefix)
349}
350
351/// The register a conversion writes and the register it reads, when it is one this may take out.
352///
353/// One definition and one use, both of them virtual, and no memory operand. The shape is checked
354/// rather than taken on trust from the opcode, since what the rewrite does is send every reader of
355/// the first register to the second and that is only the same program when there is exactly one of
356/// each.
357fn conversion(func: &mir::Func, inst: mir::Inst) -> Option<(mir::Reg, mir::Reg)> {
358 if func[inst].mem.is_some() {
359 return None;
360 }
361 let operands = &func[func[inst].operands];
362 let [def, source] = operands else { return None };
363 if def.role == Role::Use || source.role != Role::Use {
364 return None;
365 }
366 if !def.reg.is_virtual() || !source.reg.is_virtual() {
367 return None;
368 }
369 Some((def.reg, source.reg))
370}
371
372/// The same map with every chain in it followed to its end.
373///
374/// A chain is two conversions where the outer one reads what the inner one wrote, and both of them
375/// going means a reader of the outer one belongs to the inner one's source rather than to the
376/// inner one. The walk ends because machine IR is in SSA form here and every step goes to a
377/// register written earlier in the function, and the bound is there so that a map built any other
378/// way stops as well.
379fn chased(sent: &HashMap<mir::Reg, mir::Reg>) -> HashMap<mir::Reg, mir::Reg> {
380 sent.iter()
381 .map(|(&from, &first)| {
382 let mut into = first;
383 for _ in 0..sent.len() {
384 match sent.get(&into) {
385 Some(&next) => into = next,
386 None => break,
387 }
388 }
389 (from, into)
390 })
391 .collect()
392}
393
394#[cfg(test)]
395mod tests {
396 use rucc_target::x86_64::{BITS, GPR, MACHINE, RDI};
397
398 use super::*;
399
400 /// A function with one block, and the names it was built with.
401 fn empty() -> (Interner, mir::Func, mir::Block) {
402 let mut names = Interner::new();
403 let mut func = mir::Func::new(names.intern("f"));
404 let block = func.create_block();
405 (names, func, block)
406 }
407
408 /// The opcode of that name on this target.
409 fn op(names: &mut Interner, name: &str) -> mir::Opcode {
410 mir::Opcode::new(names.intern(&format!("{}{name}", BITS.prefix)))
411 }
412
413 /// The pass, over the machine this crate has a backend for.
414 fn takes(func: &mut mir::Func, names: &Interner) -> usize {
415 dead(func, &BITS, &MACHINE, names)
416 }
417
418 /// What every instruction in a block came to, as opcodes.
419 fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
420 func.insts(block).map(|inst| names.resolve(func[inst].opcode.name()).to_owned()).collect()
421 }
422
423 /// The registers one instruction reads, in the order its operands hold them.
424 fn reads(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
425 func[func[inst].operands]
426 .iter()
427 .filter(|operand| operand.role == Role::Use)
428 .map(|operand| operand.reg)
429 .collect()
430 }
431
432 /// The shape the whole pass is about, and the one the corpus is full of: a byte widened to a
433 /// word because C says to, and then the word written back out as a byte. The twenty four bits
434 /// in between are worked out and read by nobody.
435 #[test]
436 fn a_widening_whose_only_reader_is_as_narrow_as_its_source_goes() {
437 let (mut names, mut func, block) = empty();
438 let byte = func.new_vreg(GPR);
439 let wide = func.new_vreg(GPR);
440 let address = func.new_vreg(GPR);
441 let widen = op(&mut names, "movzx_8_32");
442 let store = op(&mut names, "mov_mr_8");
443 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
444 func.build(block, store)
445 .uses(wide, GPR)
446 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
447 .finish();
448
449 assert_eq!(takes(&mut func, &names), 1);
450
451 let left = shape(&func, &names, block);
452 assert_eq!(left.len(), 1, "the widening is still there: {left:?}");
453 let inst = func.insts(block).next().expect("the store is still there");
454 assert_eq!(reads(&func, inst)[0], byte, "the store was not sent to the source");
455 }
456
457 /// The same widening with a reader that reads the whole of what it wrote. Those upper bits are
458 /// read, so the instruction that worked them out is one doing its job.
459 #[test]
460 fn a_widening_something_reads_the_whole_of_stays() {
461 let (mut names, mut func, block) = empty();
462 let byte = func.new_vreg(GPR);
463 let wide = func.new_vreg(GPR);
464 let out = func.new_vreg(GPR);
465 let widen = op(&mut names, "movzx_8_32");
466 let copy = op(&mut names, "mov_rr_64");
467 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
468 func.build(block, copy).def(out, GPR).uses(wide, GPR).finish();
469
470 assert_eq!(takes(&mut func, &names), 0);
471 assert_eq!(shape(&func, &names, block).len(), 2);
472 }
473
474 /// The case no rewrite rule can reach, which is the reason this pass is here at all. The
475 /// widening is in one block and the only thing that reads it is in another, so the two are
476 /// never operands of one term and no pattern three levels deep sees them both.
477 #[test]
478 fn a_widening_whose_narrow_reader_is_in_another_block_goes_too() {
479 let (mut names, mut func, block) = empty();
480 let next = func.create_block();
481 let byte = func.new_vreg(GPR);
482 let wide = func.new_vreg(GPR);
483 let arrived = func.new_vreg(GPR);
484 let address = func.new_vreg(GPR);
485 let widen = op(&mut names, "movzx_8_32");
486 let store = op(&mut names, "mov_mr_8");
487 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
488 func.params_mut(next).push(mir::Param { reg: arrived, class: GPR });
489 *func.succs_mut(block) = vec![mir::BlockCall::with(next, vec![wide])];
490 func.build(next, store)
491 .uses(arrived, GPR)
492 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
493 .finish();
494
495 assert_eq!(takes(&mut func, &names), 1);
496
497 assert!(shape(&func, &names, block).is_empty(), "the widening is still there");
498 assert_eq!(func[block].succs[0].args, vec![byte], "the edge still carries the wide one");
499 }
500
501 /// And the same edge with a reader on the other side that wants the whole word, which is the
502 /// answer coming back across the boundary the other way.
503 #[test]
504 fn a_widening_whose_reader_in_another_block_is_wide_stays() {
505 let (mut names, mut func, block) = empty();
506 let next = func.create_block();
507 let byte = func.new_vreg(GPR);
508 let wide = func.new_vreg(GPR);
509 let arrived = func.new_vreg(GPR);
510 let address = func.new_vreg(GPR);
511 let widen = op(&mut names, "movzx_8_32");
512 let store = op(&mut names, "mov_mr_32");
513 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
514 func.params_mut(next).push(mir::Param { reg: arrived, class: GPR });
515 *func.succs_mut(block) = vec![mir::BlockCall::with(next, vec![wide])];
516 func.build(next, store)
517 .uses(arrived, GPR)
518 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
519 .finish();
520
521 assert_eq!(takes(&mut func, &names), 0);
522 assert_eq!(shape(&func, &names, block).len(), 1);
523 assert_eq!(func[block].succs[0].args, vec![wide]);
524 }
525
526 /// A chain, which is what a narrow value widened for one operation and narrowed for the next
527 /// comes out as. The middle conversion is what makes the analysis a fixpoint rather than one
528 /// walk: how much of it is read depends on how much of the one after it is, and that number is
529 /// still being worked out when it is asked for.
530 #[test]
531 fn a_chain_of_conversions_goes_the_whole_way_and_its_reader_goes_to_the_first_source() {
532 let (mut names, mut func, block) = empty();
533 let byte = func.new_vreg(GPR);
534 let wide = func.new_vreg(GPR);
535 let narrowed = func.new_vreg(GPR);
536 let out = func.new_vreg(GPR);
537 let address = func.new_vreg(GPR);
538 let widen = op(&mut names, "movzx_8_64");
539 let low = op(&mut names, "low_32");
540 let narrow = op(&mut names, "low_8");
541 let store = op(&mut names, "mov_mr_8");
542 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
543 func.build(block, low).def(narrowed, GPR).uses(wide, GPR).finish();
544 func.build(block, narrow).def(out, GPR).uses(narrowed, GPR).finish();
545 func.build(block, store)
546 .uses(out, GPR)
547 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
548 .finish();
549
550 assert_eq!(takes(&mut func, &names), 3);
551
552 let left = shape(&func, &names, block);
553 assert_eq!(left.len(), 1, "some of the three are still there: {left:?}");
554 let inst = func.insts(block).next().expect("the store is still there");
555 assert_eq!(reads(&func, inst)[0], byte, "the chain was not followed to its end");
556 }
557
558 /// A store of the whole word, which is section 37.7's warning: the bits go to memory and
559 /// something reads them from there, so a pass that thought a store read less than it stores
560 /// would take out a widening whose answer is in the program's output.
561 #[test]
562 fn a_store_reads_every_bit_of_what_it_stores() {
563 let (mut names, mut func, block) = empty();
564 let byte = func.new_vreg(GPR);
565 let wide = func.new_vreg(GPR);
566 let address = func.new_vreg(GPR);
567 let widen = op(&mut names, "movzx_8_64");
568 let store = op(&mut names, "mov_mr_64");
569 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
570 func.build(block, store)
571 .uses(wide, GPR)
572 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
573 .finish();
574
575 assert_eq!(takes(&mut func, &names), 0);
576 assert_eq!(shape(&func, &names, block).len(), 2);
577 }
578
579 /// A widening whose result is read as an address. The registers a memory operand is made of
580 /// are read whole and the description says nothing about their width, so the answer is that
581 /// everything is read rather than that nothing is.
582 #[test]
583 fn a_widening_read_as_an_address_stays() {
584 let (mut names, mut func, block) = empty();
585 let byte = func.new_vreg(GPR);
586 let wide = func.new_vreg(GPR);
587 let out = func.new_vreg(GPR);
588 let widen = op(&mut names, "movzx_8_64");
589 let load = op(&mut names, "mov_rm_32");
590 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
591 func.build(block, load)
592 .def(out, GPR)
593 .mem(mir::Mem::at(mir::Operand::read(wide, GPR)))
594 .finish();
595
596 assert_eq!(takes(&mut func, &names), 0);
597 assert_eq!(shape(&func, &names, block).len(), 2);
598 }
599
600 /// The operand an instruction of this shape reads and writes in the one place, which the
601 /// assembly names once and the description therefore has no separate width for. It is as wide
602 /// as the definition it is tied to, and an eight bit source is not enough for it.
603 #[test]
604 fn a_tied_operand_reads_as_much_as_the_definition_it_is_tied_to() {
605 let (mut names, mut func, block) = empty();
606 let byte = func.new_vreg(GPR);
607 let wide = func.new_vreg(GPR);
608 let other = func.new_vreg(GPR);
609 let sum = func.new_vreg(GPR);
610 let address = func.new_vreg(GPR);
611 let widen = op(&mut names, "movzx_8_32");
612 let add = op(&mut names, "add_rr_32");
613 let store = op(&mut names, "mov_mr_32");
614 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
615 func.build(block, add)
616 .operand(mir::Operand::write(sum, GPR).with(Constraint::Reuse(1)))
617 .uses(wide, GPR)
618 .uses(other, GPR)
619 .finish();
620 func.build(block, store)
621 .uses(sum, GPR)
622 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
623 .finish();
624
625 assert_eq!(takes(&mut func, &names), 0);
626 assert_eq!(shape(&func, &names, block).len(), 3);
627 }
628
629 /// A physical register as the source. Sending the readers there would send them to a register
630 /// the convention hands out and a call is free to destroy, which is not what SSA promises
631 /// about the virtual one they were reading.
632 #[test]
633 fn a_widening_of_a_physical_register_stays() {
634 let (mut names, mut func, block) = empty();
635 let arrived = mir::Reg::physical(RDI);
636 let wide = func.new_vreg(GPR);
637 let address = func.new_vreg(GPR);
638 let widen = op(&mut names, "movzx_8_32");
639 let store = op(&mut names, "mov_mr_8");
640 func.build(block, widen).def(wide, GPR).uses(arrived, GPR).finish();
641 func.build(block, store)
642 .uses(wide, GPR)
643 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
644 .finish();
645
646 assert_eq!(takes(&mut func, &names), 0);
647 assert_eq!(shape(&func, &names, block).len(), 2);
648 }
649
650 /// An opcode from somewhere other than this target, which is what an instruction with no
651 /// prefix on it is. Nothing is known about how much of its operands it reads, and the answer
652 /// to knowing nothing is that it reads everything.
653 #[test]
654 fn an_opcode_this_target_does_not_describe_reads_everything() {
655 let (mut names, mut func, block) = empty();
656 let byte = func.new_vreg(GPR);
657 let wide = func.new_vreg(GPR);
658 let out = func.new_vreg(GPR);
659 let widen = op(&mut names, "movzx_8_32");
660 let foreign = mir::Opcode::new(names.intern("elsewhere.narrow"));
661 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
662 func.build(block, foreign).def(out, GPR).uses(wide, GPR).finish();
663
664 assert_eq!(takes(&mut func, &names), 0);
665 assert_eq!(shape(&func, &names, block).len(), 2);
666 }
667
668 /// A conversion nothing reads at all, which is dead code rather than dead bits. It is left for
669 /// whatever removes instructions whose answers nobody wants, so that the number this gives
670 /// back is the number of widenings it found and not a count of two different things.
671 #[test]
672 fn a_conversion_nothing_reads_is_left_for_the_pass_that_owns_dead_code() {
673 let (mut names, mut func, block) = empty();
674 let byte = func.new_vreg(GPR);
675 let wide = func.new_vreg(GPR);
676 let widen = op(&mut names, "movzx_8_32");
677 func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
678
679 assert_eq!(takes(&mut func, &names), 0);
680 assert_eq!(shape(&func, &names, block).len(), 1);
681 }
682}