rucc_opt/scev.rs
1//! Scalar evolution: how a value changes across the iterations of a loop, and how many
2//! iterations there are.
3//!
4//! Design: `spec/optimizer/07-loops-and-scev.md` sections 7.4 through 7.7. This is the second
5//! half of document 07 and it answers the last two of the four questions section 7.6 says loop
6//! analysis exists for. The first two are in [`crate::loops`].
7//!
8//! # Chains of recurrences, and how much of one
9//!
10//! GCC writes how a value changes as a chain of recurrences, `{base, +, step}`, meaning a value
11//! that is `base` on the first iteration and `step` more on each one after. The representation is
12//! good because it is closed under the operations anyone wants: adding two chrecs of the same
13//! loop adds componentwise, multiplying by something invariant scales both parts, and evaluating
14//! one at a given iteration is arithmetic rather than a special case. That closure is why
15//! `j = 2 * i + 3` is as easy as `i = i + 1`, and pattern matching the second would run out of
16//! road on the first.
17//!
18//! Section 7.4 says what rucc builds and it is a subset: affine chrecs only. A value is
19//! invariant, or `{base, +, step}` with both parts invariant, or unknown. Addition, subtraction,
20//! multiplication by an invariant, shifting by a constant, and extension where the extension
21//! provably does not wrap. Nothing polynomial and nothing mutually recursive. That covers every
22//! induction variable a C programmer writes and every array subscript document 31 could use, and
23//! what it leaves out of GCC's four thousand lines is the part serving Fortran and the polyhedral
24//! framework.
25//!
26//! The one extension past affine is pointer chrecs, because C loops walk pointers and `p = p + 1`
27//! is `i = i + 1` with a scale. A `ptr_add` is addition with the byte offset as the step, which
28//! is the difference between analysing half of real C loops and analysing nearly all of them.
29//!
30//! # Trip counts, and the part that is uncomfortable
31//!
32//! Given an exit that compares an affine chrec against something invariant, solving for the
33//! iteration at which the comparison first fails is arithmetic. What makes it hard is that the
34//! answer is almost always conditional: on the loop being entered at all, and on the induction
35//! variable not wrapping before it gets there. Section 7.5 says a trip count returned without its
36//! assumptions is a miscompilation generator, and that the temptation to return one is strong
37//! because the assumptions are usually true.
38//!
39//! So [`Bound`] carries them and there is no way to read the count without seeing them.
40//! [`Bound::parts`] hands back both, and [`Bound::proven`] hands back the count only when there
41//! is nothing left to prove. A caller that means to emit a runtime check reads the assumptions
42//! and emits it, and a caller that forgets cannot get at the number.
43//!
44//! [`Bound`] and [`Estimate`] are different types on purpose. A bound is used for correctness, an
45//! estimate is used to decide whether a transformation is worth doing, and section 7.5 calls
46//! conflating them a category error that costs correctness. GCC keeps them apart as
47//! `max_loop_iterations` and `estimate_numbers_of_iterations` and the names do not stop anyone.
48//! Different structs do.
49
50use std::collections::HashMap;
51
52use rucc_base::Symbol;
53use rucc_ir::{Block, Def, Extra, Flags, Func, Imm, Inst, IntPred, Opcode, Type, Value};
54
55use crate::cfg::Cfg;
56use crate::loops::{LoopId, Loops};
57
58/// How deep the search for a step walks back through arithmetic.
59///
60/// The chain from a header parameter to the value fed back to it is two or three instructions in
61/// anything a person writes, and the walk terminates on its own because SSA has no cycles except
62/// through block parameters. The limit is here so a generated function with a thousand additions
63/// in the increment costs a bounded amount rather than a stack.
64const STEP_LIMIT: u32 = 16;
65
66/// How many blocks that do nothing but pass a value on the walk reads through.
67///
68/// One is what a canonicalized loop has. The limit is here for the same reason the one above is,
69/// which is that a generated function can have a chain of them and the cost of following it should
70/// not depend on how long somebody made it.
71const FORWARD_LIMIT: u32 = 8;
72
73/// How many times a loop is assumed to run when nothing better is known.
74///
75/// GCC's `--param avg-loop-niter`, whose default is the same number. It is a guess, so nothing may
76/// rest on it. It reaches [`Estimate`], which is only ever used to decide whether something is
77/// worth doing, and [`crate::split`], which spends it on how far to ask the runtime to look and is
78/// answered with a true count of bytes whatever it asked for.
79pub(crate) const ASSUMED_ITERATIONS: u64 = 10;
80
81/// A value that does not change inside the loop, read as `on + scale * value + offset`.
82///
83/// The `value` is a value defined outside the loop, or `None` when the linear part is a plain
84/// number. Keeping the shape rather than a bare [`Value`] is what lets `j = 2 * i + 3` come out
85/// as `{3, +, 2}` instead of unknown: the base and the step of that chrec are expressions nothing
86/// in the function computes, so a representation that could only name existing values would have
87/// to give up.
88///
89/// The `on` is a second symbol, and it is there for one shape: a pointer plus an index the loop
90/// did not start at zero. `a[i]` with `i` starting at a parameter has a first address of
91/// `a + start * 4`, which is two symbols, and a representation with room for one has to answer
92/// unknown to it. Nothing scales `on` and nothing negates it, because the thing it was added for
93/// is a pointer and a pointer is not something a loop multiplies. It is an [`Anchor`] rather than
94/// a value so that the address of a global can be one of them.
95///
96/// The `read` is the other half of the same shape, since in C that index is an `int` and what
97/// reaches the address is `sext(start)`. It is described rather than named, for the reason on
98/// [`Widening`]. The two together are what let `a[start + i]` be followed, and on the SQLite
99/// amalgamation they take 158 checks and 12 sites off the largest row of loop splitting's census.
100/// See tamnd/rucc#810.
101///
102/// Arithmetic on two of these is refused once the sum would need a third symbol, because
103/// `x + y + z` is not of this shape. That is the boundary of the subset and it is where the answer
104/// becomes unknown rather than wrong.
105///
106/// The fields are private on purpose. Every reader has to go through [`Invariant::plain`], which
107/// hands back the one symbol reading and refuses when there is a pointer in it, or through
108/// [`Invariant::on`], which hands back both halves. A reader that helped itself to `value` and
109/// `scale` would quietly drop the `on` and build an address off the wrong object.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct Invariant {
112 /// A second symbol the whole expression is measured from, or `None`. Always one of it.
113 on: Option<Anchor>,
114 /// What the linear part is built on, or `None` for a plain number.
115 value: Option<Value>,
116 /// How that value is read, when it is read at a width that is not its own.
117 read: Option<Widening>,
118 /// How many of it.
119 scale: i128,
120 /// What is added.
121 offset: i128,
122}
123
124/// What an expression is measured from.
125///
126/// Usually a value the function computed somewhere outside the loop, which whoever reads the
127/// invariant can name. Sometimes the address of a global, which nothing has to compute because it
128/// is settled at link time and is the same number everywhere in the program.
129///
130/// The second one is here because of where a `global_addr` sits. [`crate::licm`] gives it a cost of
131/// zero and so never moves it out of a loop, which is the right call: working the address out again
132/// is one instruction and holding it in a register across a loop is a register. But that leaves the
133/// instruction inside the loop, and [`Loops::is_invariant`] answers by where a value is defined, so
134/// `a[i]` on a file scope `a` came out unknown. Describing the address rather than naming a value
135/// is the same move [`Widening`] makes, and it means a reader that wants the address in front of
136/// the loop writes another `global_addr` there for the one instruction it costs. On the SQLite
137/// amalgamation that is 178 checks at 47 sites of loop splitting's largest census row.
138/// See tamnd/rucc#810.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum Anchor {
141 /// A value, which is defined outside the loop and so can be named where it is wanted.
142 Value(Value),
143 /// The address of a global, which is written again wherever it is wanted.
144 Address(Symbol),
145}
146
147impl Anchor {
148 /// The value, when it is one. `None` for an address, which no value names.
149 #[must_use]
150 pub fn value(self) -> Option<Value> {
151 match self {
152 Self::Value(value) => Some(value),
153 Self::Address(_) => None,
154 }
155 }
156}
157
158/// A value read at a type wider than its own.
159///
160/// Widening `{start, +, 1}` in `int` gives `{sext(start), +, 1}` in `long`, and `sext(start)` is an
161/// expression nothing in the function computes. A representation that could only name values had
162/// to refuse the whole widening on that account, which is what shut the door on a walk from an
163/// index the caller handed in, because in C that index is an `int`. So the extension is described
164/// rather than named and whoever builds code from the invariant emits it.
165///
166/// The value stays the narrow one. Reading it at a third width later is an extension of an
167/// extension, and the two collapse into one wherever they mean the same thing, which is everywhere
168/// except a zero extension read as signed afterwards.
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub struct Widening {
171 /// Sign extended or zero extended.
172 pub reading: Reading,
173 /// The type it is read at, which is wider than the value's own.
174 pub to: Type,
175}
176
177/// An invariant with no second symbol in it, read as `scale * value + offset`.
178///
179/// What every reader but [`crate::split`] wants, and what every reader wanted before there was an
180/// `on` at all. [`Invariant::plain`] is the only way to one, so a reader that does not know about
181/// the second symbol cannot get an expression that has one.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub struct Plain {
184 /// What it is built on, or `None` for a plain number.
185 pub value: Option<Value>,
186 /// How that value is read, when it is read at a width that is not its own.
187 pub read: Option<Widening>,
188 /// How many of it.
189 pub scale: i128,
190 /// What is added to it.
191 pub offset: i128,
192}
193
194impl Invariant {
195 /// A plain number.
196 #[must_use]
197 pub fn number(offset: i128) -> Self {
198 Self { on: None, value: None, read: None, scale: 0, offset }
199 }
200
201 /// One of a value.
202 #[must_use]
203 pub fn of(value: Value) -> Self {
204 Self { on: None, value: Some(value), read: None, scale: 1, offset: 0 }
205 }
206
207 /// So many of a value, plus a number.
208 #[must_use]
209 pub fn scaled(value: Value, scale: i128, offset: i128) -> Self {
210 Self { on: None, value: Some(value), read: None, scale, offset }
211 }
212
213 /// The address of a global.
214 ///
215 /// It goes straight into the `on` slot rather than into `value`, because that slot is the one
216 /// for the thing an address is measured from and an address is the only thing this ever is.
217 /// Nothing scales it and nothing negates it, which the rest of the arithmetic here already
218 /// refuses for whatever is in that slot.
219 #[must_use]
220 pub fn address(symbol: Symbol) -> Self {
221 Self { on: Some(Anchor::Address(symbol)), value: None, read: None, scale: 0, offset: 0 }
222 }
223
224 /// The one symbol reading, and `None` when there is a second symbol in it.
225 #[must_use]
226 pub fn plain(self) -> Option<Plain> {
227 self.on.is_none().then_some(Plain {
228 value: self.value,
229 read: self.read,
230 scale: self.scale,
231 offset: self.offset,
232 })
233 }
234
235 /// What it is measured from and how far past that, when there is a second symbol in it.
236 ///
237 /// Exactly one of this and [`Invariant::plain`] answers, so a reader that handles both has
238 /// handled every invariant there is.
239 #[must_use]
240 pub fn on(self) -> Option<(Anchor, Plain)> {
241 let on = self.on?;
242 Some((
243 on,
244 Plain { value: self.value, read: self.read, scale: self.scale, offset: self.offset },
245 ))
246 }
247
248 /// What it is measured from, when anything, and the rest of it with that taken off.
249 ///
250 /// For a reader that has to cancel the thing two expressions are measured from before it can
251 /// do arithmetic on what is left, which [`Invariant::minus`] will not do on its own because
252 /// it has no way to know the two are the same object.
253 #[must_use]
254 pub fn loose(self) -> (Option<Anchor>, Self) {
255 (self.on, Self { on: None, ..self })
256 }
257
258 /// Whether the two are the same expression apart from the number added to them.
259 #[must_use]
260 pub fn alike(self, other: Self) -> bool {
261 self.on == other.on
262 && self.value == other.value
263 && self.read == other.read
264 && self.scale == other.scale
265 }
266
267 /// The number added to it, whatever else it has in it.
268 #[must_use]
269 pub fn offset(self) -> i128 {
270 self.offset
271 }
272
273 /// The number this is, when it is one.
274 #[must_use]
275 pub fn as_number(self) -> Option<i128> {
276 (self.on.is_none() && self.symbol().is_none()).then_some(self.offset)
277 }
278
279 /// Whether this is the number zero.
280 #[must_use]
281 pub fn is_zero(self) -> bool {
282 self.as_number() == Some(0)
283 }
284
285 /// The value the linear part is built on, when the linear part has one.
286 fn symbol(self) -> Option<Value> {
287 if self.scale == 0 { None } else { self.value }
288 }
289
290 /// This as something to measure from, when it is one of a value and a number.
291 ///
292 /// Never a widened one. What an expression is measured from is a pointer, and a pointer is not
293 /// something anything here extends.
294 fn measure(self) -> Option<Anchor> {
295 (self.on.is_none() && self.read.is_none() && self.scale == 1)
296 .then_some(self.value)
297 .flatten()
298 .map(Anchor::Value)
299 }
300
301 /// The symbol both linear parts are built on and how it is read, when they agree on one or one
302 /// of them has none.
303 ///
304 /// The same value read two ways is two different numbers, so agreeing on the value is not
305 /// enough. `sext(x)` and `zext(x)` are the same bits and not the same quantity.
306 fn shared(self, other: Self) -> Option<(Option<Value>, Option<Widening>)> {
307 match (self.symbol(), other.symbol()) {
308 (None, _) => Some((other.value, other.read)),
309 (_, None) => Some((self.value, self.read)),
310 (left, right) => {
311 (left == right && self.read == other.read).then_some((left, self.read))
312 }
313 }
314 }
315
316 /// This same value read at a wider type, when the widening has a form here.
317 ///
318 /// A number means the same thing at both widths under a sign extension, and under a zero
319 /// extension once it is not negative. One of a value becomes that value read through the
320 /// extension. Anything else is refused, because the narrow arithmetic may already have wrapped
321 /// and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
322 fn widened(self, reading: Reading, to: Type) -> Option<Self> {
323 if let Some(number) = self.as_number() {
324 return (reading == Reading::Signed || number >= 0).then_some(Self::number(number));
325 }
326 if self.on.is_some() || self.scale != 1 || self.offset != 0 {
327 return None;
328 }
329 let value = self.value?;
330 // An extension of an extension. A zero extension is never negative, so reading its result
331 // as signed afterwards is the same numbers and the pair collapses into the zero extension
332 // at the outer width. The other way round it does not: a sign extension of a negative
333 // number read as unsigned afterwards is a different number entirely.
334 let reading = match (self.read.map(|read| read.reading), reading) {
335 (None, outer) => outer,
336 (Some(Reading::Unsigned), _) => Reading::Unsigned,
337 (Some(Reading::Signed), Reading::Signed) => Reading::Signed,
338 (Some(Reading::Signed), Reading::Unsigned) => return None,
339 };
340 Some(Self {
341 on: None,
342 value: Some(value),
343 read: Some(Widening { reading, to }),
344 scale: 1,
345 offset: 0,
346 })
347 }
348
349 /// The two added, when the sum is of this shape.
350 #[must_use]
351 pub fn plus(self, other: Self) -> Option<Self> {
352 let offset = self.offset.checked_add(other.offset)?;
353 // At most one of the two brought something to measure from, since a sum measured from two
354 // pointers is not an address.
355 let on = match (self.on, other.on) {
356 (None, on) | (on, None) => on,
357 (Some(_), Some(_)) => return None,
358 };
359 // The linear parts are about the same symbol, or one of them is a number, so they add.
360 if let Some((value, read)) = self.shared(other) {
361 let scale = self.scale.checked_add(other.scale)?;
362 return Some(Self { on, value, read, scale, offset });
363 }
364 // Two different symbols, which is what a pointer plus an index the loop did not start at
365 // zero is. Nothing may already be measured from anything, and one of the two has to be one
366 // of a value and a number, and that one becomes what the sum is measured from.
367 if on.is_some() {
368 return None;
369 }
370 let (on, rest) = match (self.measure(), other.measure()) {
371 (Some(on), _) => (on, other),
372 (_, Some(on)) => (on, self),
373 _ => return None,
374 };
375 Some(Self { on: Some(on), value: rest.value, read: rest.read, scale: rest.scale, offset })
376 }
377
378 /// The second subtracted from the first, when the difference is of this shape.
379 #[must_use]
380 pub fn minus(self, other: Self) -> Option<Self> {
381 self.plus(other.negated()?)
382 }
383
384 /// This with its sign flipped, which needs nothing to measure from.
385 ///
386 /// A pointer is not a thing to negate, and the second symbol is only ever there because a
387 /// pointer put it there.
388 #[must_use]
389 pub fn negated(self) -> Option<Self> {
390 if self.on.is_some() {
391 return None;
392 }
393 Some(Self {
394 on: None,
395 value: self.value,
396 read: self.read,
397 scale: self.scale.checked_neg()?,
398 offset: self.offset.checked_neg()?,
399 })
400 }
401
402 /// The two multiplied, which needs one of them to be a plain number and neither to be measured
403 /// from anything.
404 #[must_use]
405 pub fn times(self, other: Self) -> Option<Self> {
406 if self.on.is_some() || other.on.is_some() {
407 return None;
408 }
409 let (symbol, by) = match (self.as_number(), other.as_number()) {
410 (Some(by), _) => (other, by),
411 (_, Some(by)) => (self, by),
412 _ => return None,
413 };
414 Some(Self {
415 on: None,
416 value: symbol.value,
417 read: symbol.read,
418 scale: symbol.scale.checked_mul(by)?,
419 offset: symbol.offset.checked_mul(by)?,
420 })
421 }
422}
423
424/// How a value changes from one iteration of a loop to the next.
425#[derive(Clone, Copy, Debug, PartialEq, Eq)]
426pub enum Evolution {
427 /// The same on every iteration.
428 Invariant(Invariant),
429 /// `{base, +, step}`: `base` the first time round and `step` more each time after.
430 Affine(Chrec),
431 /// Not something this analysis describes. Never a claim that the value does not evolve.
432 Unknown,
433}
434
435impl Evolution {
436 /// The chrec, when this is one.
437 #[must_use]
438 pub fn chrec(self) -> Option<Chrec> {
439 match self {
440 Self::Affine(chrec) => Some(chrec),
441 _ => None,
442 }
443 }
444
445 /// The invariant expression, when this is one.
446 #[must_use]
447 pub fn invariant(self) -> Option<Invariant> {
448 match self {
449 Self::Invariant(inv) => Some(inv),
450 _ => None,
451 }
452 }
453}
454
455/// An affine chain of recurrences, `{base, +, step}`, evolving in a named type.
456///
457/// The type is not decoration. `{0, +, 1}` in `unsigned char` is not the sequence `0, 1, 2, ...`,
458/// it is that sequence modulo two hundred and fifty six, and section 7.7 says this is where a
459/// naive implementation is wrong constantly and in ways that pass every test written by someone
460/// thinking in `int`. Every operation here checks the type and every one that cannot stay right
461/// in it answers unknown.
462#[derive(Clone, Copy, Debug, PartialEq, Eq)]
463pub struct Chrec {
464 /// What the value is on the first iteration.
465 pub base: Invariant,
466 /// What is added each time round.
467 pub step: Invariant,
468 /// The type it evolves in, which is what says when it wraps.
469 pub ty: Type,
470 /// What the instruction that increments it promised. `nsw` means the sequence does not wrap
471 /// when read as signed and `nuw` means it does not when read as unsigned, and both come from
472 /// the increment rather than from anything this analysis proved.
473 pub flags: Flags,
474}
475
476impl Chrec {
477 /// Whether the sequence is known not to wrap under the reading this predicate takes.
478 #[must_use]
479 pub fn does_not_wrap(self, signed: bool) -> bool {
480 self.flags.contains(if signed { Flags::NSW } else { Flags::NUW })
481 }
482}
483
484/// Something that has to be true for a trip count to be the right answer.
485///
486/// Section 7.5 asks for exactly this: not a trip count but a trip count plus a predicate under
487/// which it holds, so the consumer either proves the predicate, emits a runtime check for it, or
488/// gives up. These are the predicates.
489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
490pub enum Assumption {
491 /// The loop is entered at all, so the distance from the counter to its limit is a number that
492 /// is not negative.
493 ///
494 /// `for (i = 0; i < n; i++)` with `n` of zero runs no times and the distance is zero, but `n`
495 /// of minus one also runs no times and the distance is minus one, so a count taken from the
496 /// distance has to be told which case it is in.
497 ///
498 /// What it does not say anything about is whether the loop comes back. A counter stepping
499 /// toward a limit under an ordering test either reaches it or is already past it, and either
500 /// way that is a finite number of steps, so a caller whose question is whether the loop ends
501 /// may have this one for nothing. [`crate::hoist`] discharges it by clamping the count at zero
502 /// and [`crate::loop_delete`] by never reading the count. That is the whole of why this is a
503 /// separate assumption from [`Assumption::Approaching`] rather than the same one worded to
504 /// cover both.
505 ///
506 /// Only ever present on a symbolic count. When the distance is a number the sign of it is
507 /// there to be read, so this is settled rather than assumed.
508 Entered,
509 /// The limit is somewhere the counter is heading, which for a loop ending on `!=` is what
510 /// makes it end at all.
511 ///
512 /// A counter stepping away from its limit never arrives, and one stepping past it keeps going
513 /// until it wraps, so what is unproven here is termination rather than which number the count
514 /// is. Nothing discharges it by clamping, because there is no number to clamp when the loop
515 /// does not come back. Document 17.2 says rucc does not take out a loop that might not end,
516 /// so a pass that deletes loops refuses this one outright.
517 ///
518 /// Only ever present on a symbolic count, for the same reason [`Assumption::Entered`] is.
519 Approaching,
520 /// The induction variable does not wrap in its own type before the exit is taken.
521 ///
522 /// Present whenever the increment did not carry the matching `nsw` or `nuw` flag. With the
523 /// flag there is nothing to assume, because the flag is the promise.
524 NoWrap(Chrec),
525 /// Signed overflow is undefined here, which is what makes `for (int i = 0; i <= n; i++)`
526 /// finite.
527 ///
528 /// GCC infers loop bounds from this in `infer_loop_bounds_from_signedness`, and it is the
529 /// single most common source of a report that the compiler broke a working program. It is
530 /// recorded rather than assumed silently so that `-fwrapv` can withdraw the count and so that
531 /// a dump can name it.
532 StrictOverflow,
533}
534
535impl Assumption {
536 /// What it says, in a line, for a dump to print.
537 ///
538 /// Section 7.5 asks that every inference of this kind be dumpable and say what it rests on,
539 /// because a user who has been bitten by one deserves a command that tells them which line
540 /// the compiler used against them. This is the sentence that command prints.
541 #[must_use]
542 pub fn describe(&self) -> String {
543 match self {
544 Self::Entered => "the loop is entered at all".to_string(),
545 Self::Approaching => "the counter is heading towards its limit".to_string(),
546 Self::NoWrap(chrec) => {
547 format!("the induction variable does not wrap in i{}", chrec.ty.bits())
548 }
549 Self::StrictOverflow => {
550 "signed overflow is undefined, so -fwrapv withdraws this count".to_string()
551 }
552 }
553 }
554}
555
556/// How many iterations, as a number or as an expression.
557#[derive(Clone, Copy, Debug, PartialEq, Eq)]
558pub enum Count {
559 /// Exactly this many.
560 Exact(u128),
561 /// This many, worked out from something the loop does not change.
562 Symbolic(Invariant),
563}
564
565/// Which reading of its operands the test the count came from took.
566///
567/// It matters to anybody widening the value a symbolic count is built out of. The count is the
568/// distance to the limit of the exit test, the limit is a value of the counter's own type, and
569/// what that value means is the reading its test took. A limit past the middle of a thirty two bit
570/// type is a large number to an unsigned test and a negative one to a signed test, and a consumer
571/// that sign extends what an unsigned test compared has turned a loop over three billion elements
572/// into a loop that runs no times.
573#[derive(Clone, Copy, Debug, PartialEq, Eq)]
574pub enum Reading {
575 /// The test read its operands as signed, so widening the count means sign extending it.
576 Signed,
577 /// The test read them as unsigned, so widening the count means zero extending it.
578 Unsigned,
579}
580
581/// How many times a loop runs at most, and what that rests on.
582///
583/// For correctness. A pass that deletes an iteration, peels one off, or decides a memory access
584/// is in bounds needs one of these. The count cannot be read without the assumptions, which is
585/// section 7.7's defence against a caller proving two of three and forgetting the third.
586#[derive(Clone, Debug, PartialEq, Eq)]
587pub struct Bound {
588 count: Count,
589 assumptions: Vec<Assumption>,
590 reading: Reading,
591}
592
593impl Bound {
594 /// The count and everything it rests on, together, because they cannot be asked for apart.
595 #[must_use]
596 pub fn parts(&self) -> (Count, &[Assumption]) {
597 (self.count, &self.assumptions)
598 }
599
600 /// How the value a symbolic count is built out of has to be read.
601 ///
602 /// Meaningless on a count that is a number, since a number has already been read.
603 #[must_use]
604 pub fn reading(&self) -> Reading {
605 self.reading
606 }
607
608 /// What has to be proved before the count means anything.
609 #[must_use]
610 pub fn assumptions(&self) -> &[Assumption] {
611 &self.assumptions
612 }
613
614 /// The count, for a caller with nothing left to prove.
615 ///
616 /// `None` does not mean the count is unknown. It means there are assumptions and this is not
617 /// the accessor for reading a count that has them.
618 #[must_use]
619 pub fn proven(&self) -> Option<Count> {
620 self.assumptions.is_empty().then_some(self.count)
621 }
622
623 /// The count, for a caller compiling a language where signed overflow is undefined.
624 ///
625 /// [`Bound::proven`] answers nothing for any `for (int i = 0; i < n; i++)` in any C program,
626 /// because `solve` puts [`Assumption::StrictOverflow`] on every count taken from a signed
627 /// test, and a pass built on `proven` alone is a pass that never fires. What that assumption
628 /// says is that the count rests on signed overflow being undefined, and `-fwrapv` is
629 /// implemented in `rucc-lower` by not setting `nsw` rather than by a flag anything down here
630 /// reads. So an increment that still carries `nsw` under `-fwrapv` does not exist, and a bound
631 /// with `StrictOverflow` and nothing else on it is a bound whose counter the front end
632 /// promised does not wrap. That promise is exactly what the assumption wanted.
633 ///
634 /// [`Assumption::NoWrap`] is the case where there is no such promise, and it is refused here.
635 /// So are [`Assumption::Entered`] and [`Assumption::Approaching`], though only in passing,
636 /// because neither ever appears on a count that is a number.
637 #[must_use]
638 pub fn under_undefined_overflow(&self) -> Option<Count> {
639 self.assumptions
640 .iter()
641 .all(|rests_on| matches!(rests_on, Assumption::StrictOverflow))
642 .then_some(self.count)
643 }
644
645 /// The count, for a caller that needs the loop to come back and not how many times.
646 ///
647 /// One assumption wider than [`Bound::under_undefined_overflow`], and the one it adds is
648 /// [`Assumption::Entered`]. What that says is whether the count is the distance to the limit
649 /// or zero, and both of those are numbers of iterations the loop has, so a pass asking whether
650 /// the loop ends has already been answered whichever way it goes. A pass multiplying by the
651 /// count has not, which is why this is a second accessor and not a loosening of the first.
652 ///
653 /// [`Assumption::Approaching`] is refused, and telling those two apart is the reason they are
654 /// two assumptions. A loop ending on `!=` whose counter steps past its limit runs until it
655 /// wraps, document 17.2 is explicit that rucc does not take out a loop that might not end, and
656 /// a count that comes back from here is one no caller has to check that against.
657 #[must_use]
658 pub fn comes_back(&self) -> Option<Count> {
659 self.assumptions
660 .iter()
661 .all(|rests_on| matches!(rests_on, Assumption::StrictOverflow | Assumption::Entered))
662 .then_some(self.count)
663 }
664}
665
666/// How many times a loop probably runs.
667///
668/// For cost decisions and never for correctness. A pass asking whether unrolling pays for itself
669/// wants one of these, and it is fine for the answer to be a guess, because being wrong makes the
670/// code slower rather than wrong. Nothing here can be turned into a [`Bound`].
671#[derive(Clone, Copy, Debug, PartialEq, Eq)]
672pub struct Estimate {
673 iterations: u64,
674 guessed: bool,
675}
676
677impl Estimate {
678 /// The number to do arithmetic with.
679 #[must_use]
680 pub fn iterations(self) -> u64 {
681 self.iterations
682 }
683
684 /// Whether nothing was known and this is the default.
685 #[must_use]
686 pub fn is_guess(self) -> bool {
687 self.guessed
688 }
689}
690
691/// An exit test, read so that the loop keeps going while it holds.
692///
693/// Not public. It is the shape [`Scev::bound_at`] and [`Scev::holds`] both want out of the same
694/// branch, and what either of them says about it is what the outside sees.
695#[derive(Clone, Copy, Debug)]
696struct Test {
697 /// The side that moves, with the predicate already turned round to put it on the left.
698 chrec: Chrec,
699 /// The side that does not.
700 limit: Invariant,
701 /// The comparison that has to hold for the loop to go round again.
702 pred: IntPred,
703 /// Whether every iteration that goes round asks it.
704 each: bool,
705}
706
707/// The analysis, which works out an answer when asked and remembers it.
708///
709/// Demand driven and memoized, per section 7.8, because the cost of scalar evolution is a
710/// function of how many distinct values get asked about rather than of the size of the function.
711/// The cache holds one loop's worth of answers per loop and the whole thing is thrown away when
712/// anything about the loops changes, which per document 04.4 is any pass that touches one. It is
713/// kept as one table per loop rather than one table keyed by both, because `Scev::holds` empties a
714/// loop's answers once for every loop, and picking them out of a single table was a walk over the
715/// answers for every loop each time. In a function of two thousand loops that walk was most of
716/// what the analysis cost.
717#[derive(Debug)]
718pub struct Scev<'a> {
719 func: &'a Func,
720 cfg: &'a Cfg,
721 loops: &'a Loops,
722 known: HashMap<LoopId, HashMap<Value, Evolution>>,
723 held: HashMap<LoopId, Option<Chrec>>,
724}
725
726impl<'a> Scev<'a> {
727 /// A fresh analysis over these loops, knowing nothing yet.
728 #[must_use]
729 pub fn new(func: &'a Func, cfg: &'a Cfg, loops: &'a Loops) -> Self {
730 Self { func, cfg, loops, known: HashMap::new(), held: HashMap::new() }
731 }
732
733 /// How this value changes across the iterations of this loop.
734 ///
735 /// The way in, and what it does before answering is settle `Scev::holds` for the loop. That has
736 /// to happen out here rather than at the point `Scev::extend` wants it, because settling it
737 /// means asking about other values and `Scev::at` parks a marker on the value it is working on.
738 /// Asked from in there, the answer would depend on what was already in flight.
739 pub fn evolution(&mut self, id: LoopId, value: Value) -> Evolution {
740 self.holds(id);
741 self.at(id, value)
742 }
743
744 /// How this value changes, with the loop's own facts already settled.
745 fn at(&mut self, id: LoopId, value: Value) -> Evolution {
746 if let Some(&known) = self.known.get(&id).and_then(|answers| answers.get(&value)) {
747 return known;
748 }
749 // Unknown while the answer is being worked out, so the cycle from a header parameter back
750 // to itself terminates instead of asking the same question forever. Anything that reaches
751 // the parameter again gets unknown and the shape it was matching fails, which is the
752 // right answer for a value defined in terms of itself through arithmetic this does not
753 // describe.
754 self.known.entry(id).or_default().insert(value, Evolution::Unknown);
755 let found = self.compute(id, value);
756 self.known.entry(id).or_default().insert(value, found);
757 found
758 }
759
760 /// How many times this loop runs at most, and what that rests on.
761 ///
762 /// Any one exit gives a valid upper bound, because a loop cannot run more times than the
763 /// first exit that fires, so this takes the first exit it can solve rather than the smallest.
764 /// That is `max_loop_iterations` and not `estimate_numbers_of_iterations`, which is why the
765 /// answer is a [`Bound`].
766 pub fn bound(&mut self, id: LoopId) -> Option<Bound> {
767 self.holds(id);
768 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
769 exits.into_iter().find_map(|from| self.bound_at(id, from))
770 }
771
772 /// The counter an exit test of this loop keeps inside its own type, when there is one.
773 ///
774 /// [`bounded_by_its_test`] is the argument and this is where its answer is written down as a
775 /// fact about the loop rather than spent on one trip count. What it buys is [`Scev::extend`]:
776 /// an unsigned counter carries no `nuw`, so widening anything built out of one used to be
777 /// refused, and the test that holds the counter holds everything walking beside it.
778 ///
779 /// Settled once per loop and then read. It is settled from [`Scev::evolution`] and
780 /// [`Scev::bound`], which are the two ways in, so that it is worked out with nothing in flight.
781 /// The cache for the loop is emptied afterwards, because the answers already in it were worked
782 /// out while this was still unknown and a conservative answer that stayed would make what the
783 /// analysis says depend on which question was asked first.
784 fn holds(&mut self, id: LoopId) -> Option<Chrec> {
785 if let Some(&known) = self.held.get(&id) {
786 return known;
787 }
788 // Unknown while it is being worked out, which is what stops the recursion below from
789 // asking the same question forever, and which is why the cache is emptied after.
790 self.held.insert(id, None);
791 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
792 let found = exits.into_iter().find_map(|from| {
793 let test = self.test_at(id, from)?;
794 let step = test.chrec.step.as_number()?;
795 (test.each && bounded_by_its_test(test.pred, step)).then_some(test.chrec)
796 });
797 self.held.insert(id, found);
798 self.known.remove(&id);
799 found
800 }
801
802 /// How many times this loop probably runs.
803 pub fn estimate(&mut self, id: LoopId) -> Estimate {
804 match self.bound(id).map(|bound| bound.count) {
805 Some(Count::Exact(exact)) => {
806 Estimate { iterations: u64::try_from(exact).unwrap_or(u64::MAX), guessed: false }
807 }
808 _ => Estimate { iterations: ASSUMED_ITERATIONS, guessed: true },
809 }
810 }
811
812 /// The evolution of a value nothing is known about yet.
813 fn compute(&mut self, id: LoopId, value: Value) -> Evolution {
814 if let Some(invariant) = self.invariant(id, value) {
815 return Evolution::Invariant(invariant);
816 }
817 match self.func[value].def {
818 Def::Param { block, index } if block == self.loops.header(id) => {
819 self.at_header(id, value, index as usize)
820 }
821 // A parameter of a block inside the loop that is not the header takes a different
822 // value depending on which way control came, and describing that is a job for the
823 // value range work of document 10 rather than for a chrec. Unless there is only one
824 // way in, in which case it does not.
825 Def::Param { .. } => match self.forwarded(value) {
826 same if same == value => Evolution::Unknown,
827 through => self.at(id, through),
828 },
829 Def::Result { inst, .. } => self.at_inst(id, inst, value),
830 }
831 }
832
833 /// The value as an expression that does not change inside the loop, if it is one.
834 fn invariant(&self, id: LoopId, value: Value) -> Option<Invariant> {
835 if let Some((imm, ty)) = constant(self.func, value) {
836 return Some(Invariant::number(imm.signed(ty)));
837 }
838 // A constant is invariant wherever it sits, which is why it is asked about first. Anything
839 // else has to be defined outside the loop.
840 if self.loops.is_invariant(self.func, id, value) {
841 return Some(Invariant::of(value));
842 }
843 // Except the address of a global, which is a link time constant and so does not change
844 // inside a loop wherever it is written. Asked after the question above and not instead of
845 // it, so that a `global_addr` already sitting outside the loop stays a value every reader
846 // can name, and this arm is only the case that used to come out unknown. See [`Anchor`].
847 symbol(self.func, value).map(Invariant::address)
848 }
849
850 /// The evolution of a parameter of the loop header, which is where an induction variable is.
851 ///
852 /// The parameter takes one value on the way in and another on the way round, which is what
853 /// other IRs spell as a phi node. If the way round is the parameter plus something invariant,
854 /// the parameter is an affine chrec and that something is its step.
855 fn at_header(&mut self, id: LoopId, value: Value, index: usize) -> Evolution {
856 let (func, cfg, loops) = (self.func, self.cfg, self.loops);
857 let header = loops.header(id);
858 // Section 7.3 wants exactly one latch and the canonicalizer makes one. Two of them means
859 // two ways round with two different increments, and picking one would be a guess.
860 let [latch] = loops.latches(id) else { return Evolution::Unknown };
861 let mut entering = None;
862 let mut around = None;
863 for &pred in cfg.predecessors(header) {
864 let Some(arg) = argument(func, pred, header, index) else { return Evolution::Unknown };
865 let arg = self.forwarded(arg);
866 let slot = if pred == *latch { &mut around } else { &mut entering };
867 if slot.replace(arg).is_some_and(|old| old != arg) {
868 return Evolution::Unknown;
869 }
870 }
871 let (Some(entering), Some(around)) = (entering, around) else { return Evolution::Unknown };
872 let Some(base) = self.invariant(id, entering) else { return Evolution::Unknown };
873 let Some((step, flags)) = self.step(id, around, value, 0) else {
874 return Evolution::Unknown;
875 };
876 affine(base, step, func[value].ty, flags)
877 }
878
879 /// The value a block parameter stands for, when there is only one way into its block.
880 ///
881 /// This is not an analysis, it is undoing a rename. A block with one predecessor has one value
882 /// for each of its parameters and it is the argument that predecessor passes, so reading
883 /// through it loses nothing and assumes nothing.
884 ///
885 /// It is here because of what canonicalization does. `crate::canon` splits the back edge of a
886 /// loop to give it a latch of its own, and after that the value going round the loop is not the
887 /// increment the loop computed, it is a parameter of a block that does nothing but pass the
888 /// increment on. Without this, every counted loop the pipeline actually produces looks like a
889 /// loop whose counter comes from somewhere unknown, and the trip count of a `for` loop in a
890 /// real function comes back as nothing.
891 fn forwarded(&self, value: Value) -> Value {
892 let mut value = value;
893 for _ in 0..FORWARD_LIMIT {
894 let Def::Param { block, index } = self.func[value].def else { return value };
895 let [pred] = self.cfg.predecessors(block) else { return value };
896 let Some(arg) = argument(self.func, *pred, block, index as usize) else { return value };
897 if arg == value {
898 return value;
899 }
900 value = arg;
901 }
902 value
903 }
904
905 /// What is added to `of` to get `value`, and what the additions promised.
906 ///
907 /// Written as its own walk rather than as the general combination below, because at the point
908 /// this runs the parameter's own evolution is not known yet and the general walk would ask
909 /// for it and get unknown.
910 fn step(&self, id: LoopId, value: Value, of: Value, depth: u32) -> Option<(Invariant, Flags)> {
911 let value = self.forwarded(value);
912 if value == of {
913 // Nothing added yet, and nothing has had a chance to overflow either.
914 return Some((Invariant::number(0), Flags::NSW.union(Flags::NUW)));
915 }
916 if depth >= STEP_LIMIT {
917 return None;
918 }
919 let Def::Result { inst, .. } = self.func[value].def else { return None };
920 let data = &self.func[inst];
921 let args = &self.func[data.args];
922 let (&lhs, &rhs) = (args.first()?, args.get(1)?);
923 let combine = |carried: (Invariant, Flags), other: Invariant, subtract: bool| {
924 let (delta, flags) = carried;
925 let moved = if subtract { delta.minus(other)? } else { delta.plus(other)? };
926 Some((moved, flags.intersection(data.flags)))
927 };
928 match data.opcode {
929 Opcode::Add => {
930 if let Some(carried) = self.step(id, lhs, of, depth + 1) {
931 return combine(carried, self.invariant(id, rhs)?, false);
932 }
933 combine(self.step(id, rhs, of, depth + 1)?, self.invariant(id, lhs)?, false)
934 }
935 Opcode::Sub => {
936 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, true)
937 }
938 // A pointer walks by bytes, and only the pointer side can be the one carrying the
939 // induction variable. The offset is the step, which is the element size the front end
940 // already multiplied in.
941 Opcode::PtrAdd => {
942 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, false)
943 }
944 _ => None,
945 }
946 }
947
948 /// The evolution of an instruction's result, from the evolutions of its operands.
949 fn at_inst(&mut self, id: LoopId, inst: Inst, value: Value) -> Evolution {
950 let func = self.func;
951 let data = &func[inst];
952 let (opcode, flags) = (data.opcode, data.flags);
953 let args = &func[data.args];
954 let ty = func[value].ty;
955 let Some(&lhs) = args.first() else { return Evolution::Unknown };
956 match opcode {
957 Opcode::Add | Opcode::PtrAdd => {
958 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
959 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
960 combine(left, right, ty, flags, false)
961 }
962 Opcode::Sub => {
963 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
964 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
965 combine(left, right, ty, flags, true)
966 }
967 Opcode::Mul => {
968 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
969 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
970 scale(left, right, ty, flags)
971 }
972 // A shift by a constant is a multiplication by a power of two, and only by a constant:
973 // a variable count is invariant in the loop and still not a number this can multiply
974 // by. A count at or above the width is poison rather than a shift to zero, so the
975 // range is checked here rather than assumed.
976 Opcode::Shl => {
977 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
978 let Some((count, count_ty)) = constant(func, rhs) else {
979 return Evolution::Unknown;
980 };
981 let count = count.unsigned();
982 if count >= u128::from(ty.bits()) || !count_ty.is_int() {
983 return Evolution::Unknown;
984 }
985 let by = Evolution::Invariant(Invariant::number(1i128 << count));
986 scale(self.at(id, lhs), by, ty, flags)
987 }
988 Opcode::SExt | Opcode::ZExt => self.extend(id, opcode, lhs, ty),
989 // A truncation is a wrap by construction, so a chrec through one describes a sequence
990 // that restarts, and this does not have a representation for that.
991 _ => Evolution::Unknown,
992 }
993 }
994
995 /// A chrec widened, which needs the sequence not to wrap at the narrow width.
996 ///
997 /// Section 7.4 allows extension only where the extension provably does not wrap, and the first
998 /// proof here is the flag the increment carries. `nsw` on the increment is the promise that the
999 /// signed sequence does not wrap, which is exactly what makes the wide sequence the same
1000 /// numbers as the narrow one.
1001 ///
1002 /// The second proof is the loop's own exit test, through [`Scev::holds`] and [`trails`], and it
1003 /// is here because of what an unsigned counter looks like. `for (unsigned i = 0; i < n; i++)`
1004 /// carries no `nuw`, because C says unsigned arithmetic wraps, so `a[i]` on that counter used
1005 /// to come back unwidened and every bounds check in the loop stayed where it was. The test that
1006 /// keeps the counter inside its type keeps everything walking beside it inside too.
1007 ///
1008 /// Each part is either a plain number or one of a value, and nothing else. A number means the
1009 /// same thing at both widths, and one of a value becomes that value read through the extension,
1010 /// which is what [`Widening`] is for. Anything with arithmetic in it is refused, because the
1011 /// narrow arithmetic may already have wrapped and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
1012 /// What that leaves out is a base like `start + 1`, and what it lets in is `start`, which is
1013 /// the shape a walk from an index the caller handed in is in. See #810.
1014 ///
1015 /// A value the loop does not change is widened by the same rule. It used to be widened only
1016 /// when it was a number, and everything else came back unknown, which is a sequence that does
1017 /// not move being harder to widen than one that does. What it cost is the row of a two
1018 /// dimensional array: `a[row * N + k]` round `k` has `(long)row * N` in it, that is invariant
1019 /// and is not a number, so the address of the whole subscript came back unknown and every pass
1020 /// reading it had nothing to work with. There is no wrapping question to answer here, because
1021 /// there is no sequence and so nothing to wrap, and the shapes that get through are the same
1022 /// ones [`Invariant::widened`] lets through for a chrec's base.
1023 fn extend(&mut self, id: LoopId, opcode: Opcode, from: Value, to: Type) -> Evolution {
1024 let narrow = self.func[from].ty;
1025 let signed = opcode == Opcode::SExt;
1026 let held = self.held.get(&id).copied().flatten();
1027 let settled = |chrec: Chrec| {
1028 chrec.does_not_wrap(signed) || (!signed && held.is_some_and(|held| trails(chrec, held)))
1029 };
1030 let reading = if signed { Reading::Signed } else { Reading::Unsigned };
1031 match self.at(id, from) {
1032 Evolution::Invariant(inv) => match inv.as_number() {
1033 // A number read at the narrow width means the same thing at the wide one under
1034 // sign extension, and under zero extension once it is not negative.
1035 Some(number) if signed || number >= 0 => Evolution::Invariant(inv),
1036 Some(_) => Evolution::Unknown,
1037 // Not a number, and still the same value read wider. This is the widening a chrec
1038 // gets, asked about something that does not move: `(long)row * 64` inside a loop
1039 // over `k` is an expression the loop does not change, and it used to come back
1040 // unknown, which made the whole of `a[row * N + k]` unknown. [`Invariant::widened`]
1041 // is the one that decides, and it refuses anything with arithmetic in it for the
1042 // reason written on it, so what gets through is one of a value and nothing else.
1043 None => match inv.widened(reading, to) {
1044 Some(wide) => Evolution::Invariant(wide),
1045 None => Evolution::Unknown,
1046 },
1047 },
1048 Evolution::Affine(chrec) if chrec.ty == narrow && settled(chrec) => {
1049 let (Some(base), Some(step)) =
1050 (chrec.base.widened(reading, to), chrec.step.widened(reading, to))
1051 else {
1052 return Evolution::Unknown;
1053 };
1054 Evolution::Affine(Chrec { base, step, ty: to, flags: chrec.flags })
1055 }
1056 _ => Evolution::Unknown,
1057 }
1058 }
1059
1060 /// Whether every way round the loop goes through this block.
1061 ///
1062 /// Walks back from the one latch while each block has one predecessor. A block reached that way
1063 /// is one the latch cannot be got to without, and the walk stops at the first join, so it never
1064 /// goes round the loop, since the header is a join by having a way in and a way round.
1065 fn asked_each_time(&self, id: LoopId, from: Block) -> bool {
1066 let [latch] = self.loops.latches(id) else { return false };
1067 let mut at = *latch;
1068 for _ in 0..self.loops.blocks(id).len() {
1069 if at == from {
1070 return true;
1071 }
1072 let &[before] = self.cfg.predecessors(at) else { return false };
1073 at = before;
1074 }
1075 false
1076 }
1077
1078 /// The trip count from the exit leaving this block, if this exit can be solved.
1079 ///
1080 /// Only a test every iteration asks gives one. A test under a condition first fails at some
1081 /// iteration and the loop leaves at the first iteration after that on which the condition lets
1082 /// the test be asked, which may be much later or never. `while (i != 1024 || j <= 0)` asks
1083 /// `j <= 0` only once `i` is 1024, so the count its test gives is 1 and the loop runs ten times.
1084 /// Every caller multiplies by the count or takes it to mean the loop ends, and a count from such
1085 /// a test is right for neither.
1086 fn bound_at(&mut self, id: LoopId, from: Block) -> Option<Bound> {
1087 let test = self.test_at(id, from)?;
1088 if !test.each {
1089 return None;
1090 }
1091 solve(test.chrec, test.limit, test.pred)
1092 }
1093
1094 /// The exit test leaving this block, read into the pieces its two readers want.
1095 ///
1096 /// [`Scev::bound_at`] spends it on a trip count and [`Scev::holds`] spends it on whether the
1097 /// counter can wrap, and both want the same reading of the same branch, so the reading is
1098 /// written once.
1099 fn test_at(&mut self, id: LoopId, from: Block) -> Option<Test> {
1100 let func = self.func;
1101 let term = func.terminator(from)?;
1102 if func[term].opcode != Opcode::BrIf {
1103 return None;
1104 }
1105 let args = &func[func[term].args];
1106 let &cond = args.first()?;
1107 let calls = &func[func.target_list(term)];
1108 let (&taken, ¬_taken) = (calls.first()?, calls.get(1)?);
1109 // Which arm keeps going. If both stay in or both leave, the branch is not the test that
1110 // ends the loop and there is nothing here to solve.
1111 let stays = match (
1112 self.loops.contains(id, taken.block),
1113 self.loops.contains(id, not_taken.block),
1114 ) {
1115 (true, false) => true,
1116 (false, true) => false,
1117 _ => return None,
1118 };
1119
1120 let Def::Result { inst, .. } = func[cond].def else { return None };
1121 if func[inst].opcode != Opcode::ICmp {
1122 return None;
1123 }
1124 let Extra::IntPred(pred) = func[inst].extra else { return None };
1125 // The loop keeps going while the test says so, so an exit taken when the test is true is
1126 // an exit whose continuing condition is the opposite one.
1127 let pred = if stays { pred } else { invert(pred) };
1128 let operands = &func[func[inst].args];
1129 let (&lhs, &rhs) = (operands.first()?, operands.get(1)?);
1130
1131 // One side evolves and the other does not. Swapping puts the one that evolves on the left
1132 // and turns the predicate round with it, so only one direction has to be solved.
1133 let (chrec, limit, pred) = match (self.at(id, lhs), self.at(id, rhs)) {
1134 (Evolution::Affine(chrec), other) => (chrec, other.invariant()?, pred),
1135 (other, Evolution::Affine(chrec)) => (chrec, other.invariant()?, swap(pred)),
1136 _ => return None,
1137 };
1138
1139 // Whether every iteration that goes round asks this test. The header runs on all of them by
1140 // being the header. Any other block runs on all of them when the loop has one latch and the
1141 // only way to that latch is through this block, which is read by walking back from the
1142 // latch while each block has one way in. That takes in the latch itself, and the block in
1143 // front of the jump `crate::canon` splits a back edge into, which is where the test of
1144 // nearly every loop by the time this runs is. With two latches an iteration can go round
1145 // the other one and never reach the test. Anywhere else is a test under a condition, which
1146 // gives no count and which [`bounded_by_its_test`] must not be given.
1147 let each = from == self.loops.header(id) || self.asked_each_time(id, from);
1148 Some(Test { chrec, limit, pred, each })
1149 }
1150}
1151
1152/// Two evolutions added, or subtracted when asked.
1153fn combine(left: Evolution, right: Evolution, ty: Type, flags: Flags, subtract: bool) -> Evolution {
1154 let apply = |a: Invariant, b: Invariant| if subtract { a.minus(b) } else { a.plus(b) };
1155 match (left, right) {
1156 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
1157 apply(a, b).map_or(Evolution::Unknown, Evolution::Invariant)
1158 }
1159 (Evolution::Affine(chrec), Evolution::Invariant(b)) => {
1160 // Adding something that does not move only moves the base.
1161 let Some(base) = apply(chrec.base, b) else { return Evolution::Unknown };
1162 affine(base, chrec.step, ty, flags.intersection(chrec.flags))
1163 }
1164 (Evolution::Invariant(a), Evolution::Affine(chrec)) => {
1165 let (Some(base), Some(step)) = (
1166 apply(a, chrec.base),
1167 if subtract { chrec.step.negated() } else { Some(chrec.step) },
1168 ) else {
1169 return Evolution::Unknown;
1170 };
1171 affine(base, step, ty, flags.intersection(chrec.flags))
1172 }
1173 (Evolution::Affine(a), Evolution::Affine(b)) => {
1174 // Two chrecs of the same loop add componentwise, which is the closure property that
1175 // makes the representation worth having. Of different types they do not, because the
1176 // two sequences wrap at different widths.
1177 if a.ty != b.ty {
1178 return Evolution::Unknown;
1179 }
1180 let (Some(base), Some(step)) = (apply(a.base, b.base), apply(a.step, b.step)) else {
1181 return Evolution::Unknown;
1182 };
1183 affine(base, step, ty, flags.intersection(a.flags).intersection(b.flags))
1184 }
1185 _ => Evolution::Unknown,
1186 }
1187}
1188
1189/// One evolution multiplied by another, which needs one of them to stand still.
1190fn scale(left: Evolution, right: Evolution, ty: Type, flags: Flags) -> Evolution {
1191 let (chrec, by) = match (left, right) {
1192 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
1193 return a.times(b).map_or(Evolution::Unknown, Evolution::Invariant);
1194 }
1195 (Evolution::Affine(chrec), Evolution::Invariant(by))
1196 | (Evolution::Invariant(by), Evolution::Affine(chrec)) => (chrec, by),
1197 // Two chrecs multiplied give a quadratic, which is a chain of recurrences with a second
1198 // step and is outside the subset section 7.4 chose.
1199 _ => return Evolution::Unknown,
1200 };
1201 let (Some(base), Some(step)) = (chrec.base.times(by), chrec.step.times(by)) else {
1202 return Evolution::Unknown;
1203 };
1204 affine(base, step, ty, flags.intersection(chrec.flags))
1205}
1206
1207/// A chrec, or invariant when the step turns out to be nothing.
1208///
1209/// A step of zero is a valid affine chrec describing a value that does not move, and section 7.7
1210/// warns that code dividing by the step to get a trip count divides by zero. Reporting it as
1211/// invariant here means the shape is right for every reader rather than only for the careful
1212/// ones, and the trip count solver still checks, because a step can also come out zero from a
1213/// header parameter incremented by an invariant that happens to be zero.
1214fn affine(base: Invariant, step: Invariant, ty: Type, flags: Flags) -> Evolution {
1215 if step.is_zero() {
1216 return Evolution::Invariant(base);
1217 }
1218 Evolution::Affine(Chrec { base, step, ty, flags })
1219}
1220
1221/// The iteration at which `chrec pred limit` first fails, with what that rests on.
1222///
1223/// The test runs on every iteration that goes round, which [`Scev::bound_at`] checks before asking,
1224/// and that is what lets the test itself stand in for a promise the counter does not carry. See
1225/// [`bounded_by_its_test`].
1226fn solve(chrec: Chrec, limit: Invariant, pred: IntPred) -> Option<Bound> {
1227 // Section 7.7's first way of being wrong. A step of zero is a loop that never leaves through
1228 // this exit, and dividing the distance by it is a crash rather than an answer.
1229 let step = chrec.step.as_number()?;
1230 if step == 0 {
1231 return None;
1232 }
1233 let signed = matches!(pred, IntPred::Slt | IntPred::Sle | IntPred::Sgt | IntPred::Sge);
1234
1235 let mut assumptions = Vec::new();
1236 if !chrec.does_not_wrap(signed) && !bounded_by_its_test(pred, step) {
1237 assumptions.push(Assumption::NoWrap(chrec));
1238 }
1239 if signed {
1240 assumptions.push(Assumption::StrictOverflow);
1241 }
1242
1243 // A test that does not read its operands as signed does not read the constants in them that
1244 // way either, and every constant reaching here was read as signed on the way in.
1245 let (base, limit) = if signed {
1246 (chrec.base, limit)
1247 } else {
1248 (unsigned_base(chrec)?, as_unsigned(limit, chrec.ty)?)
1249 };
1250
1251 // The distance the counter has to travel, always counting up. A loop going down is the same
1252 // problem with the ends swapped, which is why the step is used by size below and its sign is
1253 // spent here.
1254 let apart = step.unsigned_abs();
1255 let found = match (pred, step > 0) {
1256 (IntPred::Slt | IntPred::Ult, true) => {
1257 ordered(limit.minus(base)?, apart, false, assumptions)
1258 }
1259 (IntPred::Sle | IntPred::Ule, true) => {
1260 ordered(limit.minus(base)?, apart, true, assumptions)
1261 }
1262 (IntPred::Sgt | IntPred::Ugt, false) => {
1263 ordered(base.minus(limit)?, apart, false, assumptions)
1264 }
1265 (IntPred::Sge | IntPred::Uge, false) => {
1266 ordered(base.minus(limit)?, apart, true, assumptions)
1267 }
1268 (IntPred::Ne, _) => {
1269 let distance = if step > 0 { limit.minus(base)? } else { base.minus(limit)? };
1270 landing(distance, apart, step < 0 && limit.is_zero(), assumptions)
1271 }
1272 // Either the counter steps away from the limit, in which case the loop is endless rather
1273 // than long, or the test is one this does not solve. Silence is the answer to both.
1274 _ => None,
1275 };
1276 // Written once here rather than threaded through the two solvers, because it is a fact about
1277 // the test and neither of them looks at the test. A count taken from a test with no sign to it,
1278 // which is `!=`, is read unsigned, because that is the reading `as_unsigned` above already put
1279 // its operands through.
1280 let reading = if signed { Reading::Signed } else { Reading::Unsigned };
1281 found.map(|(count, assumptions)| Bound { count, assumptions, reading })
1282}
1283
1284/// Whether the exit test by itself rules out the counter wrapping before the loop ends.
1285///
1286/// An unsigned counter carries no `nuw`, because C says unsigned arithmetic wraps, so without this
1287/// every `for (unsigned i = 0; i < n; i++)` comes back resting on an assumption nothing downstream
1288/// can discharge. What discharges it is the test. A counter stepping up by exactly one is at the
1289/// limit before it is anywhere past it, and the test ends the loop there, so it never reaches the
1290/// top of its type. GCC works the same thing out in `scev_probably_wraps_p`.
1291///
1292/// Every part of that is load bearing. The step has to be one: `i += 2` can go from one below the
1293/// limit to one above the top of the type and come back round at the bottom, which is a loop that
1294/// runs forever rather than one that runs twice as fast. The test has to be the strict one: `<=`
1295/// lets the counter reach the limit and step once more, and a limit that is the largest number of
1296/// its type makes that last step the one that wraps. And the test has to run on every iteration
1297/// that goes round, or the counter can be stepped by a path that never asks it anything.
1298///
1299/// Nothing is claimed here about a signed counter, which needs no help: a signed counter that would
1300/// wrap is a program with undefined behaviour in it and [`Assumption::StrictOverflow`] is where
1301/// that is recorded.
1302fn bounded_by_its_test(pred: IntPred, step: i128) -> bool {
1303 matches!((pred, step), (IntPred::Ult, 1) | (IntPred::Ugt, -1))
1304}
1305
1306/// Whether this sequence stays behind one the exit test already keeps inside its type.
1307///
1308/// [`bounded_by_its_test`] says the counter the test compares never reaches the top of its type.
1309/// Everything else the loop counts with is that counter plus a fixed distance, because two affine
1310/// chrecs of the same loop with the same step differ by a constant, so a sequence starting no
1311/// further along than the counter is a sequence that gets to the top no sooner than the counter
1312/// does, which is never.
1313///
1314/// Same base is the case that matters most and the easiest to see: the test compares `i + 1` and
1315/// the subscript reads `i`, which is one loop written two ways, and the two chrecs differ only in
1316/// where they start.
1317///
1318/// Going up only. A counter going down wraps at the bottom rather than the top, so the sequence
1319/// that is safe is the one that starts further along rather than the one that starts behind, and
1320/// nothing measured so far walks an array downwards. Doing it would be turning the comparison
1321/// round, and it should come with the program that wants it.
1322fn trails(chrec: Chrec, held: Chrec) -> bool {
1323 if chrec.ty != held.ty || chrec.step != held.step {
1324 return false;
1325 }
1326 if chrec.base == held.base {
1327 return true;
1328 }
1329 let (Some(step), Some(mine), Some(theirs)) =
1330 (chrec.step.as_number(), chrec.base.as_number(), held.base.as_number())
1331 else {
1332 return false;
1333 };
1334 // Read as unsigned, which is the reading the test took, so a base that came in negative is a
1335 // large number rather than a small one and starting behind is not what it is doing.
1336 step > 0 && mine >= 0 && theirs >= 0 && mine <= theirs
1337}
1338
1339/// The same expression, read the way a test without a sign reads it.
1340///
1341/// Constants arrive here as the number their bits are when the sign bit is taken seriously,
1342/// because that is the only reading available before anybody knows what will be done with them.
1343/// An unsigned test disagrees about half of them. `for (unsigned char i = 0; i < 200; i++)` holds
1344/// its limit as minus fifty six, and a distance worked out from that is negative, which reads as
1345/// a loop that runs no times rather than one that runs two hundred.
1346///
1347/// The step is not put through this, because a step is a difference rather than a value and its
1348/// signed reading is the one that says which way the counter goes.
1349/// Where a counter starts, read unsigned.
1350///
1351/// What [`as_unsigned`] says, and one more case it has to refuse without the counter to ask. A base
1352/// with a number folded in beside its symbol is safe to read unsigned when the counter promises not
1353/// to wrap that way, because the base is the first value the counter took and it took it without
1354/// wrapping, so the sum is the number it looks like. The countdown ivopts writes tests its variable
1355/// after taking one off, and this is what its base looks like.
1356fn unsigned_base(chrec: Chrec) -> Option<Invariant> {
1357 let base = chrec.base;
1358 let plain = base.on.is_none() && base.read.is_none() && base.scale == 1;
1359 as_unsigned(base, chrec.ty).or_else(|| (plain && chrec.does_not_wrap(false)).then_some(base))
1360}
1361
1362fn as_unsigned(inv: Invariant, ty: Type) -> Option<Invariant> {
1363 match inv.as_number() {
1364 Some(number) if number >= 0 => Some(inv),
1365 Some(number) => {
1366 // Only an integer constant was read as signed in the first place. A pointer never
1367 // was, so a negative number sitting in one is an expression this cannot reinterpret.
1368 let bits = ty.is_int().then(|| ty.bits()).filter(|&bits| bits < 127)?;
1369 Some(Invariant::number(number & ((1i128 << bits) - 1)))
1370 }
1371 // A symbolic operand is whatever it is at run time, and the subtraction below cancels it
1372 // rather than reading it, so long as nothing signed has been folded in beside it. Two
1373 // symbols is two things to cancel and the subtraction only ever cancels one.
1374 None => (inv.on.is_none() && inv.scale == 1 && inv.offset == 0).then_some(inv),
1375 }
1376}
1377
1378/// The count for an exit tested with an ordering, where overshooting the limit still ends it.
1379fn ordered(
1380 distance: Invariant,
1381 step: u128,
1382 inclusive: bool,
1383 mut assumptions: Vec<Assumption>,
1384) -> Option<(Count, Vec<Assumption>)> {
1385 match distance.as_number() {
1386 Some(exact) => {
1387 if exact < 0 {
1388 // The counter starts past the limit, so the test fails the first time it runs.
1389 // That is a count of zero and it rests on nothing at all, not even on the counter
1390 // behaving, because the counter never moves.
1391 return Some((Count::Exact(0), Vec::new()));
1392 }
1393 // Rounding up, because a step that overshoots still took the iteration that overshot.
1394 let count = (exact.unsigned_abs() + u128::from(inclusive)).div_ceil(step);
1395 Some((Count::Exact(count), assumptions))
1396 }
1397 // Symbolic, and only for a step of one, because dividing an expression by anything else
1398 // needs a representation for a division and there is not one here.
1399 None if step == 1 => {
1400 assumptions.push(Assumption::Entered);
1401 let count = distance.plus(Invariant::number(i128::from(inclusive)))?;
1402 Some((Count::Symbolic(count), assumptions))
1403 }
1404 None => None,
1405 }
1406}
1407
1408/// The count for an exit tested with `!=`, where the counter has to land on the limit exactly.
1409///
1410/// This is a different problem from the one above and not a special case of it. An ordering test
1411/// ends the loop the moment the counter is past the limit, so a step that overshoots still stops.
1412/// `!=` only ends the loop on the one iteration where the counter is the limit, so a counter that
1413/// steps over the limit, or that starts on the far side of it, keeps going until it wraps. Both
1414/// of those are endless loops rather than short ones, and answering zero for either was the bug
1415/// this function exists to not have.
1416fn landing(
1417 distance: Invariant,
1418 step: u128,
1419 bottom: bool,
1420 mut assumptions: Vec<Assumption>,
1421) -> Option<(Count, Vec<Assumption>)> {
1422 match distance.as_number() {
1423 Some(exact) => {
1424 let travel = u128::try_from(exact).ok()?;
1425 // Checked outright rather than assumed, which is why nothing here needs an assumption
1426 // about the step dividing anything.
1427 (travel % step == 0).then(|| (Count::Exact(travel / step), assumptions))
1428 }
1429 // A step of one lands on everything ahead of it, so the only thing left to establish is
1430 // that the limit is ahead. `while (p != end)` is this case, and a step of anything else
1431 // would need the division a symbolic distance has no room for.
1432 //
1433 // A counter going down to zero has it established already, because `!=` reads it unsigned
1434 // and nothing unsigned is below zero, so zero is ahead of wherever it starts. The `!=`
1435 // that ivopts writes for a countdown is this case. A promise not to wrap would not do
1436 // instead, since a loop with a limit behind its counter can stop on something else, a
1437 // bounds check for one, long before the counter comes round to break the promise.
1438 None if step == 1 => {
1439 if !bottom {
1440 assumptions.push(Assumption::Approaching);
1441 }
1442 Some((Count::Symbolic(distance), assumptions))
1443 }
1444 None => None,
1445 }
1446}
1447
1448/// The predicate that is true exactly when this one is not.
1449fn invert(pred: IntPred) -> IntPred {
1450 match pred {
1451 IntPred::Eq => IntPred::Ne,
1452 IntPred::Ne => IntPred::Eq,
1453 IntPred::Slt => IntPred::Sge,
1454 IntPred::Sle => IntPred::Sgt,
1455 IntPred::Sgt => IntPred::Sle,
1456 IntPred::Sge => IntPred::Slt,
1457 IntPred::Ult => IntPred::Uge,
1458 IntPred::Ule => IntPred::Ugt,
1459 IntPred::Ugt => IntPred::Ule,
1460 IntPred::Uge => IntPred::Ult,
1461 }
1462}
1463
1464/// The predicate that says the same thing with the operands the other way round.
1465fn swap(pred: IntPred) -> IntPred {
1466 match pred {
1467 IntPred::Eq => IntPred::Eq,
1468 IntPred::Ne => IntPred::Ne,
1469 IntPred::Slt => IntPred::Sgt,
1470 IntPred::Sle => IntPred::Sge,
1471 IntPred::Sgt => IntPred::Slt,
1472 IntPred::Sge => IntPred::Sle,
1473 IntPred::Ult => IntPred::Ugt,
1474 IntPred::Ule => IntPred::Uge,
1475 IntPred::Ugt => IntPred::Ult,
1476 IntPred::Uge => IntPred::Ule,
1477 }
1478}
1479
1480/// The constant a value is, if it is one.
1481fn constant(func: &Func, value: Value) -> Option<(Imm, Type)> {
1482 let Def::Result { inst, .. } = func[value].def else { return None };
1483 if func[inst].opcode != Opcode::IConst {
1484 return None;
1485 }
1486 let Extra::Imm(at) = func[inst].extra else { return None };
1487 let ty = func[value].ty;
1488 ty.is_int().then(|| (func[at], ty))
1489}
1490
1491/// The global whose address a value is, if it is one.
1492fn symbol(func: &Func, value: Value) -> Option<Symbol> {
1493 let Def::Result { inst, .. } = func[value].def else { return None };
1494 if func[inst].opcode != Opcode::GlobalAddr {
1495 return None;
1496 }
1497 let Extra::Symbol(symbol) = func[inst].extra else { return None };
1498 Some(symbol)
1499}
1500
1501/// What this predecessor passes to the block's parameter at this position.
1502///
1503/// `None` when the predecessor branches to the block more than once with different arguments,
1504/// which a `br_if` with both arms on the same block can do and which means the parameter takes a
1505/// value that depends on the test rather than on the edge.
1506fn argument(func: &Func, pred: Block, block: Block, index: usize) -> Option<Value> {
1507 let term = func.terminator(pred)?;
1508 let mut found = None;
1509 for call in func.successors(term) {
1510 if call.block != block {
1511 continue;
1512 }
1513 let arg = *func[call.args].get(index)?;
1514 if found.replace(arg).is_some_and(|old| old != arg) {
1515 return None;
1516 }
1517 }
1518 found
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523 use rucc_base::Interner;
1524 use rucc_ir::{Builder, Extra, Flags, Func, InstData, IntPred, Opcode, Signature, Type, Value};
1525
1526 use crate::cfg::Cfg;
1527 use crate::dom::Dominators;
1528 use crate::loops::{LoopId, Loops};
1529 use crate::scev::{
1530 Anchor, Assumption, Bound, Count, Evolution, Invariant, Reading, Scev, Widening,
1531 };
1532
1533 /// A loop counting in `ty` from `from` by `step` while the counter is below `to`.
1534 ///
1535 /// ```text
1536 /// entry: jump header(from)
1537 /// header(i): test = icmp pred i, to ; br_if test, body, exit
1538 /// body: next = add i, step ; jump header(next)
1539 /// exit: ret
1540 /// ```
1541 ///
1542 /// The counter is the header's only parameter, which is what the tests ask about.
1543 struct Counted {
1544 func: Func,
1545 counter: Value,
1546 next: Value,
1547 }
1548
1549 fn counted(ty: Type, from: i128, to: i128, step: i128, pred: IntPred, flags: Flags) -> Counted {
1550 let (it, ()) = counted_with(ty, from, to, step, pred, flags, |_, _| ());
1551 it
1552 }
1553
1554 /// The same loop, with `extra` run in the body on the counter before the counter steps.
1555 ///
1556 /// The builder appends, and the body's `jump` back to the header has to stay the last
1557 /// instruction in it or the block has no terminator and the loop stops being one. So anything
1558 /// a test wants derived from the counter goes in here rather than being tacked on afterwards.
1559 fn counted_with<T>(
1560 ty: Type,
1561 from: i128,
1562 to: i128,
1563 step: i128,
1564 pred: IntPred,
1565 flags: Flags,
1566 extra: impl FnOnce(&mut Builder<'_>, Value) -> T,
1567 ) -> (Counted, T) {
1568 let mut names = Interner::new();
1569 let mut func = Func::new(names.intern("f"), Signature::new());
1570 let entry = func.create_block();
1571 let header = func.create_block();
1572 let body = func.create_block();
1573 let exit = func.create_block();
1574 let counter = func.append_param(header, ty);
1575
1576 let mut build = Builder::new(&mut func, entry);
1577 let start = build.iconst(ty, from);
1578 build.jump(header, &[start]);
1579
1580 let mut build = Builder::new(&mut func, header);
1581 let limit = build.iconst(ty, to);
1582 let test = build.icmp(pred, counter, limit);
1583 build.br_if(test, body, &[], exit, &[]);
1584
1585 let mut build = Builder::new(&mut func, body);
1586 let derived = extra(&mut build, counter);
1587 let by = build.iconst(ty, step);
1588 let next = build.binary(Opcode::Add, counter, by, flags);
1589 build.jump(header, &[next]);
1590
1591 let mut build = Builder::new(&mut func, exit);
1592 build.ret(&[]);
1593
1594 (Counted { func, counter, next }, derived)
1595 }
1596
1597 /// The analysis over a function, along with the one loop it has.
1598 fn analyse(func: &Func) -> (Cfg, Loops) {
1599 let cfg = Cfg::new(func);
1600 let doms = Dominators::new(&cfg);
1601 let loops = Loops::new(&cfg, &doms);
1602 (cfg, loops)
1603 }
1604
1605 /// The chrec of a value in the one loop of a function.
1606 fn evolution(func: &Func, value: Value) -> Evolution {
1607 let (cfg, loops) = analyse(func);
1608 let id = loops.roots()[0];
1609 Scev::new(func, &cfg, &loops).evolution(id, value)
1610 }
1611
1612 /// The trip count of the one loop of a function.
1613 fn bound(func: &Func) -> Option<Bound> {
1614 let (cfg, loops) = analyse(func);
1615 let id: LoopId = loops.roots()[0];
1616 Scev::new(func, &cfg, &loops).bound(id)
1617 }
1618
1619 #[test]
1620 fn a_counter_from_zero_by_one_is_the_chrec_everyone_expects() {
1621 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1622 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1623 assert_eq!(chrec.base, Invariant::number(0));
1624 assert_eq!(chrec.step, Invariant::number(1));
1625 assert_eq!(chrec.ty, Type::int(32));
1626 assert!(chrec.does_not_wrap(true));
1627 }
1628
1629 #[test]
1630 fn a_walk_over_a_file_scope_array_is_a_chrec_measured_from_the_symbol() {
1631 // The `global_addr` is inside the loop, which is where the compiler leaves one: working
1632 // the address out again is a single instruction and `crate::licm` would rather do that
1633 // than hold it in a register the whole way round. Answering by where a value is defined
1634 // meant `a[i]` on a file scope `a` was an address with nothing to say about it.
1635 let mut names = Interner::new();
1636 let tab = names.intern("tab");
1637 let (it, address) =
1638 counted_with(Type::int(64), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1639 let four = build.iconst(Type::int(64), 4);
1640 let by = build.binary(Opcode::Mul, counter, four, Flags::NSW);
1641 let extra = Extra::Symbol(tab);
1642 let at =
1643 build.value(InstData { extra, ..InstData::new(Opcode::GlobalAddr) }, Type::PTR);
1644 let args = build.func().push_values(&[at, by]);
1645 build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
1646 });
1647
1648 let chrec = evolution(&it.func, address).chrec().expect("the address evolves");
1649 assert_eq!(chrec.step, Invariant::number(4));
1650 // Described rather than named, so there is nothing for `plain` to hand back and a reader
1651 // of the base has to go through `on` and see what it is measured from.
1652 assert!(chrec.base.plain().is_none());
1653 let (base, rest) = chrec.base.on().expect("the base is measured from the symbol");
1654 assert_eq!(base, Anchor::Address(tab));
1655 assert_eq!(base.value(), None);
1656 assert_eq!(rest.value, None);
1657 assert_eq!(rest.offset, 0);
1658 }
1659
1660 #[test]
1661 fn the_value_fed_back_is_the_chrec_one_step_along() {
1662 let it = counted(Type::int(32), 5, 100, 3, IntPred::Slt, Flags::NSW);
1663 let chrec = evolution(&it.func, it.next).chrec().expect("the increment evolves");
1664 assert_eq!(chrec.base, Invariant::number(8));
1665 assert_eq!(chrec.step, Invariant::number(3));
1666 }
1667
1668 #[test]
1669 fn a_multiple_of_the_counter_plus_a_number_is_a_chrec_of_its_own() {
1670 // `j = 2 * i + 3` where `i = {0, +, 1}`, which is the shape section 7.4 says pattern
1671 // matching runs out of road on and chains of recurrences do not.
1672 let (it, shifted) =
1673 counted_with(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1674 let two = build.iconst(Type::int(32), 2);
1675 let three = build.iconst(Type::int(32), 3);
1676 let doubled = build.binary(Opcode::Mul, counter, two, Flags::NSW);
1677 build.binary(Opcode::Add, doubled, three, Flags::NSW)
1678 });
1679
1680 let chrec = evolution(&it.func, shifted).chrec().expect("it evolves");
1681 assert_eq!(chrec.base, Invariant::number(3));
1682 assert_eq!(chrec.step, Invariant::number(2));
1683 }
1684
1685 #[test]
1686 fn a_shift_by_a_constant_scales_the_chrec_and_a_shift_past_the_width_does_not() {
1687 let (it, (scaled, poison)) =
1688 counted_with(Type::int(32), 1, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1689 let three = build.iconst(Type::int(32), 3);
1690 let wide = build.iconst(Type::int(32), 32);
1691 (
1692 build.binary(Opcode::Shl, counter, three, Flags::NSW),
1693 build.binary(Opcode::Shl, counter, wide, Flags::NSW),
1694 )
1695 });
1696
1697 let chrec = evolution(&it.func, scaled).chrec().expect("it evolves");
1698 assert_eq!(chrec.base, Invariant::number(8));
1699 assert_eq!(chrec.step, Invariant::number(8));
1700 // A count at the width is poison rather than a shift to zero, so there is no sequence to
1701 // describe.
1702 assert_eq!(evolution(&it.func, poison), Evolution::Unknown);
1703 }
1704
1705 #[test]
1706 fn a_pointer_walked_by_the_element_size_is_a_chrec_in_bytes() {
1707 // What `for (p = a; p != end; p++)` lowers to on an array of four byte elements. Section
1708 // 7.4 calls this the one deliberate extension past affine and the difference between
1709 // analysing half of real C loops and nearly all of them.
1710 let mut names = Interner::new();
1711 let mut func = Func::new(names.intern("f"), Signature::new());
1712 let entry = func.create_block();
1713 let header = func.create_block();
1714 let body = func.create_block();
1715 let exit = func.create_block();
1716 let start = func.append_param(entry, Type::PTR);
1717 let cursor = func.append_param(header, Type::PTR);
1718
1719 let mut build = Builder::new(&mut func, entry);
1720 build.jump(header, &[start]);
1721 let mut build = Builder::new(&mut func, header);
1722 let done = build.icmp(IntPred::Eq, cursor, start);
1723 build.br_if(done, exit, &[], body, &[]);
1724 let mut build = Builder::new(&mut func, body);
1725 let four = build.iconst(Type::int(64), 4);
1726 let next = build.binary(Opcode::PtrAdd, cursor, four, Flags::NONE);
1727 build.jump(header, &[next]);
1728 let mut build = Builder::new(&mut func, exit);
1729 build.ret(&[]);
1730
1731 let chrec = evolution(&func, cursor).chrec().expect("the cursor evolves");
1732 assert_eq!(chrec.base, Invariant::of(start));
1733 assert_eq!(chrec.step, Invariant::number(4));
1734 assert_eq!(chrec.ty, Type::PTR);
1735 }
1736
1737 #[test]
1738 fn a_value_the_loop_does_not_change_widens_the_way_a_sequence_does() {
1739 // `(long)row` inside a loop over something else. There is no sequence here and so nothing
1740 // that could wrap, and the answer was unknown all the same, which made a sequence that does
1741 // not move harder to widen than one that does. What it cost is `a[row * N + k]` round `k`,
1742 // whose address came back unknown on account of the widening in the middle of it.
1743 let mut names = Interner::new();
1744 let mut func = Func::new(names.intern("f"), Signature::new());
1745 let entry = func.create_block();
1746 let header = func.create_block();
1747 let body = func.create_block();
1748 let exit = func.create_block();
1749 let row = func.append_param(entry, Type::int(32));
1750 let counter = func.append_param(header, Type::int(64));
1751
1752 let mut build = Builder::new(&mut func, entry);
1753 let zero = build.iconst(Type::int(64), 0);
1754 build.jump(header, &[zero]);
1755
1756 let mut build = Builder::new(&mut func, header);
1757 let limit = build.iconst(Type::int(64), 100);
1758 let test = build.icmp(IntPred::Slt, counter, limit);
1759 build.br_if(test, body, &[], exit, &[]);
1760
1761 let mut build = Builder::new(&mut func, body);
1762 let wide = build.unary(Opcode::SExt, row, Type::int(64));
1763 let one = build.iconst(Type::int(64), 1);
1764 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
1765 build.jump(header, &[next]);
1766 Builder::new(&mut func, exit).ret(&[]);
1767
1768 let word = Type::int(64);
1769 let widened =
1770 Invariant::of(row).widened(Reading::Signed, word).expect("one of a value widens");
1771 assert_eq!(evolution(&func, wide), Evolution::Invariant(widened));
1772 }
1773
1774 /// A value to hang an invariant on, which these never look inside.
1775 fn some_value() -> Value {
1776 let mut names = Interner::new();
1777 let mut func = Func::new(names.intern("f"), Signature::new());
1778 let entry = func.create_block();
1779 func.append_param(entry, Type::int(8))
1780 }
1781
1782 #[test]
1783 fn one_of_a_value_widens_and_arithmetic_on_it_does_not() {
1784 // What `Scev::extend` may take. A value is widened by describing the extension rather than
1785 // by naming a value nothing computes, which is what lets `for (i = start; i < n; i++)`
1786 // have a chrec at pointer width. `2 * x + 3` is refused, because the narrow arithmetic may
1787 // already have wrapped and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
1788 let value = some_value();
1789 let word = Type::int(64);
1790 assert_eq!(
1791 Invariant::of(value).widened(Reading::Signed, word),
1792 Some(Invariant {
1793 on: None,
1794 value: Some(value),
1795 read: Some(Widening { reading: Reading::Signed, to: word }),
1796 scale: 1,
1797 offset: 0,
1798 }),
1799 );
1800 assert_eq!(Invariant::scaled(value, 2, 3).widened(Reading::Signed, word), None);
1801 assert_eq!(Invariant::scaled(value, 1, 3).widened(Reading::Signed, word), None);
1802 // A number is the same number at both widths under a sign extension, and under a zero
1803 // extension once it is not negative.
1804 assert_eq!(
1805 Invariant::number(-1).widened(Reading::Signed, word),
1806 Some(Invariant::number(-1)),
1807 );
1808 assert_eq!(Invariant::number(-1).widened(Reading::Unsigned, word), None);
1809 }
1810
1811 #[test]
1812 fn an_extension_of_an_extension_collapses_only_where_it_means_the_same_thing() {
1813 // A zero extension is never negative, so reading its result as signed afterwards is the
1814 // same numbers and the pair is one zero extension at the outer width. The other way round
1815 // it is not: a sign extended negative number read as unsigned is a different quantity, and
1816 // there is nothing to collapse to.
1817 let value = some_value();
1818 let (half, word) = (Type::int(32), Type::int(64));
1819 let read = |inv: Invariant| inv.read.expect("a widened value carries how it is read");
1820
1821 let zeroed = Invariant::of(value).widened(Reading::Unsigned, half).expect("it widens");
1822 let again = zeroed.widened(Reading::Signed, word).expect("and it widens again");
1823 assert_eq!(read(again), Widening { reading: Reading::Unsigned, to: word });
1824
1825 let signed = Invariant::of(value).widened(Reading::Signed, half).expect("it widens");
1826 assert_eq!(signed.widened(Reading::Unsigned, word), None);
1827 let again = signed.widened(Reading::Signed, word).expect("and it widens again");
1828 assert_eq!(read(again), Widening { reading: Reading::Signed, to: word });
1829 }
1830
1831 #[test]
1832 fn two_invariants_on_the_same_value_read_two_ways_do_not_add() {
1833 // `sext(x)` and `zext(x)` are the same bits and not the same quantity, so a sum of them is
1834 // not two of anything and there is no shape here for it.
1835 let value = some_value();
1836 let word = Type::int(64);
1837 let signed = Invariant::of(value).widened(Reading::Signed, word).expect("it widens");
1838 let zeroed = Invariant::of(value).widened(Reading::Unsigned, word).expect("it widens");
1839 assert_eq!(signed.plus(zeroed), None);
1840 assert_eq!(
1841 signed.plus(signed),
1842 Some(Invariant {
1843 on: None,
1844 value: Some(value),
1845 read: Some(Widening { reading: Reading::Signed, to: word }),
1846 scale: 2,
1847 offset: 0,
1848 }),
1849 "the same value read the same way adds to two of it",
1850 );
1851 }
1852
1853 #[test]
1854 fn a_counter_in_unsigned_char_wraps_and_does_not_widen_without_a_promise() {
1855 // Section 7.7's second way of being wrong. `{0, +, 1}` in `unsigned char` is not
1856 // `0, 1, 2, ...`, it is that modulo two hundred and fifty six, and widening it is only
1857 // the same sequence if it does not get that far.
1858 //
1859 // An inclusive test, because a strict one is a proof of its own and the case below is
1860 // about what happens when there is no proof at all. This loop does not in fact wrap, and
1861 // the point is that nothing here can say so.
1862 let (it, wide) =
1863 counted_with(Type::int(8), 0, 100, 1, IntPred::Ule, Flags::NONE, |build, counter| {
1864 build.unary(Opcode::ZExt, counter, Type::int(32))
1865 });
1866 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1867 assert_eq!(chrec.ty, Type::int(8));
1868 assert!(!chrec.does_not_wrap(false));
1869 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1870 }
1871
1872 #[test]
1873 fn a_counter_its_own_test_holds_widens_without_a_promise() {
1874 // The same counter under the strict test, which is the shape `for (unsigned i = 0; i < n;
1875 // i++)` has. Nothing promised anything, and the test is the proof: the counter is at the
1876 // limit before it is anywhere past it, and the loop ends there.
1877 let (it, wide) =
1878 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1879 build.unary(Opcode::ZExt, counter, Type::int(32))
1880 });
1881 let narrow = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1882 assert!(!narrow.does_not_wrap(false), "nothing was promised, so nothing carries a flag");
1883 let chrec = evolution(&it.func, wide).chrec().expect("its own test holds it");
1884 assert_eq!(chrec.ty, Type::int(32));
1885 assert_eq!(chrec.base, Invariant::number(0));
1886 assert_eq!(chrec.step, Invariant::number(1));
1887 }
1888
1889 #[test]
1890 fn a_sequence_that_starts_further_along_than_the_counter_does_not_widen() {
1891 // `trails` in the direction it refuses. The test holds `i`, which starts at zero, and this
1892 // asks about `i + 1`, which starts one further along. One further along is where the
1893 // counter would be if it had gone round once more, and going round once more is the step
1894 // nothing here rules out.
1895 let (it, wide) =
1896 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1897 let one = build.iconst(Type::int(8), 1);
1898 let ahead = build.binary(Opcode::Add, counter, one, Flags::NONE);
1899 build.unary(Opcode::ZExt, ahead, Type::int(32))
1900 });
1901 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1902 }
1903
1904 #[test]
1905 fn a_counter_in_short_widens_when_the_increment_promised_it_would_not_wrap() {
1906 let (it, (wide, zero_extended)) =
1907 counted_with(Type::int(16), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1908 (
1909 build.unary(Opcode::SExt, counter, Type::int(32)),
1910 build.unary(Opcode::ZExt, counter, Type::int(32)),
1911 )
1912 });
1913
1914 let chrec = evolution(&it.func, wide).chrec().expect("it widens");
1915 assert_eq!(chrec.ty, Type::int(32));
1916 assert_eq!(chrec.base, Invariant::number(0));
1917 assert_eq!(chrec.step, Invariant::number(1));
1918 // `nsw` is a promise about the signed reading and says nothing about the unsigned one.
1919 assert_eq!(evolution(&it.func, zero_extended), Evolution::Unknown);
1920 }
1921
1922 #[test]
1923 fn a_step_of_zero_is_invariant_and_has_no_trip_count() {
1924 // Section 7.7's first way of being wrong. `i += k` with `k` of zero is a valid affine
1925 // chrec of a loop that never leaves through this exit, and code dividing the distance by
1926 // the step divides by zero.
1927 let it = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
1928 assert!(matches!(evolution(&it.func, it.counter), Evolution::Invariant(_)));
1929 assert_eq!(bound(&it.func), None);
1930 }
1931
1932 #[test]
1933 fn a_counted_loop_has_the_count_anyone_would_work_out_by_hand() {
1934 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1935 let found = bound(&it.func).expect("it is counted");
1936 let (count, assumptions) = found.parts();
1937 assert_eq!(count, Count::Exact(100));
1938 // The distance is a number and it is not negative, so being entered is not in question.
1939 // Signed overflow being undefined still is, which is what `-fwrapv` would withdraw.
1940 assert_eq!(assumptions, [Assumption::StrictOverflow]);
1941 assert_eq!(found.proven(), None);
1942 }
1943
1944 #[test]
1945 fn a_step_that_overshoots_still_takes_the_iteration_that_overshot() {
1946 // Zero, three, six, nine, and the test fails at twelve, so four iterations rather than
1947 // three and a third. Rounding the other way is an off by one in every unroller.
1948 let it = counted(Type::int(32), 0, 10, 3, IntPred::Slt, Flags::NSW);
1949 let (count, _) = bound(&it.func).expect("it is counted").parts();
1950 assert_eq!(count, Count::Exact(4));
1951 }
1952
1953 #[test]
1954 fn an_inclusive_test_runs_one_more_time() {
1955 let it = counted(Type::int(32), 0, 10, 1, IntPred::Sle, Flags::NSW);
1956 let (count, _) = bound(&it.func).expect("it is counted").parts();
1957 assert_eq!(count, Count::Exact(11));
1958 }
1959
1960 #[test]
1961 fn a_loop_whose_test_fails_first_time_runs_no_times_and_rests_on_nothing() {
1962 let it = counted(Type::int(32), 10, 0, 1, IntPred::Slt, Flags::NSW);
1963 let found = bound(&it.func).expect("it is counted");
1964 assert_eq!(found.proven(), Some(Count::Exact(0)));
1965 assert!(found.assumptions().is_empty());
1966 }
1967
1968 #[test]
1969 fn counting_down_is_the_same_problem_with_the_ends_swapped() {
1970 let it = counted(Type::int(32), 10, 0, -1, IntPred::Sgt, Flags::NSW);
1971 let (count, _) = bound(&it.func).expect("it is counted").parts();
1972 assert_eq!(count, Count::Exact(10));
1973 }
1974
1975 #[test]
1976 fn an_unsigned_test_does_not_drag_in_the_signed_overflow_assumption() {
1977 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
1978 let found = bound(&it.func).expect("it is counted");
1979 assert_eq!(found.proven(), Some(Count::Exact(100)));
1980 }
1981
1982 #[test]
1983 fn a_test_against_something_the_loop_does_not_change_gives_a_symbolic_count() {
1984 // `for (i = 0; i < n; i++)`, where the answer is `n` and is only `n` if the loop is
1985 // entered, because `n` of minus one runs no times and the distance is minus one.
1986 let mut names = Interner::new();
1987 let mut func = Func::new(names.intern("f"), Signature::new());
1988 let entry = func.create_block();
1989 let header = func.create_block();
1990 let body = func.create_block();
1991 let exit = func.create_block();
1992 let limit = func.append_param(entry, Type::int(32));
1993 let counter = func.append_param(header, Type::int(32));
1994
1995 let mut build = Builder::new(&mut func, entry);
1996 let zero = build.iconst(Type::int(32), 0);
1997 build.jump(header, &[zero]);
1998 let mut build = Builder::new(&mut func, header);
1999 let test = build.icmp(IntPred::Slt, counter, limit);
2000 build.br_if(test, body, &[], exit, &[]);
2001 let mut build = Builder::new(&mut func, body);
2002 let one = build.iconst(Type::int(32), 1);
2003 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2004 build.jump(header, &[next]);
2005 let mut build = Builder::new(&mut func, exit);
2006 build.ret(&[]);
2007
2008 let found = bound(&func).expect("it is counted");
2009 let (count, assumptions) = found.parts();
2010 assert_eq!(count, Count::Symbolic(Invariant::of(limit)));
2011 assert!(assumptions.contains(&Assumption::Entered), "{assumptions:?}");
2012 assert!(assumptions.contains(&Assumption::StrictOverflow), "{assumptions:?}");
2013 assert_eq!(found.proven(), None);
2014 }
2015
2016 /// `for (c = n; c != limit; c--)`, with the counter in sixty four bits and no flags on it.
2017 fn down_to(limit: i128) -> (Func, Value) {
2018 let mut names = Interner::new();
2019 let mut func = Func::new(names.intern("f"), Signature::new());
2020 let entry = func.create_block();
2021 let header = func.create_block();
2022 let body = func.create_block();
2023 let exit = func.create_block();
2024 let start = func.append_param(entry, Type::int(64));
2025 let counter = func.append_param(header, Type::int(64));
2026
2027 let mut build = Builder::new(&mut func, entry);
2028 build.jump(header, &[start]);
2029 let mut build = Builder::new(&mut func, header);
2030 let limit = build.iconst(Type::int(64), limit);
2031 let test = build.icmp(IntPred::Ne, counter, limit);
2032 build.br_if(test, body, &[], exit, &[]);
2033 let mut build = Builder::new(&mut func, body);
2034 let one = build.iconst(Type::int(64), 1);
2035 let next = build.binary(Opcode::Sub, counter, one, Flags::NONE);
2036 build.jump(header, &[next]);
2037 let mut build = Builder::new(&mut func, exit);
2038 build.ret(&[]);
2039 (func, start)
2040 }
2041
2042 #[test]
2043 fn a_countdown_to_zero_is_always_heading_for_it() {
2044 let (func, start) = down_to(0);
2045 let found = bound(&func).expect("it is counted");
2046 let (count, assumptions) = found.parts();
2047 assert_eq!(count, Count::Symbolic(Invariant::of(start)));
2048 assert!(!assumptions.contains(&Assumption::Approaching), "{assumptions:?}");
2049 }
2050
2051 #[test]
2052 fn a_countdown_tested_after_its_step_is_counted_when_it_cannot_wrap() {
2053 // The shape ivopts writes: the variable starts one above the count and the header takes
2054 // one off before the test, so what the test sees starts at the start less one.
2055 for (flags, counted) in [(Flags::NSW | Flags::NUW, true), (Flags::NSW, false)] {
2056 let mut names = Interner::new();
2057 let mut func = Func::new(names.intern("f"), Signature::new());
2058 let entry = func.create_block();
2059 let header = func.create_block();
2060 let body = func.create_block();
2061 let exit = func.create_block();
2062 let start = func.append_param(entry, Type::int(64));
2063 let counter = func.append_param(header, Type::int(64));
2064
2065 Builder::new(&mut func, entry).jump(header, &[start]);
2066 let mut build = Builder::new(&mut func, header);
2067 let one = build.iconst(Type::int(64), 1);
2068 let next = build.binary(Opcode::Sub, counter, one, flags);
2069 let zero = build.iconst(Type::int(64), 0);
2070 let test = build.icmp(IntPred::Ne, next, zero);
2071 build.br_if(test, body, &[], exit, &[]);
2072 Builder::new(&mut func, body).jump(header, &[next]);
2073 Builder::new(&mut func, exit).ret(&[]);
2074
2075 let found = bound(&func);
2076 assert_eq!(found.is_some(), counted, "{flags:?}");
2077 if let Some(found) = found {
2078 let at = Invariant::of(start).plus(Invariant::number(-1)).expect("it adds");
2079 assert_eq!(found.comes_back(), Some(Count::Symbolic(at)));
2080 }
2081 }
2082 }
2083
2084 #[test]
2085 fn a_countdown_to_anything_else_may_have_started_below_it() {
2086 // Started at zero, this one goes all the way round before it gets to one.
2087 let (func, _) = down_to(1);
2088 let found = bound(&func).expect("it is counted");
2089 let (_, assumptions) = found.parts();
2090 assert!(assumptions.contains(&Assumption::Approaching), "{assumptions:?}");
2091 }
2092
2093 #[test]
2094 fn the_count_records_which_reading_its_test_took() {
2095 // What a consumer widening a symbolic count has to know. The limit is a value of the
2096 // counter's type and which number that value is depends on how its test read it.
2097 let signed = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
2098 assert_eq!(bound(&signed.func).expect("it is counted").reading(), Reading::Signed);
2099 let unsigned = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
2100 assert_eq!(bound(&unsigned.func).expect("it is counted").reading(), Reading::Unsigned);
2101 }
2102
2103 #[test]
2104 fn a_counter_without_a_no_wrap_promise_carries_the_assumption_instead() {
2105 // An inclusive test, because the strict one is the case the test itself answers. Under
2106 // `<=` the counter reaches the limit and is stepped once more, so a limit at the top of
2107 // the type makes that last step the one that wraps and nothing here rules it out.
2108 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ule, Flags::NONE);
2109 let found = bound(&it.func).expect("it is counted");
2110 let (_, assumptions) = found.parts();
2111 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
2112 }
2113
2114 #[test]
2115 fn an_unsigned_counter_stepping_by_one_is_held_by_its_own_test() {
2116 // `for (unsigned i = 0; i < n; i++)` written out. Unsigned arithmetic wraps in C so the
2117 // increment carries no `nuw`, and without reading the test this would rest on an
2118 // assumption nothing downstream can discharge.
2119 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NONE);
2120 let found = bound(&it.func).expect("it is counted");
2121 assert_eq!(found.assumptions(), &[]);
2122 assert_eq!(found.proven(), Some(Count::Exact(100)));
2123 }
2124
2125 #[test]
2126 fn counting_down_by_one_is_held_the_same_way() {
2127 let it = counted(Type::int(32), 100, 0, -1, IntPred::Ugt, Flags::NONE);
2128 let found = bound(&it.func).expect("it is counted");
2129 assert_eq!(found.assumptions(), &[]);
2130 assert_eq!(found.proven(), Some(Count::Exact(100)));
2131 }
2132
2133 #[test]
2134 fn a_step_of_two_can_jump_the_limit_so_the_test_holds_nothing() {
2135 // The counter is never at the limit, so the loop can be left by a step that goes from one
2136 // below the limit to one past the top of the type and comes back round at the bottom.
2137 let it = counted(Type::int(32), 0, 100, 2, IntPred::Ult, Flags::NONE);
2138 let found = bound(&it.func).expect("it is counted");
2139 let (_, assumptions) = found.parts();
2140 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
2141 }
2142
2143 #[test]
2144 fn a_test_the_counter_can_be_stepped_without_being_asked_gives_no_count() {
2145 // ```text
2146 // header(i): br_if flag, check, latch
2147 // check: br_if i <u 100, latch, exit
2148 // latch: jump header(i + 1)
2149 // ```
2150 // The counter goes round by a path that never reaches the test, so the test says nothing
2151 // about how far the counter got, and with `flag` false the loop never ends at all.
2152 let mut names = Interner::new();
2153 let mut func = Func::new(names.intern("f"), Signature::new());
2154 let entry = func.create_block();
2155 let header = func.create_block();
2156 let check = func.create_block();
2157 let latch = func.create_block();
2158 let exit = func.create_block();
2159 let flag = func.append_param(entry, Type::int(1));
2160 let counter = func.append_param(header, Type::int(32));
2161
2162 let mut build = Builder::new(&mut func, entry);
2163 let zero = build.iconst(Type::int(32), 0);
2164 build.jump(header, &[zero]);
2165 let mut build = Builder::new(&mut func, header);
2166 build.br_if(flag, check, &[], latch, &[]);
2167 let mut build = Builder::new(&mut func, check);
2168 let limit = build.iconst(Type::int(32), 100);
2169 let test = build.icmp(IntPred::Ult, counter, limit);
2170 build.br_if(test, latch, &[], exit, &[]);
2171 let mut build = Builder::new(&mut func, latch);
2172 let one = build.iconst(Type::int(32), 1);
2173 let next = build.binary(Opcode::Add, counter, one, Flags::NONE);
2174 build.jump(header, &[next]);
2175 let mut build = Builder::new(&mut func, exit);
2176 build.ret(&[]);
2177
2178 assert!(bound(&func).is_none());
2179 }
2180
2181 #[test]
2182 fn a_test_asked_only_once_another_one_passes_gives_no_count() {
2183 // `while (i != 1024 || j <= 0) { i *= 2; ++j; }`, which is gcc.c-torture 20000731-2.
2184 //
2185 // ```text
2186 // header(i, j): br_if i != 1024, latch, check
2187 // check: br_if j <= 0, latch, exit
2188 // latch: jump header(i + i, j + 1)
2189 // ```
2190 // `j <= 0` first fails on the second iteration and the loop runs ten, because the test is
2191 // only asked once `i` is 1024. Reading a count off it said `j` ends at one.
2192 let mut names = Interner::new();
2193 let mut func = Func::new(names.intern("f"), Signature::new());
2194 let entry = func.create_block();
2195 let header = func.create_block();
2196 let check = func.create_block();
2197 let latch = func.create_block();
2198 let exit = func.create_block();
2199 let (i, j) =
2200 (func.append_param(header, Type::int(32)), func.append_param(header, Type::int(32)));
2201
2202 let mut build = Builder::new(&mut func, entry);
2203 let one = build.iconst(Type::int(32), 1);
2204 let zero = build.iconst(Type::int(32), 0);
2205 build.jump(header, &[one, zero]);
2206 let mut build = Builder::new(&mut func, header);
2207 let top = build.iconst(Type::int(32), 1024);
2208 let short = build.icmp(IntPred::Ne, i, top);
2209 build.br_if(short, latch, &[], check, &[]);
2210 let mut build = Builder::new(&mut func, check);
2211 let none = build.iconst(Type::int(32), 0);
2212 let again = build.icmp(IntPred::Sle, j, none);
2213 build.br_if(again, latch, &[], exit, &[]);
2214 let mut build = Builder::new(&mut func, latch);
2215 let twice = build.binary(Opcode::Add, i, i, Flags::NONE);
2216 let step = build.iconst(Type::int(32), 1);
2217 let next = build.binary(Opcode::Add, j, step, Flags::NSW);
2218 build.jump(header, &[twice, next]);
2219 let mut build = Builder::new(&mut func, exit);
2220 build.ret(&[]);
2221
2222 assert!(bound(&func).is_none());
2223 }
2224
2225 #[test]
2226 fn a_test_that_ends_the_loop_when_it_succeeds_is_read_the_other_way_round() {
2227 // `for (i = 0; ; i++) if (i >= 100) break;`, which is the same loop with the arms of the
2228 // branch swapped. The test that keeps the loop going is the opposite of the one written.
2229 let mut names = Interner::new();
2230 let mut func = Func::new(names.intern("f"), Signature::new());
2231 let entry = func.create_block();
2232 let header = func.create_block();
2233 let body = func.create_block();
2234 let exit = func.create_block();
2235 let counter = func.append_param(header, Type::int(32));
2236
2237 let mut build = Builder::new(&mut func, entry);
2238 let zero = build.iconst(Type::int(32), 0);
2239 build.jump(header, &[zero]);
2240 let mut build = Builder::new(&mut func, header);
2241 let limit = build.iconst(Type::int(32), 100);
2242 let done = build.icmp(IntPred::Sge, counter, limit);
2243 build.br_if(done, exit, &[], body, &[]);
2244 let mut build = Builder::new(&mut func, body);
2245 let one = build.iconst(Type::int(32), 1);
2246 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2247 build.jump(header, &[next]);
2248 let mut build = Builder::new(&mut func, exit);
2249 build.ret(&[]);
2250
2251 let (count, _) = bound(&func).expect("it is counted").parts();
2252 assert_eq!(count, Count::Exact(100));
2253 }
2254
2255 #[test]
2256 fn an_unsigned_limit_past_the_middle_of_its_type_is_not_a_negative_one() {
2257 // `for (unsigned char i = 0; i < 200; i++)`. Two hundred does not fit in a signed byte
2258 // and the constant is held as minus fifty six, so a distance taken at face value is
2259 // negative and reads as a loop that runs no times.
2260 let it = counted(Type::int(8), 0, 200, 1, IntPred::Ult, Flags::NUW);
2261 let found = bound(&it.func).expect("it is counted");
2262 assert_eq!(found.proven(), Some(Count::Exact(200)));
2263 }
2264
2265 #[test]
2266 fn a_walk_that_lands_on_a_not_equal_limit_exactly_is_counted() {
2267 // `while (i != 10)` counting by one, which is `while (p != end)` over an array once the
2268 // element size has been divided out. `!=` says nothing about how its operands are read,
2269 // so the promise it wants is the unsigned one and an `nsw` on its own is not enough.
2270 let it = counted(Type::int(32), 0, 10, 1, IntPred::Ne, Flags::NSW.union(Flags::NUW));
2271 let found = bound(&it.func).expect("it lands on its limit");
2272 // The step divides the distance and both are numbers, so it was checked rather than
2273 // assumed and there is nothing left over.
2274 assert_eq!(found.proven(), Some(Count::Exact(10)));
2275 }
2276
2277 #[test]
2278 fn a_counter_stepping_away_from_a_not_equal_limit_is_not_a_loop_that_runs_no_times() {
2279 // The distance is negative and an ordering test would read that as the loop never being
2280 // entered. `!=` reads it as the counter never arriving, which is an endless loop, and
2281 // answering zero for it was a real bug that the property test in `tests/scev.rs` found.
2282 let it = counted(Type::int(32), 48, 15, 1, IntPred::Ne, Flags::NSW);
2283 assert_eq!(bound(&it.func), None);
2284 }
2285
2286 #[test]
2287 fn a_counter_stepping_over_a_not_equal_limit_never_arrives_either() {
2288 // Zero, three, six, nine, twelve, and ten is never one of them. An ordering test would
2289 // have stopped at twelve.
2290 let it = counted(Type::int(32), 0, 10, 3, IntPred::Ne, Flags::NSW);
2291 assert_eq!(bound(&it.func), None);
2292 }
2293
2294 #[test]
2295 fn an_estimate_is_the_count_when_there_is_one_and_a_guess_when_there_is_not() {
2296 let counted_loop = counted(Type::int(32), 0, 7, 1, IntPred::Slt, Flags::NSW);
2297 let (cfg, loops) = analyse(&counted_loop.func);
2298 let id = loops.roots()[0];
2299 let estimate = Scev::new(&counted_loop.func, &cfg, &loops).estimate(id);
2300 assert_eq!(estimate.iterations(), 7);
2301 assert!(!estimate.is_guess());
2302
2303 // A loop this cannot count still has to answer, because the caller is deciding whether
2304 // something is worth doing rather than whether it is legal.
2305 let uncounted = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
2306 let (cfg, loops) = analyse(&uncounted.func);
2307 let id = loops.roots()[0];
2308 let estimate = Scev::new(&uncounted.func, &cfg, &loops).estimate(id);
2309 assert!(estimate.is_guess());
2310 assert_eq!(estimate.iterations(), super::ASSUMED_ITERATIONS);
2311 }
2312
2313 #[test]
2314 fn a_value_the_loop_does_not_touch_is_invariant_rather_than_unknown() {
2315 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
2316 let (cfg, loops) = analyse(&it.func);
2317 let id = loops.roots()[0];
2318 let mut scev = Scev::new(&it.func, &cfg, &loops);
2319 // The counter's start is an `iconst` in the entry block, which is both.
2320 assert_eq!(
2321 scev.evolution(id, it.counter).chrec().expect("it evolves").base,
2322 Invariant::number(0)
2323 );
2324 }
2325
2326 #[test]
2327 fn a_back_edge_of_its_own_does_not_hide_the_counter() {
2328 // What canonicalization leaves behind. The back edge goes through a block that does nothing
2329 // but pass the increment on, so the value arriving at the header is a parameter of that
2330 // block rather than the increment itself. Reading through it is undoing a rename and not an
2331 // analysis, and without it the trip count of every loop the pipeline produces is nothing.
2332 let mut names = Interner::new();
2333 let mut func = Func::new(names.intern("f"), Signature::new());
2334 let entry = func.create_block();
2335 let header = func.create_block();
2336 let body = func.create_block();
2337 let latch = func.create_block();
2338 let exit = func.create_block();
2339 let counter = func.append_param(header, Type::int(32));
2340 let carried = func.append_param(latch, Type::int(32));
2341
2342 let start = Builder::new(&mut func, entry).iconst(Type::int(32), 0);
2343 Builder::new(&mut func, entry).jump(header, &[start]);
2344
2345 let mut build = Builder::new(&mut func, header);
2346 let limit = build.iconst(Type::int(32), 100);
2347 let test = build.icmp(IntPred::Slt, counter, limit);
2348 build.br_if(test, body, &[], exit, &[]);
2349
2350 let mut build = Builder::new(&mut func, body);
2351 let by = build.iconst(Type::int(32), 1);
2352 let next = build.binary(Opcode::Add, counter, by, Flags::NSW);
2353 build.jump(latch, &[next]);
2354
2355 Builder::new(&mut func, latch).jump(header, &[carried]);
2356 Builder::new(&mut func, exit).ret(&[]);
2357
2358 let chrec = evolution(&func, counter).chrec().expect("the counter still evolves");
2359 assert_eq!(chrec.base, Invariant::number(0));
2360 assert_eq!(chrec.step, Invariant::number(1));
2361 let (count, _) = bound(&func).expect("it is still counted").parts();
2362 assert_eq!(count, Count::Exact(100));
2363 }
2364
2365 #[test]
2366 fn every_assumption_says_what_it_is_in_a_line() {
2367 let it = counted(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE);
2368 let found = bound(&it.func).expect("it is counted");
2369 for assumption in found.assumptions() {
2370 let line = assumption.describe();
2371 assert!(!line.is_empty());
2372 assert!(!line.contains('\n'), "an assumption is one line: {line}");
2373 }
2374 }
2375}