Skip to main content

rucc_opt/
discharge.rs

1//! Taking out a safety check whose answer is already known.
2//!
3//! Design: `spec/safe-memory/07-check-elimination.md` section 7.3, which is the first half of the
4//! Tier E budget. `rucc-safety` puts a bounds check and a lifetime check in front of every access
5//! and does not try to be clever about it, on purpose: a walk that inserts everything is a walk
6//! anybody can read, and every check that is not needed is meant to be taken out here instead.
7//! This pass takes them out, and it does the case document 07 expects to be worth the most and to
8//! be the easiest to get right, which is a second access to bytes an earlier access already had
9//! checked. All three kinds `rucc-safety` emits are the pass's business, the bounds check and the
10//! lifetime check in front of an access and the derivation check after a walk, because they are
11//! emitted together and taking out one of three is a third of a saving.
12//!
13//! # The two halves
14//!
15//! Section 7.7 asks for the pass and the condition to be separate things, and they are. What is in
16//! this file is a walk: which check runs before which, which pointer was computed from which, and
17//! how far apart two addresses are. Nothing here decides whether that is enough. The condition
18//! under which a check may go is a rule in `rules/safety.rules`, a solver has to agree with it
19//! before this crate finishes building, and `crate::rules::safety` is the table it compiles into.
20//!
21//! The split is worth the trouble because the two halves fail differently. A walk that gets the
22//! context wrong is a bug of the ordinary kind, and section 14.3's differential check accounting,
23//! which runs the instrumented program with every check and again with the discharged ones gone,
24//! is what looks for it. A removal condition that is wrong is arithmetic that is off at the ends of
25//! the type. It gives the right answer on every test anybody writes and lets one access through in
26//! the one case nobody thought of, and nothing observes that until somebody exploits it.
27//!
28//! # What it establishes and what it asks
29//!
30//! Walking the dominator tree from the entry, the pass carries a set of facts. A `check_bounds`
31//! that stays is a fact, because a check that passes says the bytes it was about lie inside one
32//! storage instance, and a check that fails does not return. A fact is remembered as the pointer's
33//! base and the constant offset from it, which is what a chain of `ptr_add` over constants comes
34//! to, plus how many bytes the access covers.
35//!
36//! At the next `check_bounds`, the pointer is normalized the same way. When a fact shares its base,
37//! the distance between the two accesses is the difference of the two offsets, and that is a number
38//! this pass has rather than a claim it makes: both addresses are the same value plus a constant.
39//! The question of whether the later bytes are inside the earlier ones is then handed to the table,
40//! which answers it in sixty four bit arithmetic rather than in the offsets, and the check goes
41//! only if the answer is yes.
42//!
43//! A check whose extent is an operand is left out of all of this, in both directions. Section 7.4's
44//! hoisted check covers as many bytes as its loop runs times, and every range compared here is a
45//! pair of numbers, so such a check is neither read as a fact nor asked about. Reading its payload
46//! would be worse than skipping it, since the size there is one element of the walk rather than the
47//! range the check is about, and a fact recorded from it would be smaller than the truth in one
48//! direction and a question asked from it smaller in the other.
49//!
50//! The capability operand has to be the `cap_of` of the check's own pointer, which is the shape
51//! `rucc-safety` emits and the shape the argument needs. The check being removed asks whether its
52//! bytes are inside the instance that owns its own pointer, its pointer is inside the range the
53//! earlier check established, and that range is inside one instance, so the answer is yes. A check
54//! whose capability came from somewhere else is asking about a different instance and is left
55//! alone. Nothing is required of the earlier check's capability, because all that is used of it is
56//! that the check passed, and a check that passed put its bytes inside one instance whatever
57//! capability it named.
58//!
59//! # The conjunct that is not about bytes
60//!
61//! A `check_bounds` tests two things, because document 06 section 6.3 put the access alignment on
62//! it rather than in a check of its own: that the bytes are inside one instance, and that the
63//! address starts where an access of that alignment may start. Everything above is about the
64//! first. A check that goes takes the second away with it, so nothing goes until something has
65//! answered it, which is `aligned` below and which reads the object the address came from and the
66//! steps taken from it. An access that assumes nothing about where it starts has nothing to
67//! answer, and a member of a packed record is exactly that.
68//!
69//! A global is settled elsewhere and arrives as [`Flags::ALIGNED`], for the reason
70//! [`Flags::STATIC`] beside it exists: how aligned a global is lives on the module and a pass is
71//! given a function. Without that the gate would cost seventeen times what it costs, which is the
72//! measurement in the changelog and is what says the flag earns its bit.
73//!
74//! What is left is a pointer this function was handed, one it loaded out of memory, and one a call
75//! gave back. It is counted rather than argued about, the same as everything else here, so
76//! `-fopt-info-missed` says what the rest of the `!aligned` fact of section 6.2.4 would be worth.
77//!
78//! # The fact nobody had to check for
79//!
80//! Section 7.2 lists four sources of a discharge and puts the frontend first, because the majority
81//! of accesses in real C are to a local or a global at a constant offset and the bounds of either
82//! are not something anybody has to find out. An `alloca` of a fixed size makes one storage
83//! instance of that many bytes and says so in its payload, so the range from its address to that
84//! many further along is inside one instance for exactly the reason a passing `check_bounds` says
85//! its own range is. When the address a check is about normalizes to such an `alloca`, that range
86//! is the fact, and the question put to the table is the same question with the same rule
87//! answering it.
88//!
89//! Two things make it worth more than a fact a check established. It is there before anything has
90//! run, so the first access to a local is discharged rather than only the second. And no call takes
91//! it away: a callee cannot free a frame slot, whatever it does to whatever the slot points at, so
92//! this fact is asked separately rather than kept in the set the walk throws away at the first call
93//! it cannot see through.
94//!
95//! Only the fixed size form. A variable length array is an `alloca` with an operand and a payload
96//! whose size field reads zero, and reading it anyway would discharge every check in the array.
97//!
98//! A global is the same fact about the other half of section 7.2's sentence, and it arrives here
99//! differently for one reason: how big a global is lives on the module and this pass is given one
100//! function. So `crate::extents` works it out over the module before the pipeline starts, asks the
101//! same rule, and writes the answer onto the check as [`Flags::STATIC`], which is what
102//! `crate::nofree` does with what a call reaches and for the same reason. What is read here is what
103//! the IR says, the same way the pass reads an opcode.
104//!
105//! It answers a lifetime check as well as a bounds check, which a local does not. What a local
106//! gives is an extent, and how long it stays alive is the block it was declared in, which is a
107//! question this pass has nothing to say about. A global has static storage duration and is alive
108//! wherever the question is asked.
109//!
110//! # The walk that stops at a step it cannot read
111//!
112//! Everything above needs the address to be a base and a constant, and an array index is not a
113//! constant. The walk stops at the first `ptr_add` whose step is a value, and what comes out is a
114//! fact about a base whose size nobody knows, which answers nothing.
115//!
116//! Section 7.2's third source is what gets past it. Document 10's ranges know something about the
117//! step even though it is not a number: an index the program has already tested against a length,
118//! or one whose low bits are all that is used, is bounded. So the walk carries on, adding the low
119//! end of the step's range to the offset and the width of the range to the size, and what it ends
120//! up with is the range of addresses the access can land in.
121//!
122//! Whether an object holding all of that range holds the one address the access actually uses is
123//! its own rule, `reached.i64`, which leaves the distance opaque so that one answer covers every
124//! value the step could take. It is a rule of its own rather than the containment rule asked about
125//! the far end of the range, and the reason is section 7.7's: turning a range of addresses into one
126//! containment question is arithmetic on the thing being proved, and a pass doing that quietly is
127//! what the split between the walk and the rule exists to stop.
128//!
129//! What the range is asked of is the list above and not a shorter one: the local an `alloca`
130//! declares, the object an allocator made where the program has tested it, and the ranges checks
131//! that already ran established. The allocation was missing from that list until tamnd/rucc#880,
132//! which is what left a loop walking an index into its own `malloc` with every check it started
133//! with however plainly the call said how many bytes it made.
134//!
135//! The range is only ever asked with and never recorded. What a check proves when it runs is that
136//! the address the program used was inside the object, and nothing at all about the rest of a
137//! range this pass made up around it. So a check discharged this way records the narrow fact, the
138//! bytes the access really wanted, which is the thing that was proved and is what a second check
139//! of the same bytes is answered by.
140//!
141//! The ranges are built only for a function that has a walk by a value in it, because they cost a
142//! copy of the control flow graph and a function without one would never ask them anything.
143//!
144//! # The lifetime half, and what it borrows from the other one
145//!
146//! A `check_live` that stays is a fact too, and a smaller one than it looks: it says the storage
147//! instance holding its own address is alive, and it says nothing about the address four bytes
148//! along, because that address might be in a different instance. On its own that fact discharges
149//! only a second lifetime check of the very same address, and the shape `rucc-safety` emits is a
150//! lifetime check per field rather than per object, so on its own it would almost never fire.
151//!
152//! What makes it fire is the bounds fact sitting next to it. A `check_bounds` that passed put its
153//! whole range inside one instance, so if the lifetime check's address is in that range, the
154//! instance that was found alive is the instance the whole range is in, and the whole range is
155//! alive. So a lifetime fact is recorded as the widest checked range containing its address, and a
156//! later lifetime check is asked about as a single byte. The question of whether that byte is in
157//! that range is the same question the bounds half asks, put to the same rule.
158//!
159//! The order the two arrive in is what makes this work rather than a coincidence to be careful
160//! about: `rucc-safety` emits the bounds check first and the lifetime check second, so the range is
161//! established by the time there is a lifetime fact to widen. A lifetime check that arrives with no
162//! range around it keeps the narrow fact, which is correct and worth little.
163//!
164//! # The derivation half, which is one question rather than two
165//!
166//! `rucc-safety` puts a `check_deriv` after every `ptr_add` off a pointer, and what it asks is not
167//! about a range at all: it asks whether the pointer that came out is still in the storage instance
168//! the pointer that went in belongs to. The runtime has some slack in it for a pointer that walked
169//! exactly off either end, and none of that slack is used here, because the case this pass answers
170//! is the one where both ends are plainly inside something.
171//!
172//! What answers it is one fact holding both ends. A `check_bounds` that passed put its whole range
173//! inside one instance, so if the address that went in and the address that came out are both in
174//! that range, the second is in the instance the first belongs to, which is the question. It has to
175//! be one fact and not one for each end: two facts saying two addresses are each inside some
176//! instance say nothing about whether it is the same instance, and that is the only thing being
177//! asked. A local is a fact of exactly this shape and is asked the same way.
178//!
179//! Both ends are asked about as a single byte, the way a lifetime check is, and for the same reason.
180//! Nothing here is claiming anything about how many bytes are readable at either address.
181//!
182//! A `check_deriv` that stays leaves no fact behind. What it establishes is that two addresses share
183//! an instance, which is not a range of bytes and does not fit in what this walk carries, and the
184//! `covered.i64` rule has nothing to say about it. Recording it would mean a second kind of fact and
185//! a second rule, and the pointer it is about nearly always gets a `check_bounds` of its own a few
186//! instructions later that establishes the range properly.
187//!
188//! # Why a call throws the facts away, and which calls do not
189//!
190//! Section 7.3 says nothing kills a bounds fact except a redefinition of the capability, which in
191//! SSA is never, and this pass is stricter than that: a call, or anything else this pass cannot see
192//! through, drops every fact it is carrying.
193//!
194//! The case is a `free` and then an allocation of something smaller at the same address. The range
195//! established before the call is no longer inside one instance after it, and what document 07
196//! leaves that to is the lifetime judgement rather than this one. Today's lifetime check is about
197//! the address rather than about the version the capability was taken at, so it would not refuse
198//! the access either, and a rate this pass reports is worth less than a hole it opens. The strict
199//! version is what is written first.
200//!
201//! A `meta_end` and a `meta_transfer` drop the facts as well. Nothing emits either one yet, so
202//! this costs nothing today and is the difference between conservative and wrong on the day the
203//! instrumentation starts ending lifetimes. `crate::nofree` treats them the same way.
204//!
205//! The two facts nobody had to check for go across a call untouched, and neither is an exception to
206//! the paragraph above because neither is in the set being thrown away. A callee cannot free a
207//! frame slot and cannot free a global, so a check the declaration answers is answered on the far
208//! side of any call at all.
209//!
210//! A call that says it reaches nothing which can free is the exception, and it is not this pass
211//! being trusting. `crate::nofree` works the answer out over the whole module before the pipeline
212//! starts and writes it onto the call site as [`Flags::NOFREE`], because the fact belongs to the
213//! callee and a pass is given one function. Reading it here is reading what the IR says, the same
214//! way the pass reads an opcode. Nothing else about a call is believed: the facts still go across
215//! an unmarked call, a call through an address, and inline assembly.
216//!
217//! What the strictness still costs is measured rather than guessed. A check that a fact would have
218//! covered if a call had not intervened is counted, so `-fopt-info-missed` says per function what
219//! is left to win.
220
221use std::collections::{HashMap, HashSet};
222
223use rucc_ir::{Block, Def, Extra, Flags, Func, Inst, Opcode, Value};
224
225use crate::range::query::Ranges;
226use crate::rules::{Piece, Subject, Table, safety};
227use crate::{Analyses, Analysis, Cfg, Fuel, Pass, Preserved, Stats, heap};
228
229/// Recorded once for each bounds check taken out.
230const REMOVED: &str = "bounds check removed, a dominating check covers the same bytes";
231
232/// Recorded once for each bounds check taken out because it was inside a local.
233const REMOVED_LOCAL: &str = "bounds check removed, its bytes are inside a local this function \
234                             declares";
235
236/// Recorded once for each bounds check taken out because it was inside a global.
237const REMOVED_STATIC: &str = "bounds check removed, its bytes are inside an object of static \
238                              storage duration";
239
240/// Recorded once for each bounds check taken out because every caller hands in the object.
241const REMOVED_HANDED: &str = "bounds check removed, its bytes are inside an object every call to \
242                              this function hands it";
243
244/// Recorded once for each bounds check taken out because an allocator made the object.
245const REMOVED_MADE: &str = "bounds check removed, its bytes are inside an object an allocator made \
246                            and this function has tested";
247
248/// Recorded once for each bounds check taken out because a range answered the step it walked by.
249const REMOVED_RANGE: &str = "bounds check removed, every address the walk can reach is inside the \
250                             object it started from";
251
252/// Recorded once for each lifetime check taken out.
253const REMOVED_LIVE: &str = "lifetime check removed, a dominating check covers the same storage";
254
255/// Recorded once for each lifetime check taken out because it was inside a global.
256const REMOVED_LIVE_STATIC: &str =
257    "lifetime check removed, its storage lives as long as the program does";
258
259/// Recorded once for each lifetime check taken out because every caller hands in the object.
260const REMOVED_LIVE_HANDED: &str = "lifetime check removed, its storage is an object every call to \
261                                   this function hands it";
262
263/// Recorded once for each lifetime check taken out because it was inside a frame slot.
264const REMOVED_LIVE_LOCAL: &str =
265    "lifetime check removed, its storage is a frame slot of this function";
266
267/// Recorded once for each lifetime check taken out because a range answered the step it walked by.
268const REMOVED_LIVE_RANGE: &str = "lifetime check removed, every address the walk can reach is in \
269                                  storage a check found alive";
270
271/// Recorded for a bounds check that would have gone if there had been fuel for it.
272const NO_FUEL: &str = "bounds check kept, the pass ran out of fuel";
273
274/// Recorded for a lifetime check that would have gone if there had been fuel for it.
275const NO_FUEL_LIVE: &str = "lifetime check kept, the pass ran out of fuel";
276
277/// Recorded once for each derivation check taken out because a range answered the step it walked by.
278const REMOVED_DERIV_RANGE: &str = "derivation check removed, every address either end can reach is \
279                                   inside one checked range";
280
281/// Recorded for a bounds check a call cost, which is the honest price of the paragraph above.
282///
283/// This one is worth reading rather than skipping. It is the number of checks that are still being
284/// paid for because `crate::nofree` could not vouch for a call, so it says per function what the
285/// rest of section 7.5's summary work would be worth before anybody writes it.
286const PAST_A_CALL: &str =
287    "bounds check kept, a call between it and the check that covers it might free";
288
289/// The same, for a lifetime check. Section 8.8 is about this number rather than the one above.
290const PAST_A_CALL_LIVE: &str =
291    "lifetime check kept, a call between it and the check that covers it might free";
292
293/// Recorded for a bounds check kept because nothing here says where the access starts.
294///
295/// The alignment conjunct of judgement J1 rides on `check_bounds`, so taking the check out takes
296/// the alignment test with it. Recorded only for a check a rule had already answered the bytes of,
297/// so the number is what the gate costs rather than how many checks have an alignment, which makes
298/// it what the `!aligned` fact of `spec/safe-memory/06-instrumentation.md` section 6.2.4 would be
299/// worth.
300const UNKNOWN_ALIGNMENT: &str =
301    "bounds check kept, nothing here says the address is aligned to what the access assumes";
302
303/// Recorded for a bounds check whose operands this pass cannot read.
304const UNKNOWN_SHAPE: &str = "bounds check left alone, its pointer is not a base and a constant";
305
306/// Recorded for a bounds check about a range the program worked out.
307const COMPUTED_EXTENT: &str =
308    "bounds check left alone, how many bytes it covers is a number only the program has";
309
310/// Recorded for a lifetime check whose operands this pass cannot read.
311const UNKNOWN_SHAPE_LIVE: &str =
312    "lifetime check left alone, its pointer is not a base and a constant";
313
314/// Recorded once for each derivation check taken out.
315const REMOVED_DERIV: &str =
316    "derivation check removed, one checked range holds both the pointer and where it walked to";
317
318/// Recorded once for each derivation check taken out because it walked inside a local.
319const REMOVED_DERIV_LOCAL: &str =
320    "derivation check removed, it walks inside a local this function declares";
321
322/// Recorded once for each derivation check taken out because it walked inside a global.
323const REMOVED_DERIV_STATIC: &str =
324    "derivation check removed, it walks inside an object of static storage duration";
325
326/// Recorded once for each derivation check taken out because every caller hands in the object.
327const REMOVED_DERIV_HANDED: &str = "derivation check removed, it walks inside an object every call \
328                                    to this function hands it";
329
330/// Recorded once for each derivation check taken out because an allocator made the object.
331const REMOVED_DERIV_MADE: &str = "derivation check removed, it walks inside an object an allocator \
332                                  made and this function has tested";
333
334/// Recorded for a derivation check that would have gone if there had been fuel for it.
335const NO_FUEL_DERIV: &str = "derivation check kept, the pass ran out of fuel";
336
337/// Recorded for a derivation check a call cost.
338const PAST_A_CALL_DERIV: &str =
339    "derivation check kept, a call between it and the range that holds both ends might free";
340
341/// Recorded for a derivation check naming a capability that is not the one it is about.
342const NOT_ITS_CAPABILITY_DERIV: &str = "derivation check left alone, the capability it names is not the one the pointer that went in \
343     carries";
344
345/// Recorded for a derivation check whose two ends are not off one value.
346const TWO_BASES_DERIV: &str =
347    "derivation check left alone, its two pointers are not built on one base";
348
349/// Recorded for a derivation check whose walk can reach past the end of the local it starts in.
350const OVER_THE_LOCAL_DERIV: &str =
351    "derivation check left alone, the walk can reach past the end of the local it starts in";
352
353/// Recorded for a derivation check on a pointer this function loaded out of memory.
354const NO_EXTENT_LOADED: &str = "derivation check left alone, nothing here says how big the object \
355                                is and the pointer to it was loaded from memory";
356
357/// Recorded for a derivation check on a pointer this function was handed.
358const NO_EXTENT_HANDED: &str = "derivation check left alone, nothing here says how big the object \
359                                is and the pointer to it was handed to this function";
360
361/// Recorded for a derivation check on a pointer into a global.
362const NO_EXTENT_GLOBAL: &str = "derivation check left alone, nothing here says how big the object \
363                                is and the pointer to it is into a global";
364
365/// Recorded for a derivation check on a pointer a call handed back.
366const NO_EXTENT_RETURNED: &str = "derivation check left alone, nothing here says how big the \
367                                  object is and the pointer to it came back from a call";
368
369/// Recorded for a derivation check on a pointer none of the shapes above describes.
370const NO_EXTENT_OTHER: &str =
371    "derivation check left alone, nothing here says how big the object its pointers are in is";
372
373/// The pass. It holds nothing, because everything it works out is about one function.
374/// Which of the places a fact comes from a run of this pass may ask.
375///
376/// Everything is asked normally and there is one pass in the pipeline. The others are here for the
377/// measurement `spec/safe-memory/13-performance.md` section 13.5 asks for and
378/// `spec/safe-memory/17-open-questions.md` question 3 is: how much each source discharges on its
379/// own, and how much the same sources discharge together. A number for a source on its own cannot
380/// be read off the remarks of a full run, because the rules are asked in an order and whichever one
381/// answers first is the one the remark names, so the second source to be asked about a check two of
382/// them could answer looks like it answered nothing.
383///
384/// The four are document 07 section 7.2's four, with the caveat the measurement found: the ranges
385/// are not a fourth kind of fact but a way of asking the other three about a subscript instead of
386/// about an address written out in the program.
387#[derive(Clone, Copy, PartialEq, Eq, Debug)]
388pub struct Sources {
389    /// How big an object is, read off whatever made it. A global's extent comes from
390    /// `crate::extents`, a local's from its `alloca`, an allocation's from the call `crate::heap`
391    /// marked. Section 7.2's first source.
392    objects: bool,
393    /// What a check that has already run established, carried down the dominator tree. Section 7.3,
394    /// and the one the literature calls redundant check elimination.
395    dominance: bool,
396    /// What every caller of this function guarantees about what it was handed, from
397    /// `crate::params`. Section 7.5.
398    summaries: bool,
399    /// The value ranges and the recurrences, which widen the one address a check names into the
400    /// range of addresses a walk can reach so that the other three can be asked about a subscript.
401    /// Section 7.4, and the half of the PICO result this pass holds. The other half is
402    /// [`crate::hoist`] and [`crate::split`], which are passes of their own and have flags of their
403    /// own.
404    ranges: bool,
405}
406
407impl Sources {
408    /// Every one of them, which is what the pipeline runs.
409    pub const ALL: Self = Self { objects: true, dominance: true, summaries: true, ranges: true };
410    /// What an object says about itself and nothing else.
411    pub const OBJECTS: Self =
412        Self { objects: true, dominance: false, summaries: false, ranges: false };
413    /// What an earlier check established and nothing else.
414    pub const DOMINANCE: Self =
415        Self { objects: false, dominance: true, summaries: false, ranges: false };
416    /// What every caller guarantees and nothing else.
417    pub const SUMMARIES: Self =
418        Self { objects: false, dominance: false, summaries: true, ranges: false };
419    /// Every fact, asked only about addresses written out in the program.
420    pub const NARROW: Self =
421        Self { objects: true, dominance: true, summaries: true, ranges: false };
422}
423
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct Discharge {
426    /// What `-f<name>` and `-fno-<name>` reach this run by.
427    name: &'static str,
428    /// Which places it may take a fact from. See [`Sources`].
429    sources: Sources,
430}
431
432/// The pass the pipeline runs, which asks everything.
433pub static DISCHARGE: Discharge = Discharge { name: "discharge", sources: Sources::ALL };
434
435/// The same pass asking an object how big it is and nothing else.
436pub static OBJECTS: Discharge = Discharge { name: "discharge-objects", sources: Sources::OBJECTS };
437
438/// The same pass asking what an earlier check established and nothing else.
439pub static DOMINANCE: Discharge =
440    Discharge { name: "discharge-dominance", sources: Sources::DOMINANCE };
441
442/// The same pass asking what every caller guarantees and nothing else.
443pub static SUMMARIES: Discharge =
444    Discharge { name: "discharge-summaries", sources: Sources::SUMMARIES };
445
446/// The same pass asking every fact, about addresses written out in the program only.
447pub static NARROW: Discharge = Discharge { name: "discharge-narrow", sources: Sources::NARROW };
448
449/// The same pass asking everything, under a name of its own.
450///
451/// [`DISCHARGE`] already asks everything, so this looks like a duplicate and is not. A pass the level
452/// did not choose goes on the end of the pipeline, so a run of `-fno-discharge -fdischarge-objects`
453/// asks its question in a different place from where the shipped pass asks it, and the two numbers
454/// are not comparable. This one is turned on the same way as the others and lands in the same place,
455/// so the sum of the parts and the whole are measured under one arrangement. What it costs against
456/// [`DISCHARGE`] is what the position is worth, which is a number the measurement wants anyway.
457pub static EVERY: Discharge = Discharge { name: "discharge-every", sources: Sources::ALL };
458
459impl Pass for Discharge {
460    fn name(&self) -> &'static str {
461        self.name
462    }
463
464    fn describe(&self) -> &'static str {
465        "a bounds, lifetime or derivation check whose answer is already known is removed"
466    }
467
468    fn preserves(&self) -> Preserved {
469        // Instructions go and blocks do not. A check is not a terminator and removing one leaves
470        // every edge where it was. What it does not leave where it was is the liveness, because
471        // the check was reading something and now nothing is.
472        Preserved::ALL.without(Analysis::Liveness)
473    }
474
475    fn run(&self, func: &mut Func, an: &mut Analyses, fuel: &mut Fuel) -> Stats {
476        let mut stats = Stats::new();
477        let Some(entry) = func.entry() else { return stats };
478        let dom = an.dominators(func);
479
480        // The graph is built for two reasons and neither is the common one, so a function with
481        // neither pays for no copy of it. The ranges want it when there is a walk the constant
482        // reader gives up on, and the allocation rule wants it to find where the program has tested
483        // what an allocator gave it.
484        let walks = self.sources.ranges && walks_by_a_value(func);
485        let cfg = (walks || (self.sources.objects && heap::allocates(func))).then(|| an.cfg(func));
486        let mut ranges = cfg.filter(|_| walks).map(|cfg| Ranges::new(&*func, cfg, dom));
487
488        // One answer per allocation rather than one per check, because a function that reads twenty
489        // fields of the same object asks the same question about the same pointer twenty times.
490        let mut checked: HashMap<Value, HashSet<Block>> = HashMap::new();
491
492        // Whether anything in here says a lifetime is over. Read once over the whole function
493        // rather than carried down the walk, because what the frame slot rule needs is that no
494        // `meta_end` runs before the check on any path, and a fact carried down the dominator
495        // tree only ever says something about the paths that go through one block.
496        let ends = ends_a_lifetime(func);
497
498        // The walk is a stack rather than recursion because the dominator tree of a long chain of
499        // blocks is as deep as the function is long, and a pass is not a place to find that out.
500        // Each block carries its own copy of what holds at its start, which is what makes a fact a
501        // call killed in one arm of a branch still hold in the other.
502        let mut going: Vec<(Inst, &'static str)> = Vec::new();
503        let mut work = vec![(entry, Scope::default())];
504        while let Some((block, mut scope)) = work.pop() {
505            for inst in func.insts(block).collect::<Vec<Inst>>() {
506                if opaque(func, inst) {
507                    scope.forget();
508                    continue;
509                }
510                match func[inst].opcode {
511                    Opcode::CheckBounds => {
512                        if func[func[inst].args].len() > 2 {
513                            stats.missed(COMPUTED_EXTENT);
514                            continue;
515                        }
516                        let Some(asked) = about(func, inst) else {
517                            stats.missed(UNKNOWN_SHAPE);
518                            continue;
519                        };
520                        // The four objects whose extent is known without anybody having checked
521                        // it. A global was worked out over the module by `crate::extents` and an
522                        // object every caller hands in by `crate::params`, both of which arrive as
523                        // a flag; a local is read off its `alloca` here and an allocation off the
524                        // call `crate::heap` marked. All four are asked of the same rule as every
525                        // other fact. The reach of a walk the constant reader could not finish is
526                        // asked last, because it is the only one that costs an analysis to answer.
527                        let why = if self.sources.objects
528                            && func[inst].flags.contains(Flags::STATIC)
529                        {
530                            Some(REMOVED_STATIC)
531                        } else if self.sources.summaries && func[inst].flags.contains(Flags::HANDED)
532                        {
533                            Some(REMOVED_HANDED)
534                        } else if self.sources.objects
535                            && declared(func, asked.base)
536                                .is_some_and(|local| covers(&local, &asked))
537                        {
538                            Some(REMOVED_LOCAL)
539                        } else if self.sources.objects
540                            && allocated(func, cfg, &mut checked, block, &[&asked])
541                        {
542                            Some(REMOVED_MADE)
543                        } else if self.sources.dominance && scope.bounds.covers(&asked) {
544                            Some(REMOVED)
545                        } else {
546                            // The same four sources in the same order, asked of the range of
547                            // addresses the walk can reach rather than of the one address the
548                            // constant reader could name. A flag has already been read above and
549                            // reading it again would say the same thing, so what is left is the
550                            // local, the allocation and what the walk carries.
551                            reach(func, ranges.as_mut(), &asked, inst).and_then(|wide| {
552                                if self.sources.objects
553                                    && declared(func, wide.base)
554                                        .is_some_and(|local| reaches(&local, &wide))
555                                {
556                                    Some(REMOVED_RANGE)
557                                } else if self.sources.objects
558                                    && allocated_around(func, cfg, &mut checked, block, &[&wide])
559                                {
560                                    Some(REMOVED_MADE)
561                                } else if self.sources.dominance && scope.bounds.reaches(&wide) {
562                                    Some(REMOVED_RANGE)
563                                } else {
564                                    None
565                                }
566                            })
567                        };
568                        // Asked once a rule has answered the bounds rather than in front of them
569                        // all, because a check that was staying anyway costs the gate nothing and
570                        // the number somebody reads has to be what it actually costs. A check kept
571                        // here still runs, so it still establishes what it was about.
572                        let why = why.filter(|_| {
573                            aligned(func, inst) || {
574                                stats.missed(UNKNOWN_ALIGNMENT);
575                                false
576                            }
577                        });
578                        let Some(why) = why else {
579                            if scope.bounds.covered_before(&asked) {
580                                stats.missed(PAST_A_CALL);
581                            }
582                            // A check that stays is a check that runs, and a check that runs
583                            // establishes what it was about. One that was removed establishes
584                            // nothing new: whatever covered it covers everything it would have.
585                            scope.bounds.held.push(asked);
586                            continue;
587                        };
588                        if !fuel.take() {
589                            stats.missed(NO_FUEL);
590                            scope.bounds.held.push(asked);
591                            continue;
592                        }
593                        // A check that goes normally establishes nothing new, because whatever
594                        // answered it covers everything it would have. The range is the one
595                        // exception: what answered it was a fact about a made up range around the
596                        // address, and the next check on these bytes has to ask for that range
597                        // again and may not get the same answer. So the narrow fact goes in, which
598                        // is the thing that was actually proved.
599                        if why == REMOVED_RANGE {
600                            scope.bounds.held.push(asked);
601                        }
602                        going.push((inst, why));
603                    }
604                    Opcode::CheckLive => {
605                        let Some(asked) = alive(func, inst) else {
606                            stats.missed(UNKNOWN_SHAPE_LIVE);
607                            continue;
608                        };
609                        // A global is alive as long as the program is, and a frame slot is alive
610                        // until the function returns, so both objects whose extent is known
611                        // without anybody having checked it answer this as well as a bounds
612                        // check. `ends` is what makes the second one true: where a local stops
613                        // being alive is written into the IR as `meta_end` and not read off the
614                        // shape of the source, so a function with one in it is a function this
615                        // does not claim anything about.
616                        let why = if self.sources.objects
617                            && func[inst].flags.contains(Flags::STATIC)
618                        {
619                            Some(REMOVED_LIVE_STATIC)
620                        } else if self.sources.summaries && func[inst].flags.contains(Flags::HANDED)
621                        {
622                            Some(REMOVED_LIVE_HANDED)
623                        } else if self.sources.objects
624                            && !ends
625                            && declared(func, asked.base)
626                                .is_some_and(|local| covers(&local, &asked))
627                        {
628                            Some(REMOVED_LIVE_LOCAL)
629                        } else if self.sources.dominance && scope.alive.covers(&asked) {
630                            Some(REMOVED_LIVE)
631                        } else {
632                            // A lifetime fact and not a bounds one, because what is being asked
633                            // is whether the storage is alive and a bounds check that passed says
634                            // nothing about that. The widening argument is the bounds arm's: a
635                            // range known alive that holds every address the walk can reach holds
636                            // the one it actually uses.
637                            reach(func, ranges.as_mut(), &asked, inst)
638                                .filter(|wide| {
639                                    (self.sources.objects
640                                        && !ends
641                                        && declared(func, wide.base)
642                                            .is_some_and(|local| reaches(&local, wide)))
643                                        || (self.sources.dominance && scope.alive.reaches(wide))
644                                })
645                                .map(|_| REMOVED_LIVE_RANGE)
646                        };
647                        let Some(why) = why else {
648                            if scope.alive.covered_before(&asked) {
649                                stats.missed(PAST_A_CALL_LIVE);
650                            }
651                            scope.alive.held.push(widened(func, &scope.bounds, asked));
652                            continue;
653                        };
654                        if !fuel.take() {
655                            stats.missed(NO_FUEL_LIVE);
656                            scope.alive.held.push(widened(func, &scope.bounds, asked));
657                            continue;
658                        }
659                        // The bounds arm's exception, for its reason. A range answered a made up
660                        // range around this address, so what was proved is about the address.
661                        if why == REMOVED_LIVE_RANGE {
662                            scope.alive.held.push(widened(func, &scope.bounds, asked));
663                        }
664                        going.push((inst, why));
665                    }
666                    Opcode::CheckDeriv => {
667                        let narrow = derives(func, inst);
668                        let why = narrow.and_then(|(from, to)| {
669                            if self.sources.objects && func[inst].flags.contains(Flags::STATIC) {
670                                Some(REMOVED_DERIV_STATIC)
671                            } else if self.sources.summaries
672                                && func[inst].flags.contains(Flags::HANDED)
673                            {
674                                Some(REMOVED_DERIV_HANDED)
675                            } else if self.sources.objects
676                                && declared(func, from.base).is_some_and(|local| {
677                                    covers(&local, &from) && covers(&local, &to)
678                                })
679                            {
680                                Some(REMOVED_DERIV_LOCAL)
681                            } else if self.sources.objects
682                                && allocated(func, cfg, &mut checked, block, &[&from, &to])
683                            {
684                                Some(REMOVED_DERIV_MADE)
685                            } else if self.sources.dominance && scope.bounds.holds_both(&from, &to)
686                            {
687                                Some(REMOVED_DERIV)
688                            } else {
689                                None
690                            }
691                        });
692                        // Asked last, and asked off the check's own operands rather than off what
693                        // `derives` worked out, because the case it is for is the one `derives`
694                        // cannot read at all: past a step the constant reader gives up on the two
695                        // ends are not one base and two constants. One thing has to hold both of
696                        // the ranges, for the same reason one thing has to hold both of the
697                        // addresses, which is that two things saying each end is inside something
698                        // say nothing about it being the same something.
699                        let why = why.or_else(|| {
700                            spread(func, ranges.as_mut(), inst, inst).and_then(|(near, far)| {
701                                if self.sources.objects
702                                    && declared(func, near.base).is_some_and(|local| {
703                                        reaches(&local, &near) && reaches(&local, &far)
704                                    })
705                                {
706                                    Some(REMOVED_DERIV_RANGE)
707                                } else if self.sources.objects
708                                    && allocated_around(
709                                        func,
710                                        cfg,
711                                        &mut checked,
712                                        block,
713                                        &[&near, &far],
714                                    )
715                                {
716                                    Some(REMOVED_DERIV_MADE)
717                                } else if self.sources.dominance
718                                    && scope.bounds.reaches_both(&near, &far)
719                                {
720                                    Some(REMOVED_DERIV_RANGE)
721                                } else {
722                                    None
723                                }
724                            })
725                        });
726                        let Some(why) = why else {
727                            match narrow {
728                                Some((from, to)) => {
729                                    if scope.bounds.held_both_before(&from, &to) {
730                                        stats.missed(PAST_A_CALL_DERIV);
731                                    }
732                                }
733                                None => {
734                                    stats.missed(unreadable(func, ranges.as_mut(), inst));
735                                }
736                            }
737                            continue;
738                        };
739                        if !fuel.take() {
740                            stats.missed(NO_FUEL_DERIV);
741                            continue;
742                        }
743                        going.push((inst, why));
744                    }
745                    _ => continue,
746                }
747            }
748            for child in dom.children(block) {
749                work.push((child, scope.clone()));
750            }
751        }
752
753        for (inst, why) in going {
754            func.remove_inst(inst);
755            stats.optimized(why);
756        }
757        stats
758    }
759}
760
761/// A range of bytes some check has already been passed on, or is being asked about.
762///
763/// The address is kept as the value it was computed from and the constant distance from it, rather
764/// than as the pointer itself, because that is what makes two of these comparable: the whole of
765/// what this pass knows about two addresses is that they are one value plus two constants.
766#[derive(Debug, Clone, Copy, PartialEq, Eq)]
767pub(crate) struct Fact {
768    /// The value the address was computed from.
769    pub(crate) base: Value,
770    /// How far past it the access starts.
771    pub(crate) offset: i128,
772    /// How many bytes it covers.
773    size: i128,
774}
775
776impl Fact {
777    /// The whole of an object whose extent is known, starting at its own address.
778    ///
779    /// The two sources of one of these are an `alloca` of a fixed size and a global, and what they
780    /// have in common is that the size is said by something other than a check that passed.
781    pub(crate) fn whole(base: Value, size: i128) -> Self {
782        Self { base, offset: 0, size }
783    }
784
785    /// A range of bytes named by where it starts and how far it runs.
786    ///
787    /// The general form of [`Fact::whole`], for a caller that has both ends of a range in hand
788    /// rather than an object. `crate::dead_plane` is the one, and what it has is a plane write
789    /// rather than an access, which is a different thing to be about and the same thing to ask.
790    pub(crate) fn range(base: Value, offset: i128, size: i128) -> Self {
791        Self { base, offset, size }
792    }
793}
794
795/// A range of addresses an access can land in, and how many bytes it takes when it does.
796///
797/// What [`reach`] works out and the only thing it is used for. It is deliberately not a [`Fact`]:
798/// a fact is something that was established and may be recorded, and this is a question and may
799/// not. The address the program uses is `base` plus somewhere between `low` and `low` plus `width`
800/// further along, and what a check proves when it runs is about that one address rather than about
801/// the range this was made out of.
802#[derive(Debug, Clone, Copy)]
803struct Reach {
804    /// The value the address was computed from.
805    base: Value,
806    /// The nearest the access can start to it.
807    low: i128,
808    /// How much further than that it can start.
809    width: i128,
810    /// How many bytes it covers.
811    size: i128,
812}
813
814/// One kind of fact, and what has become of it.
815#[derive(Debug, Clone, Default)]
816struct Known {
817    /// The ranges a check has been passed on and nothing has cast doubt on since.
818    held: Vec<Fact>,
819    /// The ones a call threw away, kept only so that the cost of throwing them away is a number
820    /// somebody can read rather than a paragraph somebody has to believe.
821    lost: Vec<Fact>,
822}
823
824impl Known {
825    /// Whether something still standing answers this.
826    fn covers(&self, asked: &Fact) -> bool {
827        self.held.iter().any(|fact| covers(fact, asked))
828    }
829
830    /// Whether something still standing answers a range of addresses an access can land in.
831    fn reaches(&self, asked: &Reach) -> bool {
832        self.held.iter().any(|fact| reaches(fact, asked))
833    }
834
835    /// Whether one thing still standing answers both of these ranges.
836    ///
837    /// One rather than one each, for the reason [`Known::holds_both`] gives, and the reason does
838    /// not change when the ends are ranges instead of addresses.
839    fn reaches_both(&self, from: &Reach, to: &Reach) -> bool {
840        self.held.iter().any(|fact| reaches(fact, from) && reaches(fact, to))
841    }
842
843    /// Whether something would have answered it before a call came along.
844    fn covered_before(&self, asked: &Fact) -> bool {
845        self.lost.iter().any(|fact| covers(fact, asked))
846    }
847
848    /// Whether one thing still standing answers both of these.
849    ///
850    /// One rather than one each, which is the whole point of asking it this way. Two facts saying
851    /// two addresses are each inside some instance say nothing about whether it is the same
852    /// instance, and that is the only thing a derivation check wants to know.
853    fn holds_both(&self, from: &Fact, to: &Fact) -> bool {
854        self.held.iter().any(|fact| covers(fact, from) && covers(fact, to))
855    }
856
857    /// Whether one would have answered both before a call came along.
858    fn held_both_before(&self, from: &Fact, to: &Fact) -> bool {
859        self.lost.iter().any(|fact| covers(fact, from) && covers(fact, to))
860    }
861
862    /// Gives up everything, because something happened that this pass cannot see through.
863    fn forget(&mut self) {
864        self.lost.append(&mut self.held);
865    }
866}
867
868/// What holds where the walk has got to.
869///
870/// The two kinds are apart because they are killed together and answered separately: a range being
871/// inside one instance and that instance being alive are different claims, and reporting them as
872/// one number would hide which of the two a check is still being paid for.
873#[derive(Debug, Clone, Default)]
874struct Scope {
875    /// Ranges a `check_bounds` established are inside one storage instance.
876    bounds: Known,
877    /// Ranges a `check_live` established are in an instance that is alive.
878    alive: Known,
879}
880
881impl Scope {
882    /// Gives up every fact of either kind.
883    fn forget(&mut self) {
884        self.bounds.forget();
885        self.alive.forget();
886    }
887}
888
889/// Whether this instruction could do something to memory that this pass cannot account for.
890///
891/// A call is the whole of it, in every spelling, and inline assembly with it. A `tail_call` ends
892/// the block and there is nothing after it to protect, and it is here anyway so that the reason a
893/// fact survives is never that the walk did not think of something.
894///
895/// A call carrying [`Flags::NOFREE`] reaches nothing that ends a lifetime, so there is nothing for
896/// it to have done to the bytes an earlier check was passed on. `crate::nofree` is what put the
897/// flag there and what argues for it.
898///
899/// A `meta_end` and a `meta_transfer` end a lifetime by saying so, which is the plainest way for a
900/// fact to stop being true, and neither is emitted today.
901fn opaque(func: &Func, inst: Inst) -> bool {
902    match func[inst].opcode {
903        Opcode::Call | Opcode::CallIndirect | Opcode::TailCall => {
904            !func[inst].flags.contains(Flags::NOFREE)
905        }
906        Opcode::InlineAsm | Opcode::MetaEnd | Opcode::MetaTransfer => true,
907        _ => false,
908    }
909}
910
911/// What a `check_bounds` is about, when it is one this pass can read.
912pub(crate) fn about(func: &Func, check: Inst) -> Option<Fact> {
913    let (base, offset) = addressed(func, check)?;
914    let Extra::Mem(info) = func[check].extra else { return None };
915    Some(Fact { base, offset, size: i128::from(func[info].size) })
916}
917
918/// What a `check_live` is about, when it is one this pass can read.
919///
920/// One byte, because that is the whole of what the check says: the instance holding this address
921/// is alive, and nothing about the address next door. The widening to a range that makes the fact
922/// useful is [`widened`], and it needs a bounds fact to do it.
923pub(crate) fn alive(func: &Func, check: Inst) -> Option<Fact> {
924    let (base, offset) = addressed(func, check)?;
925    Some(Fact { base, offset, size: 1 })
926}
927
928/// The address a check is about, as a base and a constant.
929///
930/// The capability has to be the `cap_of` of the check's own pointer. That is the shape
931/// `rucc-safety` emits and it is what the removal argument in the module comment needs, so a check
932/// that does not have it is not a check this pass has anything to say about.
933fn addressed(func: &Func, check: Inst) -> Option<(Value, i128)> {
934    let args = &func[func[check].args];
935    let &capability = args.first()?;
936    let &pointer = args.get(1)?;
937    if operand_of(func, capability, Opcode::CapOf, 0) != Some(pointer) {
938        return None;
939    }
940    Some(normal(func, pointer))
941}
942
943/// The two ends of a `check_deriv`, each as the single byte at it.
944///
945/// A derivation check asks whether the pointer that came out of a `ptr_add` is still in the storage
946/// instance the pointer that went in belongs to, so both ends have to be readable and both have to
947/// come out of the same value, which is what makes the two offsets comparable at all. One byte each
948/// because that is what is being asked about: not a range, but whether an address is in an instance.
949///
950/// The capability has to be the `cap_of` of the pointer that went in, for the reason [`addressed`]
951/// gives. The instance the check is about is the one that pointer belongs to, and a check naming
952/// some other capability is about some other instance.
953///
954/// The width operand is not read. It matters to the runtime only for a pointer that walked off the
955/// near end, where the check passes on the byte a stride further along instead of on the address
956/// itself, and this pass never gets that far: it discharges nothing it has not put inside a range
957/// outright.
958pub(crate) fn derives(func: &Func, check: Inst) -> Option<(Fact, Fact)> {
959    let args = &func[func[check].args];
960    let &capability = args.first()?;
961    let &from = args.get(1)?;
962    let &to = args.get(2)?;
963    if operand_of(func, capability, Opcode::CapOf, 0) != Some(from) {
964        return None;
965    }
966    let (base, start) = normal(func, from);
967    let (walked, end) = normal(func, to);
968    if base != walked {
969        return None;
970    }
971    Some((Fact { base, offset: start, size: 1 }, Fact { base, offset: end, size: 1 }))
972}
973
974/// The object a local is, when the address a check is about was computed from one.
975///
976/// This is the fact nobody had to check for, and section 7.2 puts it first of the four sources
977/// because it is where most of the win is. An `alloca` of a fixed size is one storage instance of
978/// that many bytes, said by the instruction that makes it rather than by a check that passed, so
979/// the bytes from its address to that many further along are inside one instance for the same
980/// reason a passing `check_bounds` says its own range is.
981///
982/// Only the fixed size form. The one that takes an operand is a variable length array, and how
983/// many bytes it is is a value the program works out rather than a number in the payload, where
984/// the field reads zero.
985///
986/// The fact holds everywhere in the function and no call takes it away, which is the other half of
987/// what makes it worth having. A callee cannot free a frame slot: what it could free is whatever a
988/// pointer stored in the slot points at, and that is a different instance and a different check.
989/// So this is asked separately from the facts the walk carries rather than pushed into them, since
990/// everything in there is thrown away at the first call this pass cannot see through.
991fn declared(func: &Func, base: Value) -> Option<Fact> {
992    let Def::Result { inst, .. } = func[base].def else { return None };
993    if func[inst].opcode != Opcode::Alloca || !func[func[inst].args].is_empty() {
994        return None;
995    }
996    let Extra::Mem(info) = func[inst].extra else { return None };
997    Some(Fact::whole(base, i128::from(func[info].size)))
998}
999
1000/// The alignment an allocator promises, in bytes.
1001///
1002/// C says storage an allocator hands back is aligned for any object with a fundamental alignment,
1003/// which is sixteen bytes on the targets this compiles for. Eight is claimed rather than sixteen
1004/// because the claim has to hold wherever this pass runs and the pass is given a function rather
1005/// than a target. What it costs is an access that assumes more than eight bytes, which is a
1006/// `long double` or a vector, keeping a check it could have lost.
1007const ALLOCATED: u64 = 8;
1008
1009/// How far into an expression [`divides`] reads before it gives up.
1010///
1011/// A subscript is a multiply and a constant and the answer is two steps in. The bound is here
1012/// because the walk is over an expression the program wrote and nothing about an expression stops
1013/// it from being as deep as the source file is long.
1014const DEEP: u32 = 4;
1015
1016/// Whether the address a check is about starts where the access assumes it does.
1017///
1018/// The alignment conjunct of judgement J1 rides on `check_bounds`, which document 06 section 6.3
1019/// settled, so a check that goes takes the test of it with it and something here has to have
1020/// answered it first. An access that assumes nothing about where it starts has nothing to answer,
1021/// and that is what an alignment of one is and what a member of a packed record gets.
1022///
1023/// What answers it is the object the address was computed from and the steps taken from it, which
1024/// is the same ground the bounds question walks. An `alloca` says what it is aligned to and an
1025/// allocator promises [`ALLOCATED`], and each step from there leaves whatever the step itself
1026/// divides by. So `p[i]` on an `int *` out of `malloc` is answered by the four in the subscript's
1027/// own multiply, and `(int *)(p + 1)` is not answered at all, which is row S7 and the whole reason
1028/// this is here.
1029///
1030/// A global is not read here at all. It arrives as [`Flags::ALIGNED`] from `crate::extents`, which
1031/// is given the module this is not, and the flag is the whole of what this asks about one.
1032///
1033/// A pointer this cannot read the origin of is zero, which answers nothing and keeps the check.
1034/// That is a block parameter, a pointer loaded out of memory, and one handed in.
1035/// [`UNKNOWN_ALIGNMENT`] counts them.
1036///
1037/// The two answers given before [`settles`] is asked are not arithmetic and so are not a rule's.
1038/// An access of one byte assumes nothing about where it starts, so there is nothing to prove about
1039/// it, and the flag is a fact `crate::extents` established over the whole module and wrote down.
1040fn aligned(func: &Func, check: Inst) -> bool {
1041    let Extra::Mem(info) = func[check].extra else { return false };
1042    let claim = u64::from(func[info].align);
1043    if claim <= 1 || func[check].flags.contains(Flags::ALIGNED) {
1044        return true;
1045    }
1046    let Some(&pointer) = func[func[check].args].get(1) else { return false };
1047    settles(settled(func, pointer), claim)
1048}
1049
1050/// Whether an address known to be a multiple of one number meets an access's claim.
1051///
1052/// The companion to [`covers`] for the alignment conjunct, and it decides nothing either. The walk
1053/// in [`settled`] worked out a number the address divides by, and whether that answers the access
1054/// is the rule file's to say. The address is opaque in the question, because nothing here knows
1055/// what it is and the answer is about every address the walk's number holds of.
1056///
1057/// It is worth saying what the rule catches that the comparison it replaced did not. `known` being
1058/// the larger number is not `claim` dividing it, and the two agree only because both are powers of
1059/// two. Every number that gets here is one, for the reason the head in `safety.model` writes out,
1060/// and now that reason is written somewhere a solver reads rather than only somewhere a person
1061/// does.
1062fn settles(known: u64, claim: u64) -> bool {
1063    let mut question = Question::default();
1064    let at = question.opaque();
1065    let at = question.app("value.i64", &[at]);
1066    let known = question.number(i128::from(known));
1067    let known = question.app("iconst.i64", &[known]);
1068    let claim = question.number(i128::from(claim));
1069    let claim = question.app("iconst.i64", &[claim]);
1070    let term = question.app("aligned.i64", &[at, known, claim]);
1071    match safety::TABLE.find(&question, term) {
1072        Some(found) => yes(&safety::TABLE, found.rule),
1073        None => false,
1074    }
1075}
1076
1077/// What a pointer is known to be aligned to, in bytes, or zero when nothing here says.
1078///
1079/// Every number involved is a power of two, so the greatest common divisor of two of them is the
1080/// smaller, which is why the steps are gathered with a `min` and why they start at the largest
1081/// number there is instead of at zero. Zero is the answer and not a step, since an alignment of
1082/// zero is not something an access can assume and a claim is never met by one.
1083fn settled(func: &Func, pointer: Value) -> u64 {
1084    let mut steps = u64::MAX;
1085    let mut value = pointer;
1086    loop {
1087        let Def::Result { inst, .. } = func[value].def else { return 0 };
1088        match func[inst].opcode {
1089            Opcode::Alloca => {
1090                let Extra::Mem(info) = func[inst].extra else { return 0 };
1091                return steps.min(u64::from(func[info].align));
1092            }
1093            Opcode::Call if func[inst].flags.contains(Flags::HEAP) => {
1094                return steps.min(ALLOCATED);
1095            }
1096            Opcode::PtrAdd => {
1097                let args = &func[func[inst].args];
1098                let (Some(&from), Some(&by)) = (args.first(), args.get(1)) else { return 0 };
1099                steps = steps.min(divides(func, by, DEEP));
1100                value = from;
1101            }
1102            _ => return 0,
1103        }
1104    }
1105}
1106
1107/// The largest power of two that divides a step, or one when nothing here says.
1108///
1109/// One is the answer for anything unreadable and it is the right one: every number divides by one,
1110/// so a step nobody can read leaves a pointer aligned to a byte and no more. Zero divides by
1111/// everything, which is a walk that took no step and has to leave what it started with alone.
1112fn divides(func: &Func, step: Value, depth: u32) -> u64 {
1113    if let Some(number) = constant(func, step) {
1114        let Ok(size) = u64::try_from(number.unsigned_abs()) else { return 1 };
1115        return if size == 0 { u64::MAX } else { 1 << size.trailing_zeros() };
1116    }
1117    let Def::Result { inst, .. } = func[step].def else { return 1 };
1118    let args = &func[func[inst].args];
1119    let (Some(&left), Some(&right)) = (args.first(), args.get(1)) else { return 1 };
1120    if depth == 0 {
1121        return 1;
1122    }
1123    match func[inst].opcode {
1124        // A subscript, which is an index nobody knows anything about times the element size.
1125        Opcode::Mul => {
1126            divides(func, left, depth - 1).saturating_mul(divides(func, right, depth - 1))
1127        }
1128        Opcode::Shl => match constant(func, right) {
1129            Some(by) if (0..64).contains(&by) => {
1130                divides(func, left, depth - 1).checked_shl(by as u32).unwrap_or(u64::MAX)
1131            }
1132            _ => 1,
1133        },
1134        // Two numbers added divide by whatever they both divide by, which is a field offset added
1135        // to a subscript and is how a member of an array of records comes out.
1136        Opcode::Add | Opcode::Sub => {
1137            divides(func, left, depth - 1).min(divides(func, right, depth - 1))
1138        }
1139        _ => 1,
1140    }
1141}
1142
1143/// The object an allocator made, when the address a check is about was computed from one and this
1144/// function has already found out it is not null.
1145///
1146/// The same shape as [`declared`] one storey up, with a marked call saying the size instead of an
1147/// `alloca` and one more thing to establish. `crate::heap` has the argument for both halves: what a
1148/// call to `malloc` says is an extent and never a lifetime, and it only says it where the program
1149/// has looked, because a null pointer is inside no object and a check on one is a check that is
1150/// meant to fail.
1151///
1152/// Nothing is claimed when the graph was not built, which is a function this found no allocation in
1153/// and so a function where the answer would have been no anyway.
1154fn allocation(
1155    func: &Func,
1156    cfg: Option<&Cfg>,
1157    checked: &mut HashMap<Value, HashSet<Block>>,
1158    block: Block,
1159    base: Value,
1160) -> Option<Fact> {
1161    let whole = heap::made(func, base)?;
1162    let cfg = cfg?;
1163    checked
1164        .entry(whole.base)
1165        .or_insert_with(|| heap::tested(func, cfg, whole.base))
1166        .contains(&block)
1167        .then_some(whole)
1168}
1169
1170/// Whether all of those bytes are inside one object an allocator made.
1171///
1172/// Every part has to be inside, and inside the same object, which is what asking [`covers`] with one
1173/// fact and several does.
1174fn allocated(
1175    func: &Func,
1176    cfg: Option<&Cfg>,
1177    checked: &mut HashMap<Value, HashSet<Block>>,
1178    block: Block,
1179    parts: &[&Fact],
1180) -> bool {
1181    let Some(first) = parts.first() else { return false };
1182    let Some(whole) = allocation(func, cfg, checked, block, first.base) else { return false };
1183    parts.iter().all(|part| covers(&whole, part))
1184}
1185
1186/// Whether every address a walk can reach is inside one object an allocator made.
1187///
1188/// [`allocated`] for the question [`reach`] and [`spread`] ask. The object comes from the same place
1189/// and is believed for the same reason, and what is asked of it is [`reaches`] rather than
1190/// [`covers`], so a walk by a step the ranges put numbers on can be answered by a call that says how
1191/// many bytes it made.
1192///
1193/// The wide path used to ask a local and the facts the walk carries and nothing else, so a program
1194/// that walked into its own `malloc` by an index kept its checks however plainly the size was
1195/// written. That is the first half of tamnd/rucc#880.
1196fn allocated_around(
1197    func: &Func,
1198    cfg: Option<&Cfg>,
1199    checked: &mut HashMap<Value, HashSet<Block>>,
1200    block: Block,
1201    spans: &[&Reach],
1202) -> bool {
1203    let Some(first) = spans.first() else { return false };
1204    let Some(whole) = allocation(func, cfg, checked, block, first.base) else { return false };
1205    spans.iter().all(|span| reaches(&whole, span))
1206}
1207
1208/// A lifetime fact grown from one address to the checked range it sits in.
1209///
1210/// The argument is in the module comment: a `check_bounds` that passed put its whole range inside
1211/// one instance, so the instance this lifetime check found alive is the instance that range is in.
1212/// With no range around the address the fact stays as it came, which is correct and answers only a
1213/// repeat of the very same check.
1214///
1215/// A local is asked about first, because the object it is is the widest range there can be for an
1216/// address computed from it and a wider fact answers more later checks. What that gives is a
1217/// lifetime check anywhere in a local discharging every later one in the same local, up to the
1218/// first call, which is the shape a function that reads several fields of a local struct has.
1219fn widened(func: &Func, bounds: &Known, asked: Fact) -> Fact {
1220    if let Some(local) = declared(func, asked.base).filter(|local| covers(local, &asked)) {
1221        return local;
1222    }
1223    bounds.held.iter().find(|fact| covers(fact, &asked)).copied().unwrap_or(asked)
1224}
1225
1226/// The value an address was computed from, and how far past it the address is.
1227///
1228/// A `ptr_add` over a constant is walked through, and anything else is where the answer stops. The
1229/// arithmetic here is exact because it is done in `i128` over offsets that came out of the IR as
1230/// sixty four bit constants, and whether it is small enough to mean anything at sixty four bits is
1231/// the rule's question rather than this function's.
1232pub(crate) fn normal(func: &Func, value: Value) -> (Value, i128) {
1233    let mut base = value;
1234    let mut offset: i128 = 0;
1235    while let Some((from, step)) = walked(func, base) {
1236        let Some(sum) = offset.checked_add(step) else { break };
1237        base = from;
1238        offset = sum;
1239    }
1240    (base, offset)
1241}
1242
1243/// Every address a walk can reach, when a step it takes is a value rather than a constant.
1244///
1245/// This is the third of the four sources section 7.2 lists, and it is the one that needs an
1246/// analysis. [`normal`] stops at the first `ptr_add` whose step it cannot read, and what it hands
1247/// back is a fact about a base nobody knows the size of. Document 10's ranges do know something
1248/// about the step: an index the program has already tested, or one a loop counts, is bounded even
1249/// though it is not constant. So the walk carries on past the step, adding the low end of its
1250/// range to the offset and the width of the range to the size.
1251///
1252/// What comes out is a range of addresses the access can land in, and it is a [`Reach`] rather than
1253/// a [`Fact`] on purpose. Whether an object holding all of that range holds the one address the
1254/// access actually uses is [`reaches`], which asks a rule with the distance left opaque, so one
1255/// answer covers every value the step could take.
1256///
1257/// It is only ever asked with. What this returns must never be recorded as established, and the
1258/// one place it could be is the push in the `check_bounds` arm, which happens only where this
1259/// returned nothing or answered nothing. The reason is that the widened range is not what a check
1260/// proves. A check that runs and passes proves the address the program used was inside the object,
1261/// and says nothing at all about the rest of the range this function made up around it.
1262fn reach(func: &Func, ranges: Option<&mut Ranges<'_>>, asked: &Fact, at: Inst) -> Option<Reach> {
1263    let wide = spanned(func, ranges?, asked.base, asked.offset, asked.size, at)?;
1264    // Nothing was walked past, so this is the fact that came in and asking it again is work
1265    // somebody already did.
1266    (wide.base != asked.base).then_some(wide)
1267}
1268
1269/// Which of the reasons a derivation check this pass could not read is kept for.
1270///
1271/// The census and nothing else. Whether the check goes has already been decided by the time this
1272/// runs, and what it answers is the question somebody reading `-fopt-info-missed` is actually
1273/// asking, which is what would have to be built for this pile to move.
1274///
1275/// It walks the same ground [`spread`] walks rather than being folded into it, because the two want
1276/// different things. [`spread`] wants an answer or nothing, and stopping at the first step it cannot
1277/// read is the fastest way to nothing. This wants to get as far as it can and name where it stopped,
1278/// so it runs only on checks that are staying and it is allowed to be the slower of the two.
1279///
1280/// The five that begin `nothing here says how big` are one refusal counted five ways. What is missing
1281/// in every one of them is how many bytes belong to the object, and where the pointer came from is
1282/// what says which piece of work would supply it: `__counted_by` and the type plane for a pointer out
1283/// of memory, section 7.5's summaries for one that was handed over, `crate::extents` reaching further
1284/// for a global, and the allocation summaries for one a call returned.
1285fn unreadable(func: &Func, ranges: Option<&mut Ranges<'_>>, check: Inst) -> &'static str {
1286    let args = &func[func[check].args];
1287    let (Some(&capability), Some(&from), Some(&to)) = (args.first(), args.get(1), args.get(2))
1288    else {
1289        return NO_EXTENT_OTHER;
1290    };
1291    if operand_of(func, capability, Opcode::CapOf, 0) != Some(from) {
1292        return NOT_ITS_CAPABILITY_DERIV;
1293    }
1294    // No ranges is a function with no walk in it that steps by a value, so every step here was a
1295    // constant, so the reader that gives up on two bases gave up on two bases.
1296    let Some(ranges) = ranges else { return TWO_BASES_DERIV };
1297    let (base, offset) = normal(func, from);
1298    let Some(near) = spanned(func, ranges, base, offset, 1, check) else {
1299        return NO_EXTENT_OTHER;
1300    };
1301    let (base, offset) = normal(func, to);
1302    let Some(far) = spanned(func, ranges, base, offset, 1, check) else {
1303        return NO_EXTENT_OTHER;
1304    };
1305    if near.base != far.base {
1306        return TWO_BASES_DERIV;
1307    }
1308    if declared(func, near.base).is_some() {
1309        return OVER_THE_LOCAL_DERIV;
1310    }
1311    match func[near.base].def {
1312        Def::Param { .. } => NO_EXTENT_HANDED,
1313        Def::Result { inst, .. } => match func[inst].opcode {
1314            Opcode::Load => NO_EXTENT_LOADED,
1315            Opcode::GlobalAddr => NO_EXTENT_GLOBAL,
1316            Opcode::Call | Opcode::CallIndirect => NO_EXTENT_RETURNED,
1317            _ => NO_EXTENT_OTHER,
1318        },
1319    }
1320}
1321
1322/// The two ends of a derivation check, each as the range of addresses it can be at.
1323///
1324/// A derivation check asks whether the pointer that came out of a walk is still in the storage
1325/// instance the pointer that went in belongs to. [`derives`] answers that only when both ends
1326/// normalize to one base over constants, and past a step the constant reader gives up on they do
1327/// not, which is why this reads the check's operands again rather than taking what that worked
1328/// out. Each end becomes a range, and the two still have to be off one base or there is nothing
1329/// comparable to ask about.
1330///
1331/// One byte each, for the reason [`derives`] gives. Nothing here claims anything about how many
1332/// bytes are readable at either address.
1333///
1334/// The capability has to be the `cap_of` of the pointer that went in, for the reason [`addressed`]
1335/// gives.
1336fn spread(
1337    func: &Func,
1338    ranges: Option<&mut Ranges<'_>>,
1339    check: Inst,
1340    at: Inst,
1341) -> Option<(Reach, Reach)> {
1342    let ranges = ranges?;
1343    let args = &func[func[check].args];
1344    let &capability = args.first()?;
1345    let &from = args.get(1)?;
1346    let &to = args.get(2)?;
1347    if operand_of(func, capability, Opcode::CapOf, 0) != Some(from) {
1348        return None;
1349    }
1350    let (base, offset) = normal(func, from);
1351    let near = spanned(func, ranges, base, offset, 1, at)?;
1352    let (base, offset) = normal(func, to);
1353    let far = spanned(func, ranges, base, offset, 1, at)?;
1354    (near.base == far.base).then_some((near, far))
1355}
1356
1357/// Every address a walk off `base` can reach, and how many bytes it takes when it gets there.
1358///
1359/// The loop is [`normal`]'s with one more thing to try. A `ptr_add` over a constant is walked
1360/// through the same way, and a `ptr_add` over a value is walked through when document 10's ranges
1361/// put numbers on that value: the low end of the range goes on the distance and the width of it on
1362/// the slack. Anything else is where the walk stops.
1363///
1364/// Nothing is returned when a step is a value the ranges say nothing useful about, rather than the
1365/// walk stopping there and handing back what it had. What it had would be a range off a `ptr_add`
1366/// nobody knows the size of, which answers nothing, so stopping would be a longer way of saying no.
1367fn spanned(
1368    func: &Func,
1369    ranges: &mut Ranges<'_>,
1370    base: Value,
1371    offset: i128,
1372    size: i128,
1373    at: Inst,
1374) -> Option<Reach> {
1375    let mut base = base;
1376    let mut low = offset;
1377    let mut width: i128 = 0;
1378    loop {
1379        // A constant step again, because past a step that needed a range there can be more of
1380        // them, and the frontend leaves a field offset as a constant under an array index.
1381        if let Some((from, step)) = walked(func, base) {
1382            low = low.checked_add(step)?;
1383            base = from;
1384            continue;
1385        }
1386        let Some(from) = operand_of(func, base, Opcode::PtrAdd, 0) else { break };
1387        let by = operand_of(func, base, Opcode::PtrAdd, 1)?;
1388        let (least, most) = ranges.at_inst(by, at).signed_bounds()?;
1389        low = low.checked_add(least)?;
1390        width = width.checked_add(most.checked_sub(least)?)?;
1391        base = from;
1392    }
1393    Some(Reach { base, low, width, size })
1394}
1395
1396/// Whether any walk in this function steps by a value rather than a constant.
1397///
1398/// The question the ranges are built for. A function without one of these would pay for a copy of
1399/// the control flow graph and never ask anything of it.
1400/// Whether anything in this function says a lifetime is over.
1401///
1402/// Nothing emits `meta_end` today, so this is false everywhere and the frame slot rule in
1403/// [`Discharge::run`] is on for every function. It is written anyway, and written over the whole
1404/// function rather than along the walk, because the day something does emit one the cheap reading
1405/// is the wrong one: a lifetime that ended in one arm of a branch has ended for a check after the
1406/// join, and a walk down the dominator tree would not have seen it. Turning the rule off for the
1407/// function is the reading that stays right when that day comes, and the finer one is a job for
1408/// whoever makes `meta_end` appear.
1409fn ends_a_lifetime(func: &Func) -> bool {
1410    func.blocks().any(|block| func.insts(block).any(|inst| func[inst].opcode == Opcode::MetaEnd))
1411}
1412
1413fn walks_by_a_value(func: &Func) -> bool {
1414    func.blocks().any(|block| {
1415        func.insts(block).any(|inst| {
1416            func[inst].opcode == Opcode::PtrAdd
1417                && func[func[inst].args].get(1).is_some_and(|&by| constant(func, by).is_none())
1418        })
1419    })
1420}
1421
1422/// The pointer one `ptr_add` over a constant was computed from, and by how much.
1423fn walked(func: &Func, value: Value) -> Option<(Value, i128)> {
1424    let from = operand_of(func, value, Opcode::PtrAdd, 0)?;
1425    let by = operand_of(func, value, Opcode::PtrAdd, 1)?;
1426    Some((from, constant(func, by)?))
1427}
1428
1429/// Operand `index` of the instruction that produced `value`, when that instruction is `opcode`.
1430pub(crate) fn operand_of(func: &Func, value: Value, opcode: Opcode, index: usize) -> Option<Value> {
1431    let Def::Result { inst, .. } = func[value].def else { return None };
1432    if func[inst].opcode != opcode {
1433        return None;
1434    }
1435    func[func[inst].args].get(index).copied()
1436}
1437
1438/// The value of an integer constant, read with its own sign.
1439pub(crate) fn constant(func: &Func, value: Value) -> Option<i128> {
1440    let Def::Result { inst, .. } = func[value].def else { return None };
1441    if func[inst].opcode != Opcode::IConst {
1442        return None;
1443    }
1444    let Extra::Imm(imm) = func[inst].extra else { return None };
1445    let ty = func[value].ty;
1446    ty.is_int().then(|| func[imm].signed(ty))
1447}
1448
1449/// Whether an established fact answers the check being asked about.
1450///
1451/// This function decides nothing. It puts the two together into the term the rule file is written
1452/// about and asks the table, which is the whole of section 7.7's split: the paragraph above worked
1453/// out that the two addresses are one value a constant apart, and whether that is enough is
1454/// somebody's proof rather than this file's opinion.
1455pub(crate) fn covers(fact: &Fact, asked: &Fact) -> bool {
1456    if fact.base != asked.base {
1457        return false;
1458    }
1459    let Some(delta) = asked.offset.checked_sub(fact.offset) else { return false };
1460    let mut question = Question::default();
1461    let at = question.opaque();
1462    let at = question.app("value.i64", &[at]);
1463    let span = question.number(fact.size);
1464    let span = question.app("iconst.i64", &[span]);
1465    let far = question.number(delta);
1466    let far = question.app("iconst.i64", &[far]);
1467    let reach = question.number(asked.size);
1468    let reach = question.app("iconst.i64", &[reach]);
1469    let term = question.app("covered.i64", &[at, span, far, reach]);
1470    match safety::TABLE.find(&question, term) {
1471        Some(found) => yes(&safety::TABLE, found.rule),
1472        None => false,
1473    }
1474}
1475
1476/// Whether an object holds every address a walk can land on.
1477///
1478/// The companion to [`covers`] for the question [`reach`] asks, and it decides nothing either. It
1479/// puts the object and the range of addresses into the term the rule file is written about and
1480/// asks the table. The distance the program actually walks is opaque in the question, which is
1481/// what makes one answer cover every value it could take.
1482fn reaches(fact: &Fact, asked: &Reach) -> bool {
1483    if fact.base != asked.base {
1484        return false;
1485    }
1486    let Some(delta) = asked.low.checked_sub(fact.offset) else { return false };
1487    let mut question = Question::default();
1488    let at = question.opaque();
1489    let at = question.app("value.i64", &[at]);
1490    let span = question.number(fact.size);
1491    let span = question.app("iconst.i64", &[span]);
1492    let delta = question.number(delta);
1493    let delta = question.app("iconst.i64", &[delta]);
1494    let width = question.number(asked.width);
1495    let width = question.app("iconst.i64", &[width]);
1496    let size = question.number(asked.size);
1497    let size = question.app("iconst.i64", &[size]);
1498    let step = question.opaque();
1499    let step = question.app("value.i64", &[step]);
1500    let term = question.app("reached.i64", &[at, span, delta, width, size, step]);
1501    match safety::TABLE.find(&question, term) {
1502        Some(found) => yes(&safety::TABLE, found.rule),
1503        None => false,
1504    }
1505}
1506
1507/// Whether the rule that fired answers yes.
1508///
1509/// A discharge rule replaces the question with a constant, and one is yes. Every rule in the file
1510/// answers that today, and reading it off the rule rather than assuming it is what keeps this
1511/// honest on the day one of them answers something else.
1512pub(crate) fn yes(table: &Table, rule: usize) -> bool {
1513    matches!(table.rules[rule].replacement, [Piece::App { .. }, Piece::Int(1)])
1514}
1515
1516/// A term built to be asked about, and nothing else.
1517///
1518/// The rules are matched against this rather than against the function, because what is being asked
1519/// about is not in the function: it is what the walk worked out about two of its instructions. So
1520/// the subject is a small arena of exactly the term being asked, built fresh for each question and
1521/// thrown away with the answer.
1522#[derive(Debug, Default)]
1523pub(crate) struct Question {
1524    held: Vec<Held>,
1525}
1526
1527/// One node of that term.
1528#[derive(Debug)]
1529enum Held {
1530    /// A number the pattern can read and a guard can be about.
1531    Int(i128),
1532    /// A head and its arguments.
1533    App(&'static str, Vec<usize>),
1534    /// Something with no structure, which is how an address the rule only names is written.
1535    Opaque,
1536}
1537
1538impl Question {
1539    /// Adds a constant and gives back where it went.
1540    ///
1541    /// Named for what it adds rather than for what it holds, because the arena also answers
1542    /// [`Subject::int`] and one name for the two would read as though building a term and asking
1543    /// about one were the same act.
1544    pub(crate) fn number(&mut self, value: i128) -> usize {
1545        self.held.push(Held::Int(value));
1546        self.held.len() - 1
1547    }
1548
1549    /// Adds an application of `head` to what is already in the arena.
1550    pub(crate) fn app(&mut self, head: &'static str, args: &[usize]) -> usize {
1551        self.held.push(Held::App(head, args.to_vec()));
1552        self.held.len() - 1
1553    }
1554
1555    /// Adds something the rule can bind and cannot look inside.
1556    pub(crate) fn opaque(&mut self) -> usize {
1557        self.held.push(Held::Opaque);
1558        self.held.len() - 1
1559    }
1560}
1561
1562impl Subject for Question {
1563    type Node = usize;
1564
1565    fn head(&self, node: usize) -> Option<(&str, usize)> {
1566        match &self.held[node] {
1567            Held::App(head, args) => Some((head, args.len())),
1568            Held::Int(_) | Held::Opaque => None,
1569        }
1570    }
1571
1572    fn arg(&self, node: usize, index: usize) -> usize {
1573        match &self.held[node] {
1574            Held::App(_, args) => args[index],
1575            // The walk only asks for an argument `head` said was there, so this is unreachable
1576            // rather than a case with an answer.
1577            Held::Int(_) | Held::Opaque => unreachable!("only an application has arguments"),
1578        }
1579    }
1580
1581    fn int(&self, node: usize) -> Option<i128> {
1582        match self.held[node] {
1583            Held::Int(value) => Some(value),
1584            Held::App(..) | Held::Opaque => None,
1585        }
1586    }
1587
1588    fn same(&self, a: usize, b: usize) -> bool {
1589        // Every node of a question is written once, so two places holding one thing are one place.
1590        a == b
1591    }
1592}
1593
1594#[cfg(test)]
1595mod tests {
1596    use rucc_base::Interner;
1597    use rucc_ir::{
1598        AsmInfo, Block, BlockCallList, Builder, Extra, Flags, Func, Inst, InstData, IntPred,
1599        MemInfo, MemOrder, Opcode, Restrict, Signature, Type, Value,
1600    };
1601
1602    use super::{DISCHARGE, Fact};
1603    use crate::stats::Kind;
1604    use crate::{Fuel, Pass, pass};
1605
1606    /// A function taking a pointer, with one block, ready to have accesses put in it.
1607    fn blank() -> (Interner, Func, Block, Value) {
1608        let mut names = Interner::new();
1609        let name = names.intern("f");
1610        let mut func = Func::new(name, Signature::new().with_params(&[Type::PTR]));
1611        let block = func.create_block();
1612        let pointer = func.append_param(block, Type::PTR);
1613        (names, func, block, pointer)
1614    }
1615
1616    /// Puts `cap_of` and a `check_bounds` over `size` bytes at `pointer` into a block.
1617    ///
1618    /// The same shape `rucc-safety` emits, written out here rather than reached for, because
1619    /// `rucc-opt` is rank 9 alongside `rucc-safety` and cannot depend on it.
1620    fn check(build: &mut Builder<'_>, pointer: Value, size: u64) {
1621        let args = build.func().push_values(&[pointer]);
1622        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
1623        let info = MemInfo {
1624            size,
1625            align: 1,
1626            order: MemOrder::NotAtomic,
1627            tbaa: None,
1628            owns: 0,
1629            restrict: Restrict::NONE,
1630        };
1631        let args = build.func().push_values(&[capability, pointer]);
1632        let extra = Extra::Mem(build.func().add_mem(info));
1633        build.inst(InstData { args, extra, ..InstData::new(Opcode::CheckBounds) }, &[]);
1634    }
1635
1636    /// Puts `cap_of` and a `check_live` at `pointer` into a block.
1637    ///
1638    /// `rucc-safety` emits this straight after the bounds check for the same access and shares the
1639    /// one `cap_of` between the two. Sharing it is not what the pass reads, so the tests build a
1640    /// second one, which is the harder shape for it to accept.
1641    fn live(build: &mut Builder<'_>, pointer: Value) {
1642        let args = build.func().push_values(&[pointer]);
1643        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
1644        let args = build.func().push_values(&[capability, pointer]);
1645        build.inst(InstData { args, ..InstData::new(Opcode::CheckLive) }, &[]);
1646    }
1647
1648    /// Both checks in front of one access, in the order `rucc-safety` writes them.
1649    fn access(build: &mut Builder<'_>, pointer: Value, size: u64) {
1650        check(build, pointer, size);
1651        live(build, pointer);
1652    }
1653
1654    /// A pointer `bytes` past another one.
1655    fn past(build: &mut Builder<'_>, pointer: Value, bytes: i128) -> Value {
1656        let offset = build.iconst(Type::int(64), bytes);
1657        let args = build.func().push_values(&[pointer, offset]);
1658        build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
1659    }
1660
1661    /// Puts the flag `crate::extents` writes onto every check in a function.
1662    ///
1663    /// The pass reads what the IR says, so what a test has to build is an IR that says it. Working
1664    /// out which checks deserve it is `crate::extents`, is about a module rather than a function,
1665    /// and has its own tests.
1666    fn marked(func: &mut Func) {
1667        flagged(func, Flags::STATIC);
1668    }
1669
1670    /// Puts that flag on every check in the function, the way an annotator before the pipeline
1671    /// would have.
1672    fn flagged(func: &mut Func, flag: Flags) {
1673        let insts: Vec<Inst> =
1674            func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
1675        for inst in insts {
1676            let check = matches!(
1677                func[inst].opcode,
1678                Opcode::CheckBounds | Opcode::CheckLive | Opcode::CheckDeriv
1679            );
1680            if check {
1681                func[inst].flags |= flag;
1682            }
1683        }
1684    }
1685
1686    /// How many checks are left in a function.
1687    fn checks(func: &Func) -> usize {
1688        func.blocks()
1689            .flat_map(|block| func.insts(block).collect::<Vec<_>>())
1690            .filter(|&inst| func[inst].opcode == Opcode::CheckBounds)
1691            .count()
1692    }
1693
1694    /// How many lifetime checks are left in a function.
1695    fn lives(func: &Func) -> usize {
1696        func.blocks()
1697            .flat_map(|block| func.insts(block).collect::<Vec<_>>())
1698            .filter(|&inst| func[inst].opcode == Opcode::CheckLive)
1699            .count()
1700    }
1701
1702    fn run(func: &mut Func) -> crate::Stats {
1703        DISCHARGE.run(func, &mut crate::machine::fixtures::analyses(), &mut Fuel::unlimited())
1704    }
1705
1706    /// The same, with one of the measurement's variants rather than the pass the pipeline runs.
1707    fn run_with(pass: &super::Discharge, func: &mut Func) -> crate::Stats {
1708        pass.run(func, &mut crate::machine::fixtures::analyses(), &mut Fuel::unlimited())
1709    }
1710
1711    #[test]
1712    fn a_run_that_may_only_ask_an_object_leaves_what_dominance_would_have_taken() {
1713        // Two checks of the same bytes on a pointer that came from outside. Nothing here says how
1714        // big the object is, so the only thing that could answer the second one is the first one
1715        // having run, and a run that may not ask that has to keep both.
1716        let (_, mut func, block, pointer) = blank();
1717        let mut build = Builder::new(&mut func, block);
1718        check(&mut build, pointer, 4);
1719        check(&mut build, pointer, 4);
1720        build.ret(&[]);
1721        let stats = run_with(&super::OBJECTS, &mut func);
1722        assert_eq!(checks(&func), 2);
1723        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 0);
1724    }
1725
1726    #[test]
1727    fn a_run_that_may_only_ask_dominance_takes_the_second_check_of_the_same_bytes() {
1728        let (_, mut func, block, pointer) = blank();
1729        let mut build = Builder::new(&mut func, block);
1730        check(&mut build, pointer, 4);
1731        check(&mut build, pointer, 4);
1732        build.ret(&[]);
1733        let stats = run_with(&super::DOMINANCE, &mut func);
1734        assert_eq!(checks(&func), 1);
1735        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
1736    }
1737
1738    #[test]
1739    fn a_run_that_may_only_ask_dominance_leaves_a_check_inside_a_local() {
1740        // The other way round. One check, nothing in front of it, and the bytes are inside an
1741        // `alloca` whose size is written on it. Only the object can answer that one.
1742        let (_, mut func, block, _) = blank();
1743        let mut build = Builder::new(&mut func, block);
1744        let slot = local(&mut build, 16);
1745        check(&mut build, slot, 4);
1746        build.ret(&[]);
1747        let stats = run_with(&super::DOMINANCE, &mut func);
1748        assert_eq!(checks(&func), 1);
1749        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 0);
1750        assert_eq!(
1751            run_with(&super::OBJECTS, &mut func).count(Kind::Optimized, super::REMOVED_LOCAL),
1752            1
1753        );
1754    }
1755
1756    #[test]
1757    fn the_measurement_variants_answer_to_names_of_their_own() {
1758        // A run that cannot be reached by a flag is a run nobody can measure with.
1759        let names: Vec<&str> = [
1760            &DISCHARGE,
1761            &super::OBJECTS,
1762            &super::DOMINANCE,
1763            &super::SUMMARIES,
1764            &super::NARROW,
1765            &super::EVERY,
1766        ]
1767        .iter()
1768        .map(|pass| pass.name())
1769        .collect();
1770        assert_eq!(
1771            names,
1772            [
1773                "discharge",
1774                "discharge-objects",
1775                "discharge-dominance",
1776                "discharge-summaries",
1777                "discharge-narrow",
1778                "discharge-every"
1779            ]
1780        );
1781        for name in names {
1782            assert!(pass::find(name).is_some(), "`{name}` is not in the pass list");
1783        }
1784    }
1785
1786    #[test]
1787    fn a_second_check_of_the_same_bytes_goes() {
1788        let (_, mut func, block, pointer) = blank();
1789        let mut build = Builder::new(&mut func, block);
1790        check(&mut build, pointer, 4);
1791        check(&mut build, pointer, 4);
1792        build.ret(&[]);
1793        let stats = run(&mut func);
1794        assert_eq!(checks(&func), 1);
1795        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
1796    }
1797
1798    /// The same check over an access that assumes something about where it starts.
1799    ///
1800    /// [`check`] assumes nothing, which is the right default for the tests above it: what they are
1801    /// about is which bytes a check covers, and an access that assumes nothing has no alignment to
1802    /// answer and so reaches every rule. These are the ones about the alignment itself.
1803    fn assuming(build: &mut Builder<'_>, pointer: Value, size: u64, align: u32) {
1804        let args = build.func().push_values(&[pointer]);
1805        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
1806        let info = MemInfo {
1807            size,
1808            align,
1809            order: MemOrder::NotAtomic,
1810            tbaa: None,
1811            owns: 0,
1812            restrict: Restrict::NONE,
1813        };
1814        let args = build.func().push_values(&[capability, pointer]);
1815        let extra = Extra::Mem(build.func().add_mem(info));
1816        build.inst(InstData { args, extra, ..InstData::new(Opcode::CheckBounds) }, &[]);
1817    }
1818
1819    #[test]
1820    fn a_check_whose_alignment_nothing_here_settles_stays() {
1821        // A pointer from outside, so nothing says what it is aligned to, and a second check of the
1822        // same bytes that dominance would otherwise take. The bytes are covered and the alignment
1823        // is not, and the check tests both, so it stays. One remark and not two: the first check
1824        // was staying whatever anybody said about its alignment, and what the number is for is
1825        // what the gate costs.
1826        let (_, mut func, block, pointer) = blank();
1827        let mut build = Builder::new(&mut func, block);
1828        assuming(&mut build, pointer, 4, 4);
1829        assuming(&mut build, pointer, 4, 4);
1830        build.ret(&[]);
1831        let stats = run(&mut func);
1832        assert_eq!(checks(&func), 2);
1833        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 0);
1834        assert_eq!(stats.count(Kind::Missed, super::UNKNOWN_ALIGNMENT), 1);
1835    }
1836
1837    #[test]
1838    fn a_check_inside_a_local_at_an_offset_the_local_is_aligned_through_goes() {
1839        // An eight byte aligned slot read four bytes in, which is a member of a record and the
1840        // commonest access there is. The offset leaves four of the eight, the access assumes four,
1841        // and the check goes the way it did before any of this.
1842        let (_, mut func, block, _) = blank();
1843        let mut build = Builder::new(&mut func, block);
1844        let slot = local(&mut build, 16);
1845        let field = past(&mut build, slot, 4);
1846        assuming(&mut build, field, 4, 4);
1847        build.ret(&[]);
1848        let stats = run(&mut func);
1849        assert_eq!(checks(&func), 0);
1850        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 1);
1851        assert_eq!(stats.count(Kind::Missed, super::UNKNOWN_ALIGNMENT), 0);
1852    }
1853
1854    #[test]
1855    fn a_check_a_cast_moved_off_the_alignment_stays_however_well_its_bytes_are_covered() {
1856        // Row S7 written in IR. The bytes are inside the slot and the slot is aligned, but the
1857        // access starts one byte in and assumes four, and one byte in is where the alignment is
1858        // lost. This is the check the misaligned read needs and the one the accounting run found
1859        // going missing.
1860        let (_, mut func, block, _) = blank();
1861        let mut build = Builder::new(&mut func, block);
1862        let slot = local(&mut build, 16);
1863        let odd = past(&mut build, slot, 1);
1864        assuming(&mut build, odd, 4, 4);
1865        build.ret(&[]);
1866        let stats = run(&mut func);
1867        assert_eq!(checks(&func), 1);
1868        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 0);
1869        assert_eq!(stats.count(Kind::Missed, super::UNKNOWN_ALIGNMENT), 1);
1870    }
1871
1872    #[test]
1873    fn a_subscript_that_steps_by_the_width_it_reads_settles_its_own_alignment() {
1874        // `p[i]` on an `int *` an allocator made. Nobody knows what the index is, and nobody has
1875        // to: the step is the index times four, four divides it whatever the index turns out to
1876        // be, and the allocation it starts from is aligned to more than that.
1877        let (_, mut func, inside, _, pointer, index) = allocation(64);
1878        let mut build = Builder::new(&mut func, inside);
1879        let four = build.iconst(Type::int(64), 4);
1880        let step = build.binary(Opcode::Mul, index, four, Flags::NONE);
1881        let args = build.func().push_values(&[pointer, step]);
1882        let at = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
1883        assuming(&mut build, at, 4, 4);
1884        build.ret(&[]);
1885        let stats = run(&mut func);
1886        assert_eq!(stats.count(Kind::Missed, super::UNKNOWN_ALIGNMENT), 0);
1887    }
1888
1889    #[test]
1890    fn what_answers_an_alignment_claim_is_the_rule_and_not_a_comparison() {
1891        // The four cases the rule is asked about, and the fifth is the reason it is a rule. A
1892        // number larger than the claim and not a multiple of it answers nothing, and the guard is
1893        // written so that the question never gets asked with one, because `super::settled` only
1894        // ever gives back a power of two. The last one is the same point from the other end: the
1895        // largest number there is is larger than every claim and divides nothing, and what the
1896        // walk means by it is that it took no step rather than that it found an alignment.
1897        assert!(super::settles(8, 8));
1898        assert!(super::settles(16, 8));
1899        assert!(!super::settles(4, 8));
1900        assert!(!super::settles(0, 8));
1901        assert!(!super::settles(u64::MAX, 8));
1902    }
1903
1904    #[test]
1905    fn a_step_by_something_nobody_can_read_settles_nothing() {
1906        // A step the ranges do bound, so the bytes are answered and the check was on its way out,
1907        // and a step nothing says the low bits of, so where the access starts is not answered. A
1908        // mask of seven is nought to seven and three is one of those.
1909        let (_, mut func, block, _, index) = indexed();
1910        let mut build = Builder::new(&mut func, block);
1911        let slot = local(&mut build, 16);
1912        let step = low_bits(&mut build, index, 7);
1913        let args = build.func().push_values(&[slot, step]);
1914        let at = build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
1915        assuming(&mut build, at, 4, 4);
1916        build.ret(&[]);
1917        let stats = run(&mut func);
1918        assert_eq!(checks(&func), 1);
1919        assert_eq!(stats.count(Kind::Missed, super::UNKNOWN_ALIGNMENT), 1);
1920    }
1921
1922    #[test]
1923    fn a_check_over_a_length_the_program_worked_out_is_not_this_pass_to_read() {
1924        // Section 7.4's hoisted check covers as many bytes as its loop runs times, which is a value
1925        // and not a number. Every range this pass compares is a pair of numbers, so it says so and
1926        // leaves the check alone rather than reading the payload, whose size is one element.
1927        let (_, mut func, block, pointer) = blank();
1928        let mut build = Builder::new(&mut func, block);
1929        check(&mut build, pointer, 4);
1930        let args = build.func().push_values(&[pointer]);
1931        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
1932        let bytes = build.iconst(Type::int(64), 4);
1933        let info = MemInfo {
1934            size: 4,
1935            align: 1,
1936            order: MemOrder::NotAtomic,
1937            tbaa: None,
1938            owns: 0,
1939            restrict: Restrict::NONE,
1940        };
1941        let extra = Extra::Mem(build.func().add_mem(info));
1942        let args = build.func().push_values(&[capability, pointer, bytes]);
1943        build.inst(InstData { args, extra, ..InstData::new(Opcode::CheckBounds) }, &[]);
1944        build.ret(&[]);
1945
1946        let stats = run(&mut func);
1947        assert_eq!(checks(&func), 2, "the second one stays");
1948        assert_eq!(stats.count(Kind::Missed, super::COMPUTED_EXTENT), 1);
1949    }
1950
1951    #[test]
1952    fn a_check_of_bytes_inside_a_checked_range_goes() {
1953        // Four bytes at offset four, inside sixteen bytes at offset zero. This is the shape the
1954        // whole pass is for: a struct whose fields are read one after another through one pointer.
1955        let (_, mut func, block, pointer) = blank();
1956        let mut build = Builder::new(&mut func, block);
1957        check(&mut build, pointer, 16);
1958        let field = past(&mut build, pointer, 4);
1959        check(&mut build, field, 4);
1960        build.ret(&[]);
1961        run(&mut func);
1962        assert_eq!(checks(&func), 1);
1963    }
1964
1965    #[test]
1966    fn a_check_of_bytes_past_the_end_of_a_checked_range_stays() {
1967        // Four bytes at offset fourteen is two bytes past the end of the sixteen that were
1968        // checked, and those two bytes are what the check is for.
1969        let (_, mut func, block, pointer) = blank();
1970        let mut build = Builder::new(&mut func, block);
1971        check(&mut build, pointer, 16);
1972        let over = past(&mut build, pointer, 14);
1973        check(&mut build, over, 4);
1974        build.ret(&[]);
1975        assert!(!run(&mut func).changed());
1976        assert_eq!(checks(&func), 2);
1977    }
1978
1979    #[test]
1980    fn a_check_of_bytes_before_a_checked_range_stays() {
1981        // The guard's `delta` is not negative, and this is why. A read four bytes below what was
1982        // checked is a read of somebody else's memory, and it is the bug the check exists for.
1983        let (_, mut func, block, pointer) = blank();
1984        let mut build = Builder::new(&mut func, block);
1985        check(&mut build, pointer, 16);
1986        let under = past(&mut build, pointer, -4);
1987        check(&mut build, under, 4);
1988        build.ret(&[]);
1989        assert!(!run(&mut func).changed());
1990        assert_eq!(checks(&func), 2);
1991    }
1992
1993    #[test]
1994    fn a_check_through_a_pointer_nothing_relates_to_the_first_stays() {
1995        let mut names = Interner::new();
1996        let name = names.intern("two");
1997        let mut func = Func::new(name, Signature::new().with_params(&[Type::PTR, Type::PTR]));
1998        let block = func.create_block();
1999        let one = func.append_param(block, Type::PTR);
2000        let other = func.append_param(block, Type::PTR);
2001        let mut build = Builder::new(&mut func, block);
2002        check(&mut build, one, 16);
2003        check(&mut build, other, 4);
2004        build.ret(&[]);
2005        assert!(!run(&mut func).changed());
2006        assert_eq!(checks(&func), 2);
2007    }
2008
2009    #[test]
2010    fn a_check_a_call_stands_between_stays_and_is_counted() {
2011        // The conservatism the module comment argues for, and the number that says what it costs.
2012        let (mut names, mut func, block, pointer) = blank();
2013        let mut build = Builder::new(&mut func, block);
2014        check(&mut build, pointer, 16);
2015        let callee = names.intern("might_free");
2016        let signature = build.func().add_signature(Signature::new());
2017        build.call(callee, signature, &[]);
2018        check(&mut build, pointer, 4);
2019        build.ret(&[]);
2020        let stats = run(&mut func);
2021        assert!(!stats.changed());
2022        assert_eq!(checks(&func), 2);
2023        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 1);
2024    }
2025
2026    #[test]
2027    fn a_check_a_call_that_cannot_free_stands_between_goes() {
2028        // The other side of the paragraph above. The summary said this call reaches nothing that
2029        // ends a lifetime, so the range the first check established is still one range.
2030        let (mut names, mut func, block, pointer) = blank();
2031        let mut build = Builder::new(&mut func, block);
2032        check(&mut build, pointer, 16);
2033        let callee = names.intern("counts_them");
2034        let signature = build.func().add_signature(Signature::new());
2035        let call = build.call(callee, signature, &[]);
2036        check(&mut build, pointer, 4);
2037        build.ret(&[]);
2038        func[call].flags |= Flags::NOFREE;
2039        let stats = run(&mut func);
2040        assert_eq!(checks(&func), 1);
2041        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
2042        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 0);
2043    }
2044
2045    #[test]
2046    fn inline_assembly_throws_the_facts_away_whatever_it_is_flagged() {
2047        // There is no flag that would make this safe. The template is text the compiler does not
2048        // read, so nothing worked anything out about what it reaches.
2049        let (mut names, mut func, block, pointer) = blank();
2050        let mut build = Builder::new(&mut func, block);
2051        check(&mut build, pointer, 16);
2052        build.inline_asm(
2053            AsmInfo {
2054                template: names.intern("nop"),
2055                constraints: names.intern(""),
2056                clobbers: names.intern(""),
2057                targets: BlockCallList::EMPTY,
2058            },
2059            &[],
2060            &[],
2061            Flags::NONE,
2062        );
2063        check(&mut build, pointer, 4);
2064        build.ret(&[]);
2065        let stats = run(&mut func);
2066        assert!(!stats.changed());
2067        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 1);
2068    }
2069
2070    #[test]
2071    fn a_check_that_only_one_path_covers_stays() {
2072        // The dominator tree is what makes this right. The check in the arm covers the one in the
2073        // join on one path and not on the other, and a check that goes has to be one that ran.
2074        let (_, mut func, block, pointer) = blank();
2075        let arm = func.create_block();
2076        let join = func.create_block();
2077        let mut build = Builder::new(&mut func, block);
2078        let condition = build.iconst(Type::int(32), 1);
2079        build.br_if(condition, arm, &[], join, &[]);
2080        let mut build = Builder::new(&mut func, arm);
2081        check(&mut build, pointer, 16);
2082        build.jump(join, &[]);
2083        let mut build = Builder::new(&mut func, join);
2084        check(&mut build, pointer, 4);
2085        build.ret(&[]);
2086        assert!(!run(&mut func).changed());
2087        assert_eq!(checks(&func), 2);
2088    }
2089
2090    #[test]
2091    fn a_check_a_dominating_block_covers_goes() {
2092        let (_, mut func, block, pointer) = blank();
2093        let after = func.create_block();
2094        let mut build = Builder::new(&mut func, block);
2095        check(&mut build, pointer, 16);
2096        build.jump(after, &[]);
2097        let mut build = Builder::new(&mut func, after);
2098        let field = past(&mut build, pointer, 8);
2099        check(&mut build, field, 8);
2100        build.ret(&[]);
2101        run(&mut func);
2102        assert_eq!(checks(&func), 1);
2103    }
2104
2105    #[test]
2106    fn fuel_stops_the_removing_and_not_the_looking() {
2107        let (_, mut func, block, pointer) = blank();
2108        let mut build = Builder::new(&mut func, block);
2109        check(&mut build, pointer, 4);
2110        check(&mut build, pointer, 4);
2111        check(&mut build, pointer, 4);
2112        build.ret(&[]);
2113        let mut fuel = Fuel::of(1);
2114        let stats = DISCHARGE.run(&mut func, &mut crate::machine::fixtures::analyses(), &mut fuel);
2115        assert_eq!(checks(&func), 2);
2116        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
2117        assert_eq!(stats.count(Kind::Missed, super::NO_FUEL), 1);
2118    }
2119
2120    #[test]
2121    fn a_second_lifetime_check_of_the_same_address_goes() {
2122        // The narrow fact on its own, with no range around it to widen into.
2123        let (_, mut func, block, pointer) = blank();
2124        let mut build = Builder::new(&mut func, block);
2125        live(&mut build, pointer);
2126        live(&mut build, pointer);
2127        build.ret(&[]);
2128        let stats = run(&mut func);
2129        assert_eq!(lives(&func), 1);
2130        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE), 1);
2131    }
2132
2133    #[test]
2134    fn a_lifetime_check_inside_a_checked_range_goes() {
2135        // The shape the pass is for, with both halves of it. Sixteen bytes are checked and found
2136        // alive, then a field four bytes in is read, and neither check in front of it survives.
2137        let (_, mut func, block, pointer) = blank();
2138        let mut build = Builder::new(&mut func, block);
2139        access(&mut build, pointer, 16);
2140        let field = past(&mut build, pointer, 4);
2141        access(&mut build, field, 4);
2142        build.ret(&[]);
2143        let stats = run(&mut func);
2144        assert_eq!(checks(&func), 1);
2145        assert_eq!(lives(&func), 1);
2146        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
2147        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE), 1);
2148    }
2149
2150    #[test]
2151    fn a_lifetime_check_outside_every_checked_range_stays() {
2152        // Four bytes at offset twenty are past the sixteen that were checked, so nothing says the
2153        // address is in the instance that was found alive, and it might be in no instance at all.
2154        let (_, mut func, block, pointer) = blank();
2155        let mut build = Builder::new(&mut func, block);
2156        access(&mut build, pointer, 16);
2157        let over = past(&mut build, pointer, 20);
2158        live(&mut build, over);
2159        build.ret(&[]);
2160        assert!(!run(&mut func).changed());
2161        assert_eq!(lives(&func), 2);
2162    }
2163
2164    #[test]
2165    fn a_lifetime_check_with_no_range_around_it_does_not_widen() {
2166        // Without the bounds check the first lifetime check speaks only for its own address, so
2167        // the one four bytes along is a different question and stays.
2168        let (_, mut func, block, pointer) = blank();
2169        let mut build = Builder::new(&mut func, block);
2170        live(&mut build, pointer);
2171        let field = past(&mut build, pointer, 4);
2172        live(&mut build, field);
2173        build.ret(&[]);
2174        assert!(!run(&mut func).changed());
2175        assert_eq!(lives(&func), 2);
2176    }
2177
2178    #[test]
2179    fn a_lifetime_check_a_call_stands_between_stays_and_is_counted() {
2180        // Section 8.8's number. This is the one the summaries were written for.
2181        let (mut names, mut func, block, pointer) = blank();
2182        let mut build = Builder::new(&mut func, block);
2183        access(&mut build, pointer, 16);
2184        let callee = names.intern("might_free");
2185        let signature = build.func().add_signature(Signature::new());
2186        build.call(callee, signature, &[]);
2187        let field = past(&mut build, pointer, 4);
2188        live(&mut build, field);
2189        build.ret(&[]);
2190        let stats = run(&mut func);
2191        assert!(!stats.changed());
2192        assert_eq!(lives(&func), 2);
2193        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL_LIVE), 1);
2194    }
2195
2196    #[test]
2197    fn a_lifetime_check_a_call_that_cannot_free_stands_between_goes() {
2198        let (mut names, mut func, block, pointer) = blank();
2199        let mut build = Builder::new(&mut func, block);
2200        access(&mut build, pointer, 16);
2201        let callee = names.intern("counts_them");
2202        let signature = build.func().add_signature(Signature::new());
2203        let call = build.call(callee, signature, &[]);
2204        let field = past(&mut build, pointer, 4);
2205        live(&mut build, field);
2206        build.ret(&[]);
2207        func[call].flags |= Flags::NOFREE;
2208        let stats = run(&mut func);
2209        assert_eq!(lives(&func), 1);
2210        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE), 1);
2211    }
2212
2213    #[test]
2214    fn ending_a_lifetime_throws_the_facts_away() {
2215        // Nothing emits `meta_end` yet, so this is the test that says what will happen when
2216        // something does, rather than a test of anything the compiler does today.
2217        let (_, mut func, block, pointer) = blank();
2218        let mut build = Builder::new(&mut func, block);
2219        access(&mut build, pointer, 16);
2220        let size = build.iconst(Type::int(64), 16);
2221        let args = build.func().push_values(&[pointer, size]);
2222        build.inst(InstData { args, ..InstData::new(Opcode::MetaEnd) }, &[]);
2223        access(&mut build, pointer, 16);
2224        build.ret(&[]);
2225        let stats = run(&mut func);
2226        assert!(!stats.changed());
2227        assert_eq!(checks(&func), 2);
2228        assert_eq!(lives(&func), 2);
2229        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 1);
2230        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL_LIVE), 1);
2231    }
2232
2233    #[test]
2234    fn fuel_runs_out_over_both_kinds_of_check() {
2235        let (_, mut func, block, pointer) = blank();
2236        let mut build = Builder::new(&mut func, block);
2237        access(&mut build, pointer, 16);
2238        access(&mut build, pointer, 4);
2239        build.ret(&[]);
2240        let mut fuel = Fuel::of(1);
2241        let stats = DISCHARGE.run(&mut func, &mut crate::machine::fixtures::analyses(), &mut fuel);
2242        assert_eq!(checks(&func), 1);
2243        assert_eq!(lives(&func), 2);
2244        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
2245        assert_eq!(stats.count(Kind::Missed, super::NO_FUEL_LIVE), 1);
2246    }
2247
2248    #[test]
2249    fn a_distance_too_large_to_be_a_real_access_is_not_discharged() {
2250        // The guard's bound. The two readings of the arithmetic agree while the numbers stay
2251        // small, so a rule proved at sixty four bits is not asked about anything else. Nothing
2252        // here is wrong, it simply is not proved, and a check that is not proved to be unnecessary
2253        // stays.
2254        let huge = i128::from(u64::MAX) * 4;
2255        let fact = Fact { base: Value::new(0), offset: 0, size: huge };
2256        let asked = Fact { base: Value::new(0), offset: huge / 2, size: 4 };
2257        assert!(!super::covers(&fact, &asked));
2258    }
2259
2260    #[test]
2261    fn a_range_of_addresses_wider_than_the_rule_allows_is_not_discharged() {
2262        // The guard on `reached.i64` bounds each of the three numbers at four gigabytes, for the
2263        // reason the rule file gives: past there the compiler's `i128` reading of the guard and the
2264        // solver's sixty four bit reading part company, and a rule proved under one and run under
2265        // the other is a rule proved about arithmetic that is not happening. A step whose range is
2266        // that wide is the usual case rather than a corner, since an index nothing has bounded says
2267        // nothing about where the access lands.
2268        let base = Value::new(0);
2269        let whole = Fact::whole(base, i128::from(u64::MAX) * 4);
2270        let asked = super::Reach { base, low: 0, width: i128::from(u64::MAX), size: 4 };
2271        assert!(!super::reaches(&whole, &asked));
2272    }
2273
2274    #[test]
2275    fn a_range_of_addresses_that_ends_where_the_object_does_is_discharged() {
2276        // Sixteen bytes, a step somewhere in nought to eleven, four bytes read. The last address
2277        // the walk can reach is the last one in the object, which is inside it.
2278        let base = Value::new(0);
2279        let whole = Fact::whole(base, 16);
2280        let asked = super::Reach { base, low: 0, width: 12, size: 4 };
2281        assert!(super::reaches(&whole, &asked));
2282        let over = super::Reach { base, low: 0, width: 13, size: 4 };
2283        assert!(!super::reaches(&whole, &over), "one byte further runs off the end");
2284    }
2285
2286    #[test]
2287    fn a_walk_by_a_bounded_step_off_a_local_takes_its_derivation_check_with_it() {
2288        // The shape `derives` cannot read at all: the pointer that went in is the slot and the one
2289        // that came out is a value past it, so the two are not one base and two constants. Both
2290        // ends widen to the slot, the slot holds both ranges, and one thing holding both is what a
2291        // derivation check asks about.
2292        let (_, mut func, block, _, index) = indexed();
2293        let mut build = Builder::new(&mut func, block);
2294        let slot = local(&mut build, 16);
2295        let step = low_bits(&mut build, index, 7);
2296        let at = walk(&mut build, slot, step);
2297        deriv(&mut build, slot, at, 4);
2298        build.ret(&[]);
2299        let stats = run(&mut func);
2300        assert_eq!(derivs(&func), 0);
2301        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_RANGE), 1);
2302    }
2303
2304    #[test]
2305    fn a_walk_that_can_leave_the_local_keeps_its_derivation_check() {
2306        // Nought to fifteen off a slot of eight. Every step is bounded and the answer is still no,
2307        // because the question is whether the slot holds every address the walk can reach.
2308        let (_, mut func, block, _, index) = indexed();
2309        let mut build = Builder::new(&mut func, block);
2310        let slot = local(&mut build, 8);
2311        let step = low_bits(&mut build, index, 15);
2312        let at = walk(&mut build, slot, step);
2313        deriv(&mut build, slot, at, 4);
2314        build.ret(&[]);
2315        let stats = run(&mut func);
2316        assert_eq!(derivs(&func), 1);
2317        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_RANGE), 0);
2318        assert_eq!(stats.count(Kind::Missed, super::OVER_THE_LOCAL_DERIV), 1);
2319    }
2320
2321    #[test]
2322    fn a_lifetime_check_a_bounded_walk_lands_inside_a_checked_range_goes() {
2323        // An access over thirty two bytes establishes the range, and the lifetime check beside it
2324        // makes that range one a check found alive. The lifetime check on the walk then goes,
2325        // because every address the walk can reach is in the range that was found alive.
2326        //
2327        // Written off a parameter rather than a slot because a slot answers the narrow question on
2328        // its own. What has to answer this one is a range a check was passed on.
2329        let (_, mut func, block, pointer, index) = indexed();
2330        let mut build = Builder::new(&mut func, block);
2331        access(&mut build, pointer, 32);
2332        let step = low_bits(&mut build, index, 7);
2333        let at = walk(&mut build, pointer, step);
2334        live(&mut build, at);
2335        build.ret(&[]);
2336        let stats = run(&mut func);
2337        assert_eq!(lives(&func), 1, "the one in front of the access stays");
2338        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_RANGE), 1);
2339    }
2340
2341    #[test]
2342    fn a_lifetime_check_a_bounded_walk_can_leave_the_checked_range_keeps_it() {
2343        // The same over eight bytes, under a walk that can go fifteen past the start. A range of
2344        // eight bytes does not hold an address fifteen along from where it begins.
2345        let (_, mut func, block, pointer, index) = indexed();
2346        let mut build = Builder::new(&mut func, block);
2347        access(&mut build, pointer, 8);
2348        let step = low_bits(&mut build, index, 15);
2349        let at = walk(&mut build, pointer, step);
2350        live(&mut build, at);
2351        build.ret(&[]);
2352        let stats = run(&mut func);
2353        assert_eq!(lives(&func), 2);
2354        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_RANGE), 0);
2355    }
2356
2357    /// A stack slot of `size` bytes, in the entry block where the verifier wants one.
2358    fn local(build: &mut Builder<'_>, size: u64) -> Value {
2359        let info = MemInfo {
2360            size,
2361            align: 8,
2362            order: MemOrder::NotAtomic,
2363            tbaa: None,
2364            owns: 0,
2365            restrict: Restrict::NONE,
2366        };
2367        let extra = Extra::Mem(build.func().add_mem(info));
2368        build.value(InstData { extra, ..InstData::new(Opcode::Alloca) }, Type::PTR)
2369    }
2370
2371    /// A function taking a pointer and an index, with one block.
2372    fn indexed() -> (Interner, Func, Block, Value, Value) {
2373        let mut names = Interner::new();
2374        let name = names.intern("f");
2375        let mut func = Func::new(name, Signature::new().with_params(&[Type::PTR, Type::int(64)]));
2376        let block = func.create_block();
2377        let pointer = func.append_param(block, Type::PTR);
2378        let index = func.append_param(block, Type::int(64));
2379        (names, func, block, pointer, index)
2380    }
2381
2382    /// A pointer a value past another one.
2383    fn walk(build: &mut Builder<'_>, pointer: Value, by: Value) -> Value {
2384        let args = build.func().push_values(&[pointer, by]);
2385        build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
2386    }
2387
2388    /// The low bits of a value, which is a step the ranges can put a number on.
2389    fn low_bits(build: &mut Builder<'_>, value: Value, mask: i128) -> Value {
2390        let bits = build.iconst(Type::int(64), mask);
2391        build.binary(Opcode::And, value, bits, Flags::NONE)
2392    }
2393
2394    #[test]
2395    fn a_walk_by_a_step_the_ranges_bound_inside_a_local_goes() {
2396        // Section 7.2's third source. The step is not a constant, so the walk stops at the
2397        // `ptr_add` and the fact that comes out is about a base nobody knows the size of. What
2398        // the ranges say is that the step is somewhere in nought to seven, so the four bytes the
2399        // access wants are somewhere in nought to eleven, and all of that is inside the sixteen
2400        // the slot is.
2401        let (_, mut func, block, _, index) = indexed();
2402        let mut build = Builder::new(&mut func, block);
2403        let slot = local(&mut build, 16);
2404        let step = low_bits(&mut build, index, 7);
2405        let at = walk(&mut build, slot, step);
2406        check(&mut build, at, 4);
2407        build.ret(&[]);
2408        let stats = run(&mut func);
2409        assert_eq!(checks(&func), 0);
2410        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_RANGE), 1);
2411    }
2412
2413    #[test]
2414    fn a_walk_by_a_step_the_ranges_cannot_bound_is_left_alone() {
2415        // The same function with the mask taken off. A parameter can be anything, so the range of
2416        // addresses the walk reaches is the whole of memory and no slot covers it.
2417        let (_, mut func, block, _, index) = indexed();
2418        let mut build = Builder::new(&mut func, block);
2419        let slot = local(&mut build, 16);
2420        let at = walk(&mut build, slot, index);
2421        check(&mut build, at, 4);
2422        build.ret(&[]);
2423        let stats = run(&mut func);
2424        assert_eq!(checks(&func), 1);
2425        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_RANGE), 0);
2426    }
2427
2428    #[test]
2429    fn a_walk_a_bounded_step_can_take_off_the_end_of_a_local_is_left_alone() {
2430        // Nought to seven again, four bytes again, and a slot of eight this time. The step being
2431        // bounded is not the question. The question is whether every address it can reach is
2432        // inside the slot, and seven plus four is not.
2433        let (_, mut func, block, _, index) = indexed();
2434        let mut build = Builder::new(&mut func, block);
2435        let slot = local(&mut build, 8);
2436        let step = low_bits(&mut build, index, 7);
2437        let at = walk(&mut build, slot, step);
2438        check(&mut build, at, 4);
2439        build.ret(&[]);
2440        let stats = run(&mut func);
2441        assert_eq!(checks(&func), 1);
2442        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_RANGE), 0);
2443    }
2444
2445    #[test]
2446    fn a_constant_step_past_a_bounded_one_is_walked_too() {
2447        // A field of an element of an array of structs, which is the shape this is for. The array
2448        // index needs a range and the field offset does not, and the walk has to get through both.
2449        let (_, mut func, block, _, index) = indexed();
2450        let mut build = Builder::new(&mut func, block);
2451        let slot = local(&mut build, 32);
2452        let step = low_bits(&mut build, index, 15);
2453        let element = walk(&mut build, slot, step);
2454        let field = past(&mut build, element, 8);
2455        check(&mut build, field, 4);
2456        build.ret(&[]);
2457        let stats = run(&mut func);
2458        assert_eq!(checks(&func), 0);
2459        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_RANGE), 1);
2460    }
2461
2462    #[test]
2463    fn what_a_range_discharge_records_is_the_bytes_and_not_the_range() {
2464        // The second check is the same bytes as the first, and the first went because a made up
2465        // range around it was inside the slot. What the first one proved is that those bytes are
2466        // in the slot, so the second one goes on that rather than on the ranges being asked all
2467        // over again.
2468        let (_, mut func, block, _, index) = indexed();
2469        let mut build = Builder::new(&mut func, block);
2470        let slot = local(&mut build, 16);
2471        let step = low_bits(&mut build, index, 7);
2472        let at = walk(&mut build, slot, step);
2473        check(&mut build, at, 4);
2474        check(&mut build, at, 4);
2475        build.ret(&[]);
2476        let stats = run(&mut func);
2477        assert_eq!(checks(&func), 0);
2478        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_RANGE), 1);
2479        assert_eq!(stats.count(Kind::Optimized, super::REMOVED), 1);
2480    }
2481
2482    /// A stack slot whose size the program works out, which is what a variable length array is.
2483    fn growable(build: &mut Builder<'_>, size: Value) -> Value {
2484        let info = MemInfo {
2485            size: 0,
2486            align: 8,
2487            order: MemOrder::NotAtomic,
2488            tbaa: None,
2489            owns: 0,
2490            restrict: Restrict::NONE,
2491        };
2492        let extra = Extra::Mem(build.func().add_mem(info));
2493        let args = build.func().push_values(&[size]);
2494        build.value(InstData { args, extra, ..InstData::new(Opcode::Alloca) }, Type::PTR)
2495    }
2496
2497    #[test]
2498    fn a_check_of_bytes_inside_a_local_goes_with_nothing_in_front_of_it() {
2499        // Section 7.2's first source. No check established this and none had to: an `alloca` of
2500        // sixteen bytes is sixteen bytes of one storage instance because that is what it makes.
2501        let (_, mut func, block, _) = blank();
2502        let mut build = Builder::new(&mut func, block);
2503        let slot = local(&mut build, 16);
2504        let field = past(&mut build, slot, 8);
2505        check(&mut build, field, 4);
2506        build.ret(&[]);
2507        let stats = run(&mut func);
2508        assert_eq!(checks(&func), 0);
2509        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 1);
2510    }
2511
2512    #[test]
2513    fn a_check_past_the_end_of_a_local_stays() {
2514        // The slot is sixteen bytes and the access runs to twenty. Nothing about it being a local
2515        // says anything about the four bytes after it, which belong to whatever the frame puts
2516        // there next.
2517        let (_, mut func, block, _) = blank();
2518        let mut build = Builder::new(&mut func, block);
2519        let slot = local(&mut build, 16);
2520        let field = past(&mut build, slot, 16);
2521        check(&mut build, field, 4);
2522        build.ret(&[]);
2523        let stats = run(&mut func);
2524        assert_eq!(checks(&func), 1);
2525        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 0);
2526    }
2527
2528    #[test]
2529    fn a_check_of_bytes_inside_a_local_goes_across_a_call() {
2530        // The other half of what makes the fact worth having. A callee cannot free a frame slot,
2531        // so unlike everything the walk carries this one is not thrown away at a call.
2532        let (mut names, mut func, block, _) = blank();
2533        let mut build = Builder::new(&mut func, block);
2534        let slot = local(&mut build, 16);
2535        let callee = names.intern("might_free");
2536        let signature = build.func().add_signature(Signature::new());
2537        build.call(callee, signature, &[]);
2538        check(&mut build, slot, 4);
2539        build.ret(&[]);
2540        let stats = run(&mut func);
2541        assert_eq!(checks(&func), 0);
2542        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 1);
2543        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 0);
2544    }
2545
2546    #[test]
2547    fn a_check_inside_a_variable_length_array_stays() {
2548        // How many bytes it is is a value the program works out, and the payload's size field
2549        // reads zero. A pass that read it anyway would discharge every check in the array.
2550        let (_, mut func, block, _) = blank();
2551        let mut build = Builder::new(&mut func, block);
2552        let bytes = build.iconst(Type::int(64), 64);
2553        let slot = growable(&mut build, bytes);
2554        check(&mut build, slot, 4);
2555        build.ret(&[]);
2556        let stats = run(&mut func);
2557        assert_eq!(checks(&func), 1);
2558        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LOCAL), 0);
2559    }
2560
2561    #[test]
2562    fn a_lifetime_check_in_a_local_goes_with_nothing_in_front_of_it() {
2563        // The frame slot rule, and the point is that neither of these has a check in front of it.
2564        // A slot is alive until the function returns, so a lifetime check anywhere inside one is
2565        // asking a question the `alloca` already answered.
2566        let (_, mut func, block, _) = blank();
2567        let mut build = Builder::new(&mut func, block);
2568        let slot = local(&mut build, 16);
2569        live(&mut build, slot);
2570        let field = past(&mut build, slot, 12);
2571        live(&mut build, field);
2572        build.ret(&[]);
2573        let stats = run(&mut func);
2574        assert_eq!(lives(&func), 0);
2575        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_LOCAL), 2);
2576    }
2577
2578    #[test]
2579    fn a_lifetime_check_past_the_end_of_a_local_stays() {
2580        // The slot answers for its own bytes and no further, so an address outside it is a
2581        // different instance and a question nothing has answered.
2582        let (_, mut func, block, _) = blank();
2583        let mut build = Builder::new(&mut func, block);
2584        let slot = local(&mut build, 16);
2585        live(&mut build, slot);
2586        let field = past(&mut build, slot, 24);
2587        live(&mut build, field);
2588        build.ret(&[]);
2589        let stats = run(&mut func);
2590        assert_eq!(lives(&func), 1);
2591        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_LOCAL), 1);
2592    }
2593
2594    #[test]
2595    fn something_ending_a_lifetime_turns_the_frame_slot_rule_off() {
2596        // The gate, and with it the widening the frame slot rule usually hides. With a `meta_end`
2597        // anywhere in the function the slot answers nothing, so the first check stays and pays,
2598        // and what takes the second one out is the first one widened to the whole slot.
2599        let (_, mut func, block, pointer) = blank();
2600        let mut build = Builder::new(&mut func, block);
2601        let slot = local(&mut build, 16);
2602        live(&mut build, slot);
2603        let field = past(&mut build, slot, 12);
2604        live(&mut build, field);
2605        let size = build.iconst(Type::int(64), 16);
2606        let args = build.func().push_values(&[pointer, size]);
2607        build.inst(InstData { args, ..InstData::new(Opcode::MetaEnd) }, &[]);
2608        build.ret(&[]);
2609        let stats = run(&mut func);
2610        assert_eq!(lives(&func), 1);
2611        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_LOCAL), 0);
2612        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE), 1);
2613    }
2614
2615    /// Puts `cap_of` and a `check_deriv` for a walk from `from` to `to` into a block.
2616    ///
2617    /// The stride is the width of one element, which is what `rucc-safety` passes and what the
2618    /// runtime uses for a pointer that walked off the near end. This pass does not read it.
2619    fn deriv(build: &mut Builder<'_>, from: Value, to: Value, stride: i128) {
2620        let args = build.func().push_values(&[from]);
2621        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
2622        let width = build.iconst(Type::int(64), stride);
2623        let args = build.func().push_values(&[capability, from, to, width]);
2624        build.inst(InstData { args, ..InstData::new(Opcode::CheckDeriv) }, &[]);
2625    }
2626
2627    /// How many derivation checks are left in a function.
2628    fn derivs(func: &Func) -> usize {
2629        func.blocks()
2630            .flat_map(|block| func.insts(block).collect::<Vec<_>>())
2631            .filter(|&inst| func[inst].opcode == Opcode::CheckDeriv)
2632            .count()
2633    }
2634
2635    #[test]
2636    fn a_walk_inside_a_checked_range_goes() {
2637        // Sixteen bytes were checked, and the walk goes from the start of them to eight in. Both
2638        // ends are in one range, so the second address is in the instance the first belongs to.
2639        let (_, mut func, block, pointer) = blank();
2640        let mut build = Builder::new(&mut func, block);
2641        check(&mut build, pointer, 16);
2642        let field = past(&mut build, pointer, 8);
2643        deriv(&mut build, pointer, field, 4);
2644        build.ret(&[]);
2645        let stats = run(&mut func);
2646        assert_eq!(derivs(&func), 0);
2647        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV), 1);
2648    }
2649
2650    #[test]
2651    fn a_walk_that_leaves_the_checked_range_stays() {
2652        // Four bytes were checked and the walk goes eight past them. Nothing here says the two
2653        // addresses are in one instance, which is the whole of what the check is about.
2654        let (_, mut func, block, pointer) = blank();
2655        let mut build = Builder::new(&mut func, block);
2656        check(&mut build, pointer, 4);
2657        let field = past(&mut build, pointer, 8);
2658        deriv(&mut build, pointer, field, 4);
2659        build.ret(&[]);
2660        let stats = run(&mut func);
2661        assert_eq!(derivs(&func), 1);
2662        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV), 0);
2663    }
2664
2665    #[test]
2666    fn two_ranges_holding_one_end_each_do_not_answer_a_walk() {
2667        // The case the one fact rule is written for. Both addresses have been checked, so both are
2668        // inside some instance, and nothing says it is the same one. The walk stays.
2669        let (_, mut func, block, pointer) = blank();
2670        let mut build = Builder::new(&mut func, block);
2671        check(&mut build, pointer, 4);
2672        let field = past(&mut build, pointer, 64);
2673        check(&mut build, field, 4);
2674        deriv(&mut build, pointer, field, 4);
2675        build.ret(&[]);
2676        let stats = run(&mut func);
2677        assert_eq!(derivs(&func), 1);
2678        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV), 0);
2679    }
2680
2681    #[test]
2682    fn a_walk_inside_a_local_goes_with_nothing_in_front_of_it() {
2683        // The shape almost every derivation check in real code has: a field of a local struct.
2684        // `rucc-safety` emits the walk before the bounds check on what it produced, so a fact from
2685        // an earlier check is usually the wrong size for it and the local is what answers.
2686        let (_, mut func, block, _) = blank();
2687        let mut build = Builder::new(&mut func, block);
2688        let slot = local(&mut build, 16);
2689        let field = past(&mut build, slot, 8);
2690        deriv(&mut build, slot, field, 4);
2691        build.ret(&[]);
2692        let stats = run(&mut func);
2693        assert_eq!(derivs(&func), 0);
2694        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_LOCAL), 1);
2695    }
2696
2697    #[test]
2698    fn a_walk_off_the_end_of_a_local_stays() {
2699        // Where the slot stops is where the fact stops. One past the end is the case the runtime
2700        // has slack for and this pass does not use any of it.
2701        let (_, mut func, block, _) = blank();
2702        let mut build = Builder::new(&mut func, block);
2703        let slot = local(&mut build, 16);
2704        let field = past(&mut build, slot, 16);
2705        deriv(&mut build, slot, field, 4);
2706        build.ret(&[]);
2707        let stats = run(&mut func);
2708        assert_eq!(derivs(&func), 1);
2709        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_LOCAL), 0);
2710    }
2711
2712    #[test]
2713    fn a_walk_a_call_stands_between_stays_and_is_counted() {
2714        // The same price the other two kinds pay, reported the same way, so the cost of not
2715        // trusting a call is a number per function rather than a paragraph.
2716        let (mut names, mut func, block, pointer) = blank();
2717        let mut build = Builder::new(&mut func, block);
2718        check(&mut build, pointer, 16);
2719        let callee = names.intern("might_free");
2720        let signature = build.func().add_signature(Signature::new());
2721        build.call(callee, signature, &[]);
2722        let field = past(&mut build, pointer, 8);
2723        deriv(&mut build, pointer, field, 4);
2724        build.ret(&[]);
2725        let stats = run(&mut func);
2726        assert_eq!(derivs(&func), 1);
2727        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL_DERIV), 1);
2728    }
2729
2730    #[test]
2731    fn a_check_the_module_says_is_inside_a_global_goes_with_nothing_in_front_of_it() {
2732        // The other half of section 7.2's first source. The size of a global lives on the module
2733        // and this pass is given one function, so the answer arrives as a flag `crate::extents`
2734        // wrote before the pipeline started, and all three kinds carry it.
2735        let (_, mut func, block, pointer) = blank();
2736        let mut build = Builder::new(&mut func, block);
2737        let field = past(&mut build, pointer, 8);
2738        deriv(&mut build, pointer, field, 1);
2739        access(&mut build, field, 4);
2740        build.ret(&[]);
2741        marked(&mut func);
2742        let stats = run(&mut func);
2743        assert_eq!(checks(&func), 0);
2744        assert_eq!(lives(&func), 0);
2745        assert_eq!(derivs(&func), 0);
2746        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_STATIC), 1);
2747        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_STATIC), 1);
2748        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_STATIC), 1);
2749    }
2750
2751    #[test]
2752    fn a_check_the_module_says_every_caller_hands_in_goes_with_nothing_in_front_of_it() {
2753        // Section 7.5's summaries, arriving the same way a global's extent does and for the same
2754        // reason: which object a caller passes is a fact about a different function. What the flag
2755        // says is an extent and a lifetime, because the objects `crate::params` believes are a
2756        // caller's frame slot and a global and both are alive for as long as the call runs.
2757        let (_, mut func, block, pointer) = blank();
2758        let mut build = Builder::new(&mut func, block);
2759        let field = past(&mut build, pointer, 8);
2760        deriv(&mut build, pointer, field, 1);
2761        access(&mut build, field, 4);
2762        build.ret(&[]);
2763        flagged(&mut func, Flags::HANDED);
2764        let stats = run(&mut func);
2765        assert_eq!(checks(&func), 0);
2766        assert_eq!(lives(&func), 0);
2767        assert_eq!(derivs(&func), 0);
2768        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_HANDED), 1);
2769        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_HANDED), 1);
2770        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_HANDED), 1);
2771    }
2772
2773    /// A function that takes an index, allocates `size` bytes and tests the answer against null.
2774    ///
2775    /// Gives back the block where the test has passed, the block where it has not, the pointer and
2776    /// the index. The flag is put on by hand, because which calls deserve it is a question about a
2777    /// module and `crate::heap` is what answers it.
2778    ///
2779    /// The index is there for the tests about a walk by a value. A parameter on its own is any
2780    /// number at all, so a test that wants a bounded one puts [`low_bits`] over it the same way the
2781    /// local tests do.
2782    fn allocation(size: i128) -> (Interner, Func, Block, Block, Value, Value) {
2783        let mut names = Interner::new();
2784        let name = names.intern("f");
2785        let mut func = Func::new(name, Signature::new().with_params(&[Type::int(64)]));
2786        let entry = func.create_block();
2787        let inside = func.create_block();
2788        let outside = func.create_block();
2789        let index = func.append_param(entry, Type::int(64));
2790        let mut build = Builder::new(&mut func, entry);
2791        let signature = build.func().add_signature(
2792            Signature::new().with_params(&[Type::int(64)]).with_returns(&[Type::PTR]),
2793        );
2794        let bytes = build.iconst(Type::int(64), size);
2795        let call = build.call(names.intern("malloc"), signature, &[bytes]);
2796        let at = build.func();
2797        at[call].flags |= Flags::HEAP;
2798        let pointer = at[call].results().next().expect("a call that gives back a pointer");
2799        let zero = build.iconst(Type::int(64), 0);
2800        let null = build.unary(Opcode::IntToPtr, zero, Type::PTR);
2801        let condition = build.icmp(IntPred::Ne, pointer, null);
2802        build.br_if(condition, inside, &[], outside, &[]);
2803        let mut build = Builder::new(&mut func, outside);
2804        build.ret(&[]);
2805        (names, func, inside, outside, pointer, index)
2806    }
2807
2808    #[test]
2809    fn a_check_inside_an_allocation_the_program_tested_goes() {
2810        // The third of the objects whose extent nobody had to check for. `malloc(16)` says how
2811        // many bytes it made in the call, and the branch on null is what makes it true here.
2812        let (_, mut func, inside, _, pointer, _) = allocation(16);
2813        let mut build = Builder::new(&mut func, inside);
2814        let field = past(&mut build, pointer, 8);
2815        deriv(&mut build, pointer, field, 1);
2816        access(&mut build, field, 4);
2817        build.ret(&[]);
2818        let stats = run(&mut func);
2819        assert_eq!(checks(&func), 0);
2820        assert_eq!(derivs(&func), 0);
2821        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 1);
2822        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_MADE), 1);
2823        // The lifetime check is the one an allocation says nothing about, because a `free` in this
2824        // same function can end it, and it is what reports a use after free.
2825        assert_eq!(lives(&func), 1);
2826    }
2827
2828    #[test]
2829    fn a_check_on_an_allocation_nobody_tested_stays() {
2830        // Down the other arm the pointer is null, a null pointer is inside no object at all, and
2831        // the check is one that is supposed to fail.
2832        let (_, mut func, _, outside, pointer, _) = allocation(16);
2833        let mut build = Builder::new(&mut func, outside);
2834        access(&mut build, pointer, 4);
2835        build.ret(&[]);
2836        let stats = run(&mut func);
2837        assert_eq!(checks(&func), 1);
2838        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 0);
2839    }
2840
2841    #[test]
2842    fn a_check_past_the_end_of_an_allocation_stays() {
2843        // Four bytes at offset fourteen is two bytes past the sixteen that were asked for, and
2844        // those two bytes are what the check is for.
2845        let (_, mut func, inside, _, pointer, _) = allocation(16);
2846        let mut build = Builder::new(&mut func, inside);
2847        let field = past(&mut build, pointer, 14);
2848        access(&mut build, field, 4);
2849        build.ret(&[]);
2850        let stats = run(&mut func);
2851        assert_eq!(checks(&func), 1);
2852        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 0);
2853    }
2854
2855    #[test]
2856    fn a_walk_that_leaves_an_allocation_stays() {
2857        // One end inside and the other past the end is a walk out of the object, which is what a
2858        // derivation check is there to catch, so both ends have to be inside before it goes.
2859        let (_, mut func, inside, _, pointer, _) = allocation(16);
2860        let mut build = Builder::new(&mut func, inside);
2861        let field = past(&mut build, pointer, 32);
2862        deriv(&mut build, pointer, field, 1);
2863        build.ret(&[]);
2864        let stats = run(&mut func);
2865        assert_eq!(derivs(&func), 1);
2866        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_MADE), 0);
2867    }
2868
2869    #[test]
2870    fn a_check_inside_an_allocation_goes_across_a_call() {
2871        // The other reason a fact read off the instruction is worth having. How many bytes an
2872        // allocator made is not something a callee can change, so unlike a fact from a check that
2873        // ran this one is still there on the far side of a call.
2874        let (mut names, mut func, inside, _, pointer, _) = allocation(16);
2875        let mut build = Builder::new(&mut func, inside);
2876        access(&mut build, pointer, 4);
2877        let signature = build.func().add_signature(Signature::new());
2878        build.call(names.intern("g"), signature, &[]);
2879        access(&mut build, pointer, 4);
2880        build.ret(&[]);
2881        let stats = run(&mut func);
2882        assert_eq!(checks(&func), 0);
2883        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 2);
2884        // Both lifetime checks stay, and the second one is the one a `free` inside `g` would make
2885        // report.
2886        assert_eq!(lives(&func), 2);
2887    }
2888
2889    /// A function that allocates `size` bytes and never looks at what it got back.
2890    ///
2891    /// The shape `bench/safety/a-strided-column-sum.c` has. The size on its own must not answer a
2892    /// check here, because reading through what `malloc` gave back without testing it is the bug
2893    /// this compiler is for.
2894    fn untested(size: i128) -> (Interner, Func, Block, Value, Value) {
2895        let mut names = Interner::new();
2896        let name = names.intern("f");
2897        let mut func = Func::new(name, Signature::new().with_params(&[Type::int(64)]));
2898        let block = func.create_block();
2899        let index = func.append_param(block, Type::int(64));
2900        let mut build = Builder::new(&mut func, block);
2901        let signature = build.func().add_signature(
2902            Signature::new().with_params(&[Type::int(64)]).with_returns(&[Type::PTR]),
2903        );
2904        let bytes = build.iconst(Type::int(64), size);
2905        let call = build.call(names.intern("malloc"), signature, &[bytes]);
2906        let at = build.func();
2907        at[call].flags |= Flags::HEAP;
2908        let pointer = at[call].results().next().expect("a call that gives back a pointer");
2909        (names, func, block, pointer, index)
2910    }
2911
2912    #[test]
2913    fn a_walk_by_a_step_the_ranges_bound_inside_an_allocation_goes() {
2914        // The first half of tamnd/rucc#880. The step is not a constant, so the walk stops at the
2915        // `ptr_add` and what answers the check has to be asked of the range of addresses it can
2916        // reach. That range is nought to seven plus the four bytes the access wants, all of it
2917        // inside the sixteen the call says it made, and the branch on null is what makes the
2918        // sixteen true here.
2919        let (_, mut func, inside, _, pointer, index) = allocation(16);
2920        let mut build = Builder::new(&mut func, inside);
2921        let step = low_bits(&mut build, index, 7);
2922        let at = walk(&mut build, pointer, step);
2923        check(&mut build, at, 4);
2924        build.ret(&[]);
2925        let stats = run(&mut func);
2926        assert_eq!(checks(&func), 0);
2927        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 1);
2928    }
2929
2930    #[test]
2931    fn a_walk_by_a_step_that_can_leave_an_allocation_stays() {
2932        // The same function with the mask widened. Nought to thirty one plus four bytes runs off
2933        // the end of sixteen, and the bytes past the end are what the check is for.
2934        let (_, mut func, inside, _, pointer, index) = allocation(16);
2935        let mut build = Builder::new(&mut func, inside);
2936        let step = low_bits(&mut build, index, 31);
2937        let at = walk(&mut build, pointer, step);
2938        check(&mut build, at, 4);
2939        build.ret(&[]);
2940        let stats = run(&mut func);
2941        assert_eq!(checks(&func), 1);
2942        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 0);
2943    }
2944
2945    #[test]
2946    fn a_derivation_by_a_step_the_ranges_bound_inside_an_allocation_goes() {
2947        // The same for the derivation check, which is the one the column sum is left with. Both
2948        // ends have to be inside and inside the same object: the near end is the pointer itself and
2949        // the far end is anywhere in nought to seven past it.
2950        let (_, mut func, inside, _, pointer, index) = allocation(16);
2951        let mut build = Builder::new(&mut func, inside);
2952        let step = low_bits(&mut build, index, 7);
2953        let at = walk(&mut build, pointer, step);
2954        deriv(&mut build, pointer, at, 1);
2955        build.ret(&[]);
2956        let stats = run(&mut func);
2957        assert_eq!(derivs(&func), 0);
2958        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_MADE), 1);
2959    }
2960
2961    #[test]
2962    fn a_walk_into_an_allocation_nobody_tested_stays() {
2963        // The other half of the rule, which this does not weaken. A program that walks into what
2964        // `malloc` gave back without ever looking at it is a program that reads through null when
2965        // the allocation fails, and the checks are what report it.
2966        let (_, mut func, block, pointer, index) = untested(16);
2967        let mut build = Builder::new(&mut func, block);
2968        let step = low_bits(&mut build, index, 7);
2969        let at = walk(&mut build, pointer, step);
2970        check(&mut build, at, 4);
2971        deriv(&mut build, pointer, at, 1);
2972        build.ret(&[]);
2973        let stats = run(&mut func);
2974        assert_eq!(checks(&func), 1);
2975        assert_eq!(derivs(&func), 1);
2976        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_MADE), 0);
2977        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_DERIV_MADE), 0);
2978    }
2979
2980    #[test]
2981    fn a_check_every_caller_hands_in_goes_across_a_call() {
2982        // The reason the flag is worth having at all. A frame slot of the caller is not something
2983        // the callee's own callees can free, so the fact does not die at a call the way a fact
2984        // from a check that ran does.
2985        let (mut names, mut func, block, pointer) = blank();
2986        let mut build = Builder::new(&mut func, block);
2987        access(&mut build, pointer, 4);
2988        let signature = build.func().add_signature(Signature::new());
2989        build.call(names.intern("g"), signature, &[]);
2990        access(&mut build, pointer, 4);
2991        build.ret(&[]);
2992        flagged(&mut func, Flags::HANDED);
2993        let stats = run(&mut func);
2994        assert_eq!(checks(&func), 0);
2995        assert_eq!(lives(&func), 0);
2996        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_HANDED), 2);
2997        assert_eq!(stats.count(Kind::Optimized, super::REMOVED_LIVE_HANDED), 2);
2998    }
2999
3000    #[test]
3001    fn a_check_inside_a_global_goes_across_a_call() {
3002        // A callee can free what a global points at and cannot free the global, which lives as
3003        // long as the program does. So this is the one fact besides a local that a call leaves
3004        // standing, and it is read off the instruction rather than out of the scope for that
3005        // reason.
3006        let (mut names, mut func, block, pointer) = blank();
3007        let mut build = Builder::new(&mut func, block);
3008        let callee = names.intern("might_free");
3009        let signature = build.func().add_signature(Signature::new());
3010        build.call(callee, signature, &[]);
3011        access(&mut build, pointer, 4);
3012        build.ret(&[]);
3013        marked(&mut func);
3014        let stats = run(&mut func);
3015        assert_eq!(checks(&func), 0);
3016        assert_eq!(lives(&func), 0);
3017        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL), 0);
3018        assert_eq!(stats.count(Kind::Missed, super::PAST_A_CALL_LIVE), 0);
3019    }
3020
3021    #[test]
3022    fn a_check_the_module_marked_costs_fuel_like_any_other() {
3023        // A discharge is a discharge whatever established the fact, so `-fpass-fuel` has to stop
3024        // this one too or a bisection would step over it.
3025        let (_, mut func, block, pointer) = blank();
3026        let mut build = Builder::new(&mut func, block);
3027        access(&mut build, pointer, 4);
3028        build.ret(&[]);
3029        marked(&mut func);
3030        let stats =
3031            DISCHARGE.run(&mut func, &mut crate::machine::fixtures::analyses(), &mut Fuel::of(1));
3032        assert_eq!(checks(&func) + lives(&func), 1);
3033        assert_eq!(stats.count(Kind::Missed, super::NO_FUEL_LIVE), 1);
3034    }
3035
3036    #[test]
3037    fn a_walk_whose_two_ends_are_off_two_pointers_with_no_ranges_says_the_same() {
3038        // Nothing in this function steps by a value, so the ranges are never built and the answer
3039        // has to come out of the constant reader alone. That reader stopped for one reason, and it
3040        // is the same reason.
3041        let (_, mut func, block, pointer) = blank();
3042        let other = func.append_param(block, Type::PTR);
3043        let mut build = Builder::new(&mut func, block);
3044        let at = past(&mut build, other, 8);
3045        deriv(&mut build, pointer, at, 4);
3046        build.ret(&[]);
3047        let stats = run(&mut func);
3048        assert_eq!(derivs(&func), 1);
3049        assert_eq!(stats.count(Kind::Missed, super::TWO_BASES_DERIV), 1);
3050    }
3051
3052    #[test]
3053    fn a_walk_whose_two_ends_are_off_two_pointers_says_so() {
3054        // Nothing comparable to ask about. Both ends are readable and each is somewhere inside
3055        // something, and two facts of that shape say nothing at all about it being one something,
3056        // which is the only thing a derivation check wants to know.
3057        let (_, mut func, block, pointer, index) = indexed();
3058        let other = func.append_param(block, Type::PTR);
3059        let mut build = Builder::new(&mut func, block);
3060        let step = low_bits(&mut build, index, 7);
3061        let at = walk(&mut build, other, step);
3062        deriv(&mut build, pointer, at, 4);
3063        build.ret(&[]);
3064        let stats = run(&mut func);
3065        assert_eq!(derivs(&func), 1);
3066        assert_eq!(stats.count(Kind::Missed, super::TWO_BASES_DERIV), 1);
3067    }
3068
3069    #[test]
3070    fn a_walk_off_a_pointer_this_function_was_handed_says_so() {
3071        // The largest pile after a loaded pointer, 1321 checks on SQLite. Everything about the
3072        // shape is readable: one base, a step the ranges bound, both ends off that base. What is
3073        // missing is how many bytes belong to the object, and a pointer that arrived as a
3074        // parameter is one nothing in the function can say that about. Section 7.5's summaries are
3075        // what would.
3076        let (_, mut func, block, pointer, index) = indexed();
3077        let mut build = Builder::new(&mut func, block);
3078        let step = low_bits(&mut build, index, 7);
3079        let at = walk(&mut build, pointer, step);
3080        deriv(&mut build, pointer, at, 4);
3081        build.ret(&[]);
3082        let stats = run(&mut func);
3083        assert_eq!(derivs(&func), 1);
3084        assert_eq!(stats.count(Kind::Missed, super::NO_EXTENT_HANDED), 1);
3085    }
3086
3087    #[test]
3088    fn a_walk_off_a_pointer_this_function_loaded_says_so() {
3089        // The largest pile of the lot, 2155 checks on SQLite, and the shape is `p->field[i]`. The
3090        // extent of what a pointer in memory points at is not written down anywhere the compiler
3091        // can see today, which is what `__counted_by` and the type plane are for.
3092        let (_, mut func, block, pointer, index) = indexed();
3093        let mut build = Builder::new(&mut func, block);
3094        let info = MemInfo {
3095            size: 8,
3096            align: 8,
3097            order: MemOrder::NotAtomic,
3098            tbaa: None,
3099            owns: 0,
3100            restrict: Restrict::NONE,
3101        };
3102        let args = build.func().push_values(&[pointer]);
3103        let extra = Extra::Mem(build.func().add_mem(info));
3104        let held = build.value(InstData { args, extra, ..InstData::new(Opcode::Load) }, Type::PTR);
3105        let step = low_bits(&mut build, index, 7);
3106        let at = walk(&mut build, held, step);
3107        deriv(&mut build, held, at, 4);
3108        build.ret(&[]);
3109        let stats = run(&mut func);
3110        assert_eq!(derivs(&func), 1);
3111        assert_eq!(stats.count(Kind::Missed, super::NO_EXTENT_LOADED), 1);
3112    }
3113
3114    #[test]
3115    fn a_walk_off_a_global_says_so() {
3116        // 485 checks on SQLite, and the one pile of the four where somebody does know the answer.
3117        // A global's extent is on the module, `crate::extents` reads it and writes the fact onto
3118        // every check it can settle before the pipeline starts, and it cannot settle this one
3119        // because it runs before anything has put a number on the index. See tamnd/rucc#878.
3120        let (mut names, mut func, block, _, index) = indexed();
3121        let mut build = Builder::new(&mut func, block);
3122        let extra = Extra::Symbol(names.intern("g"));
3123        let base = build.value(InstData { extra, ..InstData::new(Opcode::GlobalAddr) }, Type::PTR);
3124        let step = low_bits(&mut build, index, 7);
3125        let at = walk(&mut build, base, step);
3126        deriv(&mut build, base, at, 4);
3127        build.ret(&[]);
3128        let stats = run(&mut func);
3129        assert_eq!(derivs(&func), 1);
3130        assert_eq!(stats.count(Kind::Missed, super::NO_EXTENT_GLOBAL), 1);
3131    }
3132
3133    #[test]
3134    fn a_walk_off_a_pointer_the_check_does_not_name_stays() {
3135        // The capability has to be the `cap_of` of the pointer that went in. One naming something
3136        // else is asking about a different instance and is not this pass's to answer.
3137        let (_, mut func, block, pointer) = blank();
3138        let mut build = Builder::new(&mut func, block);
3139        check(&mut build, pointer, 16);
3140        let field = past(&mut build, pointer, 8);
3141        let args = build.func().push_values(&[field]);
3142        let capability = build.value(InstData { args, ..InstData::new(Opcode::CapOf) }, Type::CAP);
3143        let width = build.iconst(Type::int(64), 4);
3144        let args = build.func().push_values(&[capability, pointer, field, width]);
3145        build.inst(InstData { args, ..InstData::new(Opcode::CheckDeriv) }, &[]);
3146        build.ret(&[]);
3147        let stats = run(&mut func);
3148        assert_eq!(derivs(&func), 1);
3149        assert_eq!(stats.count(Kind::Missed, super::NOT_ITS_CAPABILITY_DERIV), 1);
3150    }
3151}