rucc_opt/memssa.rs
1//! Memory SSA: the chain, and the budgeted walk back to the store a load sees.
2//!
3//! Design: `spec/optimizer/09-memory-ssa.md`. The representation is in `rucc-ir` and this is what
4//! builds it and what reads it.
5//!
6//! # One variable
7//!
8//! GCC has had this since 2004 and calls it virtual operands: a statement that reads memory
9//! carries a VUSE, one that writes memory carries a VDEF, and both are versions of one artificial
10//! variable called `.MEM`. LLVM calls the same three things `MemoryUse`, `MemoryDef` and
11//! `MemoryPhi`. The idea in both is to reuse the scalar SSA machinery for memory by pretending
12//! memory is one scalar, and it is the right idea, so this does the same.
13//!
14//! The consequence is that the def-use chain over memory is maximally conservative. Every store
15//! kills every load, structurally. All of the precision comes from walking it, which is what
16//! [`Walk::clobber`] does.
17//!
18//! [`build`] is the construction: place a memory parameter at every join the memory versions
19//! reach, which is the same iterated dominance frontier that SSA construction uses, and thread
20//! the operand through every instruction that touches memory. A memory phi is an ordinary block
21//! parameter, so nothing here is a side table and the CFG updates that keep memory SSA in step
22//! with the blocks are the ones every other value already needed.
23//!
24//! # The walk
25//!
26//! [`Walk::clobber`] is GCC's `walk_non_aliased_vuses` at `gcc/tree-ssa-alias.cc:3915`. Given the
27//! version of memory a load reads, it walks back through the defs, asks the alias analysis at each
28//! one whether that def could have written what the load reads, and stops at the first one that
29//! could. Two parts of GCC's interface are worth copying and both are here.
30//!
31//! **The budget.** `sccvn-max-alias-queries-per-access`, default 1000 at `gcc/params.opt:1020`,
32//! and it is [`MAX_ALIAS_QUERIES_PER_ACCESS`] here under the same name, because a user who knows
33//! to raise GCC's should not have to learn a second one. The walk is worst case quadratic: every
34//! load can walk back through every store and each step is an alias query, so a function with a
35//! thousand of each and no disambiguation is a million queries per pass that uses it, and there
36//! are four such passes. Exceeding the budget gives [`Clobber::Unknown`], which is not an answer
37//! and is not a no.
38//!
39//! **`translate`.** When the walk reaches a def it cannot see past, the caller may adjust the
40//! reference and carry on, which is [`Step::Retry`]. This is what lets value numbering follow a
41//! load through a `memcpy` by rewriting the reference to the copy's source, and section 9.2 says
42//! it is the mechanism behind a surprising fraction of GCC's memory optimization. Without it the
43//! walk is a stopping condition. With it, it is a way to rewrite the question.
44//!
45//! A rewrite is counted, as [`Counts::rewritten`], for the same reason the steps and the budget
46//! exhaustions are: it is the one thing in the walk that starts the walk again, so it is where the
47//! work goes when the work goes somewhere unexpected, and it is what says whether the callback is
48//! reaching anything at all on a build rather than only on the build somebody last looked at.
49//!
50//! # Five answers, not two
51//!
52//! [`Clobber`] has five variants and the shape of it is deliberate. Section 9.6 names two ways
53//! this goes wrong and the type is what rules both out.
54//!
55//! The first is a caller treating a budget exhaustion as a no. There is no `Option` anywhere in
56//! the return and there is no default arm to fall into, so [`Clobber::Unknown`] has to be handled
57//! by name.
58//!
59//! The second is partial overlap. A four byte store followed by a one byte load at offset one:
60//! the load sees the store, but it cannot be replaced by the stored value, because the byte it
61//! wants is somewhere inside that value and getting it out is a shift and a truncate. So a
62//! clobber that wrote exactly the bytes of the reference is [`Clobber::Exact`], one that wrote
63//! some of them is [`Clobber::Partial`], and one that may have written them is
64//! [`Clobber::Maybe`]. Section 9.5 says getting this down to two answers is a class of
65//! miscompilation.
66//!
67//! # What is conservative on purpose
68//!
69//! Every atomic and every fence is a full memory def and a full memory use. Section 9.5 says this
70//! is correct and it is what M4 should do, and that doing better means modelling the memory model
71//! rather than the memory, which is post-1.0. The failure mode it names is treating a relaxed
72//! atomic load as an ordinary load because it orders nothing: it orders nothing and it is still a
73//! load, and hoisting it out of a loop changes an observable. Atomics are never moved.
74//!
75//! `volatile` is checked before anything else and is never walked past. Alias analysis says
76//! nothing about how many times an access happens and `volatile` constrains that too, so it is a
77//! separate bit rather than a strong alias fact.
78//!
79//! # The cache
80//!
81//! There is not one. Section 9.3 is explicit: build the uncached walk, instrument how many alias
82//! queries a `-O2` compilation makes, and add caching only if that number is a measurable
83//! fraction of compile time. GCC has run without it for twenty years and LLVM's caching walker is
84//! a large part of its MemorySSA complexity and a known source of invalidation bugs. The
85//! instrumentation is the M4 deliverable and it is [`Counts`]. The number that decides it is the
86//! fraction of walks that end by exhausting the budget rather than by finding a clobber: above
87//! one percent and the budget is too small or the alias analysis is too weak, and both of those
88//! are better fixed than cached around.
89
90use std::collections::{HashMap, HashSet};
91
92use rucc_base::hash::Set;
93use rucc_ir::{Block, BlockCall, Def, Flags, Func, Inst, InstData, MemOrder, Opcode, Type, Value};
94
95use crate::alias::{Access, Alias, Answer, Options};
96use crate::cfg::Cfg;
97use crate::dom::Dominators;
98use crate::outside::Outside;
99
100/// How many alias queries one walk may make before it gives up.
101///
102/// GCC's `sccvn-max-alias-queries-per-access`, default 1000 at `gcc/params.opt:1020`, under the
103/// same name on purpose. Exceeding it gives [`Clobber::Unknown`] rather than a wrong answer.
104pub const MAX_ALIAS_QUERIES_PER_ACCESS: u32 = 1000;
105
106/// What the walk found.
107///
108/// Five variants, and section 9.6 is why. Three of them are a clobber and they differ in how much
109/// of the reference the clobber covers, because a caller that cannot tell `Exact` from `Partial`
110/// replaces a one byte load with the wrong byte of a four byte store. The other two are the ways
111/// a walk ends without one, and `Unknown` is not a no.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum Clobber {
114 /// This instruction wrote exactly the bytes the reference covers.
115 ///
116 /// The only answer redundant load elimination may act on by taking the stored value, and
117 /// even then only after checking the two types are the same width.
118 Exact(Inst),
119 /// This instruction wrote some of the reference, or wrote all of it and more.
120 ///
121 /// The load sees it, and what it sees cannot be had without taking part of what was stored
122 /// or combining it with something else, which is document 16's decision rather than this
123 /// one's.
124 Partial(Inst),
125 /// This instruction may have written the reference, and there is no telling how much.
126 Maybe(Inst),
127 /// Nothing in this function wrote it. The walk reached the start of the chain.
128 NoClobber,
129 /// The walk ran out of budget, or the paths into a join disagreed. Nothing is known.
130 Unknown,
131}
132
133impl Clobber {
134 /// The instruction, for the three answers that name one.
135 #[must_use]
136 pub const fn inst(self) -> Option<Inst> {
137 match self {
138 Self::Exact(inst) | Self::Partial(inst) | Self::Maybe(inst) => Some(inst),
139 Self::NoClobber | Self::Unknown => None,
140 }
141 }
142}
143
144/// What a caller does when the walk reaches a def it cannot see past.
145///
146/// GCC's `translate` callback, section 9.2. A caller with no rewrite to offer says [`Step::Stop`]
147/// and gets the clobber. One that can see through the def rewrites the reference and the walk
148/// carries on with the new one.
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum Step {
151 /// Stop here. This is the answer.
152 Stop,
153 /// Carry on past this def, asking about this reference instead.
154 Retry(Access),
155}
156
157/// What the walks have cost, which section 9.7 asks for as its own counter.
158///
159/// The walk is charged to whichever pass made it, so `-ftime-report` shows it under GVN and PRE
160/// and not under memory SSA. That is misleading, and the fix section 9.7 asks for is to report
161/// the step count separately from the wall time, because it is the thing to look at when a
162/// pathological input turns up.
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
164pub struct Counts {
165 walks: u64,
166 steps: u64,
167 exhausted: u64,
168 rewritten: u64,
169}
170
171impl Counts {
172 /// How many walks were made.
173 #[must_use]
174 pub const fn walks(&self) -> u64 {
175 self.walks
176 }
177
178 /// How many defs those walks looked at, which is one alias query each.
179 #[must_use]
180 pub const fn steps(&self) -> u64 {
181 self.steps
182 }
183
184 /// How many walks ended by running out of budget.
185 ///
186 /// This is the number section 9.3 says decides whether the cache gets built. Above one
187 /// percent of walks and the budget is too small or the alias analysis is too weak.
188 #[must_use]
189 pub const fn exhausted(&self) -> u64 {
190 self.exhausted
191 }
192
193 /// How many times a caller rewrote the reference and the walk carried on with the new one.
194 ///
195 /// A rewrite starts a walk of its own, so this is both how much work the `translate` callback
196 /// is asking for and how much it is getting, and it is the counter that says whether the
197 /// callback is doing anything at all on a given build.
198 #[must_use]
199 pub const fn rewritten(&self) -> u64 {
200 self.rewritten
201 }
202}
203
204/// Puts a function on the memory chain, and says whether it did.
205///
206/// Construction is the same iterated dominance frontier SSA construction uses, over one variable:
207/// the blocks that write memory are the definitions, the joins their versions reach get a memory
208/// parameter, and a walk of the dominator tree threads the operand through every instruction that
209/// touches memory. Linear with a dominance frontier factor, per section 9.7.
210///
211/// It gives back `false` and changes nothing for a function that has no memory operations at all,
212/// for a declaration, and for one that is already on the chain. The first of those is the reason
213/// the answer is a `bool` rather than nothing: a function with no memory in it must not get a
214/// `mem_entry`, because a chain that starts and reaches nothing is a chain the verifier turns
215/// down and a reader would have to interpret.
216pub fn build(func: &mut Func) -> bool {
217 let Some(entry) = func.entry() else {
218 return false;
219 };
220 let cfg = Cfg::new(func);
221 let doms = Dominators::new(&cfg);
222
223 // Where the writes are, which is where the versions of memory are defined.
224 let mut defs = vec![entry];
225 let mut any = false;
226 for block in func.blocks() {
227 // A block nothing reaches is one the verifier turns down on its own, and it is not on
228 // the dominator tree either, so threading would leave it off the chain and the chain
229 // would then be neither all of the function nor none of it. Running the cleanup that
230 // deletes it first is the caller's job.
231 if !cfg.reaches(block) {
232 return false;
233 }
234 let mut writes = false;
235 for inst in func.insts(block) {
236 if func.carries_mem(inst) {
237 return false;
238 }
239 let opcode = func[inst].opcode;
240 any |= opcode.touches_memory();
241 writes |= opcode.writes_memory();
242 }
243 if writes && block != entry {
244 defs.push(block);
245 }
246 }
247 // An entry block with nothing in it has no terminator either, so this is not a function the
248 // verifier would have let through and there is nothing sensible to build over it.
249 let Some(first) = func.insts(entry).next() else {
250 return false;
251 };
252 if !any {
253 return false;
254 }
255
256 let joins = iterated_frontier(&cfg, &doms, &defs);
257 let mut params = HashMap::new();
258 for block in func.blocks().collect::<Vec<_>>() {
259 if joins.contains(&block) {
260 params.insert(block, func.append_param(block, Type::MEM));
261 }
262 }
263
264 let start = start_of_chain(func, first);
265 let ends = thread(func, &doms, ¶ms, entry, start);
266 pass_it_on(func, ¶ms, &ends);
267 true
268}
269
270/// Takes the chain back off, and says whether it did.
271///
272/// The inverse of [`build`], and it is here because the back end has never seen memory SSA and is
273/// not going to: `rucc_codegen::capability` says outright that the chain comes off before it runs.
274/// Nothing was taking it off, so until this existed the only way to use the chain was to not use
275/// it. A pass that wants the walk builds the chain, does its work and strips it, which is a linear
276/// walk each way on top of whatever the pass itself costs.
277///
278/// Keeping the chain across passes instead would be cheaper and is a much bigger claim to make,
279/// since every edit to the control flow graph in the optimizer would have to keep the memory
280/// parameters in step with the blocks. That is worth wanting later and is not what this is.
281///
282/// Three things come off, in the order they have to. Every instruction on the chain loses its
283/// incoming version and its outgoing one, which is [`Func::without_mem`], and what it produced
284/// otherwise is forwarded to what the bare one produces. Every memory parameter comes off the
285/// block that has it and the matching argument comes off every branch to that block. The
286/// `mem_entry` at the top goes last, because until the rest is off it is a definition with
287/// readers.
288///
289/// It gives back `false` and changes nothing for a function that is not on the chain.
290pub fn strip(func: &mut Func) -> bool {
291 let mut forward: Vec<(Value, Value)> = Vec::new();
292 let mut gone: Vec<Inst> = Vec::new();
293 let mut entry = None;
294 for block in func.blocks().collect::<Vec<Block>>() {
295 for inst in func.insts(block).collect::<Vec<Inst>>() {
296 if func[inst].opcode == Opcode::MemEntry {
297 entry = Some(inst);
298 continue;
299 }
300 if !func.carries_mem(inst) {
301 continue;
302 }
303 let bare = func.without_mem(inst);
304 func.insert_before(bare, inst);
305 // The results the bare one kept are at the same positions, and the version of memory
306 // the old one produced is past the end of them, so zipping forwards exactly the ones
307 // that have somewhere to go.
308 for (old, new) in func[inst].results().zip(func[bare].results()) {
309 forward.push((old, new));
310 }
311 gone.push(inst);
312 }
313 }
314 if entry.is_none() && gone.is_empty() {
315 return false;
316 }
317 for inst in gone {
318 func.remove_inst(inst);
319 }
320 let forward: HashMap<Value, Value> = forward.into_iter().collect();
321 if !forward.is_empty() {
322 substitute(func, &forward);
323 }
324 drop_params(func);
325 if let Some(inst) = entry {
326 func.remove_inst(inst);
327 }
328 true
329}
330
331/// Takes the memory parameter off every block that has one, and the argument off every branch to
332/// it.
333///
334/// A parameter that goes has to take the argument in the same position out of every branch, and
335/// only the caller knows which branches there are, which is why [`Func::retain_params`] does not
336/// do it. The position is worked out before anything is removed, because renumbering the
337/// parameters and rewriting the arguments cannot both go first.
338fn drop_params(func: &mut Func) {
339 let mut at: HashMap<Block, Vec<usize>> = HashMap::new();
340 let mut going: HashSet<Value> = HashSet::new();
341 for block in func.blocks().collect::<Vec<Block>>() {
342 let mut keep = Vec::new();
343 for (index, ¶m) in func[block].params.iter().enumerate() {
344 if func[param].ty.is_mem() {
345 going.insert(param);
346 } else {
347 keep.push(index);
348 }
349 }
350 if keep.len() != func[block].params.len() {
351 at.insert(block, keep);
352 }
353 }
354 if at.is_empty() {
355 return;
356 }
357 for block in func.blocks().collect::<Vec<Block>>() {
358 let Some(terminator) = func.terminator(block) else {
359 continue;
360 };
361 for target in func.target_list(terminator).iter() {
362 let call = func[target];
363 let Some(keep) = at.get(&call.block) else {
364 continue;
365 };
366 let args: Vec<Value> = keep.iter().map(|&index| func[call.args][index]).collect();
367 let args = func.push_values(&args);
368 func.set_block_call(target, BlockCall { args, ..call });
369 }
370 }
371 for block in at.keys().copied().collect::<Vec<Block>>() {
372 func.retain_params(block, |param| !going.contains(¶m));
373 }
374}
375
376/// The `mem_entry` above that instruction, which is where every chain starts.
377///
378/// It goes at the very top of the entry block, and the verifier insists on that: a start to the
379/// chain anywhere else would have instructions above it that are on the chain and reach a version
380/// of memory defined below them.
381fn start_of_chain(func: &mut Func, first: Inst) -> Value {
382 let span = func.span(first);
383 let inst = func.create_inst(InstData::new(Opcode::MemEntry), &[Type::MEM], span);
384 func.insert_before(inst, first);
385 func[inst].results().next().expect("mem_entry produces one value")
386}
387
388/// Threads the operand through every instruction that touches memory, and says which version of
389/// memory each block ends with.
390///
391/// The walk is over the dominator tree rather than the CFG, because the version reaching the top
392/// of a block is the one its immediate dominator ended with unless the block has a parameter of
393/// its own. That is the ordinary SSA renaming and memory is an ordinary variable here.
394fn thread(
395 func: &mut Func,
396 doms: &Dominators,
397 params: &HashMap<Block, Value>,
398 entry: Block,
399 start: Value,
400) -> HashMap<Block, Value> {
401 // An instruction cannot grow a result, so threading one makes a new instruction beside it and
402 // the old one goes away. What the old one produced is forwarded to what the new one produces,
403 // at the same positions, in one substitution at the end rather than as each is replaced,
404 // because an instruction threaded early can be an operand of one threaded late.
405 let mut forward: Vec<(Value, Value)> = Vec::new();
406 let mut ends = HashMap::new();
407 let mut stack = vec![(entry, start)];
408 while let Some((block, incoming)) = stack.pop() {
409 let mut current = params.get(&block).copied().unwrap_or(incoming);
410 for inst in func.insts(block).collect::<Vec<_>>() {
411 if !func[inst].opcode.touches_memory() {
412 continue;
413 }
414 let fresh = func.with_mem(inst, current);
415 func.insert_before(fresh, inst);
416 for (old, new) in func[inst].results().zip(func[fresh].results()) {
417 forward.push((old, new));
418 }
419 func.remove_inst(inst);
420 if let Some(next) = func.mem_out(fresh) {
421 current = next;
422 }
423 }
424 ends.insert(block, current);
425 stack.extend(doms.children(block).map(|child| (child, current)));
426 }
427
428 let forward: HashMap<Value, Value> = forward.into_iter().collect();
429 if !forward.is_empty() {
430 substitute(func, &forward);
431 }
432 ends
433}
434
435/// Replaces every use of what a threaded instruction produced with what its replacement produces.
436fn substitute(func: &mut Func, forward: &HashMap<Value, Value>) {
437 let with = |value: Value| forward.get(&value).copied().unwrap_or(value);
438 for block in func.blocks().collect::<Vec<_>>() {
439 for inst in func.insts(block).collect::<Vec<_>>() {
440 let args = func[inst].args;
441 func.rewrite(args, with);
442 for call in func.successors(inst).collect::<Vec<_>>() {
443 func.rewrite(call.args, with);
444 }
445 }
446 }
447 // And the names, which go where the readers went, for the same reason `crate::uses::substitute`
448 // moves them. A call is an instruction that carries memory and `int x = f();` names what one
449 // produced, so a value rewritten here can be a value a declaration is spelled by.
450 let mut moving: Vec<Value> = forward.keys().copied().collect();
451 moving.sort_unstable();
452 for from in moving {
453 func.rename_value(from, with(from));
454 }
455}
456
457/// Passes the version of memory each block ends with to the joins it branches to.
458fn pass_it_on(func: &mut Func, params: &HashMap<Block, Value>, ends: &HashMap<Block, Value>) {
459 for block in func.blocks().collect::<Vec<_>>() {
460 let Some(terminator) = func.terminator(block) else {
461 continue;
462 };
463 let Some(&value) = ends.get(&block) else {
464 continue;
465 };
466 for at in func.target_list(terminator).iter() {
467 let call = func[at];
468 if !params.contains_key(&call.block) {
469 continue;
470 }
471 // The memory parameter was appended last, so the argument goes last too, which is
472 // the same rule the operand follows and for the same reason.
473 let args = func.append_arg(call.args, value);
474 func.set_block_call(at, BlockCall { args, ..call });
475 }
476 }
477}
478
479/// The blocks that need a memory parameter, which is the iterated dominance frontier of the
480/// blocks that define a version of memory.
481fn iterated_frontier(cfg: &Cfg, doms: &Dominators, defs: &[Block]) -> HashSet<Block> {
482 let frontier = frontiers(cfg, doms);
483 let mut placed = HashSet::new();
484 let mut seen: HashSet<Block> = defs.iter().copied().collect();
485 let mut work: Vec<Block> = defs.to_vec();
486 while let Some(block) = work.pop() {
487 let Some(targets) = frontier.get(&block) else {
488 continue;
489 };
490 for &target in targets {
491 if placed.insert(target) && seen.insert(target) {
492 work.push(target);
493 }
494 }
495 }
496 placed
497}
498
499/// The dominance frontier of every block, by Cytron's walk from each join up to its immediate
500/// dominator.
501fn frontiers(cfg: &Cfg, doms: &Dominators) -> HashMap<Block, Vec<Block>> {
502 let mut frontier: HashMap<Block, Vec<Block>> = HashMap::new();
503 for block in cfg.reverse_postorder() {
504 let preds = cfg.predecessors(block);
505 if preds.len() < 2 {
506 continue;
507 }
508 let Some(top) = doms.immediate_dominator(block) else {
509 continue;
510 };
511 for &pred in preds {
512 let mut runner = pred;
513 while runner != top {
514 let at = frontier.entry(runner).or_default();
515 if !at.contains(&block) {
516 at.push(block);
517 }
518 let Some(next) = doms.immediate_dominator(runner) else {
519 break;
520 };
521 runner = next;
522 }
523 }
524 }
525 frontier
526}
527
528/// The walk back through the memory chain.
529///
530/// It borrows the function rather than owning anything, and it holds the alias analysis because
531/// every step is a query and the escape analysis inside it is worth building once.
532#[derive(Debug)]
533pub struct Walk<'a> {
534 func: &'a Func,
535 cfg: Cfg,
536 alias: Alias<'a>,
537 limit: u32,
538 counts: Counts,
539 /// The versions the walk under way has been to. Emptied for each walk rather than made again,
540 /// so the room it grew to is used again.
541 seen: Seen,
542}
543
544/// A set of versions of memory, hashed with [`rucc_base::hash::Mix`] rather than SipHash.
545///
546/// A walk starts one of these for every load it is asked about and puts every version it passes
547/// into it, and on jtckdint's `test.c` hashing them was more than a percent of the build. A value
548/// is a small dense number that nobody outside picks, so there is nothing for SipHash to defend
549/// against.
550type Seen = Set<Value>;
551
552impl<'a> Walk<'a> {
553 /// A walk over this function, with GCC's budget.
554 #[must_use]
555 pub fn new(func: &'a Func, outside: &'a Outside) -> Self {
556 Self::with(func, outside, Options::default(), MAX_ALIAS_QUERIES_PER_ACCESS)
557 }
558
559 /// The same, with the alias options the command line left and a budget of your own.
560 #[must_use]
561 pub fn with(func: &'a Func, outside: &'a Outside, options: Options, limit: u32) -> Self {
562 Self {
563 func,
564 cfg: Cfg::new(func),
565 alias: Alias::with(func, outside, options),
566 limit,
567 counts: Counts::default(),
568 seen: Seen::default(),
569 }
570 }
571
572 /// What the walks have cost so far.
573 #[must_use]
574 pub const fn counts(&self) -> &Counts {
575 &self.counts
576 }
577
578 /// The same walk, with what the module's functions were worked out to do to memory.
579 ///
580 /// Handed straight to the oracle underneath, where [`Alias::knowing`] says what it is for.
581 #[must_use]
582 pub fn knowing(mut self, summaries: &'a crate::modref::Summaries) -> Self {
583 self.alias = self.alias.knowing(summaries);
584 self
585 }
586
587 /// The alias analysis underneath, whose own counters say which layer answered.
588 #[must_use]
589 pub const fn alias(&self) -> &Alias<'a> {
590 &self.alias
591 }
592
593 /// The store this load sees.
594 ///
595 /// [`Clobber::Unknown`] for an instruction that reads nothing, for one that is not on the
596 /// chain, and for a walk that ran out of budget, because all three mean the same thing to a
597 /// caller, which is that nothing was established.
598 pub fn clobber(&mut self, load: Inst) -> Clobber {
599 self.clobber_with(load, &mut |_, _| Step::Stop)
600 }
601
602 /// The same, with the chance to rewrite the reference at every def the walk cannot see past.
603 ///
604 /// Section 9.2's `translate`. The callback is handed the reference as it stands and the def
605 /// in the way, and answers [`Step::Stop`] to take the clobber or [`Step::Retry`] to carry on
606 /// past it asking about something else. Following a load through a `memcpy` by rewriting the
607 /// reference to the copy's source is the case worth having it for, since that is what a
608 /// struct assignment lowers to.
609 ///
610 /// Section 9.6 calls a `translate` that rewrites the reference wrongly the subtlest bug in
611 /// the document and essentially untestable by unit test, so the defence is differential
612 /// execution per document 41 rather than anything here.
613 pub fn clobber_with(
614 &mut self,
615 load: Inst,
616 translate: &mut dyn FnMut(&Access, Inst) -> Step,
617 ) -> Clobber {
618 let (Some(reference), Some(version)) = (self.alias.reads(load), self.func.mem_in(load))
619 else {
620 return Clobber::Unknown;
621 };
622 self.counts.walks += 1;
623 let mut budget = self.limit;
624 let mut seen = std::mem::take(&mut self.seen);
625 seen.clear();
626 let answer = self.back(reference, version, &mut budget, &mut seen, translate);
627 self.seen = seen;
628 // Nothing new on any path back is nothing that wrote it, which is the same answer as
629 // reaching the start of the chain and is only reachable through a cycle of parameters.
630 answer.unwrap_or(Clobber::NoClobber)
631 }
632
633 /// One version of memory, and everything that reaches it.
634 ///
635 /// `None` means this version has already been accounted for on another path, which is the
636 /// neutral answer: it is how a loop is cut, since the back edge of a loop whose body writes
637 /// nothing relevant leads back to the parameter the walk started from.
638 fn back(
639 &mut self,
640 reference: Access,
641 version: Value,
642 budget: &mut u32,
643 seen: &mut Seen,
644 translate: &mut dyn FnMut(&Access, Inst) -> Step,
645 ) -> Option<Clobber> {
646 if !seen.insert(version) {
647 return None;
648 }
649 match self.func[version].def {
650 // A memory phi. The answer is the same down every path into the block or it is not
651 // an answer, which is conservative and is what keeps a caller from acting on a store
652 // that only one predecessor made.
653 Def::Param { block, index } => {
654 let mut answer = None;
655 let func = self.func;
656 // By place rather than by copying the list out, since the walk below needs the
657 // walker and a phi is the step it takes most often.
658 for at in 0..self.cfg.predecessors(block).len() {
659 let pred = self.cfg.predecessors(block)[at];
660 let Some(terminator) = func.terminator(pred) else {
661 continue;
662 };
663 for call in func.successors(terminator) {
664 if call.block != block {
665 continue;
666 }
667 let Some(&incoming) = self.func[call.args].get(index as usize) else {
668 continue;
669 };
670 let one = self.back(reference, incoming, budget, seen, translate);
671 answer = combine(answer, one);
672 if answer == Some(Clobber::Unknown) {
673 return answer;
674 }
675 }
676 }
677 answer
678 }
679 Def::Result { inst, .. } => {
680 if self.func[inst].opcode == Opcode::MemEntry {
681 return Some(Clobber::NoClobber);
682 }
683 if *budget == 0 {
684 self.counts.exhausted += 1;
685 return Some(Clobber::Unknown);
686 }
687 *budget -= 1;
688 self.counts.steps += 1;
689 let past = match self.wrote(&reference, inst) {
690 None => reference,
691 Some(answer) => match translate(&reference, inst) {
692 Step::Stop => return Some(answer),
693 // A rewritten question is a walk of its own and gets a visited set of its
694 // own. The set is there to stop a cycle being walked twice, and what makes
695 // the second time round pointless is that the answer at a version is an
696 // answer about one reference: a version this walk has already been to was
697 // visited asking something else, and what it said then says nothing about
698 // what is being asked now. Carrying the set across the rewrite loses an
699 // answer rather than repeating one, because a version declined as already
700 // seen contributes nothing to the join above it, and a join whose two paths
701 // disagree would come back holding whichever of them was walked first
702 // rather than `Unknown`.
703 Step::Retry(next) => {
704 self.counts.rewritten += 1;
705 let before = self.func.mem_in(inst)?;
706 let mut fresh = Seen::default();
707 return self.back(next, before, budget, &mut fresh, translate);
708 }
709 },
710 };
711 let next = self.func.mem_in(inst)?;
712 self.back(past, next, budget, seen, translate)
713 }
714 }
715 }
716
717 /// Whether this def wrote the reference, and how much of it.
718 ///
719 /// `None` is the answer that lets the walk carry on, and it is only given where the alias
720 /// analysis said the two cannot touch the same byte.
721 fn wrote(&mut self, reference: &Access, inst: Inst) -> Option<Clobber> {
722 // Section 9.5, and it is first. Alias analysis says nothing about how many times an
723 // access happens and `volatile` constrains that too, so this is a separate bit rather
724 // than a strong alias fact, and it is checked before the analysis is asked anything.
725 if reference.volatile || self.func[inst].flags.contains(Flags::VOLATILE) {
726 return Some(Clobber::Maybe(inst));
727 }
728 // Every atomic and every fence is a full def and a full use. Pessimistic for lock-free
729 // code and correct, and section 9.5 says doing better means modelling the memory model
730 // rather than the memory, which is post-1.0.
731 if self.ordered(inst) {
732 return Some(Clobber::Maybe(inst));
733 }
734 if let Some(write) = self.alias.writes(inst) {
735 return match self.alias.query(reference, &write) {
736 Answer::No(_) => None,
737 Answer::May => Some(self.extent(reference, &write, inst)),
738 };
739 }
740 // A call, or anything else that writes memory without an access saying what. What a call
741 // touches is its attributes and the escape analysis, which is section 8.4's, and without
742 // those the honest answer is that it wrote everything.
743 match self.alias.clobbered_by(reference, inst) {
744 Answer::No(_) => None,
745 Answer::May => Some(Clobber::Maybe(inst)),
746 }
747 }
748
749 /// How much of the reference a write that may touch it covered.
750 ///
751 /// Two accesses to the same origin with both offsets and both sizes known are two runs of
752 /// bytes at known places, and comparing them is what tells `Exact` from `Partial`. Anything
753 /// less is `Maybe`, since a `May` from the alias analysis is not a proof that anything was
754 /// written at all.
755 ///
756 /// `Exact` is the same bytes and not merely a superset of them. A four byte store and the
757 /// one byte load at offset one inside it is `Partial`, because the byte the load wants is
758 /// somewhere in the value the store wrote and getting it out is a shift and a truncate that
759 /// document 16 decides on rather than this. Two runs that are the same bytes can still be
760 /// two different types, and checking that is the caller's as well.
761 fn extent(&self, reference: &Access, write: &Access, inst: Inst) -> Clobber {
762 if reference.origin != write.origin {
763 return Clobber::Maybe(inst);
764 }
765 let (Some(want), Some(wrote)) = (reference.range(), write.range()) else {
766 return Clobber::Maybe(inst);
767 };
768 if want == wrote {
769 Clobber::Exact(inst)
770 } else if wrote.0 < want.1 && want.0 < wrote.1 {
771 Clobber::Partial(inst)
772 } else {
773 // No overlap at all, which the alias analysis should have said no to. Saying `Maybe`
774 // rather than walking past is the conservative reading of a disagreement.
775 Clobber::Maybe(inst)
776 }
777 }
778
779 /// Whether the instruction orders memory, which is every atomic and every fence.
780 fn ordered(&self, inst: Inst) -> bool {
781 use rucc_ir::Extra;
782 let order = match self.func[inst].extra {
783 Extra::Mem(at) => self.func[at].order,
784 Extra::Rmw(_, at) => self.func[at].order,
785 Extra::Order(order) => order,
786 _ => return false,
787 };
788 order != MemOrder::NotAtomic
789 }
790}
791
792/// Two answers from two paths into a join.
793///
794/// The same answer on both is the answer. Nothing on one path is whatever the other said, which
795/// is how a cycle contributes nothing. Anything else is a disagreement, and a disagreement is
796/// `Unknown` rather than the weaker of the two, because there is no order on these that a caller
797/// could act on.
798fn combine(a: Option<Clobber>, b: Option<Clobber>) -> Option<Clobber> {
799 match (a, b) {
800 (None, other) | (other, None) => other,
801 (Some(one), Some(other)) if one == other => Some(one),
802 _ => Some(Clobber::Unknown),
803 }
804}
805
806#[cfg(test)]
807mod tests {
808 use rucc_base::Interner;
809 use rucc_ir::{Builder, MemInfo, Module, Restrict, Signature, parse, verify_func};
810
811 use super::*;
812
813 /// A module and a function built from the text, which is how these are written.
814 fn read(text: &str) -> (Module, Interner) {
815 let mut names = Interner::new();
816 let module = parse(text, &mut names).expect("the text parses");
817 (module, names)
818 }
819
820 const HEADER: &str = "\
821; ModuleID = 'mem.c'
822; format 0
823target triple = \"x86_64-unknown-linux-gnu\"
824target datalayout = \"e-p:64:64-i64:64-f80:128-S128\"
825";
826
827 fn wrap(signature: &str, body: &str) -> String {
828 format!("{HEADER}\nfunc @f{signature}, linkage(external) {{\n{body}}}\n")
829 }
830
831 /// Builds memory SSA over the function and insists the result verifies, which is where most
832 /// of the strength of these tests is: the rules in the verifier are the specification of the
833 /// chain and construction has to satisfy all of them.
834 fn built(text: &str) -> (Module, bool) {
835 let (mut module, names) = read(text);
836 let id = module.funcs().next().expect("one function");
837 let changed = build(&mut module[id]);
838 if let Err(errors) = verify_func(&module, &module[id], &names) {
839 panic!("{errors:#?}");
840 }
841 (module, changed)
842 }
843
844 fn one(module: &Module) -> &Func {
845 &module[module.funcs().next().expect("one function")]
846 }
847
848 /// The instruction with that opcode, counting from the top of the function.
849 fn nth(func: &Func, opcode: Opcode, want: usize) -> Inst {
850 func.blocks()
851 .flat_map(|block| func.insts(block).collect::<Vec<_>>())
852 .filter(|&inst| func[inst].opcode == opcode)
853 .nth(want)
854 .expect("that many of them")
855 }
856
857 #[test]
858 fn a_function_with_no_memory_in_it_gets_no_chain() {
859 let text = wrap(
860 "(i32) -> i32",
861 "block0(%0: i32):
862 %1 = add %0, %0
863 return %1
864",
865 );
866 let (module, changed) = built(&text);
867 assert!(!changed);
868 assert_eq!(one(&module).blocks().count(), 1);
869 }
870
871 #[test]
872 fn a_straight_line_is_threaded_in_order() {
873 let text = wrap(
874 "(ptr) -> i32",
875 "block0(%0: ptr):
876 %1 = iconst.i32 7
877 store %1 -> %0, align 4
878 %2 = load.i32 %0, align 4
879 return %2
880",
881 );
882 let (module, changed) = built(&text);
883 assert!(changed);
884 let func = one(&module);
885 let start = nth(func, Opcode::MemEntry, 0);
886 let store = nth(func, Opcode::Store, 0);
887 let load = nth(func, Opcode::Load, 0);
888 assert_eq!(func.mem_in(store), func.mem_out(start));
889 assert_eq!(func.mem_in(load), func.mem_out(store));
890 assert_eq!(func.mem_out(load), None);
891 }
892
893 #[test]
894 fn a_join_gets_a_memory_parameter_and_every_branch_passes_one() {
895 let text = wrap(
896 "(ptr, i1) -> i32",
897 "block0(%0: ptr, %1: i1):
898 br_if %1, block1, block2
899
900block1:
901 %2 = iconst.i32 7
902 store %2 -> %0, align 4
903 jump block3
904
905block2:
906 jump block3
907
908block3:
909 %3 = load.i32 %0, align 4
910 return %3
911",
912 );
913 let (module, _) = built(&text);
914 let func = one(&module);
915 let join = func.blocks().nth(3).expect("four blocks");
916 assert_eq!(func[join].params.len(), 1);
917 let param = func[join].params[0];
918 assert!(func[param].ty.is_mem());
919 assert_eq!(func.mem_in(nth(func, Opcode::Load, 0)), Some(param));
920 }
921
922 #[test]
923 fn a_block_that_only_reads_needs_no_parameter() {
924 let text = wrap(
925 "(ptr, i1) -> i32",
926 "block0(%0: ptr, %1: i1):
927 br_if %1, block1, block2
928
929block1:
930 %2 = load.i32 %0, align 4
931 jump block3
932
933block2:
934 jump block3
935
936block3:
937 %3 = load.i32 %0, align 4
938 return %3
939",
940 );
941 let (module, _) = built(&text);
942 let func = one(&module);
943 // One version of memory reaches the whole function, so no join needs a parameter and
944 // every load reads what `mem_entry` produced.
945 for block in func.blocks() {
946 assert!(func[block].params.iter().all(|¶m| !func[param].ty.is_mem()));
947 }
948 }
949
950 #[test]
951 fn every_arm_of_a_switch_passes_its_own_version_along() {
952 let text = wrap(
953 "(ptr, i32) -> i32",
954 "block0(%0: ptr, %1: i32):
955 switch %1, block1, [0 => block2, 1 => block3]
956
957block1:
958 %2 = iconst.i32 1
959 store %2 -> %0, align 4
960 jump block4
961
962block2:
963 %3 = iconst.i32 2
964 store %3 -> %0, align 4
965 jump block4
966
967block3:
968 jump block4
969
970block4:
971 %4 = load.i32 %0, align 4
972 return %4
973",
974 );
975 let (module, _) = built(&text);
976 let func = one(&module);
977 let join = func.blocks().nth(4).expect("five blocks");
978 let param = *func[join].params.last().expect("a parameter");
979 assert!(func[param].ty.is_mem());
980 // Each arm reaches the join with the version it ended on, and the two that wrote reach
981 // it with the version their own store produced.
982 for (arm, want) in [(1, Some(0)), (2, Some(1)), (3, None)] {
983 let block = func.blocks().nth(arm).expect("that block");
984 let jump = func.terminator(block).expect("a terminator");
985 let call = func.successors(jump).next().expect("one target");
986 let sent = *func[call.args].last().expect("an argument");
987 let expect = match want {
988 Some(store) => func.mem_out(nth(func, Opcode::Store, store)),
989 None => func.mem_out(nth(func, Opcode::MemEntry, 0)),
990 };
991 assert_eq!(Some(sent), expect, "arm {arm} passed the wrong version");
992 }
993 }
994
995 #[test]
996 fn a_function_with_a_block_nothing_reaches_is_left_alone() {
997 let text = wrap(
998 "(ptr) -> i32",
999 "block0(%0: ptr):
1000 %1 = iconst.i32 7
1001 store %1 -> %0, align 4
1002 jump block2
1003
1004block1:
1005 %2 = iconst.i32 9
1006 store %2 -> %0, align 4
1007 jump block2
1008
1009block2:
1010 %3 = load.i32 %0, align 4
1011 return %3
1012",
1013 );
1014 // Block 1 has no predecessor. Half a function on the chain is worse than none of it, so
1015 // this declines rather than producing something the verifier would turn down.
1016 let (mut module, _) = read(&text);
1017 let id = module.funcs().next().expect("one function");
1018 assert!(!build(&mut module[id]));
1019 assert_eq!(module[id].blocks().filter(|&b| !module[id][b].params.is_empty()).count(), 1);
1020 }
1021
1022 /// The last load in the function, which is the one every walk here starts from.
1023 fn last_load(func: &Func) -> Inst {
1024 func.blocks()
1025 .flat_map(|block| func.insts(block).collect::<Vec<_>>())
1026 .filter(|&inst| func[inst].opcode == Opcode::Load)
1027 .last()
1028 .expect("a load")
1029 }
1030
1031 /// A load, a store and the walk between them, over a function written as text.
1032 fn walked(text: &str) -> (Clobber, Counts) {
1033 let (module, changed) = built(text);
1034 assert!(changed, "the function has memory in it");
1035 let func = one(&module);
1036 let outside = Outside::of(&module);
1037 let mut walk = Walk::new(func, &outside);
1038 let answer = walk.clobber(last_load(func));
1039 (answer, *walk.counts())
1040 }
1041
1042 #[test]
1043 fn a_load_sees_the_store_before_it() {
1044 let text = wrap(
1045 "(ptr) -> i32",
1046 "block0(%0: ptr):
1047 %1 = iconst.i32 7
1048 store %1 -> %0, align 4
1049 %2 = load.i32 %0, align 4
1050 return %2
1051",
1052 );
1053 let (answer, counts) = walked(&text);
1054 assert!(matches!(answer, Clobber::Exact(_)));
1055 assert_eq!(counts.walks(), 1);
1056 assert_eq!(counts.steps(), 1);
1057 assert_eq!(counts.exhausted(), 0);
1058 }
1059
1060 #[test]
1061 fn a_load_walks_past_a_store_to_another_object() {
1062 let text = wrap(
1063 "() -> i32",
1064 "block0:
1065 %0 = alloca, size 8, align 8
1066 %1 = alloca, size 8, align 8
1067 %2 = iconst.i32 7
1068 store %2 -> %0, align 4
1069 %3 = load.i32 %1, align 4
1070 return %3
1071",
1072 );
1073 let (answer, counts) = walked(&text);
1074 assert_eq!(answer, Clobber::NoClobber);
1075 // It looked at the store, said no, and reached the start of the chain.
1076 assert_eq!(counts.steps(), 1);
1077 }
1078
1079 #[test]
1080 fn a_load_of_one_byte_of_a_wider_store_is_partial() {
1081 let text = wrap(
1082 "() -> i8",
1083 "block0:
1084 %0 = alloca, size 8, align 8
1085 %1 = iconst.i32 7
1086 store %1 -> %0, align 4
1087 %2 = iconst.i64 1
1088 %3 = ptr_add %0, %2
1089 %4 = load.i8 %3, align 1
1090 return %4
1091",
1092 );
1093 let (answer, _) = walked(&text);
1094 assert!(matches!(answer, Clobber::Partial(_)), "{answer:?}");
1095 }
1096
1097 #[test]
1098 fn a_load_after_a_call_that_cannot_reach_it_walks_past_the_call() {
1099 let text = wrap(
1100 "() -> i32",
1101 "block0:
1102 %0 = alloca, size 8, align 8
1103 %1 = iconst.i32 7
1104 store %1 -> %0, align 4
1105 call @g() : ()
1106 %2 = load.i32 %0, align 4
1107 return %2
1108",
1109 );
1110 // The local's address never leaves the function, so the call cannot touch it and the
1111 // walk goes straight past to the store. That is the escape layer paying for itself.
1112 let (answer, _) = walked(&text);
1113 assert!(matches!(answer, Clobber::Exact(_)), "{answer:?}");
1114 }
1115
1116 #[test]
1117 fn a_load_after_a_call_that_could_have_the_address_sees_the_call() {
1118 let text = wrap(
1119 "(ptr) -> i32",
1120 "block0(%0: ptr):
1121 %1 = iconst.i32 7
1122 store %1 -> %0, align 4
1123 call @g() : ()
1124 %2 = load.i32 %0, align 4
1125 return %2
1126",
1127 );
1128 let (answer, _) = walked(&text);
1129 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1130 }
1131
1132 #[test]
1133 fn a_load_after_an_atomic_store_sees_it_whatever_it_wrote() {
1134 let text = wrap(
1135 "() -> i32",
1136 "block0:
1137 %0 = alloca, size 8, align 8
1138 %1 = alloca, size 8, align 8
1139 %2 = iconst.i32 7
1140 atomic_store %2 -> %0, align 4, release
1141 %3 = load.i32 %1, align 4
1142 return %3
1143",
1144 );
1145 // Two different objects, and it still stops: an atomic is a full def and a full use, per
1146 // section 9.5, and this is the test that says so rather than a comment.
1147 let (answer, _) = walked(&text);
1148 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1149 }
1150
1151 #[test]
1152 fn a_load_after_a_volatile_store_sees_it_whatever_it_wrote() {
1153 let text = wrap(
1154 "() -> i32",
1155 "block0:
1156 %0 = alloca, size 8, align 8
1157 %1 = alloca, size 8, align 8
1158 %2 = iconst.i32 7
1159 store.volatile %2 -> %0, align 4
1160 %3 = load.i32 %1, align 4
1161 return %3
1162",
1163 );
1164 let (answer, _) = walked(&text);
1165 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1166 }
1167
1168 #[test]
1169 fn paths_that_disagree_are_unknown_rather_than_the_weaker_of_the_two() {
1170 let text = wrap(
1171 "(i1) -> i32",
1172 "block0(%0: i1):
1173 %1 = alloca, size 8, align 8
1174 br_if %0, block1, block2
1175
1176block1:
1177 %2 = iconst.i32 7
1178 store %2 -> %1, align 4
1179 jump block3
1180
1181block2:
1182 jump block3
1183
1184block3:
1185 %3 = load.i32 %1, align 4
1186 return %3
1187",
1188 );
1189 let (answer, _) = walked(&text);
1190 assert_eq!(answer, Clobber::Unknown);
1191 }
1192
1193 #[test]
1194 fn a_loop_that_writes_nothing_relevant_walks_out_of_it() {
1195 let text = wrap(
1196 "(i32) -> i32",
1197 "block0(%0: i32):
1198 %1 = alloca, size 8, align 8
1199 %2 = alloca, size 8, align 8
1200 %3 = iconst.i32 7
1201 store %3 -> %1, align 4
1202 jump block1(%0)
1203
1204block1(%4: i32):
1205 %5 = iconst.i32 1
1206 %6 = sub %4, %5
1207 store %5 -> %2, align 4
1208 %7 = icmp sgt %6, %5
1209 br_if %7, block1(%6), block2
1210
1211block2:
1212 %8 = load.i32 %1, align 4
1213 return %8
1214",
1215 );
1216 // The store in the loop is to the other object, so the walk goes round the back edge,
1217 // meets the parameter it started from, contributes nothing, and takes the answer from
1218 // the path that leaves the loop.
1219 let (answer, counts) = walked(&text);
1220 assert!(matches!(answer, Clobber::Exact(_)), "{answer:?}");
1221 assert_eq!(counts.exhausted(), 0);
1222 }
1223
1224 #[test]
1225 fn a_budget_of_nothing_gives_unknown_and_says_so() {
1226 let text = wrap(
1227 "(ptr) -> i32",
1228 "block0(%0: ptr):
1229 %1 = iconst.i32 7
1230 store %1 -> %0, align 4
1231 %2 = load.i32 %0, align 4
1232 return %2
1233",
1234 );
1235 let (module, _) = built(&text);
1236 let func = one(&module);
1237 let load = nth(func, Opcode::Load, 0);
1238 let outside = Outside::of(&module);
1239 let mut walk = Walk::with(func, &outside, Options::default(), 0);
1240 assert_eq!(walk.clobber(load), Clobber::Unknown);
1241 assert_eq!(walk.counts().exhausted(), 1);
1242 }
1243
1244 #[test]
1245 fn translate_carries_the_walk_past_a_def_it_would_have_stopped_at() {
1246 let text = wrap(
1247 "(ptr) -> i32",
1248 "block0(%0: ptr):
1249 %1 = iconst.i32 7
1250 store %1 -> %0, align 4
1251 memcpy %0, %0, size 4, align 4
1252 %2 = load.i32 %0, align 4
1253 return %2
1254",
1255 );
1256 let (module, _) = built(&text);
1257 let func = one(&module);
1258 let load = nth(func, Opcode::Load, 0);
1259
1260 // With no rewrite to offer, the copy is where it stops.
1261 let outside = Outside::of(&module);
1262 let mut walk = Walk::new(func, &outside);
1263 let stopped_at = walk.clobber(load).inst().expect("something wrote it");
1264 assert_eq!(func[stopped_at].opcode, Opcode::Memcpy);
1265
1266 // The same walk, with a caller that can see through the copy. It says nothing about the
1267 // reference here, which is enough to show the callback is reached and obeyed.
1268 let mut walk = Walk::new(func, &outside);
1269 let mut seen = Vec::new();
1270 let answer = walk.clobber_with(load, &mut |reference, inst| {
1271 seen.push(func[inst].opcode);
1272 if func[inst].opcode == Opcode::Memcpy { Step::Retry(*reference) } else { Step::Stop }
1273 });
1274 assert_eq!(seen, [Opcode::Memcpy, Opcode::Store]);
1275 assert_eq!(answer.inst().map(|inst| func[inst].opcode), Some(Opcode::Store));
1276
1277 // One rewrite offered and one taken, which is the counter a caller reads to find out
1278 // whether its callback reached anything.
1279 assert_eq!(walk.counts().rewritten(), 1);
1280 }
1281
1282 #[test]
1283 fn building_twice_changes_nothing_the_second_time() {
1284 let text = wrap(
1285 "(ptr) -> i32",
1286 "block0(%0: ptr):
1287 %1 = load.i32 %0, align 4
1288 return %1
1289",
1290 );
1291 let (mut module, _) = read(&text);
1292 let id = module.funcs().next().expect("one function");
1293 let func = &mut module[id];
1294 assert!(build(func));
1295 let before = func.counts().insts;
1296 assert!(!build(func));
1297 assert_eq!(func.counts().insts, before);
1298 }
1299
1300 /// The builder path rather than the parser path, since a pass that adds a store adds it with
1301 /// the builder and the chain has to survive that too.
1302 #[test]
1303 fn a_function_built_by_hand_threads_the_same_way() {
1304 let mut names = Interner::new();
1305 let i32_ = Type::int(32);
1306 let mut func = Func::new(
1307 names.intern("f"),
1308 Signature::new().with_params(&[Type::PTR]).with_returns(&[i32_]),
1309 );
1310 let entry = func.create_block();
1311 let addr = func.append_param(entry, Type::PTR);
1312 let info = MemInfo {
1313 size: 4,
1314 align: 4,
1315 order: MemOrder::NotAtomic,
1316 tbaa: None,
1317 owns: 0,
1318 restrict: Restrict::NONE,
1319 };
1320 let mut b = Builder::new(&mut func, entry);
1321 let seven = b.iconst(i32_, 7);
1322 b.store(seven, addr, info, Flags::NONE);
1323 let read = b.load(i32_, addr, info, Flags::NONE);
1324 b.ret(&[read]);
1325
1326 assert!(build(&mut func));
1327 let store = nth(&func, Opcode::Store, 0);
1328 let load = nth(&func, Opcode::Load, 0);
1329 assert_eq!(func.mem_in(load), func.mem_out(store));
1330 }
1331
1332 /// Builds the chain, takes it back off, and insists the result verifies both times. A half
1333 /// removed chain is exactly the kind of thing that would pass a shape assertion and fail on a
1334 /// real file, so the verifier is the assertion that matters here too.
1335 fn stripped(text: &str) -> (Module, bool) {
1336 let (mut module, names) = read(text);
1337 let id = module.funcs().next().expect("one function");
1338 build(&mut module[id]);
1339 if let Err(errors) = verify_func(&module, &module[id], &names) {
1340 panic!("after building: {errors:#?}");
1341 }
1342 let changed = strip(&mut module[id]);
1343 if let Err(errors) = verify_func(&module, &module[id], &names) {
1344 panic!("after stripping: {errors:#?}");
1345 }
1346 (module, changed)
1347 }
1348
1349 /// Nothing anywhere in the function is on the chain any more.
1350 fn off(func: &Func) {
1351 for block in func.blocks() {
1352 assert!(
1353 func[block].params.iter().all(|¶m| !func[param].ty.is_mem()),
1354 "a block kept a memory parameter"
1355 );
1356 for inst in func.insts(block) {
1357 assert_ne!(
1358 func[inst].opcode,
1359 Opcode::MemEntry,
1360 "the start of the chain is still here"
1361 );
1362 assert!(!func.carries_mem(inst), "an instruction is still on the chain");
1363 }
1364 }
1365 }
1366
1367 #[test]
1368 fn a_straight_line_comes_off_the_chain_the_way_it_went_on() {
1369 let text = wrap(
1370 "(ptr) -> i32",
1371 "block0(%0: ptr):
1372 %1 = iconst.i32 7
1373 store %1 -> %0, align 4
1374 %2 = load.i32 %0, align 4
1375 return %2
1376",
1377 );
1378 let (module, changed) = stripped(&text);
1379 assert!(changed);
1380 let func = one(&module);
1381 off(func);
1382 // The instructions are the same ones doing the same thing, which is the whole claim: the
1383 // address the load reads is still the function's parameter and the value returned is
1384 // still what the load read.
1385 let load = nth(func, Opcode::Load, 0);
1386 let param = func[func.entry().expect("an entry")].params[0];
1387 assert_eq!(func[func[load].args][0], param);
1388 let ret = nth(func, Opcode::Return, 0);
1389 assert_eq!(func[func[ret].args][0], func[load].results().next().expect("a result"));
1390 }
1391
1392 #[test]
1393 fn a_join_gives_its_memory_parameter_back_and_so_does_every_branch_to_it() {
1394 let text = wrap(
1395 "(ptr, i1) -> i32",
1396 "block0(%0: ptr, %1: i1):
1397 br_if %1, block1, block2
1398
1399block1:
1400 %2 = iconst.i32 7
1401 store %2 -> %0, align 4
1402 jump block3
1403
1404block2:
1405 jump block3
1406
1407block3:
1408 %3 = load.i32 %0, align 4
1409 return %3
1410",
1411 );
1412 let (module, changed) = stripped(&text);
1413 assert!(changed);
1414 let func = one(&module);
1415 off(func);
1416 let join = func.blocks().nth(3).expect("four blocks");
1417 assert!(func[join].params.is_empty(), "the join kept a parameter");
1418 for block in func.blocks() {
1419 let Some(terminator) = func.terminator(block) else { continue };
1420 for call in func.successors(terminator) {
1421 assert!(func[call.args].is_empty(), "a branch kept an argument");
1422 }
1423 }
1424 }
1425
1426 #[test]
1427 fn a_parameter_that_was_never_memory_keeps_its_place() {
1428 // The argument a branch passes goes by position, so a block with a memory parameter
1429 // beside an ordinary one is where taking the wrong one out would show.
1430 let text = wrap(
1431 "(ptr, i1) -> i32",
1432 "block0(%0: ptr, %1: i1):
1433 %2 = iconst.i32 7
1434 br_if %1, block1(%2), block2
1435
1436block1(%3: i32):
1437 store %3 -> %0, align 4
1438 jump block3
1439
1440block2:
1441 jump block3
1442
1443block3:
1444 %4 = load.i32 %0, align 4
1445 return %4
1446",
1447 );
1448 let (module, _) = stripped(&text);
1449 let func = one(&module);
1450 off(func);
1451 let arm = func.blocks().nth(1).expect("four blocks");
1452 assert_eq!(func[arm].params.len(), 1);
1453 let param = func[arm].params[0];
1454 assert_eq!(func[param].ty, Type::int(32));
1455 let store = nth(func, Opcode::Store, 0);
1456 assert_eq!(func[func[store].args][0], param, "the store lost the value it writes");
1457 }
1458
1459 #[test]
1460 fn a_function_that_was_never_on_the_chain_is_left_alone() {
1461 let text = wrap(
1462 "(i32) -> i32",
1463 "block0(%0: i32):
1464 %1 = add %0, %0
1465 return %1
1466",
1467 );
1468 let (mut module, names) = read(&text);
1469 let id = module.funcs().next().expect("one function");
1470 assert!(!strip(&mut module[id]));
1471 if let Err(errors) = verify_func(&module, &module[id], &names) {
1472 panic!("{errors:#?}");
1473 }
1474 }
1475
1476 #[test]
1477 fn a_call_that_returns_something_keeps_it() {
1478 // A call is threaded like a store and gives back a value as well, so its results are the
1479 // one place where the version of memory sits behind something that has a reader.
1480 let text = format!(
1481 "{HEADER}\nfunc @f() -> i32, linkage(external) {{\nblock0:\n %0 = call @g() : () -> \
1482 i32\n return %0\n}}\n"
1483 );
1484 let (module, changed) = stripped(&text);
1485 assert!(changed);
1486 let func = one(&module);
1487 off(func);
1488 let call = nth(func, Opcode::Call, 0);
1489 let ret = nth(func, Opcode::Return, 0);
1490 assert_eq!(func[call].results().count(), 1);
1491 assert_eq!(func[func[ret].args][0], func[call].results().next().expect("a result"));
1492 }
1493}