Skip to main content

rucc_codegen/
coverage.rs

1//! Which IR opcodes have somewhere to go, and which do not.
2//!
3//! Design: `spec/10-backend.md` section 10.2, under **Coverage**.
4//!
5//! Every opcode has to be lowered by something or be a hole somebody wrote down. Without this the
6//! way a hole is found is that somebody compiles a program containing one and the selector reports
7//! that it cannot lower an instruction, which is a fine diagnostic and a bad discovery mechanism:
8//! it turns a gap in the rule set into a user's problem rather than a failing build.
9//!
10//! # The three answers
11//!
12//! An opcode is lowered by a rule, or somewhere a rule cannot reach, or nowhere.
13//!
14//! The first is the ordinary answer and the one this can check by itself. [`crate::term`] says
15//! every name a rule could be written at, the table says every name one is written at, and an
16//! opcode is covered when each of its names is in both. That is what makes this a check about
17//! widths rather than about opcodes: an `add` with a rule at four widths and no rule at the fifth
18//! is not covered, and would be reported here as the missing name rather than as a covered opcode.
19//!
20//! The second is [`ELSEWHERE`], which is not a gap. `spec/10-backend.md` names five of them and
21//! there are more now, and they are all the same kind of thing: an opcode whose lowering depends on
22//! something no pattern can see. Where a call's arguments go depends on the signature, where a
23//! local lives depends on the frame, an unconditional jump is an edge and edges live on the block,
24//! and a `memcpy` is a run of moves whose length is a constant the pattern would have to count. A
25//! rule matches one term and can say none of that.
26//!
27//! The third is [`GAPS`], which is the number `spec/15-testing.md` section 15.8 says we keep. Each
28//! entry names why it is there and the issue that closes it, so that an opcode nobody has written a
29//! rule for is a decision somebody wrote down rather than a surprise.
30//!
31//! [`WIDTHS`] and [`NAMES`] are the same third answer said about something smaller than an opcode.
32//! A width on [`WIDTHS`] has no names at all, so no opcode is missing a rule at it, and a name on
33//! [`NAMES`] is one width of an opcode that lowers at its other widths. Both carry the issue that
34//! closes them for the same reason [`GAPS`] does.
35//!
36//! # What makes the lists honest
37//!
38//! An entry that stops being true fails. An opcode on either list that a rule starts covering is a
39//! stale entry and the tests below say so by name, which is the same rule the exclusion lists in
40//! the compatibility harness are kept under: a list nothing checks is a list that only grows.
41//!
42//! The direction this cannot check is an opcode moving from [`GAPS`] to [`ELSEWHERE`] without the
43//! list following it, because where an opcode is lowered by name is a `match` arm and there is
44//! nothing to ask about a `match` arm from here. What that costs is one line of a list going out of
45//! date; what it does not cost is a gap going unnoticed, since the opcode is still on a list and
46//! still counted.
47//!
48//! # The other question
49//!
50//! All of the above is about the rule set as it is written. [`Fired`] is about the rule set as it
51//! is used: which rules a compilation actually reached. A rule nothing reaches is proved and dead
52//! weight, or it is a construct the corpus does not contain and somebody should know which. The
53//! selector marks a rule as it fires it, the driver writes the marks out under
54//! `-Zrule-coverage=FILE`, and the harness in `tamnd/rucc-compat` unions those files over a corpus,
55//! which is what turns coverage of the rule set into a number. `spec/20-execution-testing.md`
56//! section 20.9 is the design and `tamnd/rucc#261` is the work.
57
58use core::fmt;
59use core::fmt::Write as _;
60
61use rucc_ir::Opcode;
62use rucc_target::Arch;
63
64use crate::select::{Table, Test};
65use crate::term;
66
67/// An opcode no rule is written about, and the place that lowers it instead.
68///
69/// Not one of these is a gap. Each is an opcode whose lowering depends on something a pattern
70/// cannot see, so the answer lives where that something is known.
71pub static ELSEWHERE: &[(Opcode, &str)] = &[
72    // The convention. What a call's operands are is whatever the signature made them, and which
73    // register each one arrives in depends on the classification of every argument before it.
74    (Opcode::Call, "`crate::abi`, which builds a call out of the convention"),
75    (Opcode::CallIndirect, "`crate::abi`, the same instruction with the callee in a register"),
76    // The frame, which is not known until the allocator has finished running out of registers.
77    (Opcode::Alloca, "`crate::lower`, as an address into a frame `crate::frame` lays out later"),
78    // A relocation, which is right because of what the linker does rather than because of what
79    // any bitvector equals.
80    (Opcode::GlobalAddr, "`crate::lower`, a `lea` off the instruction pointer with a name on it"),
81    // No instruction at all. The IR keeps the width the same and the machine has one register
82    // file for both, so the value is already where it needs to be.
83    (Opcode::PtrToInt, "`crate::lower`, which renames the value rather than computing anything"),
84    (Opcode::IntToPtr, "`crate::lower`, the same rename the other way round"),
85    // Memory SSA, which is built at -O2, read by the passes that need it, and taken back off
86    // before selection. Nothing in the back end has ever seen a value of type `mem`.
87    (Opcode::MemEntry, "nothing at all, since memory SSA comes off before the back end runs"),
88    // The edges and the two ways of writing down that control does not arrive.
89    (Opcode::Jump, "`crate::layout`, since an edge is on the block and not in the block"),
90    (Opcode::Unreachable, "nothing at all, which is the answer for a place control does not reach"),
91    (Opcode::UnreachableHint, "nothing at all, for the same reason"),
92    // Rewritten into the opcodes above before selection ever sees them.
93    (Opcode::Switch, "`crate::switch`, into the tests its clusters need"),
94    (Opcode::FConst, "`crate::expand`, into a constant in memory and a load of it"),
95    (Opcode::FNeg, "`crate::expand`, into the sign bit flip it is"),
96    (Opcode::UIToFP, "`crate::expand`, into a signed conversion with a widening or a halving"),
97    (Opcode::FPToUI, "`crate::expand`, into a signed conversion with a narrowing or a correction"),
98    (Opcode::Memcpy, "`crate::expand`, into the moves it stands for"),
99    (Opcode::Memset, "`crate::expand`, into the fills it stands for"),
100    (Opcode::Memmove, "`crate::expand`, into a call, since the two regions may overlap"),
101    (Opcode::Bswap, "`crate::expand`, into the shifts and masks that reverse the bytes"),
102    // The ordered accesses, which this machine already makes ordered. `crate::expand` says what
103    // total store order gives for nothing and what the one ordering it does not give costs.
104    (Opcode::AtomicLoad, "`crate::expand`, into the plain load that is already an acquire"),
105    (Opcode::AtomicStore, "`crate::expand`, into the plain store, and a barrier at the strongest"),
106    // The barrier itself, which is one instruction or none and neither is a rewrite of anything.
107    // The template, which is a string and not a term. What an empty one stands for is no
108    // instructions and the places its operands share, and what a template with instructions in it
109    // stands for needs an assembler, which is `tamnd/rucc#349`.
110    (
111        Opcode::InlineAsm,
112        "`crate::lower`, as the places its operands share, while its template is empty",
113    ),
114    (
115        Opcode::Fence,
116        "`crate::lower`, as an `mfence` at the strongest ordering and nothing below it",
117    ),
118    (Opcode::Ctpop, "`crate::expand`, into the halving sum that counts the set bits"),
119    (Opcode::Ctlz, "`crate::expand`, into a smear and a set bit count"),
120    (Opcode::Cttz, "`crate::expand`, into a mask of the low zeroes and a set bit count"),
121    (Opcode::UAddOverflow, "`crate::expand`, into an add and a comparison against an operand"),
122    (Opcode::SAddOverflow, "`crate::expand`, into an add and the sign bit of the operands"),
123    (Opcode::USubOverflow, "`crate::expand`, into a subtract and a comparison of the operands"),
124    (Opcode::SSubOverflow, "`crate::expand`, into a subtract and the sign bit of the operands"),
125    (Opcode::UMulOverflow, "`crate::expand`, into a multiply and the high half of the product"),
126    (Opcode::SMulOverflow, "`crate::expand`, into the same, with the high half corrected for sign"),
127    // The variable argument list, which is four opcodes reading a structure the ABI describes.
128    (Opcode::VaStart, "`crate::varargs`, which writes the register save area the ABI describes"),
129    (Opcode::VaArg, "`crate::varargs`, into the walk over that structure"),
130    (Opcode::VaObject, "`crate::varargs`, the same walk for something that arrived in memory"),
131    (Opcode::VaCopy, "`crate::varargs`, into a copy of the structure"),
132    (Opcode::VaEnd, "`crate::varargs`, which removes it, since there is nothing to undo"),
133    // Memory safety. A check is a call to the runtime, and the rewrite happens after the optimizer
134    // has run so that the descriptor table only has rows for checks that survived it.
135    (Opcode::CheckBounds, "`rucc_safety::lower`, into a call carrying the row that describes it"),
136    (Opcode::CheckLive, "`rucc_safety::lower`, the same call over the lifetime plane"),
137    (Opcode::CheckDeriv, "`rucc_safety::lower`, the same call where the pointer is computed"),
138    // The capability the checks were reading, which the same pass takes out once they are calls,
139    // because a call to the runtime is handed an address and finds the rest for itself.
140    (Opcode::CapOf, "`rucc_safety::lower`, which removes it, since nothing reads it any more"),
141];
142
143/// An opcode nothing lowers, why it is here, and the issue that closes it.
144///
145/// This is the count `spec/15-testing.md` section 15.8 asks for. It is not zero yet and the
146/// spec says it should be, which is the honest reading of where the back end is: every one of
147/// these is a feature nobody has written, and all but three of them are opcodes the front end
148/// cannot produce either, so a program that reaches one of these is a program that reaches an
149/// unimplemented builtin first.
150pub static GAPS: &[(Opcode, &str, &str)] = &[
151    (Opcode::Splat, "a vector, and no rule is written about a lane count", "tamnd/rucc#200"),
152    (
153        Opcode::TargetIntrinsic,
154        "the same, since what needs one is a vector builtin",
155        "tamnd/rucc#200",
156    ),
157    (Opcode::BlockAddr, "the address of a label", "tamnd/rucc#353"),
158    (Opcode::IndirectBr, "the branch a computed goto turns into", "tamnd/rucc#353"),
159    (
160        Opcode::FRem,
161        "a call to `fmod`, so a link line question as much as a lowering one",
162        "tamnd/rucc#226",
163    ),
164    (
165        Opcode::Fma,
166        "a call or one instruction, depending on what the machine is told it has",
167        "tamnd/rucc#226",
168    ),
169    (
170        Opcode::AtomicRmw,
171        "a `lock` prefix, which is an operand form nothing here has",
172        "tamnd/rucc#311",
173    ),
174    (Opcode::Cmpxchg, "the same, and a result that is a pair", "tamnd/rucc#311"),
175    (Opcode::Bitreverse, "a node nothing writes and nothing lowers", "tamnd/rucc#363"),
176    (Opcode::Expect, "a branch weight nothing reads yet", "tamnd/rucc#364"),
177    (Opcode::Prefetch, "one instruction, once the hints have somewhere to go", "tamnd/rucc#313"),
178    (Opcode::FrameAddress, "a walk up the frame pointers", "tamnd/rucc#312"),
179    (Opcode::ReturnAddress, "the same walk, one word further along", "tamnd/rucc#312"),
180    (
181        Opcode::StackSave,
182        "a frame that can grow, as a variable length array needs",
183        "tamnd/rucc#291",
184    ),
185    (Opcode::StackRestore, "the same", "tamnd/rucc#291"),
186    (
187        Opcode::SetjmpMarker,
188        "a call that returns twice, which the allocator has to be told about",
189        "tamnd/rucc#223",
190    ),
191    (Opcode::LongjmpMarker, "the same", "tamnd/rucc#223"),
192    (Opcode::TailCall, "a terminator nothing writes and nothing lowers", "tamnd/rucc#365"),
193    // Memory safety. These are a gap in a different sense from the rest: nothing emits one yet
194    // either, since the passes that would are milestones S2 and after, so there is no program the
195    // back end can be handed that reaches one. The four the S1 pass does emit are on `ELSEWHERE`.
196    (
197        Opcode::CapLoad,
198        "a capability, whose runtime shape `spec/safe-memory/05-representation.md` decides",
199        "tamnd/rucc#428",
200    ),
201    (Opcode::CapStore, "the same, and a store into the slot beside a pointer", "tamnd/rucc#428"),
202    (
203        Opcode::CapNull,
204        "the same, and it is whatever the representation says nothing is",
205        "tamnd/rucc#428",
206    ),
207    (Opcode::CapNarrow, "the same, and arithmetic on the bounds it holds", "tamnd/rucc#428"),
208    (Opcode::CapRecover, "the same, and a read of the shadow planes", "tamnd/rucc#428"),
209    (Opcode::CheckType, "a read of the type plane, which is S5's", "tamnd/rucc#431"),
210    (Opcode::CheckInit, "the same, over the init plane, which is S5's too", "tamnd/rucc#431"),
211    (Opcode::CheckRace, "the same, over the epoch plane, which is S5's as well", "tamnd/rucc#431"),
212    // The plane writes, which the runtime does for itself today because the only ranges anything
213    // asks about are the ones its own allocator handed out. A stack object needs these.
214    (Opcode::MetaBegin, "a write over a range of the lifetime plane", "tamnd/rucc#428"),
215    (
216        Opcode::MetaEnd,
217        "the same write, with the version bumped past every capability",
218        "tamnd/rucc#428",
219    ),
220    (Opcode::MetaType, "the same over the type plane, which is S5's", "tamnd/rucc#431"),
221    (Opcode::MetaInit, "the same over the init plane, which is S5's", "tamnd/rucc#431"),
222    (
223        Opcode::MetaTransfer,
224        "the same, and the state a range is in while a device owns it, which is S2's",
225        "tamnd/rucc#428",
226    ),
227    (
228        Opcode::SafeRegionBegin,
229        "nothing at all, once the count document 10 section 10.2 asks for has been taken",
230        "tamnd/rucc#428",
231    ),
232    (Opcode::SafeRegionEnd, "the same, which is to say nothing", "tamnd/rucc#428"),
233];
234
235/// A width no rule is written at, why, and the issue that closes it.
236///
237/// The other half of coverage, and the half an opcode list cannot say. An opcode is covered when
238/// every name it has is a name a rule is written at, and a width with no name has no names to
239/// check: an `add` of two `__int128`s is not a missing rule for `add`, it is a width the rule
240/// language cannot spell. So the widths are written down here for the same reason the opcodes are
241/// written down above.
242pub static WIDTHS: &[(&str, &str, &str)] = &[
243    (
244        "one bit",
245        "everything but and, or, xor, a constant, and the widening out of one",
246        "tamnd/rucc#352",
247    ),
248    (
249        "a hundred and twenty eight bits",
250        "no register pair, so nothing at that width has a name",
251        "tamnd/rucc#351",
252    ),
253    (
254        "eighty bits",
255        "a long double is on the x87 stack and no rule is about that stack",
256        "tamnd/rucc#326",
257    ),
258    (
259        "a vector of any lane count",
260        "a rule at a width says nothing about how many lanes",
261        "tamnd/rucc#200",
262    ),
263];
264
265/// A name a rule could be written at and deliberately is not, why, and the issue that puts it
266/// back.
267///
268/// The third list, and the one that is about a name rather than about an opcode or a width. An
269/// opcode on [`GAPS`] has no lowering at any width and a width on [`WIDTHS`] has no names at all,
270/// and neither of those can say that `add` is lowered at four widths and left alone at two.
271///
272/// This list used to be all of the narrow arithmetic. C promotes the operands of an arithmetic
273/// operator to `int` before the operator is applied, so `char a, b; a + b` is an `int` addition of
274/// two sign extended chars and there is no C program that asks the back end to add two bytes.
275/// Rules were written at those names anyway, ahead of the pass that would reach them, and they sat
276/// proved and never selected: `tamnd/rucc#261` measured that and `tamnd/rucc#368` took them out.
277/// Most of them are back, because the width narrowing pass in `tamnd/rucc#375` is that caller and
278/// it writes a byte add out of the truncation the assignment back to a `char` already was.
279///
280/// What is left is what the pass will not narrow. A divide is not narrowed because the most
281/// negative byte over minus one is a defined hundred and twenty eight at four bytes and is the
282/// overflow that raises at one, so it wants a range analysis saying that pair cannot happen. A
283/// truth value widened to a byte is not narrowed because it is a truncation of an extension that
284/// started narrower than the truncation ends, which is a third shape the pass does not have.
285///
286/// Not every narrow name was ever here, because promotion is not the only way a narrow operation
287/// is born. Reading a bitfield is a shift and a mask by constants at the width of the storage
288/// unit, writing one is a mask, a shift and an `or` of two values, and a truth test on a narrow
289/// scalar is an `icmp_ne` at that scalar's width. Those fire, so those always had rules.
290pub static NAMES: &[(&str, &str, &str)] = &[
291    ("sdiv.i8", "a narrow divide, which wants a range analysis before it can be narrowed", NARROW),
292    ("sdiv.i16", "the same", NARROW),
293    ("udiv.i8", "the same", NARROW),
294    ("udiv.i16", "the same", NARROW),
295    ("srem.i8", "the same", NARROW),
296    ("srem.i16", "the same", NARROW),
297    ("urem.i8", "the same", NARROW),
298    ("urem.i16", "the same", NARROW),
299    ("zext.i1.i8", "a truth value widened to a byte, which nothing asks for at that width", NARROW),
300    ("zext.i1.i16", "the same", NARROW),
301];
302
303/// The issue every entry of [`NAMES`] waits on, since they all wait on the same one.
304const NARROW: &str = "tamnd/rucc#375";
305
306/// What a target's rules cover, and what they do not.
307#[derive(Debug)]
308pub struct Report {
309    /// The rule file this is about, so that anything said about it names a file to open.
310    pub source: &'static str,
311    /// How many opcodes the IR has.
312    pub opcodes: usize,
313    /// The opcodes every name of which a rule is written at.
314    pub by_rule: Vec<Opcode>,
315    /// How many names those are, which is one per opcode and width.
316    pub names: usize,
317    /// A name a rule could be written at and none is, which is what a missing rule looks like.
318    pub uncovered: Vec<(Opcode, &'static str)>,
319    /// A name on [`NAMES`], which is a missing rule somebody decided to be missing.
320    pub deferred: Vec<(Opcode, &'static str)>,
321    /// A name a rule is written at that nothing can ever be called, which is a dead rule.
322    pub unreachable: Vec<&'static str>,
323    /// The opcodes lowered somewhere a rule cannot reach.
324    pub elsewhere: Vec<Opcode>,
325    /// The opcodes nothing lowers.
326    pub gaps: Vec<Opcode>,
327    /// The opcodes on none of the three lists, which is what a new opcode is until somebody says
328    /// where it goes.
329    pub unaccounted: Vec<Opcode>,
330}
331
332impl fmt::Display for Report {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        write!(
335            f,
336            "rucc-codegen: {} lowers {} of the {} IR opcodes by rule at {} names, {} are lowered \
337             where no rule reaches, {} have no lowering yet and {} names are left for later",
338            self.source,
339            self.by_rule.len(),
340            self.opcodes,
341            self.names,
342            self.elsewhere.len(),
343            self.gaps.len(),
344            self.deferred.len()
345        )
346    }
347}
348
349/// What a table covers.
350///
351/// Nothing is executed and nothing is compiled. The rule set and the naming of instructions are
352/// both data, and the answer is a comparison of two lists.
353#[must_use]
354pub fn report(table: &Table) -> Report {
355    let named = term::heads();
356    let patterns = pattern_heads(table);
357
358    let mut by_rule = Vec::new();
359    let mut uncovered = Vec::new();
360    let mut deferred = Vec::new();
361    for &(opcode, name) in &named {
362        if patterns.contains(&name) {
363            by_rule.push(opcode);
364        } else if NAMES.iter().any(|&(deliberate, ..)| deliberate == name) {
365            deferred.push((opcode, name));
366        } else {
367            uncovered.push((opcode, name));
368        }
369    }
370    // An opcode is covered when every name it has is covered, so one missing width takes the
371    // whole opcode off the list however many of its other widths are there. A name on `NAMES` does
372    // not take it off, because the opcode is lowered and the entry says which widths were left for
373    // later and why: that is a narrower claim than the opcode having nowhere to go, and putting it
374    // on `GAPS` instead would say the wrong thing about an `add` that lowers perfectly well at
375    // four widths.
376    for &(opcode, _) in &uncovered {
377        by_rule.retain(|&covered| covered != opcode);
378    }
379    by_rule.sort_unstable();
380    by_rule.dedup();
381
382    let names = named.len() - uncovered.len() - deferred.len();
383    let unreachable: Vec<&'static str> = patterns
384        .iter()
385        .filter(|head| !named.iter().any(|(_, name)| name == *head))
386        .copied()
387        .collect();
388
389    let elsewhere: Vec<Opcode> = ELSEWHERE.iter().map(|&(opcode, _)| opcode).collect();
390    let gaps: Vec<Opcode> = GAPS.iter().map(|&(opcode, ..)| opcode).collect();
391    let unaccounted: Vec<Opcode> = Opcode::all()
392        .filter(|opcode| {
393            !by_rule.contains(opcode) && !elsewhere.contains(opcode) && !gaps.contains(opcode)
394        })
395        .collect();
396
397    Report {
398        source: table.source,
399        opcodes: Opcode::all().count(),
400        by_rule,
401        names,
402        uncovered,
403        deferred,
404        unreachable,
405        elsewhere,
406        gaps,
407        unaccounted,
408    }
409}
410
411/// Every name a rule in a table is written about, which is the first test the trie makes.
412///
413/// Node zero is the root of the trie over the patterns and the first thing any walk asks is what
414/// the term in hand is called, so its tests are exactly the set of pattern heads. There is no
415/// wildcard there to worry about: a rule matching any term at all is one nobody has written and
416/// one that would be an error to write, since a lowering has to know what it is lowering.
417fn pattern_heads(table: &Table) -> Vec<&'static str> {
418    let Some(root) = table.nodes.first() else { return Vec::new() };
419    let mut found: Vec<&'static str> = root
420        .tests
421        .iter()
422        .filter_map(|(test, _)| match test {
423            Test::App { head, .. } => Some(*head),
424            // Neither can be at the root. A pattern is a term with a head, so the first step of
425            // every one of them is a head, and there is nothing bound yet to be the same as.
426            Test::Int(_) | Test::Same(_) => None,
427        })
428        .collect();
429    found.sort_unstable();
430    found.dedup();
431    found
432}
433
434/// The rules a target lowers by, or `None` where no back end in this crate covers it.
435///
436/// The same question [`crate::pipeline::Machine::for_target`] answers about the rest of a machine,
437/// and it is here as well because a caller that wants to write down what a run covered has a
438/// target and no machine. An architecture that gets a rule file at M6 gets an arm here at the same
439/// time, and until then it has no rules to report coverage of rather than an empty set of them.
440#[must_use]
441pub fn table(arch: Arch) -> Option<&'static Table> {
442    match arch {
443        Arch::X86_64 => Some(&crate::select::x86_64::TABLE),
444        Arch::Aarch64 | Arch::Riscv64 => None,
445    }
446}
447
448/// Which rules fired, over one function or over a whole compilation.
449///
450/// A bit per rule and nothing else. This is on the path of every instruction selected, so what it
451/// costs is paid by every compilation whether or not anybody asked for the number, and the cheapest
452/// thing that answers the question is a flag per rule set once.
453///
454/// The index of a rule is how this is kept and not how it is written down. An index moves the
455/// moment a rule is added above it, so [`Fired::listing`] names the rule file and the line instead:
456/// a line is a place somebody can open, and a report written by one build can still be read against
457/// a rule file that has grown since.
458#[derive(Debug, Clone, Default, PartialEq, Eq)]
459pub struct Fired {
460    /// One entry per rule, true once that rule has fired. It grows to fit the highest index
461    /// marked rather than being sized from a table, so nothing here has to be told which target
462    /// is being compiled for.
463    seen: Vec<bool>,
464}
465
466impl Fired {
467    /// Nothing has fired yet.
468    #[must_use]
469    pub const fn new() -> Fired {
470        Fired { seen: Vec::new() }
471    }
472
473    /// Records that the rule at this index fired.
474    pub fn mark(&mut self, rule: usize) {
475        if self.seen.len() <= rule {
476            self.seen.resize(rule + 1, false);
477        }
478        self.seen[rule] = true;
479    }
480
481    /// Whether the rule at this index fired.
482    #[must_use]
483    pub fn has(&self, rule: usize) -> bool {
484        self.seen.get(rule).copied().unwrap_or(false)
485    }
486
487    /// How many rules fired.
488    #[must_use]
489    pub fn count(&self) -> usize {
490        self.seen.iter().filter(|fired| **fired).count()
491    }
492
493    /// Takes in everything another one recorded.
494    ///
495    /// One compilation is many functions and one command line is many files, and the question is
496    /// about all of them together. Merging rather than writing a file per function is also what
497    /// keeps the answer the same however the work was scheduled.
498    pub fn merge(&mut self, other: &Fired) {
499        if self.seen.len() < other.seen.len() {
500            self.seen.resize(other.seen.len(), false);
501        }
502        for (mine, theirs) in self.seen.iter_mut().zip(&other.seen) {
503            *mine |= *theirs;
504        }
505    }
506
507    /// What `-Zrule-coverage=FILE` writes.
508    ///
509    /// One line per rule in the table, in the order the rule file writes them, each saying whether
510    /// the rule fired and naming the file and line it is written at. Every rule is listed rather
511    /// than only the ones that fired, so that one of these files says what the whole rule set was
512    /// as well as what this compilation reached: a reader unioning them over a corpus needs both
513    /// and would otherwise have to parse the rule file to get the second.
514    ///
515    /// The first line is a comment holding the count, which is the number a person wants and the
516    /// one thing here that is not worth making them add up.
517    #[must_use]
518    pub fn listing(&self, table: &Table) -> String {
519        let fired = table.rules.iter().enumerate().filter(|(index, _)| self.has(*index)).count();
520        let mut out = format!(
521            "# rucc rule coverage: {fired} of {} rules in {} fired\n",
522            table.rules.len(),
523            table.source
524        );
525        for (index, rule) in table.rules.iter().enumerate() {
526            let word = if self.has(index) { "fired" } else { "unused" };
527            let _ = writeln!(out, "{word} {}:{} {}", table.source, rule.line, rule.pattern);
528        }
529        out
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use crate::select::x86_64::TABLE;
537
538    /// The claim the whole module is for, in the direction that matters: a name an instruction
539    /// can be called by is a name a rule is written at. This is the width check as much as the
540    /// opcode check, since a name is an opcode and a width together.
541    #[test]
542    fn every_name_an_instruction_can_have_is_one_a_rule_is_written_at() {
543        let report = report(&TABLE);
544        assert!(
545            report.uncovered.is_empty(),
546            "nothing in {} lowers these, and each is an opcode at a width the rule language can \
547             spell: {:?}",
548            report.source,
549            report.uncovered
550        );
551    }
552
553    /// And the other direction, which costs nothing to ask and finds a rule that can never fire.
554    /// A pattern head no instruction is ever called by is a rule written against a name that was
555    /// renamed or misspelled, and it would sit there proved and unreachable.
556    #[test]
557    fn every_name_a_rule_is_written_at_is_one_an_instruction_can_have() {
558        let report = report(&TABLE);
559        assert!(
560            report.unreachable.is_empty(),
561            "{} has rules for these and no instruction is ever called one: {:?}",
562            report.source,
563            report.unreachable
564        );
565    }
566
567    /// Every opcode is one of the three things, so a new opcode in the IR fails this until
568    /// somebody says where it goes. That is the whole point: the answer for a new opcode should
569    /// be written down when it is added rather than discovered by a user compiling a program.
570    #[test]
571    fn every_opcode_is_lowered_or_is_a_gap_somebody_wrote_down() {
572        let report = report(&TABLE);
573        assert!(
574            report.unaccounted.is_empty(),
575            "no rule lowers these, `ELSEWHERE` does not say where they are lowered and `GAPS` \
576             does not say why they are not: {:?}",
577            report.unaccounted
578        );
579        assert_eq!(
580            report.by_rule.len() + report.elsewhere.len() + report.gaps.len(),
581            report.opcodes,
582            "the three lists overlap, so an opcode is counted twice"
583        );
584    }
585
586    /// An entry that starts being covered fails, which is the rule every list in this project is
587    /// kept under. An opcode a rule now lowers is one that should be off both lists, and a list
588    /// that keeps claiming otherwise is a list nobody can read.
589    #[test]
590    fn an_entry_a_rule_now_covers_is_a_stale_entry() {
591        let report = report(&TABLE);
592        for &(opcode, where_) in ELSEWHERE {
593            assert!(
594                !report.by_rule.contains(&opcode),
595                "`{}` is lowered by a rule now, so the `ELSEWHERE` entry saying it is lowered by \
596                 {where_} is stale",
597                opcode.name()
598            );
599        }
600        for &(opcode, why, issue) in GAPS {
601            assert!(
602                !report.by_rule.contains(&opcode),
603                "`{}` is lowered by a rule now, so the `GAPS` entry saying it is {why} is stale \
604                 and {issue} may be closed",
605                opcode.name()
606            );
607            assert!(
608                !report.elsewhere.contains(&opcode),
609                "`{}` is on both lists, so it is both lowered and not lowered",
610                opcode.name()
611            );
612        }
613    }
614
615    /// The same staleness rule one list down. A name a rule is written at is a name that is not
616    /// left for later, and an entry claiming otherwise is one that should have gone when the rule
617    /// arrived. The other direction is checked too: a name no instruction can ever have is a
618    /// misspelling, and it would sit here excusing nothing.
619    #[test]
620    fn a_name_a_rule_is_written_at_is_not_a_name_left_for_later() {
621        let heads = pattern_heads(&TABLE);
622        let named = term::heads();
623        for &(name, why, issue) in NAMES {
624            assert!(
625                !heads.contains(&name),
626                "`{name}` is lowered by a rule now, so the `NAMES` entry saying it is {why} is \
627                 stale and {issue} may be closer than it says"
628            );
629            assert!(
630                named.iter().any(|&(_, head)| head == name),
631                "`{name}` is not a name any instruction can have, so the `NAMES` entry excuses \
632                 nothing"
633            );
634        }
635        let report = report(&TABLE);
636        assert_eq!(report.deferred.len(), NAMES.len(), "{:?}", report.deferred);
637    }
638
639    /// Every gap names an issue, since a gap with no issue behind it is a gap nobody has decided
640    /// anything about, which is the thing this module exists to stop.
641    #[test]
642    fn every_gap_names_the_issue_that_closes_it() {
643        let issues = GAPS
644            .iter()
645            .map(|&(_, _, issue)| issue)
646            .chain(WIDTHS.iter().map(|&(_, _, issue)| issue))
647            .chain(NAMES.iter().map(|&(_, _, issue)| issue));
648        for issue in issues {
649            let number = issue
650                .strip_prefix("tamnd/rucc#")
651                .unwrap_or_else(|| panic!("{issue} is not an issue in this project's tracker"));
652            assert!(number.parse::<u32>().is_ok(), "{issue} does not name an issue number");
653        }
654    }
655
656    /// The count, which `spec/15-testing.md` section 15.8 says we keep about ourselves. CI runs
657    /// this test with the output shown, so the number lands in a log next to the rule proof
658    /// rather than in a file somebody has to go and read.
659    #[test]
660    fn the_count_is_reported() {
661        let report = report(&TABLE);
662        println!("{report}");
663        for &(opcode, why, issue) in GAPS {
664            println!("rucc-codegen: no lowering for `{}`, which is {why}: {issue}", opcode.name());
665        }
666        for &(width, why, issue) in WIDTHS {
667            println!("rucc-codegen: no rule at {width}, which is {why}: {issue}");
668        }
669        for &(name, why, issue) in NAMES {
670            println!("rucc-codegen: no rule at `{name}`, which is {why}: {issue}");
671        }
672        assert_eq!(report.gaps.len(), GAPS.len());
673    }
674
675    /// What the root of the trie is, which is the assumption [`pattern_heads`] rests on. If the
676    /// rule compiler ever built the trie some other way this would say so, rather than the
677    /// coverage numbers quietly becoming a report about an empty list.
678    #[test]
679    fn the_root_of_the_trie_is_the_head_of_every_pattern() {
680        let heads = pattern_heads(&TABLE);
681        assert!(!heads.is_empty(), "the table has rules and the root of the trie tests nothing");
682        for rule in TABLE.rules {
683            let head = rule
684                .pattern
685                .strip_prefix('(')
686                .and_then(|rest| rest.split([' ', ')']).next())
687                .expect("a pattern is an application");
688            assert!(
689                heads.contains(&head),
690                "line {}: {} is a pattern whose head the root of the trie does not test",
691                rule.line,
692                rule.pattern
693            );
694        }
695    }
696
697    /// The one target with a rule file, and the two that get one at M6. A machine that can be
698    /// compiled for has rules to report the coverage of, and one that cannot has none rather than
699    /// an empty set of them, which are different answers and would read the same as a number.
700    #[test]
701    fn a_target_with_a_back_end_is_a_target_with_a_rule_set() {
702        let x86 = table(Arch::X86_64).expect("x86-64 is what this crate lowers for");
703        assert_eq!(x86.source, TABLE.source);
704        assert!(!x86.rules.is_empty());
705        assert!(table(Arch::Aarch64).is_none(), "there is no aarch64 rule file yet");
706        assert!(table(Arch::Riscv64).is_none(), "there is no riscv64 rule file yet");
707    }
708
709    /// What a rule is called outside this process. The index is not it: a rule added at the top of
710    /// the file moves every index below it, and a report from last week would then be a report
711    /// about the wrong rules. The file and the line do not move that way and are somewhere to look.
712    #[test]
713    fn a_rule_is_written_down_as_the_place_it_is_written_at() {
714        let mut fired = Fired::new();
715        fired.mark(0);
716        let listing = fired.listing(&TABLE);
717        let first =
718            format!("fired {}:{} {}", TABLE.source, TABLE.rules[0].line, TABLE.rules[0].pattern);
719        assert!(listing.contains(&first), "{listing}");
720        assert!(listing.lines().next().is_some_and(|line| line.starts_with('#')), "{listing}");
721    }
722
723    /// Every rule is listed and not only the ones that fired, which is what lets one of these files
724    /// be read on its own. A reader that only got the rules that fired would have to parse the rule
725    /// file to find out what the rest of them were.
726    #[test]
727    fn one_file_says_what_the_whole_rule_set_is() {
728        let listing = Fired::new().listing(&TABLE);
729        let lines: Vec<&str> = listing.lines().collect();
730        assert_eq!(lines.len(), TABLE.rules.len() + 1, "one line per rule and one for the count");
731        assert_eq!(
732            lines.iter().filter(|line| line.starts_with("unused ")).count(),
733            TABLE.rules.len()
734        );
735        assert!(lines[0].contains(&format!("0 of {} rules", TABLE.rules.len())), "{}", lines[0]);
736    }
737
738    /// A compilation is many functions and a command line is many files, and the question is about
739    /// all of them at once. Merging is also what keeps the answer the same however the work was
740    /// scheduled, which is the rule `spec/03-architecture.md` section 3.7 holds everything to.
741    #[test]
742    fn what_two_runs_reached_is_what_either_of_them_reached() {
743        let mut one = Fired::new();
744        one.mark(3);
745        one.mark(3);
746        assert_eq!(one.count(), 1, "a rule that fires twice is one rule");
747        let mut two = Fired::new();
748        two.mark(0);
749        two.mark(9);
750        one.merge(&two);
751        assert_eq!(one.count(), 3);
752        assert!(one.has(0) && one.has(3) && one.has(9));
753        assert!(!one.has(1));
754
755        // The merge is symmetric, since neither order of two files is the right one.
756        let mut back = Fired::new();
757        back.mark(0);
758        back.mark(9);
759        let mut three = Fired::new();
760        three.mark(3);
761        back.merge(&three);
762        assert_eq!(back, one);
763    }
764}