Skip to main content

rucc_opt/
pipeline.rs

1//! The pipelines, one per optimization level, and the manager that runs one.
2//!
3//! Section 9.1 of `spec/09-optimizer.md` says the pipelines are written out rather than assembled
4//! from flags, and gives the reason: the prior art ran the same pipeline at every level and named
5//! that as a limitation. A level here is a list of pass names, and the list is the definition of
6//! the level rather than something that emerges from which flags happen to be set.
7//!
8//! Section 9.10 says the manager is deliberately boring. There is no adaptive ordering and no
9//! scheduling heuristic, because document 03's determinism rule needs the same input to produce
10//! the same output on every host and predictability is worth more than the last percent.
11//!
12//! What the manager does beyond running the list is the four things that make a pass debuggable:
13//! it counts each pass's transformations against its fuel, it collects what each pass said it did
14//! and did not do, it dumps the IR around whichever passes were asked for, and it verifies any
15//! function a pass changed.
16//!
17//! That last one is section 41.4 of `spec/optimizer/41-correctness.md`, which reads GCC's
18//! `execute_function_todo` and takes six things from it. Three of them are already true here by
19//! construction and are worth naming so that nobody looks for them. GCC verifies what the IR
20//! currently is, by consulting `curr_properties`, because its IR passes through GENERIC, GIMPLE
21//! with and without a CFG, GIMPLE in SSA, and RTL. rucc has one IR, it is in SSA from the moment
22//! the lowering walk builds it, and it always has a CFG, so the applicable set never varies and a
23//! bitmask saying so would have nothing to say. GCC guards the verifiers with `!seen_error()`,
24//! because after a user error the IR is legitimately malformed and an internal error raised over
25//! it hides the real diagnostic. Here the optimizer is not reached at all after a parse, check or
26//! lowering error, which is the same guard placed one level up where it cannot be forgotten. And
27//! GCC asserts that a verifier did not change the dominator state. Here a verifier takes the
28//! module by shared reference, so that is a type error rather than an assertion.
29//!
30//! What is left of the six is the part below: verify what changed, not everything, and say which
31//! function it was.
32
33use std::collections::{HashMap, HashSet};
34use std::fmt::Write as _;
35use std::sync::Arc;
36
37use rucc_base::{Interner, Symbol};
38use rucc_ir::{Datum, FuncId, Global, Imm, Linkage, Module, Pic};
39use rucc_session::OptLevel;
40
41use crate::{
42    Analyses, CallGraph, Fuel, Gates, Machine, Pass, Preserved, Stats, constant_p, dce, extents,
43    heap, image, ipasra, ipcp, libcall, load, modref, nofree, number, objsize, outside, params,
44    pass, purity, readonly, reload,
45};
46
47/// The passes that read a summary [`nofree::annotate`], [`extents::annotate`],
48/// [`params::annotate`] or [`heap::annotate`] writes onto the IR.
49///
50/// A list rather than one name because there will be more of them: section 7.5 asks for three more
51/// summary fields and section 7.3's lifetime elimination is the next thing to want this one. A pass
52/// that reads a summary and is not named here reads whatever the last build left, which is nothing,
53/// so the cost of forgetting to add a name is a missed optimization.
54///
55/// The five after the first are `crate::discharge`'s measurement runs, and leaving them out was a
56/// missed optimization of exactly that kind: a run measuring what an object says about itself, with
57/// no table saying how big any global is, answers that objects say nothing, and the number looks
58/// like a result rather than like a list with a name missing from it.
59const READS_SUMMARIES: &[&str] = &[
60    "discharge",
61    "discharge-objects",
62    "discharge-dominance",
63    "discharge-summaries",
64    "discharge-narrow",
65    "discharge-every",
66];
67
68/// Which passes build an alias oracle, and so want the module facts it asks about.
69///
70/// A list for the same reason as the one above, and it will grow the same way: the redundant load
71/// elimination of `spec/optimizer/16-gvn-and-pre.md` section 16.2 and the dead store elimination of
72/// document 17 both want one, and neither is written. A pass left off here builds its oracle on an
73/// empty table, which answers `May` to every question it would have used the module for, so what
74/// forgetting a name costs is a missed optimization rather than a wrong answer.
75const READS_OUTSIDE: &[&str] = &[load::NAME, reload::NAME];
76
77/// Which passes ask what a call is allowed to do.
78///
79/// Two, which are two of the four consumers section 34.6 of `spec/optimizer/34-ipa.md` names.
80/// Document 17's dead code elimination deletes a call whose result nothing reads. Document 16's
81/// value numbering makes two calls with the same arguments one value. The other two turned out to
82/// want the finer answer rather than this one and are in the list below: document 27.1's
83/// speculation predicate and document 08.4's call handling both read the mod and ref summaries,
84/// which say which memory rather than whether any. A list from the start for the reason the two
85/// above it are lists, which is that a pass left out of one reads the empty answer and loses an
86/// optimization rather than producing a wrong program.
87const READS_PURITY: &[&str] = &[dce::NAME, number::NAME];
88
89/// Which passes ask what a call does to the memory it was handed.
90///
91/// The two that move a load, which is the question section 34.6 says the per parameter answer is
92/// worth having for: whether the call in the middle of this loop can have written the array about
93/// to be reloaded. A list for the same reason as the three above it.
94const READS_MODREF: &[&str] = &[load::NAME, reload::NAME];
95
96/// `-O0`. Two passes, and neither of them is an optimization. Section 9.1 gives this level SSA
97/// construction, which the lowering walk in `spec/08-ir.md` already does, and mem2reg for the
98/// allocas that are left, which is the next pass to be written.
99///
100/// `expect` is here because what it takes out is a node the front end writes for every
101/// `__builtin_expect` in the program and gcc writes for none of them. Left standing it would be an
102/// instruction in the output of a level whose whole contract is that it emits what it was given.
103///
104/// `simplify-cfg` is here because a branch on a condition that is a constant is not a missed
105/// optimization, it is a call to a function the program never calls, and a program that calls a
106/// function it never calls is one that does not link. That is issue 359, gcc removes the code at
107/// every level including this one, and a `-O0` that emitted it would be a `-O0` some correct
108/// programs cannot be built at. Nothing else runs, and no analysis beyond the graph the pass
109/// reads reachability out of is computed.
110const O0: &[&str] = &["expect", "simplify-cfg"];
111
112/// `-O1`. Section 9.1 asks for one e-graph round, conservative inlining, simplify-CFG, SROA,
113/// GVN, DCE, LICM and the loop canonicalizations. Folding, control flow simplification and dead
114/// code elimination are the part of that which exists, with the peephole among them. They run in
115/// that order because folding and the peephole are what make most of the dead code there is to
116/// eliminate, because a constant a fold produced is a branch condition the control flow pass can
117/// then read, and because the comparison that branch was on is dead once it has.
118///
119/// `image` has a `fold` on each side of it, which is the other place in this list where a pass is
120/// named twice in a row, and both of them are the position rather than the pass. What it reads is
121/// a load from a `const` global at a constant byte offset, and until something has folded the
122/// address there is no constant byte offset: a subscript arrives from the front end as the index
123/// sign extended and multiplied by the element size, so without the `fold` ahead of it every array
124/// and every string in the program is a load it cannot answer. The `fold` behind it is the mirror
125/// of that. What `image` writes is a constant where a load stood, and what stands on top of it is
126/// whatever the program did with the value it read, so a `const double` converted to an `int` and
127/// compared against one is three folds in a row and only the first of them is this pass. Nothing
128/// later in the list would do it in time: the branch passes read the condition, and a condition
129/// still spelled as a conversion of a constant is a branch they leave standing. Running `image`
130/// before the pipeline rather than inside it is the alternative that does not work, and
131/// `crate::image` says at length why.
132///
133/// The peephole runs on both sides of `narrow`, which is the one place in this list where a pass
134/// is named twice, so the reason is worth stating. The rewrite table is written at a width, and
135/// the widths below `int` are unreachable from C source: the integer promotions mean an addition
136/// of two `char` values arrives here as an `add.i32`, so a rule about `add.i8` matches nothing
137/// that a front end can produce. `narrow` is what puts the width back, and it is therefore the
138/// only producer the narrow half of the table has. Running the peephole only before it left
139/// sixty nine of the first hundred and twenty five rules unable to fire on any program, which is
140/// issue 505 and is what the corpus measured. Running it only after it would give up the smaller
141/// trees the peephole hands `narrow`, since a subtree `narrow` redoes has to have one reader and
142/// an identity left standing is a second one. Both sides costs one more walk over each function
143/// and is what the pass is for.
144///
145/// `phiopt` comes after `thread` and the order between them is not arbitrary. Both look at a
146/// diamond whose arms carry a value to a join. Where the join then branches on that value,
147/// threading removes a branch and costs nothing, and if-conversion would have turned the same
148/// shape into a `select` the join branches on instead, which is strictly worse. Threading first
149/// leaves if-conversion the diamonds whose value is used rather than tested, which are the ones it
150/// is for.
151///
152/// `prune` is between `phiopt` and `simplify-cfg` and both sides of that are load bearing. It reads
153/// document 10's ranges off the graph to find a branch that can only go one way and a switch case
154/// nothing can reach, so it has to run after the two passes that change the graph most. What it
155/// leaves is a jump where a branch was and a block nothing reaches, and `simplify-cfg` is the pass
156/// that takes those out, so it has to run before it rather than after.
157///
158/// `canon` is where document 26's loop pipeline opens, so it goes after the value level passes and
159/// before the cleanup. It gives every loop a preheader, one latch, exits of its own and loop closed
160/// form, which is what lets the loop passes that follow it write `insert at the end of the
161/// preheader` rather than each making one. On its own it generates nothing: the blocks it adds are
162/// empty and the parameters it adds have one argument each, and `simplify-cfg` runs straight after
163/// it and takes both back out to a fixed point. That is section 26.7's arrangement, and it is why
164/// the position matters more than the pass does until the loop passes land on top of it.
165///
166/// `header-copy` is section 26.7's third step and `canon` runs again after it, which is the same
167/// section's instruction to re-canonicalize the loops it changed. It has to: what the copy leaves
168/// is a loop entered from a block that branches two ways, and a block that branches two ways is not
169/// a preheader. Nothing between the two needs the properties, so the second run is bookkeeping
170/// against the loop passes that come later rather than something this level's output depends on,
171/// and `simplify-cfg` after it takes out the blocks and parameters both runs added that nothing
172/// used.
173///
174/// `licm` comes after the copy and the canonicalization behind it, and section 27.1 says why it has
175/// to. What it may move in front of a loop depends on what runs on every entry to the loop, and
176/// after that pair that is the whole body rather than the header alone. Running it before the
177/// copy would leave it the header, which is most of the pass's value gone. It is also the reason
178/// the copy exists, so the two are one arrangement read from either end.
179///
180/// It is in the three speed levels and not in `-Os` or `-Oz`. Moving a computation out of a loop
181/// does not remove one, so there are no bytes in it for a level whose cost model is size, and the
182/// one thing it can cost is a spill inside the loop, which is bytes. That trade is worth making for
183/// time and there is nothing on the other side of it for space.
184///
185/// `unroll` runs after `licm` and only at the two speed levels. After, because what it does is copy
186/// the body, and a computation licm has already moved in front of the loop is one the copies do not
187/// each get their own of. It needs the same shape licm does and for the same reason, a loop that
188/// tests at the bottom with a preheader in front of it, so it sits at the end of the same run of
189/// loop passes rather than anywhere of its own. `simplify-cfg` straight after it is what turns the
190/// chain of copies into one block, since each copy now ends in a jump to the next and a block with
191/// one way in and one way out is a block that goes away.
192///
193/// `number` goes straight after that `simplify-cfg` and immediately before `load-forward`, and the
194/// two are one arrangement rather than two passes that happen to be adjacent. On its own it removes
195/// an instruction here and there, because the arithmetic a person writes is not usually written
196/// twice. What it is really for is the arithmetic the front end writes underneath: a subscript
197/// lowered twice is the same multiply and add twice, and giving the two one name is what turns a
198/// store and a load that `load-forward` was refusing into a store and a load of the same address.
199/// Running it the other way round would leave the pass after it nothing it did not already have.
200///
201/// `load-forward` goes next, and the position is the whole of what
202/// the pass is worth. It is the block local half of document 16, so what it can find is bounded by
203/// how much code is in one block, and `simplify-cfg` merging the straight line chains is what makes
204/// the blocks the largest they are ever going to be. At the two speed levels that position is also
205/// just after `unroll`, which is where the case the pass was written for lives: the body
206/// copies now sit in one block, and a copy that stored to an array slot and read it straight back
207/// is a store and a load of the same address with nothing in between.
208///
209/// `fold` runs a second time after it, and it is not there out of habit. What forwarding leaves
210/// behind is a value that arrived as a constant through memory, `grid[i] = 3` read back as a load
211/// that is now the literal three, and nothing else this late in the list would fold the arithmetic
212/// on top of it. The first `fold` ran before any of this existed.
213///
214/// `simplify` runs after that second `fold` for the same reason the second `fold` runs at all.
215/// Folding does not remove an instruction whose answer is a constant somebody still adds, it only
216/// writes the constant down, and an index folded to zero leaves a `ptr_add x, 0` behind. That is
217/// an identity the peephole takes and nothing else in the list is about. The unrolled body is
218/// where they come from: the copy that runs first subscripts the array at zero, so the multiply
219/// that worked its offset out is a multiply by zero, and until now the last thing any level did to
220/// that arithmetic was fold it. The add of zero reached the selector and was written out as an
221/// `addq $0`. Over the corpus at `-O2` the run is worth 3000 bytes across 1830 programs, 224 of
222/// them smaller and 4 larger, with every result unchanged.
223///
224/// A second `simplify-cfg` runs after that `simplify` at `-O1`, `-Os` and `-Oz`, and the two speed
225/// levels already had one further down for what `ivopts` and the second `licm` leave behind. What
226/// it is for is the branch nobody has to take any more. Forwarding a load turns a comparison of
227/// what was read into a comparison of what was written, `fold` settles it, and what is then left is
228/// a conditional branch on a constant with a block on the other side of it that the program cannot
229/// reach. Nothing else at these three levels looks at an edge after `load-forward` has run, so
230/// until now the branch and the block it guards were both written out. The block is usually the
231/// interesting half, since it is where the work that was never going to happen is, and at the two
232/// size levels a block that goes is bytes that go.
233///
234/// `hoist` is the first of the two check passes and it runs where it does because of what is above
235/// it. It needs a loop that tests at the bottom, which is what `header-copy` makes, and it needs a
236/// preheader to put a check in, which is what the `canon` after it puts back. Running it before
237/// `discharge` rather than after is deliberate as well: what it leaves in the preheader is a check
238/// over the whole range the loop sweeps, and that is a fact `discharge` can then use on anything
239/// else in front of the loop that is about the same bytes.
240///
241/// `discharge` is second to last, between `hoist` and `dce`, and both neighbours are the reason. It
242/// reads the dominator tree to find a safety check whose bytes an earlier check already covered, so
243/// it wants the graph after the block merging rather than before, when a straight run of code is
244/// still several blocks and a fact does not reach the check it would cover. What it leaves behind
245/// is the `cap_of` the check it removed was reading, which nothing now reads, so `dce` after it is
246/// what makes the function smaller rather than shorter by one instruction. It is in every level
247/// except `-O0`, which keeps every check on purpose: document 14 measures against a build where
248/// nothing was discharged, and that build is `-O0`.
249///
250/// `short-circuit-free` is the collapse of section 22.5 restricted to the cases that cost nothing,
251/// which are the ones where both halves of the `&&` ask about the same two values, so that what it
252/// writes is one comparison or a constant and not an and on top of two comparisons. The full
253/// version of that pass is a speed for size trade and belongs to `-O2`. This version is not a trade
254/// at all, so there is nothing here to decline. It sits where `-O2` puts the full pass, which is
255/// immediately above `thread`, and that pass is the reason: threading turns the shape this matches
256/// into one it does not.
257const O1: &[&str] = &[
258    "expect",
259    "fold",
260    "image",
261    "fold",
262    "simplify",
263    "narrow",
264    "simplify",
265    "short-circuit-free",
266    "thread",
267    "phiopt",
268    "prune",
269    "canon",
270    "header-copy",
271    "canon",
272    "licm",
273    "simplify-cfg",
274    "number",
275    "load-forward",
276    "constant-p",
277    "fold",
278    "simplify",
279    "simplify-cfg",
280    "hoist",
281    "discharge",
282    "dead-plane",
283    "coalesce",
284    "plane-sink",
285    "dce",
286    "loop-delete",
287];
288
289/// `-O2`. The level the code quality claim is about. Section 9.1 asks for two e-graph rounds
290/// around the loop pipeline, the full inlining cost model, Memory SSA and the full alias
291/// analysis stack, and then the scalar and machine passes on top.
292///
293/// `short-circuit` is the one pass here that `-O1` does not have, and section 22.5 is where the
294/// level comes from. It folds the two branches of an `a && b` into one, which costs the right
295/// operand's work on the path that was skipping it and buys a branch the machine no longer has to
296/// guess. That is a trade worth making when the aim is speed and the branch is hard to call, and
297/// it is not one to make by default, which is what `-O1` is. What `-O1` has in its place is
298/// `short-circuit-free`, which is the same pass taking only the collapses that cost nothing, so
299/// this one is the trade and not the transformation.
300///
301/// It runs before `thread` and `phiopt` rather than after, and the order is not arbitrary. Both of
302/// those look at edges, and the collapse removes a block and turns two edges into one, so running
303/// it first hands them a smaller graph with nothing lost. The other way round, threading is free
304/// to give the second branch's block another predecessor, and a block two edges reach is one the
305/// collapse will not touch, so a chain that was foldable stops being foldable.
306///
307/// `canon` and `licm` run a second time after `split`, and that pair is the only thing here that
308/// looks at what `split` wrote. A guard goes in the preheader of the loop being split, which for an
309/// inner loop is a block inside the loops around it, and the guard asks the runtime how big each
310/// object is. On a matrix multiply that is four queries per entry to the innermost loop, two of
311/// them about a pointer that has not changed since it was allocated, and the pass that would take
312/// those out ran seven passes ago. `spec/safe-memory/13-performance.md` section 13.1 measured the
313/// cost and tamnd/rucc#893 is the rest of it.
314///
315/// `plane-sink` runs twice, once between `hoist` and `split` and once near the end. The first one
316/// is there for the loops `split` is about to cut in two. What `split` hands back is a run of
317/// iterations with no checks in it that can leave at its own test or at the guard into the rest,
318/// and a loop with two ways out is one `plane-sink` does not take, so on a copy whose checks came
319/// out the plane writes stayed in the half that runs every iteration and went only from the half
320/// that almost never does. `a-byte-at-a-time-copy` went from 2545314219 instructions to 282430669
321/// on that alone. The second run is for what the passes in between leave in a shape the first one
322/// could not take, and it finds nothing to do on a loop the first run already emptied.
323///
324/// `ivopts` goes last of the loop passes, because it is the one that decides what the loop's
325/// variables finally are and everything above it is still moving code around. It is followed by
326/// `simplify-cfg` and the pair cannot be separated. Section 28.4 has a loop stop asking its counter
327/// anything, and the counter goes on being incremented round the loop until the parameter carrying
328/// it is taken away. `crate::dce` says in its own documentation that it cannot do that, because the
329/// only reader left is the addition feeding the parameter back and a use count never reaches zero
330/// on a cycle. `crate::simplify_cfg` can, and says it was written for this. Without it the loop
331/// pays for the new pointer and keeps the old counter as well, which over the corpus is about half
332/// of what choosing badly costs.
333const O2: &[&str] = &[
334    "expect",
335    "fold",
336    "image",
337    "fold",
338    "simplify",
339    "narrow",
340    "simplify",
341    "switch-conv",
342    "short-circuit",
343    "thread",
344    "phiopt",
345    "prune",
346    "canon",
347    "header-copy",
348    "canon",
349    "licm",
350    "unroll",
351    "simplify-cfg",
352    "number",
353    "load-forward",
354    "redundant-load",
355    "constant-p",
356    "fold",
357    "simplify",
358    "hoist",
359    "plane-sink",
360    "split",
361    "canon",
362    "licm",
363    "ivopts",
364    "simplify-cfg",
365    "discharge",
366    "dead-plane",
367    "coalesce",
368    "plane-sink",
369    "dce",
370    "loop-delete",
371];
372
373/// `-O3`. `-O2` plus loop vectorization, larger inlining and unrolling thresholds, interchange
374/// and distribution where the dependence analysis is confident, and function specialization.
375const O3: &[&str] = &[
376    "expect",
377    "fold",
378    "image",
379    "fold",
380    "simplify",
381    "narrow",
382    "simplify",
383    "switch-conv",
384    "short-circuit",
385    "thread",
386    "phiopt",
387    "prune",
388    "canon",
389    "header-copy",
390    "canon",
391    "licm",
392    "unroll",
393    "simplify-cfg",
394    "number",
395    "load-forward",
396    "redundant-load",
397    "constant-p",
398    "fold",
399    "simplify",
400    "hoist",
401    "plane-sink",
402    "split",
403    "canon",
404    "licm",
405    "ivopts",
406    "simplify-cfg",
407    "discharge",
408    "dead-plane",
409    "coalesce",
410    "plane-sink",
411    "dce",
412    "loop-delete",
413];
414
415/// `-Os`. `-O2`'s passes under a size cost model: inlining only where it shrinks, no unrolling
416/// and no vectorization.
417///
418/// The second peephole is here rather than cut for size, because every rule it can fire replaces
419/// a term with a strictly smaller one. Tier one of `spec/optimizer/13-rewrite-rules.md` is
420/// defined that way, so a level that wants smaller code wants more of it and not less.
421///
422/// `short-circuit` is the pass this level drops from `-O2`, for the mirror of that reason. What it
423/// removes is a branch, which is time, and what it adds is the right operand's instructions on a
424/// path that did not run them and an and on top. The code comes out no smaller and usually a byte
425/// or two larger, so a level whose cost model is size has nothing to gain from it. What it keeps is
426/// `short-circuit-free` below.
427///
428/// `hoist` is dropped here as well, and the reason is the same trade read the other way.
429/// It takes a check out of a loop body and puts one in the preheader, plus the address arithmetic
430/// the new check needs, so the loop runs faster and the function is a few instructions larger. That
431/// is a speed transformation with a size cost, which is what `-Os` and `-Oz` are for declining.
432///
433/// `short-circuit-free` is here for the reason the `-O1` list gives, and the reason reads the same
434/// at a level whose cost model is size. The collapse it is restricted to takes a branch and a block
435/// away and adds nothing, so declining it would be declining something smaller.
436///
437/// `header-copy-small` is the same pass `-O1` and above run under section 26.6's smaller budget.
438/// The copy is code growth and this level pays for it once per loop, so five instructions is what
439/// it will pay. What it gets back is a body that is one region and an exit test at the bottom,
440/// which is slightly smaller in the steady state, so the trade is worth making at a limit that
441/// keeps the header small and not at one that copies twenty instructions to save two.
442const OS: &[&str] = &[
443    "expect",
444    "fold",
445    "image",
446    "fold",
447    "simplify",
448    "narrow",
449    "simplify",
450    "switch-conv",
451    "short-circuit-free",
452    "thread",
453    "phiopt",
454    "prune",
455    "canon",
456    "header-copy-small",
457    "canon",
458    "simplify-cfg",
459    "number",
460    "load-forward",
461    "constant-p",
462    "fold",
463    "simplify",
464    "simplify-cfg",
465    "discharge",
466    "dead-plane",
467    "coalesce",
468    "plane-sink",
469    "dce",
470    "loop-delete",
471];
472
473/// `-Oz`. `-Os` and additionally the outliner, with instruction selection preferring the smaller
474/// encoding wherever there is a choice.
475///
476/// Header copying is the pass this level drops from `-Os`, which section 26.6 asks for by name. It
477/// is the one loop canonicalization that makes the function bigger, `-Oz` is the level that would
478/// rather have the branch than the bytes, and every reason to want the do-while form here is a
479/// speed reason.
480const OZ: &[&str] = &[
481    "expect",
482    "fold",
483    "image",
484    "fold",
485    "simplify",
486    "narrow",
487    "simplify",
488    "switch-conv",
489    "short-circuit-free",
490    "thread",
491    "phiopt",
492    "prune",
493    "canon",
494    "simplify-cfg",
495    "number",
496    "load-forward",
497    "constant-p",
498    "fold",
499    "simplify",
500    "simplify-cfg",
501    "discharge",
502    "dead-plane",
503    "coalesce",
504    "plane-sink",
505    "dce",
506    "loop-delete",
507];
508
509/// The passes this level runs, before the command line adds to or removes from them.
510#[must_use]
511pub const fn for_level(level: OptLevel) -> &'static [&'static str] {
512    match level {
513        OptLevel::O0 => O0,
514        OptLevel::O1 => O1,
515        OptLevel::O2 => O2,
516        OptLevel::O3 => O3,
517        OptLevel::Os => OS,
518        OptLevel::Oz => OZ,
519    }
520}
521
522/// Which passes the IR is written out around.
523///
524/// Empty by default, which is the whole point: a dump is a debugging aid and writing files
525/// nobody asked for is not one.
526#[derive(Debug, Clone, Default, PartialEq, Eq)]
527pub struct Dumps {
528    /// Every pass, on both sides.
529    all: bool,
530    /// The passes to write out before.
531    before: Vec<String>,
532    /// The passes to write out after.
533    after: Vec<String>,
534}
535
536impl Dumps {
537    /// Adds one `-fdump-ir=` argument.
538    ///
539    /// # Errors
540    ///
541    /// When the argument is not `all`, `before-<pass>` or `after-<pass>`, or when it names a
542    /// pass this compiler does not have. A misspelled pass name that quietly dumped nothing
543    /// would look exactly like a pass that did not run.
544    pub fn add(&mut self, spec: &str) -> Result<(), String> {
545        if spec == "all" {
546            self.all = true;
547            return Ok(());
548        }
549        let (side, name) = match spec.split_once('-') {
550            Some(("before", name)) => (&mut self.before, name),
551            Some(("after", name)) => (&mut self.after, name),
552            _ => {
553                return Err(format!(
554                    "`{spec}` is not a dump this compiler makes, which are `all`, \
555                     `before-<pass>` and `after-<pass>`"
556                ));
557            }
558        };
559        if pass::find(name).is_none() {
560            return Err(format!("`{name}` is not a pass this compiler has, see --print-pipeline"));
561        }
562        side.push(name.to_owned());
563        Ok(())
564    }
565
566    /// Whether anything is dumped at all.
567    #[must_use]
568    pub fn is_empty(&self) -> bool {
569        !self.all && self.before.is_empty() && self.after.is_empty()
570    }
571
572    /// Whether the IR is written out before this pass runs.
573    #[must_use]
574    pub fn wants_before(&self, name: &str) -> bool {
575        self.all || self.before.iter().any(|it| it == name)
576    }
577
578    /// Whether the IR is written out after this pass runs.
579    #[must_use]
580    pub fn wants_after(&self, name: &str) -> bool {
581        self.all || self.after.iter().any(|it| it == name)
582    }
583}
584
585/// What the command line asked the optimizer for.
586#[derive(Debug, Clone, PartialEq, Eq)]
587pub struct Options {
588    /// Which pipeline to start from.
589    pub level: OptLevel,
590    /// The passes `-f<name>` added and `-fno-<name>` removed, in the order they were given, so
591    /// that the last mention of a pass is the one that decides.
592    pub toggles: Vec<(String, bool)>,
593    /// What `-fpass-fuel=<pass>=<n>` limited, by pass name.
594    pub fuel: HashMap<String, u32>,
595    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
596    ///
597    /// This is the outer search of the two in section 4.5 of
598    /// `spec/optimizer/04-pass-manager.md`. Halving this finds the pass, and halving
599    /// `-fpass-fuel` for that pass finds the rewrite inside it. Two searches of twenty
600    /// compilations each beat one search over a space nobody knows the shape of.
601    pub global_fuel: Option<u32>,
602    /// What `-fdisable-<pass>` and `-fenable-<pass>` said about which functions a pass runs on.
603    pub gates: Gates,
604    /// What `-fdump-ir=` asked to see.
605    pub dumps: Dumps,
606    /// Whether the verifier runs after every pass that changed anything.
607    pub verify: bool,
608    /// Which definitions in this module something else may replace at load time.
609    ///
610    /// The analyses that read a body and write down what they found have to stop at a name like
611    /// that, because the body they read is not the one that will run. [`Pic::Library`] is the
612    /// answer when the object may end up in a shared library and the exported names in it are
613    /// interposable, which is what `-fPIC` alone means and is gcc's default.
614    ///
615    /// [`Pic::Executable`] is the answer for everything else, and that includes
616    /// `-fno-semantic-interposition`, where the build has promised that the definition here is the
617    /// one that runs. It is a promise and not a deduction, and it is the one every distribution
618    /// makes, because a library that cannot inline its own functions into each other pays for the
619    /// possibility of an interposition that never happens.
620    ///
621    /// This is not the same value the code generator is given. How an address is reached does not
622    /// change under that promise, and gcc does not change it either: a variable a shared library
623    /// exports is still read out of the global offset table, because the promise is about which
624    /// definition runs rather than about how many copies of the variable there are.
625    pub interposition: Pic,
626    /// Whether a call to a library function may be taken to mean what the standard says it means.
627    ///
628    /// `-fno-builtin` and `-ffreestanding` turned around, which is the pair section 20.1 of
629    /// `spec/optimizer/20-idioms-and-libcalls.md` describes. False stops [`crate::libcall`] from
630    /// reading a `printf` as anything but a call to whatever the program links against.
631    pub builtins: bool,
632    /// The library names `-fno-builtin-<name>` took away one at a time.
633    pub no_builtin: Vec<String>,
634}
635
636impl Default for Options {
637    /// The default level with nothing added to it, and the verifier on in a debug build, which
638    /// is what section 9.10 asks for.
639    fn default() -> Self {
640        Self {
641            level: OptLevel::default(),
642            toggles: Vec::new(),
643            fuel: HashMap::new(),
644            global_fuel: None,
645            gates: Gates::default(),
646            dumps: Dumps::default(),
647            verify: cfg!(debug_assertions),
648            interposition: Pic::Executable,
649            builtins: true,
650            no_builtin: Vec::new(),
651        }
652    }
653}
654
655impl Options {
656    /// The options a level asks for on its own.
657    #[must_use]
658    pub fn for_level(level: OptLevel) -> Self {
659        Self { level, ..Self::default() }
660    }
661
662    /// The passes the level and the `-f` flags chose, in order, before the gates are consulted.
663    ///
664    /// A pass named by `-f<name>` that the level did not choose is appended, because the only
665    /// place it could go that does not need an ordering rule nobody wrote down is the end.
666    #[must_use]
667    pub fn chosen(&self) -> Vec<&'static str> {
668        let mut names: Vec<&str> = for_level(self.level).to_vec();
669        for (name, on) in &self.toggles {
670            let name = name.as_str();
671            match *on {
672                true if !names.contains(&name) => names.push(name),
673                true => {}
674                // A pass that says it is required stays, since turning it off is a compile that
675                // fails rather than one that optimizes less. See [`Pass::required`].
676                false => names.retain(|it| *it != name || required(it)),
677            }
678        }
679        names.into_iter().filter_map(pass::find).map(Pass::name).collect()
680    }
681
682    /// Whether a module at a time transformation the level asked for is still asked for.
683    ///
684    /// [`Options::chosen`] cannot answer this. Everything it returns is a [`Pass`], which is one
685    /// function at a time, and section 34.6's propagation is a module at a time because what a
686    /// parameter holds is something the callers say. The last word wins, as it does there, so a
687    /// command line with both spellings on it means the one written second.
688    #[must_use]
689    pub fn wants(&self, name: &str) -> bool {
690        self.toggles.iter().rfind(|(it, _)| it == name).is_none_or(|&(_, on)| on)
691    }
692}
693
694/// Whether the pass of that name is one `-fno-<name>` does not turn off.
695fn required(name: &str) -> bool {
696    pass::find(name).is_some_and(|pass| pass.required())
697}
698
699impl Options {
700    /// The passes that will run, in order, over at least one function.
701    ///
702    /// A pass `-fenable-<name>` reached that the level did not choose is appended after them,
703    /// for the same reason and in the same place. It runs only over the functions the gate names,
704    /// which is the whole point of the flag: a pass being in this list is not the same question as
705    /// a pass running on the function somebody is looking at.
706    #[must_use]
707    pub fn passes(&self) -> Vec<&'static dyn Pass> {
708        let mut names = self.chosen();
709        for name in self.gates.enabled() {
710            // Through the pass list rather than straight from the gate, because the name the
711            // pass holds outlives this call and the one the gate holds does not.
712            let Some(found) = pass::find(name) else { continue };
713            if !names.contains(&found.name()) {
714                names.push(found.name());
715            }
716        }
717        names.into_iter().filter_map(pass::find).collect()
718    }
719}
720
721/// One written out copy of the IR.
722#[derive(Debug, Clone, PartialEq, Eq)]
723pub struct Dump {
724    /// What to call it, which is a number, a side and a pass name, as in `01-after-fold`. The
725    /// number is there so that a directory listing is in the order the passes ran.
726    pub name: String,
727    /// The module, in the textual form from `spec/08-ir.md`.
728    pub text: String,
729}
730
731/// What one pass had to say about one function.
732///
733/// One of these per pass per function with a body, whether or not the pass said anything, because
734/// a pass that reports nothing being visible as a pass that reports nothing is the point of the
735/// record. Section 42.2 of `spec/optimizer/42-measurement.md` has the argument.
736#[derive(Debug, Clone, PartialEq, Eq)]
737pub struct Remark {
738    /// Which pass, by the name a `-f` flag spells.
739    pub pass: &'static str,
740    /// Which function, by the name in the source.
741    pub func: Symbol,
742    /// What it said.
743    pub stats: Stats,
744}
745
746/// What running the pipeline produced beyond the changed module.
747#[derive(Debug, Clone, Default, PartialEq, Eq)]
748pub struct Report {
749    /// The dumps asked for, in the order they were taken. The manager does not write files,
750    /// because nothing below the driver in `spec/18-package-layout.md` knows what a file is.
751    pub dumps: Vec<Dump>,
752    /// A pass that left the IR in a state the verifier refuses, named, with what it said.
753    pub broke: Vec<String>,
754    /// How much fuel each pass spent, which is the number a bisection halves.
755    pub spent: Vec<(&'static str, u32)>,
756    /// What every pass said about every function, in the order the passes ran and then in the
757    /// order the module holds its functions. This is what `-fopt-info` prints.
758    pub remarks: Vec<Remark>,
759}
760
761impl Report {
762    /// Everything one pass said across the whole module, added up.
763    ///
764    /// The counts of an event are addable across functions because an event names a site in a
765    /// pass rather than a fact about a program, which is the reason [`crate::stats::Event::what`]
766    /// is a fixed string.
767    #[must_use]
768    pub fn totals(&self, pass: &str) -> Stats {
769        let mut total = Stats::new();
770        for remark in self.remarks.iter().filter(|it| it.pass == pass) {
771            total.merge(&remark.stats);
772        }
773        total
774    }
775}
776
777/// Runs the pipeline over the module.
778///
779/// Every pass sees every function with a body, one at a time, and a pass runs over the whole
780/// module before the next one starts. That order is what makes the dumps readable: a dump is
781/// the state of the program between two passes rather than between two functions.
782pub fn run(module: &mut Module, names: &mut Interner, opts: &Options) -> Report {
783    let mut report = Report::default();
784    let chosen = opts.chosen();
785    // One cache per function, kept across passes because a pass runs over the whole module
786    // before the next one starts. A cache that lived only as long as one function would be
787    // thrown away between every pass and would never answer a second question. Section 4.2 of
788    // `spec/optimizer/04-pass-manager.md` is the plan for turning the loop inside out, and the
789    // day that happens this map becomes a local in the inner loop.
790    let mut cached: HashMap<FuncId, Analyses> = HashMap::new();
791    // The machine, once for the module, because every function in it is compiled for the same
792    // target at the same goal. It goes into each function's cache rather than into a parameter of
793    // its own, per `crate::machine`.
794    let machine = Machine::of(module, opts.level);
795    // What the whole pipeline has left, which every pass draws its own allowance out of and
796    // gives the unspent part of back. A pass past the end of it is given nothing rather than
797    // skipped, so it still runs, still reports, and still transforms nothing.
798    let mut budget = opts.global_fuel;
799    // What each pass has left of what `-fpass-fuel` gave it. One allowance across every place
800    // the list names that pass, rather than one allowance each, because the number in the flag
801    // is meant to be the number of rewrites that happened. A peephole that runs twice under
802    // `-fpass-fuel=simplify=5` and rewrites ten things would make the bisection in section 4.5
803    // of `spec/optimizer/04-pass-manager.md` step over the rewrite it was looking for.
804    let mut allowance = opts.fuel.clone();
805    let passes = opts.passes();
806    // First of all and whatever the pass list says, because the instruction is a question the
807    // front end left for the IR and nothing after this is allowed to see one. The walk is skipped
808    // at `-O0`, which answers every question as not known, the way gcc does at that level.
809    objsize::answer(module, opts.interposition, opts.level != OptLevel::O0);
810    // The same for `__builtin_constant_p`, but only at `-O0`, where every question is answered
811    // zero the way gcc answers it there. Above that the question waits for `constant-p` in the
812    // list, which is after the folding that can turn the value into a constant.
813    if opts.level == OptLevel::O0 {
814        constant_p::answer(module, false);
815    }
816    // Before anything runs, because each of these is a fact about the module and every pass after
817    // this sees one function. Only when a pass in this run reads them: a flag nothing looks at
818    // would show up in every `-O0` dump and mean nothing to anybody reading one.
819    if passes.iter().any(|pass| READS_SUMMARIES.contains(&pass.name())) {
820        nofree::annotate(module, names, opts.interposition);
821        extents::annotate(module, opts.interposition);
822        params::annotate(module, opts.interposition);
823        heap::annotate(module, names);
824    }
825    // In the same place and for the same reason, except that this one is read by a pass rather
826    // than by a summary, so it is handed over on the analysis cache instead of written onto the
827    // module. Only when the run has that pass in it, since it is a copy of the module's read only
828    // data and nothing else would ever look at it.
829    let images = if passes.iter().any(|pass| pass.name() == image::NAME) {
830        Arc::new(image::Images::of(module, opts.interposition))
831    } else {
832        Arc::default()
833    };
834    // And the same again for the alias oracle's half of the module, which is what each name
835    // refers to, what a callee is declared to do, the tree of type nodes and the layout. Built
836    // only for a run with a pass that asks, since the empty one answers `May` and every pass here
837    // is correct against that.
838    let outside = if passes.iter().any(|pass| READS_OUTSIDE.contains(&pass.name())) {
839        Arc::new(outside::Outside::of(module))
840    } else {
841        Arc::default()
842    };
843    // And once more for what each function is allowed to do, which wants the call graph under it
844    // and is the one thing here that reads every body in the module rather than looking at the
845    // outside of each one. Section 34.6 puts it at `-O1` and above, which is where gcc turns
846    // `-fipa-pure-const` on, and the level is the gate rather than the pass list alone because
847    // `-O0` has `dce` in it and the promise of that level is compile time.
848    let wants_purity =
849        opts.level != OptLevel::O0 && passes.iter().any(|pass| READS_PURITY.contains(&pass.name()));
850    // And the per parameter answer a level above that, where section 34.6 puts it and where gcc
851    // turns `-fipa-modref` on for anything that is not `-O0` or a debug build. A level above
852    // because this one reads every instruction of every body rather than every call in each one,
853    // so it is the more expensive of the two and `-O1` is the level whose promise is compile time.
854    let wants_modref = !matches!(opts.level, OptLevel::O0 | OptLevel::O1)
855        && passes.iter().any(|pass| READS_MODREF.contains(&pass.name()));
856    // And section 34.6's propagation, at the level it puts it at, which is where gcc turns
857    // `-fipa-cp` on (`gcc/opts.cc:654`). A transformation rather than an analysis, so it is not in
858    // the pass list: everything in that list is a [`Pass`], which is one function at a time, and
859    // what a parameter holds is something the callers say. The level decides and `-fno-ipa-cp`
860    // overrides, which is what the list itself gets from [`Options::chosen`].
861    let wants_ipcp = !matches!(opts.level, OptLevel::O0 | OptLevel::O1) && opts.wants(ipcp::NAME);
862    // And section 34.6's other half, at the same level, which is where gcc turns `-fipa-sra` on as
863    // well. After the propagation rather than before it: a parameter the propagation turned into a
864    // constant in the body is a parameter nothing reads any more, and this is what then takes it
865    // out along with the argument at every call.
866    let wants_ipasra =
867        !matches!(opts.level, OptLevel::O0 | OptLevel::O1) && opts.wants(ipasra::NAME);
868    // Before the call graph, because it is the one transformation here that takes a call away
869    // altogether and a graph built over the module after it is the smaller of the two. `-O1` and
870    // above, which is where gcc folds these, and off under `-fno-builtin` or `-ffreestanding`,
871    // since a freestanding program left with a call to a `puts` it never wrote will not link.
872    if opts.level != OptLevel::O0 && opts.builtins && opts.wants(libcall::NAME) {
873        let mut fuel = match (allowance.get(libcall::NAME).copied(), budget) {
874            (Some(count), Some(left)) => Fuel::of(count.min(left)),
875            (Some(count), None) => Fuel::of(count),
876            (None, Some(left)) => Fuel::of(left),
877            (None, None) => Fuel::unlimited(),
878        };
879        let folded = libcall::fold(module, names, &opts.no_builtin, opts.interposition, &mut fuel);
880        for (id, stats) in folded {
881            if opts.verify {
882                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
883                    let func = names.resolve(module[id].name);
884                    for error in errors {
885                        report.broke.push(format!(
886                            "the {} pass left invalid IR in {func}, {error}",
887                            libcall::NAME
888                        ));
889                    }
890                }
891            }
892            report.remarks.push(Remark { pass: libcall::NAME, func: module[id].name, stats });
893        }
894        report.spent.push((libcall::NAME, fuel.spent()));
895        if let Some(left) = &mut budget {
896            *left -= fuel.spent();
897        }
898        if let Some(left) = allowance.get_mut(libcall::NAME) {
899            *left -= fuel.spent();
900        }
901    }
902    // One graph for all four, because building it is a walk over the module and none of them adds
903    // an edge to it. The two transformations take edges away, by leaving a call nothing reaches or
904    // an address nothing hands out, and a graph that still holds those is the conservative one.
905    let graph = (wants_purity || wants_modref || wants_ipcp || wants_ipasra)
906        .then(|| CallGraph::of(module, opts.interposition));
907    // Before the two below rather than after them, because it is the one of the three that changes
908    // a body, and an answer worked out from a body should be worked out from the body the passes
909    // will see. It leaves the edges alone, so the graph under it is the same graph either way.
910    if let (true, Some(graph)) = (wants_ipcp, graph.as_ref()) {
911        let mut fuel = match (allowance.get(ipcp::NAME).copied(), budget) {
912            (Some(count), Some(left)) => Fuel::of(count.min(left)),
913            (Some(count), None) => Fuel::of(count),
914            (None, Some(left)) => Fuel::of(left),
915            (None, None) => Fuel::unlimited(),
916        };
917        for (id, stats) in ipcp::propagate(module, graph, &mut fuel) {
918            if opts.verify {
919                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
920                    let func = names.resolve(module[id].name);
921                    for error in errors {
922                        report.broke.push(format!(
923                            "the {} pass left invalid IR in {func}, {error}",
924                            ipcp::NAME
925                        ));
926                    }
927                }
928            }
929            report.remarks.push(Remark { pass: ipcp::NAME, func: module[id].name, stats });
930        }
931        report.spent.push((ipcp::NAME, fuel.spent()));
932        if let Some(left) = &mut budget {
933            *left -= fuel.spent();
934        }
935        if let Some(left) = allowance.get_mut(ipcp::NAME) {
936            *left -= fuel.spent();
937        }
938    }
939    if let (true, Some(graph)) = (wants_ipasra, graph.as_ref()) {
940        let mut fuel = match (allowance.get(ipasra::NAME).copied(), budget) {
941            (Some(count), Some(left)) => Fuel::of(count.min(left)),
942            (Some(count), None) => Fuel::of(count),
943            (None, Some(left)) => Fuel::of(left),
944            (None, None) => Fuel::unlimited(),
945        };
946        for (id, stats) in ipasra::remove(module, graph, names, &mut fuel) {
947            if opts.verify {
948                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
949                    let func = names.resolve(module[id].name);
950                    for error in errors {
951                        report.broke.push(format!(
952                            "the {} pass left invalid IR in {func}, {error}",
953                            ipasra::NAME
954                        ));
955                    }
956                }
957            }
958            report.remarks.push(Remark { pass: ipasra::NAME, func: module[id].name, stats });
959        }
960        report.spent.push((ipasra::NAME, fuel.spent()));
961        if let Some(left) = &mut budget {
962            *left -= fuel.spent();
963        }
964        if let Some(left) = allowance.get_mut(ipasra::NAME) {
965            *left -= fuel.spent();
966        }
967    }
968    let purity = match (wants_purity, graph.as_ref()) {
969        (true, Some(graph)) => {
970            let mut facts = purity::Facts::of_module(module, names);
971            purity::infer(module, graph, &mut facts);
972            Arc::new(facts)
973        }
974        _ => Arc::default(),
975    };
976    let modref = match (wants_modref, graph.as_ref()) {
977        (true, Some(graph)) => {
978            let mut summaries = modref::Summaries::of_module(module);
979            modref::summarize(module, graph, &mut summaries);
980            Arc::new(summaries)
981        }
982        _ => Arc::default(),
983    };
984    // Every name the module had before any pass ran, which is what a table a pass asks for has to
985    // stay clear of, and the number the next table's name is made from. See `crate::readonly`.
986    let taken: HashSet<Symbol> = module
987        .funcs()
988        .map(|id| module[id].name)
989        .chain(module.globals().map(|id| module[id].name))
990        .chain(module.aliases().map(|id| module[id].name))
991        .collect();
992    let mut tables = 0;
993    for (index, pass) in passes.into_iter().enumerate() {
994        let name = pass.name();
995        if opts.dumps.wants_before(name) {
996            report.dumps.push(dump(index, "before", name, module, names));
997        }
998        let mut fuel = match (allowance.get(name).copied(), budget) {
999            // Whichever limit is tighter, because two limits that disagree mean the one that
1000            // stops first, and a bisection that started with the global one has to stay inside
1001            // it while the per pass one is halved.
1002            (Some(count), Some(left)) => Fuel::of(count.min(left)),
1003            (Some(count), None) => Fuel::of(count),
1004            (None, Some(left)) => Fuel::of(left),
1005            (None, None) => Fuel::unlimited(),
1006        };
1007        // What the level and the `-f` flags decided, which is what a gate overrides for the
1008        // functions it names and leaves alone for the ones it does not.
1009        let default = chosen.contains(&name);
1010        for id in module.funcs() {
1011            if module[id].is_declaration() {
1012                continue;
1013            }
1014            if !opts.gates.allows(name, default, id.raw(), names.resolve(module[id].name)) {
1015                // No remark either. A pass that did not run on a function has nothing to say
1016                // about it, and a record saying it found nothing would read as a pass that
1017                // looked.
1018                continue;
1019            }
1020            let an = cached.entry(id).or_insert_with(|| {
1021                Analyses::new(machine)
1022                    .reading(Arc::clone(&images))
1023                    .about(Arc::clone(&outside))
1024                    .calling(Arc::clone(&purity))
1025                    .touching(Arc::clone(&modref))
1026            });
1027            let pointer_bits = module.datalayout.pointer_bits;
1028            let mut data = readonly::ReadOnly::new(names, &taken, pointer_bits, tables);
1029            let stats = pass.run_emitting(&mut module[id], an, &mut fuel, &mut data);
1030            tables = data.next();
1031            for table in data.into_tables() {
1032                add_table(module, table);
1033            }
1034            // A pass that changed nothing preserved everything, whatever it says about itself,
1035            // so the cheap case does not need every pass to have a second opinion about it.
1036            // A pass that did change something is taken at its word, and in a checked build the
1037            // word is checked.
1038            let keeps = if stats.changed() { pass.preserves() } else { Preserved::ALL };
1039            for broken in an.settle(&module[id], keeps, opts.verify) {
1040                let func = names.resolve(module[id].name);
1041                report.broke.push(format!(
1042                    "the {name} pass said it preserved {} of {func} and did not",
1043                    broken.name()
1044                ));
1045            }
1046            // Here rather than after the pass, and this function rather than the module. A pass
1047            // is a function pass, so the only thing it can have broken is the function it was
1048            // given, and walking the other ones again after every one of them is the quadratic
1049            // walk `rucc_ir::verify_func` exists to avoid. Doing it here is also what lets the
1050            // message name the function, which the module walk could not, and it puts the
1051            // failure next to the pass that caused it rather than at the end of the module.
1052            if stats.changed() && opts.verify {
1053                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
1054                    let func = names.resolve(module[id].name);
1055                    for error in errors {
1056                        report
1057                            .broke
1058                            .push(format!("the {name} pass left invalid IR in {func}, {error}"));
1059                    }
1060                }
1061            }
1062            // The record is the only place the manager learns that anything happened, which is
1063            // why the pass cannot leave recording until later. See `crate::stats`.
1064            report.remarks.push(Remark { pass: name, func: module[id].name, stats });
1065        }
1066        // Added to rather than pushed, so a pass the list names twice is one line here with what
1067        // both of its runs spent. That is the number a bisection halves, and two lines under one
1068        // name would be two numbers where the flag takes one.
1069        match report.spent.iter_mut().find(|(it, _)| *it == name) {
1070            Some((_, total)) => *total += fuel.spent(),
1071            None => report.spent.push((name, fuel.spent())),
1072        }
1073        if let Some(left) = &mut budget {
1074            // Never below zero, because the allowance the pass was given was at most this.
1075            *left -= fuel.spent();
1076        }
1077        if let Some(left) = allowance.get_mut(name) {
1078            // Same, and for the same reason.
1079            *left -= fuel.spent();
1080        }
1081        if opts.dumps.wants_after(name) {
1082            report.dumps.push(dump(index, "after", name, module, names));
1083        }
1084    }
1085    // Whatever a list without `constant-p` in it, or a gate that kept the pass off a function,
1086    // left standing. Nothing below the optimizer lowers the instruction, so the answer is written
1087    // here, and it is the one the pass would have given.
1088    constant_p::answer(module, true);
1089    report
1090}
1091
1092/// Adds a table a pass asked for to the module, as the read only array its load expects.
1093///
1094/// Internal, so that it is in no other object's way, and constant, which is what puts it in
1095/// `.rodata`. Aligned to its cell, which is all a load of one cell asks for.
1096fn add_table(module: &mut Module, table: readonly::Table) {
1097    let bytes = table.ty.bits() / 8;
1098    let cells: Vec<Datum> = table
1099        .cells
1100        .iter()
1101        .map(|&cell| Datum::Scalar {
1102            ty: table.ty,
1103            value: module.add_imm(Imm::int(cell, table.ty)),
1104        })
1105        .collect();
1106    let init = module.push_data(&cells);
1107    let mut global = Global::new(table.name, u64::from(bytes) * cells.len() as u64, bytes);
1108    global.linkage = Linkage::Internal;
1109    global.constant = true;
1110    global.init = Some(init);
1111    module.add_global(global);
1112}
1113
1114/// The module written out, under a name that sorts in the order the passes ran.
1115fn dump(index: usize, side: &str, name: &str, module: &Module, names: &Interner) -> Dump {
1116    Dump { name: format!("{index:02}-{side}-{name}"), text: rucc_ir::print(module, names) }
1117}
1118
1119/// Renders what `--print-pipeline` prints.
1120///
1121/// One line per pass, numbered from one, with what the pass does after it. A level that runs
1122/// nothing says so rather than printing an empty list, because an empty answer and a broken
1123/// command look the same.
1124#[must_use]
1125pub fn print(opts: &Options) -> String {
1126    let mut out = String::new();
1127    let _ = writeln!(out, "level: {}", opts.level);
1128    // Only when it was asked for, so the listing of a compilation nobody is bisecting is the
1129    // same listing it has always been. A run under a budget is a run whose output is not the
1130    // one the level asked for, and the listing is where that has to be visible.
1131    if let Some(count) = opts.global_fuel {
1132        let _ = writeln!(out, "global fuel: {count}");
1133    }
1134    let passes = opts.passes();
1135    if passes.is_empty() {
1136        let _ = writeln!(out, "no passes");
1137        return out;
1138    }
1139    for (index, pass) in passes.iter().enumerate() {
1140        let _ = write!(out, "{}: {}, {}", index + 1, pass.name(), pass.describe());
1141        // Only when a gate mentions the pass, so the listing of a compilation nobody is
1142        // debugging is the same listing it has always been.
1143        if let Some(note) = opts.gates.note(pass.name()) {
1144            let _ = write!(out, " [{note}]");
1145        }
1146        out.push('\n');
1147    }
1148    out
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153    use rucc_base::Interner;
1154    use rucc_ir::{
1155        Builder, Extra, Flags, Func, IntPred, MemInfo, MemOrder, Module, Opcode, Restrict,
1156        Signature, Type,
1157    };
1158    use rucc_session::OptLevel;
1159    use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
1160
1161    use super::{Dumps, Options, for_level};
1162    use crate::stats::Kind;
1163    use crate::{Pass, ipasra, ipcp, libcall, pass};
1164
1165    /// A module with one function whose body has something to fold in it.
1166    fn module() -> (Interner, Module) {
1167        let mut names = Interner::new();
1168        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1169        let mut module = Module::new(names.intern("test.c"), &target);
1170        let func = foldable(&mut names, "f");
1171        module.add_func(func);
1172        (names, module)
1173    }
1174
1175    /// A module with two of them, called `f` and `g`, in that order, so `f` is function 0.
1176    fn two_functions() -> (Interner, Module) {
1177        let mut names = Interner::new();
1178        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1179        let mut module = Module::new(names.intern("test.c"), &target);
1180        for name in ["f", "g"] {
1181            let func = foldable(&mut names, name);
1182            module.add_func(func);
1183        }
1184        (names, module)
1185    }
1186
1187    /// A module with one function holding two identities the peephole takes, on a value that
1188    /// arrives as a parameter so that folding cannot get to them first.
1189    fn identities() -> (Interner, Module) {
1190        let mut names = Interner::new();
1191        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1192        let mut module = Module::new(names.intern("test.c"), &target);
1193        let i32_ = Type::int(32);
1194        let mut func = Func::new(
1195            names.intern("h"),
1196            Signature::new().with_params(&[i32_]).with_returns(&[i32_]),
1197        );
1198        let entry = func.create_block();
1199        let x = func.append_param(entry, i32_);
1200        let mut build = Builder::new(&mut func, entry);
1201        let zero = build.iconst(i32_, 0);
1202        let one = build.iconst(i32_, 1);
1203        let sum = build.binary(Opcode::Add, x, zero, Flags::NONE);
1204        let product = build.binary(Opcode::Mul, sum, one, Flags::NONE);
1205        build.ret(&[product]);
1206        module.add_func(func);
1207        (names, module)
1208    }
1209
1210    /// A function that returns a sign extension of a constant, which folding rewrites.
1211    fn foldable(names: &mut Interner, name: &str) -> Func {
1212        let mut func =
1213            Func::new(names.intern(name), Signature::new().with_returns(&[Type::int(64)]));
1214        let block = func.create_block();
1215        let mut build = Builder::new(&mut func, block);
1216        let narrow = build.iconst(Type::int(32), 7);
1217        let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
1218        build.ret(&[wide]);
1219        func
1220    }
1221
1222    /// Whether the pass said anything about the function, which it only does when it ran on it.
1223    fn spoke_about(report: &super::Report, pass: &str, func: &str, names: &Interner) -> bool {
1224        report.remarks.iter().any(|it| it.pass == pass && names.resolve(it.func) == func)
1225    }
1226
1227    /// A module with a loop short enough for the unroller to flatten, over an array a parameter
1228    /// points at.
1229    ///
1230    /// Four iterations, which is a trip count the unroller takes whole. The copy that runs first
1231    /// subscripts the array at zero, so what works its offset out is a multiply by zero, and
1232    /// folding that is what leaves the addition this is here to look for.
1233    fn a_short_loop() -> (Interner, Module) {
1234        let mut names = Interner::new();
1235        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1236        let mut module = Module::new(names.intern("test.c"), &target);
1237        let (i32_, i64_) = (Type::int(32), Type::int(64));
1238        let signature = Signature::new().with_params(&[Type::PTR]).with_returns(&[i32_]);
1239        let mut func = Func::new(names.intern("sum"), signature);
1240        let entry = func.create_block();
1241        let head = func.create_block();
1242        let body = func.create_block();
1243        let exit = func.create_block();
1244        let p = func.append_param(entry, Type::PTR);
1245        let i = func.append_param(head, i32_);
1246        let acc = func.append_param(head, i32_);
1247
1248        let mut build = Builder::new(&mut func, entry);
1249        let zero = build.iconst(i32_, 0);
1250        build.jump(head, &[zero, zero]);
1251
1252        let mut build = Builder::new(&mut func, head);
1253        let four = build.iconst(i32_, 4);
1254        let more = build.icmp(IntPred::Slt, i, four);
1255        build.br_if(more, body, &[], exit, &[]);
1256
1257        let mut build = Builder::new(&mut func, body);
1258        let wide = build.unary(Opcode::SExt, i, i64_);
1259        let scale = build.iconst(i64_, 4);
1260        let offset = build.binary(Opcode::Mul, wide, scale, Flags::NSW);
1261        let at = build.binary(Opcode::PtrAdd, p, offset, Flags::NONE);
1262        let read = build.load(i32_, at, plain(), Flags::NONE);
1263        let total = build.binary(Opcode::Add, acc, read, Flags::NONE);
1264        let one = build.iconst(i32_, 1);
1265        let next = build.binary(Opcode::Add, i, one, Flags::NSW);
1266        build.jump(head, &[next, total]);
1267
1268        let mut build = Builder::new(&mut func, exit);
1269        build.ret(&[acc]);
1270        module.add_func(func);
1271        (names, module)
1272    }
1273
1274    /// Memory with nothing said about it, which is what a plain subscript reads through.
1275    fn plain() -> MemInfo {
1276        MemInfo {
1277            size: 4,
1278            align: 4,
1279            order: MemOrder::NotAtomic,
1280            tbaa: None,
1281            owns: 0,
1282            restrict: Restrict::NONE,
1283        }
1284    }
1285
1286    /// Every addition in the module whose right operand is the constant zero.
1287    fn adds_of_zero(module: &Module) -> usize {
1288        let mut found = 0;
1289        for id in module.funcs() {
1290            let func = &module[id];
1291            for block in func.blocks() {
1292                for inst in func.insts(block) {
1293                    if !matches!(func[inst].opcode, Opcode::Add | Opcode::PtrAdd) {
1294                        continue;
1295                    }
1296                    let args = &func[func[inst].args];
1297                    let Some(&rhs) = args.get(1) else { continue };
1298                    let rucc_ir::Def::Result { inst: from, .. } = func[rhs].def else { continue };
1299                    if func[from].opcode != Opcode::IConst {
1300                        continue;
1301                    }
1302                    let Extra::Imm(at) = func[from].extra else { continue };
1303                    found += usize::from(func[at].signed(func[rhs].ty) == 0);
1304                }
1305            }
1306        }
1307        found
1308    }
1309
1310    /// An index the unroller worked out to zero does not leave the addition behind.
1311    ///
1312    /// The peephole is what removes it and the peephole used to run only near the top of the
1313    /// list, before the unroller had made any of these. Folding writes the constant down and
1314    /// leaves the addition, so an `add x, 0` reached the selector and was written out as an
1315    /// `addq $0` the machine runs for nothing. tamnd/rucc#875.
1316    #[test]
1317    fn an_index_folded_to_zero_is_not_added_to_anything() {
1318        let (mut names, mut module) = a_short_loop();
1319        assert_eq!(adds_of_zero(&module), 0, "the fixture already has one before anything runs");
1320        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1321        assert!(report.broke.is_empty(), "{:?}", report.broke);
1322        assert!(spent(&report, "unroll").is_some_and(|it| it > 0), "the loop was not unrolled");
1323        assert_eq!(adds_of_zero(&module), 0, "{}", rucc_ir::print(&module, &names));
1324    }
1325
1326    #[test]
1327    fn every_pass_a_pipeline_names_is_a_pass_that_exists() {
1328        for level in
1329            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
1330        {
1331            for name in for_level(level) {
1332                assert!(
1333                    pass::find(name).is_some(),
1334                    "{level} names `{name}` and no pass answers to it"
1335                );
1336            }
1337        }
1338    }
1339
1340    #[test]
1341    fn a_pass_a_pipeline_names_twice_is_never_named_twice_in_a_row() {
1342        // Running a pass again after another pass has been through is the point of naming it
1343        // twice, and `simplify` around `narrow` is why the rule that used to be here, which was
1344        // that no level names a pass twice at all, is not the rule any more. Two runs with
1345        // nothing between them is still a mistake: the second one sees exactly what the first
1346        // one finished with, so it can only report that it found nothing.
1347        for level in
1348            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
1349        {
1350            for pair in for_level(level).windows(2) {
1351                assert_ne!(pair[0], pair[1], "{level} runs `{}` twice in a row", pair[0]);
1352            }
1353        }
1354    }
1355
1356    #[test]
1357    fn a_pass_the_pipeline_runs_twice_gets_one_allowance_and_reports_one_number() {
1358        // `-fpass-fuel=<pass>=<n>` is halved to find one rewrite, so the number in the flag has
1359        // to be the number of rewrites that happened however many times the list names the pass.
1360        // The peephole is named more than once from `-O1` up and the function below holds two
1361        // identities it takes, so a cap of one has to stop after one rather than after one per
1362        // occurrence.
1363        assert!(for_level(OptLevel::O2).iter().filter(|it| **it == "simplify").count() > 1);
1364
1365        let (mut names, mut module) = identities();
1366        let free = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1367        assert_eq!(spent(&free, "simplify"), Some(2), "{:?}", free.spent);
1368
1369        let (mut names, mut module) = identities();
1370        let mut opts = Options::for_level(OptLevel::O2);
1371        opts.fuel.insert("simplify".to_owned(), 1);
1372        let capped = super::run(&mut module, &mut names, &opts);
1373        assert_eq!(capped.spent.iter().filter(|(name, _)| *name == "simplify").count(), 1);
1374        assert_eq!(spent(&capped, "simplify"), Some(1), "{:?}", capped.spent);
1375    }
1376
1377    #[test]
1378    fn an_identity_only_the_narrow_pass_can_produce_is_still_taken() {
1379        // Issue 505, and the reason the peephole is named on both sides of `narrow`. C promotes
1380        // before it operates, so `unsigned char x; (unsigned char)(x & 255)` arrives here as a
1381        // thirty two bit `and` of a zero extension, and the rule that says `and` with every bit
1382        // set is the value has nothing at eight bits to match. `narrow` is the only producer that
1383        // width has. Before this ran twice the `and.i8` below reached the back end untouched.
1384        let mut names = Interner::new();
1385        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1386        let mut module = Module::new(names.intern("test.c"), &target);
1387        let (i8_, i32_) = (Type::int(8), Type::int(32));
1388        let mut func =
1389            Func::new(names.intern("f"), Signature::new().with_params(&[i8_]).with_returns(&[i8_]));
1390        let entry = func.create_block();
1391        let x = func.append_param(entry, i8_);
1392        let mut build = Builder::new(&mut func, entry);
1393        let wide = build.unary(Opcode::ZExt, x, i32_);
1394        let mask = build.iconst(i32_, 255);
1395        let kept = build.binary(Opcode::And, wide, mask, Flags::NONE);
1396        let back = build.unary(Opcode::Trunc, kept, i8_);
1397        build.ret(&[back]);
1398        module.add_func(func);
1399
1400        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1401        assert!(report.broke.is_empty(), "{:?}", report.broke);
1402        let text = rucc_ir::print(&module, &names);
1403        assert!(!text.contains("and."), "the masking survived the pipeline\n{text}");
1404    }
1405
1406    /// What a pass spent, or `None` if it did not run.
1407    fn spent(report: &super::Report, pass: &str) -> Option<u32> {
1408        report.spent.iter().find(|(name, _)| *name == pass).map(|&(_, count)| count)
1409    }
1410
1411    /// The names of the passes a set of options would run, in order.
1412    fn names(opts: &Options) -> Vec<&'static str> {
1413        opts.passes().into_iter().map(Pass::name).collect()
1414    }
1415
1416    #[test]
1417    fn every_level_that_splits_a_loop_looks_at_what_the_split_wrote() {
1418        // A guard goes in the preheader of the loop being split, which for an inner loop is inside
1419        // the loops around it, and it asks the runtime how big an object is. Nothing after `split`
1420        // moves anything, so a level that splits and then stops leaves those queries where they
1421        // cost the most.
1422        for level in [super::O1, super::O2, super::O3, super::OS, super::OZ] {
1423            let Some(at) = level.iter().position(|pass| *pass == "split") else {
1424                continue;
1425            };
1426            assert!(
1427                level[at..].contains(&"licm"),
1428                "a level splits a loop and never looks at the guard again"
1429            );
1430        }
1431    }
1432
1433    #[test]
1434    fn every_level_that_chooses_induction_variables_takes_the_old_one_away_afterwards() {
1435        // The counter a loop stops asking anything is still incremented round it, and what removes
1436        // the parameter carrying it is `simplify-cfg` rather than `dce`. See the comment on `O2`.
1437        // A level that chooses and then stops keeps both variables and is worse off than if it had
1438        // never chosen at all.
1439        for level in [super::O1, super::O2, super::O3, super::OS, super::OZ] {
1440            let Some(at) = level.iter().position(|pass| *pass == "ivopts") else {
1441                continue;
1442            };
1443            assert!(
1444                level[at + 1..].contains(&"simplify-cfg"),
1445                "a level chooses induction variables and leaves the one it stopped using behind"
1446            );
1447        }
1448    }
1449
1450    #[test]
1451    fn every_run_of_the_pass_that_reads_a_summary_is_named_as_one_that_does() {
1452        // A run left off the list gets no table of globals and no caller guarantees, and answers
1453        // that there were none rather than that nobody built them.
1454        for pass in pass::PASSES {
1455            let name = pass.name();
1456            assert_eq!(
1457                name.starts_with("discharge"),
1458                super::READS_SUMMARIES.contains(&name),
1459                "`{name}` and READS_SUMMARIES disagree about whether it reads a summary"
1460            );
1461        }
1462    }
1463
1464    #[test]
1465    fn the_level_that_optimizes_nothing_still_removes_what_nothing_reaches() {
1466        // Two passes at `-O0`, and neither of them is an optimization. See the comment on the
1467        // level itself, and issue 359.
1468        assert_eq!(names(&Options::for_level(OptLevel::O0)), ["expect", "simplify-cfg"]);
1469        assert!(names(&Options::for_level(OptLevel::O2)).len() > 1);
1470    }
1471
1472    #[test]
1473    fn a_pass_is_removed_by_no_and_added_by_the_bare_name_and_the_last_word_wins() {
1474        let mut opts = Options::for_level(OptLevel::O2);
1475        opts.toggles.push(("fold".to_owned(), false));
1476        assert!(!names(&opts).contains(&"fold"), "{:?}", names(&opts));
1477        opts.toggles.push(("fold".to_owned(), true));
1478        assert!(names(&opts).contains(&"fold"), "{:?}", names(&opts));
1479
1480        let mut off = Options::for_level(OptLevel::O0);
1481        off.toggles.push(("fold".to_owned(), true));
1482        assert_eq!(
1483            names(&off),
1484            ["expect", "simplify-cfg", "fold"],
1485            "a pass the level did not choose is still reachable"
1486        );
1487    }
1488
1489    #[test]
1490    fn asking_for_a_pass_twice_does_not_run_it_twice() {
1491        let mut opts = Options::for_level(OptLevel::O2);
1492        let before = names(&opts);
1493        opts.toggles.push(("fold".to_owned(), true));
1494        assert_eq!(names(&opts), before);
1495    }
1496
1497    #[test]
1498    fn the_pipeline_listing_names_the_level_and_every_pass_in_order() {
1499        let text = super::print(&Options::for_level(OptLevel::O2));
1500        assert!(text.starts_with("level: -O2\n"), "{text}");
1501        assert!(text.contains("1: expect, "), "{text}");
1502        assert!(text.contains("2: fold, "), "{text}");
1503        // Turning off everything the level asked for leaves the one pass that cannot be turned
1504        // off, since the back end has no rule for what it removes. See `Pass::required`.
1505        let mut none = Options::for_level(OptLevel::O0);
1506        none.toggles.push(("expect".to_owned(), false));
1507        none.toggles.push(("simplify-cfg".to_owned(), false));
1508        let none = super::print(&none);
1509        assert!(none.contains("1: expect, "), "{none}");
1510        assert!(!none.contains("simplify-cfg"), "{none}");
1511    }
1512
1513    #[test]
1514    fn running_the_pipeline_changes_the_module_and_reports_what_it_spent() {
1515        let (mut names, mut module) = module();
1516        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1517        // Folding rewrites the sign extension into a constant, and then the constant it was
1518        // extending is read by nothing and dead code elimination takes it out. One
1519        // transformation each, which is what the two of them together are for. Asserted by
1520        // name rather than as the whole vector, so a pass added later does not fail this.
1521        assert_eq!(spent(&report, "fold"), Some(1));
1522        assert_eq!(spent(&report, "dce"), Some(1));
1523        assert!(report.broke.is_empty(), "{:?}", report.broke);
1524        assert!(report.dumps.is_empty(), "nothing asked for a dump");
1525        assert!(rucc_ir::print(&module, &names).contains("iconst.i64 7"));
1526    }
1527
1528    #[test]
1529    fn the_analyses_survive_a_pass_that_keeps_them_and_not_one_that_does_not() {
1530        // The pipeline half of the analysis manager. A branch on a constant, so `simplify-cfg`
1531        // has something to do and says it preserved nothing, and the whole run comes out with
1532        // the verifier and the manager both satisfied. What a pass that lied would produce is in
1533        // `crate::analysis`, where a lie can be told on purpose.
1534        let mut names = Interner::new();
1535        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1536        let mut module = Module::new(names.intern("test.c"), &target);
1537        let mut func = Func::new(names.intern("f"), Signature::new());
1538        let entry = func.create_block();
1539        let dead = func.create_block();
1540        let exit = func.create_block();
1541        let mut build = Builder::new(&mut func, entry);
1542        let never = build.iconst(Type::int(1), 0);
1543        build.br_if(never, dead, &[], exit, &[]);
1544        for block in [dead, exit] {
1545            let mut build = Builder::new(&mut func, block);
1546            build.ret(&[]);
1547        }
1548        module.add_func(func);
1549        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1550        // The fold, and then the merge of the arm it left with one way into it.
1551        assert_eq!(spent(&report, "simplify-cfg"), Some(2));
1552        assert!(report.broke.is_empty(), "{:?}", report.broke);
1553        let text = rucc_ir::print(&module, &names);
1554        // The labels, which start a line, and not the mentions of one, which are indented. One
1555        // left: the arm nothing reaches went, and the arm that is always taken came up into the
1556        // entry, which is what is left of the branch.
1557        assert_eq!(text.matches("\nblock").count(), 1, "there is more than one block:\n{text}");
1558    }
1559
1560    #[test]
1561    fn no_pass_that_optimizes_runs_at_no_optimization_however_much_there_is_to_do() {
1562        let (mut names, mut module) = module();
1563        let before = rucc_ir::print(&module, &names);
1564        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O0));
1565        // The two passes the level runs looked, found no `__builtin_expect`, no branch they could
1566        // read and no block nothing reaches, and spent nothing. The constant arithmetic the fixture
1567        // is full of is still there, which is the part of `-O0` that has not changed.
1568        assert_eq!(report.spent, vec![("expect", 0), ("simplify-cfg", 0)]);
1569        assert_eq!(rucc_ir::print(&module, &names), before);
1570    }
1571
1572    #[test]
1573    fn a_gate_takes_a_pass_away_from_one_function_and_leaves_the_other_alone() {
1574        let (mut names, mut module) = two_functions();
1575        let mut opts = Options::for_level(OptLevel::O2);
1576        opts.gates.add(false, "fold=g").expect("g is a function and fold is a pass");
1577        let report = super::run(&mut module, &mut names, &opts);
1578        assert!(spoke_about(&report, "fold", "f", &names));
1579        assert!(!spoke_about(&report, "fold", "g", &names), "fold ran where it was gated off");
1580        assert!(spoke_about(&report, "dce", "g", &names), "one pass gated off is not all of them");
1581        // What the gate is for: the two functions came out different, and the difference is one
1582        // pass on one function rather than a level on a file.
1583        let text = rucc_ir::print(&module, &names);
1584        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1585    }
1586
1587    #[test]
1588    fn a_function_can_be_gated_by_the_number_it_has_in_the_module() {
1589        let (mut names, mut module) = two_functions();
1590        let mut opts = Options::for_level(OptLevel::O2);
1591        opts.gates.add(false, "fold=0").expect("0 is a function and fold is a pass");
1592        let report = super::run(&mut module, &mut names, &opts);
1593        assert!(!spoke_about(&report, "fold", "f", &names), "function 0 is the first one");
1594        assert!(spoke_about(&report, "fold", "g", &names));
1595    }
1596
1597    #[test]
1598    fn enabling_a_pass_reaches_one_function_at_a_level_that_did_not_ask_for_it() {
1599        let (mut names, mut module) = two_functions();
1600        let mut opts = Options::for_level(OptLevel::O0);
1601        opts.gates.add(true, "fold=1").expect("1 is a function and fold is a pass");
1602        let running: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
1603        assert_eq!(
1604            running,
1605            ["expect", "simplify-cfg", "fold"],
1606            "the flag has to put the pass in the pipeline"
1607        );
1608        let report = super::run(&mut module, &mut names, &opts);
1609        assert!(!spoke_about(&report, "fold", "f", &names), "nothing asked for f");
1610        assert!(spoke_about(&report, "fold", "g", &names));
1611        let text = rucc_ir::print(&module, &names);
1612        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1613    }
1614
1615    #[test]
1616    fn a_pass_gated_off_everywhere_runs_on_nothing_and_still_says_so() {
1617        let (mut names, mut module) = two_functions();
1618        let before = rucc_ir::print(&module, &names);
1619        let mut opts = Options::for_level(OptLevel::O2);
1620        for pass in pass::PASSES {
1621            opts.gates.add(false, pass.name()).expect("a pass in the list is a pass that exists");
1622        }
1623        let report = super::run(&mut module, &mut names, &opts);
1624        assert!(report.remarks.is_empty(), "a pass that did not run has nothing to report");
1625        assert_eq!(spent(&report, "fold"), Some(0), "the pass is still in the pipeline");
1626        assert_eq!(rucc_ir::print(&module, &names), before);
1627    }
1628
1629    #[test]
1630    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
1631        let mut opts = Options::for_level(OptLevel::O2);
1632        // `narrow` rather than `fold`, because a gate names a pass and the level runs some of its
1633        // passes more than once. A note on one of those is printed against every run of it, and
1634        // the count at the bottom would then be counting repeats rather than what it is asking.
1635        opts.gates.add(false, "narrow=2-4").expect("narrow is a pass");
1636        let text = super::print(&opts);
1637        assert!(text.contains("6: narrow, "), "{text}");
1638        assert!(text.contains("[off for 2-4]"), "{text}");
1639        assert_eq!(text.matches('[').count(), 1, "a pass no gate mentions says nothing extra");
1640    }
1641
1642    #[test]
1643    fn every_pass_at_no_fuel_leaves_the_module_exactly_as_it_found_it() {
1644        // The check section 9.10 asks for by name, and the reason it is here rather than in each
1645        // pass is that it has to hold for every pass that is ever added.
1646        for pass in pass::PASSES {
1647            let (mut names, mut module) = module();
1648            let before = rucc_ir::print(&module, &names);
1649            let mut opts = Options::for_level(OptLevel::O0);
1650            // The level's own passes out of the way first, so that what this measures is the one
1651            // pass under test. A pass turned off and then on again is on, so this is right for
1652            // those passes as well as for the others. `expect` cannot be turned off, so it is
1653            // starved of fuel instead and is expected in the report ahead of the pass under test.
1654            opts.toggles.push(("simplify-cfg".to_owned(), false));
1655            opts.toggles.push((pass.name().to_owned(), true));
1656            opts.fuel.insert("expect".to_owned(), 0);
1657            opts.fuel.insert(pass.name().to_owned(), 0);
1658            let report = super::run(&mut module, &mut names, &opts);
1659            let mut want = vec![("expect", 0)];
1660            if pass.name() != "expect" {
1661                want.push((pass.name(), 0));
1662            }
1663            assert_eq!(report.spent, want, "{} spent fuel it had none of", pass.name());
1664            assert_eq!(
1665                rucc_ir::print(&module, &names),
1666                before,
1667                "{} transformed the module at fuel zero",
1668                pass.name()
1669            );
1670        }
1671    }
1672
1673    #[test]
1674    fn fuel_is_shared_across_the_functions_of_a_module() {
1675        let mut names = Interner::new();
1676        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1677        let mut module = Module::new(names.intern("test.c"), &target);
1678        for which in ["f", "g"] {
1679            let mut func =
1680                Func::new(names.intern(which), Signature::new().with_returns(&[Type::int(64)]));
1681            let block = func.create_block();
1682            let mut build = Builder::new(&mut func, block);
1683            let narrow = build.iconst(Type::int(32), 7);
1684            let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
1685            build.ret(&[wide]);
1686            module.add_func(func);
1687        }
1688        let mut opts = Options::for_level(OptLevel::O2);
1689        opts.fuel.insert("fold".to_owned(), 1);
1690        let report = super::run(&mut module, &mut names, &opts);
1691        // One fold across both functions, because fuel is per pass and per compilation. Dead
1692        // code elimination has its own and spends it on the constant the one fold orphaned.
1693        assert_eq!(spent(&report, "fold"), Some(1));
1694        assert_eq!(spent(&report, "dce"), Some(1));
1695        let text = rucc_ir::print(&module, &names);
1696        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1697    }
1698
1699    #[test]
1700    fn global_fuel_is_spent_by_the_passes_in_order_and_the_rest_get_none() {
1701        let (mut names, mut module) = module();
1702        let mut opts = Options::for_level(OptLevel::O2);
1703        opts.global_fuel = Some(1);
1704        let report = super::run(&mut module, &mut names, &opts);
1705        // Folding is first and there is one thing to fold, so it takes the one unit and dead
1706        // code elimination gets nothing. Without the budget it would have taken the constant
1707        // that fold orphaned, which is what the other test measures.
1708        assert_eq!(spent(&report, "fold"), Some(1));
1709        assert_eq!(spent(&report, "dce"), Some(0));
1710        let text = rucc_ir::print(&module, &names);
1711        assert!(text.contains("iconst.i64 7"), "{text}");
1712        assert!(text.contains("iconst.i32 7"), "the orphaned constant is still there, {text}");
1713    }
1714
1715    #[test]
1716    fn a_budget_of_nothing_leaves_the_module_alone_and_still_runs_every_pass() {
1717        let (mut names, mut module) = module();
1718        let before = rucc_ir::print(&module, &names);
1719        let mut opts = Options::for_level(OptLevel::O2);
1720        opts.global_fuel = Some(0);
1721        let report = super::run(&mut module, &mut names, &opts);
1722        assert_eq!(rucc_ir::print(&module, &names), before);
1723        assert!(report.spent.iter().all(|(_, spent)| *spent == 0), "{:?}", report.spent);
1724        // Every pass, because a pass out of fuel is a pass that ran and did nothing rather than
1725        // a pass that was skipped, and a bisection that skipped passes would be searching a
1726        // different pipeline at every step. One line per name rather than one per place the list
1727        // names it, because what a name was given is one allowance across all of them.
1728        let mut want: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
1729        // And the three transformations that are not in that list, because they are a module at a
1730        // time rather than one function at a time. They spend out of the same budget and are
1731        // bisected the same way, so they belong in the same accounting.
1732        want.push(ipcp::NAME);
1733        want.push(ipasra::NAME);
1734        want.push(libcall::NAME);
1735        want.sort_unstable();
1736        want.dedup();
1737        let mut got: Vec<&str> = report.spent.iter().map(|&(name, _)| name).collect();
1738        got.sort_unstable();
1739        assert_eq!(got, want);
1740    }
1741
1742    #[test]
1743    fn the_module_at_a_time_removal_is_on_at_the_level_and_off_when_the_flag_says_so() {
1744        let mut opts = Options::for_level(OptLevel::O2);
1745        assert!(opts.wants(ipasra::NAME));
1746        opts.toggles.push((ipasra::NAME.to_owned(), false));
1747        assert!(!opts.wants(ipasra::NAME));
1748    }
1749
1750    #[test]
1751    fn the_module_at_a_time_propagation_is_on_at_the_level_and_off_when_the_flag_says_so() {
1752        // The same reading of a toggle that [`Options::chosen`] gives the pass list, done by hand
1753        // because what this names is not a pass.
1754        let mut opts = Options::for_level(OptLevel::O2);
1755        assert!(opts.wants(ipcp::NAME));
1756        opts.toggles.push((ipcp::NAME.to_owned(), false));
1757        assert!(!opts.wants(ipcp::NAME));
1758        opts.toggles.push((ipcp::NAME.to_owned(), true));
1759        assert!(opts.wants(ipcp::NAME), "the last word on the command line is the one that wins");
1760    }
1761
1762    #[test]
1763    fn the_tighter_of_the_two_limits_is_the_one_that_stops_the_pass() {
1764        // A pass allowed more than the budget gets the budget.
1765        let (mut names, mut under) = module();
1766        let mut opts = Options::for_level(OptLevel::O2);
1767        opts.global_fuel = Some(0);
1768        opts.fuel.insert("fold".to_owned(), 9);
1769        assert_eq!(spent(&super::run(&mut under, &mut names, &opts), "fold"), Some(0));
1770
1771        // And a pass allowed less than the budget keeps its own limit, with the budget left
1772        // over for whatever comes after it.
1773        let (mut names, mut over) = module();
1774        let mut opts = Options::for_level(OptLevel::O2);
1775        opts.global_fuel = Some(9);
1776        opts.fuel.insert("fold".to_owned(), 0);
1777        let report = super::run(&mut over, &mut names, &opts);
1778        assert_eq!(spent(&report, "fold"), Some(0));
1779        assert_eq!(spent(&report, "dce"), Some(0), "nothing was orphaned for it to remove");
1780    }
1781
1782    #[test]
1783    fn the_pipeline_listing_says_when_there_is_a_budget_and_says_nothing_when_there_is_not() {
1784        let opts = Options::for_level(OptLevel::O2);
1785        assert!(!super::print(&opts).contains("global fuel"));
1786        let with = Options { global_fuel: Some(12), ..Options::for_level(OptLevel::O2) };
1787        assert!(super::print(&with).contains("global fuel: 12"), "{}", super::print(&with));
1788    }
1789
1790    #[test]
1791    fn a_dump_is_taken_on_the_side_that_asked_for_it_and_not_the_other() {
1792        let (mut names, mut module) = module();
1793        let mut opts = Options::for_level(OptLevel::O2);
1794        opts.dumps.add("after-fold").expect("a pass that exists");
1795        let report = super::run(&mut module, &mut names, &opts);
1796        // The level folds three times, twice at the top on either side of `image` and once after
1797        // the loop pipeline, and what a dump request names is a pass rather than a position, so
1798        // every run is written out. The side is what this is about: not one of the three is a
1799        // `before`.
1800        assert_eq!(report.dumps.len(), 3, "every run of the pass, one dump each");
1801        assert!(
1802            report.dumps.iter().all(|dump| dump.name.ends_with("-after-fold")),
1803            "{:?}",
1804            report.dumps.iter().map(|dump| &dump.name).collect::<Vec<&String>>()
1805        );
1806        assert_eq!(report.dumps[0].name, "01-after-fold");
1807        assert!(report.dumps[0].text.contains("iconst.i64 7"));
1808    }
1809
1810    #[test]
1811    fn asking_for_all_dumps_gives_both_sides_of_every_pass() {
1812        let (mut interner, mut module) = module();
1813        let opts = {
1814            let mut opts = Options::for_level(OptLevel::O2);
1815            opts.dumps.add("all").expect("all is always a dump");
1816            opts
1817        };
1818        let report = super::run(&mut module, &mut interner, &opts);
1819        // Both sides of every pass in the level, numbered by position, whatever the level
1820        // holds. Written out of the pipeline rather than as a literal, because the point of
1821        // the test is the pairing and the numbering and not which passes exist this month.
1822        let taken: Vec<&str> = report.dumps.iter().map(|d| d.name.as_str()).collect();
1823        let expected: Vec<String> = names(&opts)
1824            .into_iter()
1825            .enumerate()
1826            .flat_map(|(at, name)| {
1827                [format!("{at:02}-before-{name}"), format!("{at:02}-after-{name}")]
1828            })
1829            .collect();
1830        assert_eq!(taken, expected);
1831        // Either side of the fold, which is the pass that has something to do to this fixture,
1832        // found by name rather than by position so that a pass in front of it does not move it.
1833        let side = |which: &str| {
1834            let tail = format!("-{which}-fold");
1835            let dump = report.dumps.iter().find(|dump| dump.name.ends_with(&tail));
1836            dump.expect("the level folds").text.clone()
1837        };
1838        assert!(side("before").contains("sext.i64"));
1839        assert!(!side("after").contains("sext.i64"));
1840    }
1841
1842    #[test]
1843    fn every_pass_leaves_a_record_for_every_function_whether_or_not_it_had_anything_to_say() {
1844        let (mut names, mut module) = module();
1845        let opts = Options::for_level(OptLevel::O2);
1846        let report = super::run(&mut module, &mut names, &opts);
1847        let ran: Vec<&'static str> = opts.passes().into_iter().map(Pass::name).collect();
1848        // One function in the fixture, so one record per pass, and the passes in the order they
1849        // ran. A pass that found nothing is in here with an empty record, which is the point:
1850        // a pass that fires on nothing is either dead code or a bug, and output that leaves it
1851        // out cannot say which.
1852        let seen: Vec<&'static str> = report.remarks.iter().map(|it| it.pass).collect();
1853        assert_eq!(seen, ran);
1854        assert!(report.remarks.iter().all(|it| names.resolve(it.func) == "f"));
1855        assert!(
1856            report.remarks.iter().any(|it| it.pass == "simplify" && it.stats.is_empty()),
1857            "there is nothing in the fixture for the peephole to do"
1858        );
1859    }
1860
1861    #[test]
1862    fn a_pass_spends_one_unit_of_fuel_for_each_rewrite_it_reports() {
1863        // The invariant that keeps the record honest, checked over every pass rather than
1864        // written into each one. Fuel is taken immediately before a transformation and a
1865        // rewrite is recorded immediately after it, so the two counts are the same number
1866        // arrived at from two directions. A pass where they disagree either transformed without
1867        // asking, which breaks bisection, or rewrote without recording, which means the manager
1868        // did not run the verifier over what it produced.
1869        let (mut names, mut module) = module();
1870        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1871        for (pass, spent) in &report.spent {
1872            assert_eq!(
1873                report.totals(pass).total(Kind::Optimized),
1874                *spent,
1875                "{pass} spent {spent} units of fuel and did not say on what"
1876            );
1877        }
1878        assert!(report.spent.iter().any(|(_, spent)| *spent > 0), "nothing happened at all");
1879    }
1880
1881    #[test]
1882    fn what_the_passes_said_is_what_opt_info_prints() {
1883        let (mut names, mut module) = module();
1884        let report = super::run(&mut module, &mut names, &Options::for_level(OptLevel::O2));
1885        let text = crate::optinfo::render("t.c", &report, &names, crate::Wants::all());
1886        assert!(
1887            text.contains(
1888                "t.c: f: optimized: instruction with constant operands folded to a constant (1) [fold]"
1889            ),
1890            "{text}"
1891        );
1892        assert!(
1893            text.contains(
1894                "t.c: f: optimized: instruction with no effects and no users removed (1) [dce]"
1895            ),
1896            "{text}"
1897        );
1898        // Nothing in the fixture is a miss, so asking only for the misses gets nothing back,
1899        // and that is different from the flag having been left off.
1900        let mut misses = crate::Wants::none();
1901        misses.add("missed").expect("that kind exists");
1902        assert_eq!(crate::optinfo::render("t.c", &report, &names, misses), "");
1903    }
1904
1905    #[test]
1906    fn the_verifier_says_which_function_it_refused_and_leaves_the_others_out_of_it() {
1907        // Two functions with the same foldable body, and a block in the second one that nothing
1908        // reaches, which the verifier refuses. The pass is not what put it there, and the
1909        // complaint says the pass anyway, because a pass that hands back a function the
1910        // verifier will not take is where the search has to start whoever wrote the block.
1911        let mut names = Interner::new();
1912        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1913        let mut module = Module::new(names.intern("test.c"), &target);
1914        module.add_func(foldable(&mut names, "f"));
1915        let mut g = foldable(&mut names, "g");
1916        let stranded = g.create_block();
1917        let mut build = Builder::new(&mut g, stranded);
1918        let seven = build.iconst(Type::int(64), 7);
1919        build.ret(&[seven]);
1920        module.add_func(g);
1921
1922        // Folding on its own, because simplify-CFG would take the stranded block out and there
1923        // would be nothing left to complain about.
1924        let mut opts = Options::for_level(OptLevel::O0);
1925        opts.toggles.push(("simplify-cfg".to_owned(), false));
1926        opts.toggles.push(("fold".to_owned(), true));
1927        opts.verify = true;
1928        let report = super::run(&mut module, &mut names, &opts);
1929
1930        assert_eq!(report.broke.len(), 1, "{:?}", report.broke);
1931        let complaint = &report.broke[0];
1932        assert!(complaint.starts_with("the fold pass left invalid IR in g,"), "{complaint}");
1933        assert!(complaint.contains("this block is not reachable"), "{complaint}");
1934    }
1935
1936    #[test]
1937    fn a_function_a_pass_did_not_change_is_not_verified_after_it() {
1938        // The stranded block is in `f` this time and `f` has nothing to fold, so the pass runs
1939        // over an invalid function, changes nothing, and says nothing. That is the whole trade:
1940        // the verifier answers for the rewrite that just happened, and a function no rewrite
1941        // touched was already answered for when it was built.
1942        let mut names = Interner::new();
1943        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1944        let mut module = Module::new(names.intern("test.c"), &target);
1945        let mut f = Func::new(names.intern("f"), Signature::new().with_returns(&[Type::int(64)]));
1946        for _ in 0..2 {
1947            let block = f.create_block();
1948            let mut build = Builder::new(&mut f, block);
1949            let seven = build.iconst(Type::int(64), 7);
1950            build.ret(&[seven]);
1951        }
1952        module.add_func(f);
1953        module.add_func(foldable(&mut names, "g"));
1954
1955        let mut opts = Options::for_level(OptLevel::O0);
1956        opts.toggles.push(("simplify-cfg".to_owned(), false));
1957        opts.toggles.push(("fold".to_owned(), true));
1958        opts.verify = true;
1959        let report = super::run(&mut module, &mut names, &opts);
1960
1961        assert!(report.broke.is_empty(), "{:?}", report.broke);
1962        // And it did run on it, so this is the verifier staying quiet rather than the pass
1963        // being skipped.
1964        assert!(spoke_about(&report, "fold", "f", &names));
1965    }
1966
1967    #[test]
1968    fn a_dump_of_a_pass_that_does_not_exist_is_refused_rather_than_ignored() {
1969        let mut dumps = Dumps::default();
1970        assert!(dumps.add("after-no-such-pass").is_err());
1971        assert!(dumps.add("sideways-fold").is_err());
1972        assert!(dumps.add("fold").is_err());
1973        assert!(dumps.is_empty());
1974    }
1975}