---
title: "Optgen: A Generator for Local Optimizations (2015)"
description: "Optgen searches for and verifies local compiler rewrites, then uses them to test which simplifications existing compilers miss."
canonical: "https://research.elamur.ai/free/en/papers/buchwald-2015-optgen-generator-local-optimizations/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/buchwald-2015-optgen-generator-local-optimizations/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2015](https://md.research.elamur.ai/free/en/papers/2015/) / Optgen: A Generator for Local Optimizations

# Optgen: A Generator for Local Optimizations

Paper · 2015 · Sebastian Buchwald

**Authors:** Sebastian Buchwald · **Year:** 2015 · **Venue:** Lecture notes in computer science · **Licence:** No open licence stated (free-to-read copy; rights reserved) — text kept private

Cited by **4** papers in our library of more than 163,000 papers whose bibliographies we read · Lecture notes in computer science

- [PDF](https://link.springer.com/content/pdf/10.1007/978-3-662-46663-6_9.pdf)
- [DOI 10.1007/978-3-662-46663-6_9](https://doi.org/10.1007/978-3-662-46663-6_9)

## Summary

A compiler can often replace a small calculation with a cheaper one by inspecting just the operations that produce its result. The difficulty is deciding which replacements to teach the compiler. A collection written by hand can leave out useful identities, particularly when arithmetic and bitwise operations interact or when a rule depends on a particular constant. Optgen turns the construction of that collection into a search. It enumerates integer expressions within a cost bound, looks for cheaper expressions with the same behavior, and verifies the proposed rewrites with a satisfiability modulo theories solver. The search takes place at the compiler’s intermediate representation, where relationships between operations are available directly through their operands.

Constants pose the largest practical problem. Even a binary operation with constant operands has too many concrete cases to enumerate directly at a wide integer width. Optgen groups rules that have the same structure and looks for a shared explanation. A generalized rule can compute a constant for the replacement, require a condition on its input constants, or do both. The paper also separates the width at which examples are discovered from the width at which a rewrite is proved. A search over narrow integers can suggest a wide-integer identity, which the solver then checks at the destination width. Each successful check establishes the validity of that rule at that width. Coverage of the wider search space is a separate question.

Optgen generated tests that identified 63 local optimizations missing from at least one of GCC 4.9, LLVM 3.5, and ICC 15. These tests came from the configuration with constants and a pattern bound of two operations. The paper also found cases where a compiler applied an identity even though an intermediate result was shared with another calculation. A replacement can use fewer operations as an isolated expression and still increase the work in the surrounding program when the original operations have to remain.

A separate experiment used libFirm and SPEC CINT2000 to study what happens when a compiler repeatedly applies local optimizations until the program stops changing. The paper reports a 3.22 % average reduction in executed instructions for that phase. It then enabled analyses that identify which bits have known values and which bits can affect observable results. With those analyses, it reports a further 0.64 % average improvement by the same measure, with an improvement of 3.14 % for 186.crafty. The compiler tests establish coverage and placement problems for particular rewrites. The benchmark experiment measures the effect of an optimization phase and its analyses on complete programs.

## Deep dive: Optgen: A Generator for Local Optimizations

Optgen searches for and verifies local compiler rewrites, then uses them to test which simplifications existing compilers miss. · about 35 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### What makes a compiler rewrite local

A compiler represents a program internally before it selects the final machine instructions. This intermediate representation, or IR, gives optimization passes a vocabulary for describing calculations and how their results are used. An addition, a bitwise operation, and a constant can each appear as parts of an expression in the IR. A local rewrite matches a small pattern in that expression and substitutes an equivalent expression. Its applicability can be determined from the values and operations named by the pattern, so the compiler can use it even while constructing the IR.

A pattern that examines a small number of operations can reach across a larger region of the program. The paper illustrates this using static single assignment form, or SSA. When a value has a single definition, the compiler can follow an operand from its use back to the operation that defines it. The operations involved in one rewrite can therefore be separated in the program’s layout. The pattern stays local because it follows a bounded set of dependencies.

The paper’s example uses an inclusive OR whose operand is an exclusive OR. If the outer OR already includes one of the inputs to the exclusive OR, the inner operation can be replaced so that the result uses a single inclusive OR. At a bit where the shared input is set, the outer OR already determines the result. At a bit where that input is clear, the exclusive OR passes through the other input. In the IR graph, the pattern can follow the relevant operands to recognize these relationships. In the assembly layout shown in the paper, intervening basic blocks separate the instructions involved. A peephole rule that looks for the corresponding instruction sequence cannot match it there. A sequence matcher must account for any intervening basic blocks, which are straight-line regions of the program, even if those blocks contribute nothing to the expression under simplification.

There are also identities that are less easy to spot from their surface form. A specific mask can interact with subtraction so that a longer calculation preserves only the top bit of an input. A negation surrounding an addition and a subtraction can sometimes be eliminated by expressing the result with a different grouping. A compiler engineer could discover and implement each transformation individually. The paper asks how to find a collection systematically, with a way to check each member against the [semantics](https://md.research.elamur.ai/free/en/concepts/semantics/) of the operations.

This makes validity and coverage distinct parts of the problem. A valid rewrite preserves the result wherever its stated conditions apply. A search with good coverage finds the improvements that fit its declared language and budget. Verification can establish validity for a supplied rule. To make a claim about coverage, the system also needs a defined space of candidates and a reason its enumeration or pruning accounts for that space. For Optgen that space depends on the available operations, their costs, the bound, and the integer width.

#### From a better instruction sequence to a collection of rules

The paper situates Optgen in the history of superoptimization. It describes Massalin’s approach as taking a particular assembly instruction sequence and enumerating alternatives to find a shortest equivalent sequence. Candidate sequences can be tested on selected inputs before undergoing a more expensive equivalence check. The paper also describes an early pruning method that rejects a sequence containing a known suboptimal subsequence. Both ideas have counterparts in Optgen. Its evaluation on sample inputs filters comparisons, and its rule matcher avoids considering larger expressions whose simplification is already covered.

Denali, as discussed in the paper, starts with stated equivalences and uses them to explore ways to express a given computation. It represents equivalent forms together in an E-graph. Once it has those forms, it asks whether a realization fits a cycle budget. A satisfying assignment can identify a realization at the budget, and ruling out the next lower budget establishes minimality within that search. The reuse of equivalences is central to Denali. For Optgen, discovering the equivalences that will become rewrite rules is itself the job.

The paper discusses STOKE as another way to manage a large search. Its sampling procedure can explore longer alternative instruction sequences by giving up a guarantee of optimality. The paper notes that such sequences can sometimes express a computation in a substantially different way. Optgen chooses bounded enumeration because the intended product is a collection of small rules with a well-defined scope. The earlier search approaches illustrate how the goal of the search determines which regions are worth exploring and what kind of guarantee is useful.

Finding an improvement for one specific sequence can take too long to repeat as a standard phase of a general-purpose compiler. Bansal and Aiken’s approach moves the search before ordinary compilation. It starts by compiling training programs and collecting candidate instruction sequences. Running those sequences on selected inputs provides a way to index them by behavior. The tool then enumerates short instruction sequences and looks for matching entries, followed by more testing and a Boolean satisfiability check. A compiler can subsequently look up the resulting rules. Optgen shares that division between expensive discovery and inexpensive use, while moving the search to expressions in the IR. [Automatic Generation of Peephole Superoptimizers](https://md.research.elamur.ai/free/en/papers/bansal-2006-automatic-generation-peephole-superoptimizers/)

The assembly level provides access to target instructions and supports target-specific cost estimates. The IR makes data dependencies and shared values easier to see, and it provides a place to express a simplification that can be common to several targets. The paper also recognizes earlier work at the IR level. It describes ALIVe as a means of checking supplied local optimizations, and it points to Tate and colleagues’ use of ideas from Denali in an intermediate representation. Optgen’s contribution is the systematic discovery of bounded local integer rewrites and the treatment of constants that discovery requires.

#### Why constants change the search

The difference between useful coverage and practical enumeration becomes sharp when the operands can be constants. On a 32-bit architecture there are 2³² possible values for a single constant, and the paper gives 2⁶⁴ as the number of constant-folding cases for each binary operation if every pair of literals is written out. Constant folding means evaluating an operation during compilation when its operands are already known. A compiler needs a way to express that whole family compactly, even for a simple operation.

Only allowing a small set of literals makes the candidate space manageable, an approach the paper describes for earlier peephole generators. It also leaves out identities that depend on other values or on relationships between constants. A mask that keeps just the top bit is one example of a value with a structural role. More broadly, an identity might hold whenever masks are disjoint, with no particular mask value fixed in advance. A useful rule language needs to express both kinds of identity. Optgen therefore treats concrete enumeration as a source of candidates, introduces symbolic constants to represent families, and verifies the resulting rules at the width where they will be used.

### The method, step by step

#### From expressions to verified replacements

The inputs are a choice of operations, a cost for each operation, a cost limit, and an integer bit width. The implementation described in the paper supports bitwise complement and negation as unary operations, together with addition, subtraction, AND, OR, and exclusive OR as binary operations. The paper describes two implementation requirements for adding an operation. Optgen must be able to evaluate it on constant operands and translate it to the solver’s language. These serve different parts of the search. Direct evaluation supplies sample results quickly, and the translation gives a precise meaning to the operation in a proof.

A bit width fixes how many bits each operand and result contains. Bitwise operations act at corresponding positions in those fixed-width values. AND sets a result bit when both inputs have a set bit, OR sets it when an input does, exclusive OR sets it when the inputs differ, and complement flips all the bits. Fixed-width arithmetic and bitwise operations can therefore be considered together. For arithmetic identities that depend on discarded high bits or on the location of the top bit, the width is an essential part of the claim being checked.

How Optgen discovers and verifies local rewrites The steps in order.

Before enumeration, Optgen produces random input assignments. An expression’s outputs on these assignments determine a semantic hash used to look up expressions that might be equivalent to it. If the outputs differ for an assignment, that assignment demonstrates that the expressions differ. Agreement on a finite sample leaves open the possibility of a difference elsewhere. The semantic hash is a search index whose candidates still need checking.

The paper walks through a configuration for 8-bit AND and OR, each with cost 1, with a cost limit of 2. For cost 0, Optgen introduces the variable `x` and all constant values from 0 to 255. At this point the rule matcher has no previously discovered rewrites to consult. The generator sends expressions onward to the semantic checker, which looks in the corresponding hash bucket. A bucket is the collection of expressions associated with a hash value. When a new expression has no equivalent representative there, it is retained for subsequent comparisons and for constructing expressions of higher cost.

The next cost level can contain a binary operation, so Optgen introduces `y` as another variable. It forms an AND with `x` in both operands. This expression has the same behavior as the simpler variable for every input the generator tries. The solver establishes that the agreement holds over the entire domain of the test width. Because the variable costs less, the resulting identity becomes a directed rewrite.

```
x & x → x
```

Here `x` denotes an input value. The symbol `&` is bitwise AND and `→` directs the rewrite from the matched expression to its replacement. The fact that `x` appears twice on the left means both operands must be the same value.

The search also finds that an AND with a zero operand can be replaced by zero. On an expression such as `x & 1`, the procedure may instead encounter a misleading hash match. The paper uses the constant `1` as a hypothetical candidate from that bucket. If the candidate fails the solver check, the generator retains the new expression under the same hash for future searches. A collision can arise because inputs used for hashing fail to distinguish expressions, and hashing itself is used only to select candidates for closer comparison.

At the next cost level, the generator can form an outer AND between an inner AND and zero. The known rule for AND with zero applies with the whole inner operation in place of its variable. The matcher can discard this candidate before semantic checking. That avoids rediscovering the same improvement with an unnecessary restriction on the left side. The general rule remains available to simplify every such instance, including ones built from operations other than AND.

For an equivalence check, the solver receives the question of whether the two expressions can return different results on any common assignment. A satisfiable check supplies an assignment that separates the expressions. If there is no such assignment, the equality holds throughout the selected fixed-width domain. With a conditional rule, the same question is restricted to assignments that satisfy the rule’s condition. The cost comparison gives the direction of a discovered optimization. The solver establishes equal results, leaving the cost attached to the expression and the placement of the resulting rewrite to different parts of the process.

#### Finding a rule that matches

Matching is frequent enough to warrant its own index. Every generated expression can be checked against prior rewrites, and the same machinery helps identify individual rules covered by a more general one. Optgen builds a tree from the left sides of rules. To insert a rule, it visits the root operation before its operands and proceeds recursively in that order. This is a preorder traversal. A path in the index records the sequence of operation and operand types encountered, with the actual rule available at a leaf.

Searching follows the same traversal. A variable in a rule can match a whole operand expression. In that case the search can skip the descendants of that operand in the candidate and continue with the next position in the enclosing pattern. Several branches of the index can fit the same operation because a rule might name that operation explicitly or accept a variable in its place. The index finds plausible rules. Exact literals, repeated variables, and any condition on captured constants still determine whether a rule applies.

The paper traces the matcher on an OR with the constant `3`, followed by an AND with `1`. One branch leads to the rule for AND with zero. The inner OR is acceptable as the value of the variable, but `1` differs from the required zero. Another branch leads to a rule for an OR followed by an AND where the constants have to be bitwise disjoint. This time the expression has the required structure and the two constants can be bound. Their set bits overlap, so the condition fails. The example shows why reaching a leaf in the tree is only part of deciding applicability.

#### Making semantic comparisons cheaper

If the hash bucket contains several representatives, doing a solver check against each of them would make collisions expensive. Optgen equips each bucket with witnesses, input assignments on which particular members differ. It maintains the property that for every pair in a bucket, some witness in that bucket distinguishes the pair. A new expression can agree with at most one representative on all the witnesses. Agreement with two would require those two to agree with each other on their distinguishing assignment.

The generator first evaluates the new expression on the bucket’s witnesses. A representative that disagrees on any witness can be discarded from the comparison. If there is a survivor, Optgen performs the solver check against it. If that check finds a difference, the new expression has to be inserted as a separate representative. The counterexample returned by the solver is the witness needed to distinguish the new entry from the survivor. Earlier witnesses already distinguish it from the other entries eliminated by evaluation. In this part of the enumeration, the invariant limits the expensive step to at most one solver check for each generated expression that reaches semantic comparison. Generalizing rules and rechecking them at a different width are additional proof tasks.

The initial random sample and the bucket-specific witnesses have complementary roles. Random assignments supply a common way to look up possible equivalents across the enumeration. Witnesses are drawn from particular failed comparisons, so they document distinctions that actually matter inside a bucket. The final equivalence decision remains a proof. This separation lets the generator use empirical evaluations extensively while requiring validity over all fixed-width inputs for a rewrite it accepts.

#### Generalizing constants from concrete rules

Rules for constant folding emerge initially as instances with literal values on both sides. These instances contain redundant information. If both arguments of an AND are known during compilation, a single rule can instruct the compiler to evaluate the AND at compilation time. More interesting rules may compute a new literal from a subset of the input literals and place the result inside an expression that still has runtime inputs.

Optgen groups instances by a syntax hash computed from their shape while ignoring the values of constants. Unlike the semantic hash, this hash organizes concrete rules for generalization. The generalizer considers collections whose expressions have the same syntactic structure. It then tries to explain each replacement constant as a function of the constants available on the left side. In the paper’s implementation, candidate functions come from the expressions already enumerated. Their ordering by cost gives simpler expressions priority.

```
f(x, y) = x & y
```

In this formula, `f` is the function being sought to compute the replacement literal. The arguments `x` and `y` are placeholders for the values of the matched constants in this function, `=` specifies the function’s result, and `&` is bitwise AND. In the paper’s example, constant pairs drawn from the concrete folding rules provide sample inputs to `f`, and the known results on their right sides give the expected outputs.

```
c0 & c1 → eval(c0 & c1)
```

Here `c0` and `c1` are symbolic constants. A match binds each to a literal already present in the expression. The left-side `&` is the matched AND, while `eval` on the right denotes evaluation during compilation. The `→` symbol gives the replacement direction. The new rule can cover the whole family if it passes verification. A function that fits the concrete examples can still fail to explain the general case, in which case the solver rejects the proposal and the generalizer continues searching.

A different kind of generalization is needed when a rewrite has the right structure only for certain constants. The examples in the paper include an OR by a constant inside an AND by another constant. The inner OR sets some bits regardless of the runtime value. If the outer AND clears every one of those positions, the inner OR is redundant. If the masks overlap, the OR can contribute a set bit that survives the AND. Optgen searches its enumerated expressions for a function of the symbolic constants whose zero result marks the applicable cases. In the example it finds the intersection of the two masks.

```
(c1 & c2) == 0 ⇒ (x | c1) & c2 → x & c2
```

Here `x` is the runtime input and `c1` and `c2` stand for matched constants. The operators `&` and `|` are bitwise AND and OR, respectively. The test `== 0` asks whether the intersection has any set bits. The implication `⇒` makes that test a precondition for the rewrite `→`. The `0` is the all-clear bit vector at the checked width. The solver checks that whenever the precondition holds, both calculations give equal results for any `x`. Computing the precondition from constants alone makes it possible to decide whether the rule applies during compilation.

Pruning affects what the generalizer can observe. The paper points out that the disjoint-mask rule covers a case where the outer AND uses zero, but that concrete expression would have been discarded by the simpler rule for AND with zero. Thus the set of concrete examples for a generalization is partial. The paper proposes using superoptimization to look for expressions consistent with those partial functions. If a candidate generalization were invalid, the verifier’s counterexample could refine the partial information and drive another search. In the implemented search, the required expressions for the constant computations and the precondition must already be available from enumeration.

#### Discovering with narrow integers and verifying with wider ones

Symbolic constants make it possible to retain the same rule syntax while changing the bit width. The rule for disjoint masks can be constructed from 8-bit examples and expressed again for 32-bit operands. At each width the verifier checks a statement about the complete domain for that width. A successful narrow proof is evidence that the structure is worth trying, and the wide proof is the authority for its use on wide operands.

A literal that survives generalization needs a way to be translated. For the remaining concrete constants, Optgen tries padding their most significant or least significant ends with zeros or ones. The paper describes four possibilities and sends the resulting candidates to the solver. Padding at the high end can preserve a pattern among the low bits, and padding at the low end can preserve the placement of a pattern relative to the high end. A candidate that changes an essential property of the rule will fail verification. The authors report that these extensions were sufficient in their experience to obtain the corresponding wider rules.

The authors also compare what happens when the generation width increases while the verification width stays fixed. They report that for complement, AND, OR, and exclusive OR with a cost limit of 3, generating at 3 bits and at 4 bits yielded the same 32-bit rule set. The agreement shows that the larger search produced no additional rules in that comparison. The ability to prove a candidate at the destination width and the ability to find all useful candidates there are separate. The former follows from the proof for that candidate. The latter depends on what the narrow search, the generalizer, and the extension procedure can express and discover.

#### Using information about individual bits

The paper then moves from generating rules to using them in a compiler. Local simplifications can already be tried during IR construction. A later phase can keep applying them until no further changes occur, a state called a fixpoint. Such a phase gives the compiler an opportunity to compute information about a larger part of the program and use that information to enable rewrites with broader conditions.

The running example is an addition by a constant followed by a mask. Some positions in the sum can be unaffected by the addition. When the mask selects only those positions, the addition can be dropped from the computation of that masked result. The paper expresses the case with symbolic constants as follows.

```
((c0 | −c0) & c1) == 0 ⇒ (x + c0) & c1 → x & c1
```

Here `c0` is the addend and `c1` is the mask, both compile-time constants. The input `x` can vary at runtime. The signs `+` and unary `−` denote fixed-width addition and negation. The operators `|` and `&` are bitwise OR and AND. The test `== 0` asks whether the mask selects any bits flagged by the condition expression. If it does not, `⇒` permits the rewrite directed by `→`. Parentheses specify which operation applies to which operands. The expression combining the addend with its negation supplies a mask of positions that can be affected by adding that constant.

The constant-bit analysis extends the observation from literals to arbitrary values with known bits. For `y & 42`, the paper gives `00?0 ?0?0` for the low 8 bits. Here a zero denotes a guaranteed clear bit and `?` denotes a position whose value is unknown to the analysis. With `y | 42` it obtains `??1? 1?1?`, where a one denotes a guaranteed set bit. The analysis stores its information in two vectors. In `zeros`, a clear bit denotes a guaranteed zero and a set bit leaves open the possibility of a one. In `ones`, a set bit denotes a guaranteed one and a clear bit leaves open the possibility of a zero.

This is a forward data-flow analysis. Information about operands is propagated to the operations that use them. The analysis starts optimistically with the `zeros` vectors filled with clear bits and the `ones` vectors filled with set bits. It then updates information according to the operations until it reaches a fixpoint. A literal supplies exact information. A load from memory is treated as unknown in the transfer described in the paper, with all positions set in `zeros` and cleared in `ones`.

For AND and OR, the transfer applies the corresponding bitwise operator to the respective operand vectors. The paper gives this example for bits known to be set.

```
ones(x & y) = ones(x) & ones(y)
```

Here `x` and `y` are operands, `ones` returns their known-one vector or the vector for the resulting expression, `&` is bitwise AND, and `=` defines the transfer result. A bit in the result is known to be set if both operand bits are known to be set.

Complement requires changing which vector the transfer consults.

```
ones(∼x) = ∼zeros(x)
```

Here `x` is the input, `∼` is bitwise complement, `zeros(x)` has clear bits exactly where the input is known to be clear, and `ones(∼x)` records the resulting known set bits. The equality `=` defines the known-one transfer.

```
zeros(∼x) = ∼ones(x)
```

Here `x` is the input, `∼` flips each bit, and `ones(x)` records the input’s known set bits. The equality `=` defines `zeros(∼x)`, whose cleared positions are the positions known to be clear after the flip.

Exclusive OR needs information from both vectors because a bit is set when the inputs differ.

```
ones(x ⊕ y) = (ones(x) & ∼zeros(y)) | (ones(y) & ∼zeros(x))
```

Here `x` and `y` are the input values, `⊕` is bitwise exclusive OR, `∼` is complement, `&` is AND, and `|` is OR. The functions `ones` and `zeros` supply the two vectors defined above, and `=` assigns the result vector for known ones. The parenthesized terms cover the possibilities in which one operand is known to be set and the other is known to be clear.

```
zeros(x ⊕ y) = (zeros(x) & ∼ones(y)) | (zeros(y) & ∼ones(x))
```

Here `x` and `y` are again input values, `zeros` and `ones` return their analysis vectors, `⊕` denotes exclusive OR, `∼` denotes complement, `&` denotes AND, and `|` denotes OR. The equality `=` defines the result’s `zeros` vector. The right side describes the positions where the inputs could differ, leaving a clear bit where the result is guaranteed to be zero.

For addition, a bit’s value can depend on carries from lower positions. The analysis therefore uses fixed-width addition on the vectors, then identifies the positions for which it lacks a guaranteed result. The paper first computes two provisional sums.

```
vo = ones(x) + ones(y)
```

Here `x` and `y` are the addends, `ones` gives their known-one vectors, `+` denotes fixed-width addition, and `=` defines the provisional sum `vo` obtained from those vectors.

```
vz = zeros(x) + zeros(y)
```

Here `x` and `y` are the addends, `zeros` returns vectors with clear bits where zeros are guaranteed, `+` is fixed-width addition, and `=` defines the other provisional sum, `vz`.

The analysis identifies positions with unknown inputs and positions on which the provisional sums differ.

```
xnc = ones(x) ⊕ zeros(x)
```

Here `x` is the first addend, `ones(x)` and `zeros(x)` are its analysis vectors, `⊕` compares the vectors bit by bit through exclusive OR, and `=` defines `xnc` as the positions at which they disagree. These are the positions where `x` is not known to be constant.

```
ync = ones(y) ⊕ zeros(y)
```

Here `y` is the other addend, `ones(y)` and `zeros(y)` are its analysis vectors, `⊕` is exclusive OR, and `=` defines `ync` as the positions of unknown bits in `y`.

```
vnc = vo ⊕ vz
```

Here `vo` and `vz` are the provisional sums, `⊕` is exclusive OR, and `=` defines `vnc`, which flags positions that differ between the sums.

```
nc = xnc | ync | vnc
```

Here `xnc` and `ync` flag the unknown input positions, `vnc` flags positions where the provisional sums differ, and `|` joins these sets bit by bit. The equality `=` defines `nc`, the mask of positions treated as unknown in the result.

The final analysis vectors incorporate that mask.

```
ones(x + y) = vz & ∼nc
```

Here `x + y` denotes the sum of the operands, `ones` names its known-one vector, `vz` is the provisional sum formed from the `zeros` vectors, and `nc` is the unknown-result mask. The complement `∼` clears the flags for unknown positions in the mask used by bitwise AND `&`. The equality `=` assigns a known set bit only where the provisional sum gives one and the analysis considers the position known.

```
zeros(x + y) = vz | nc
```

Here `x + y` is the sum and `zeros` names the result vector in which a clear bit indicates a guaranteed zero. The provisional sum is `vz`, `nc` is the unknown-result mask, `|` is bitwise OR, and `=` defines the vector. Marking all unknown positions as set leaves clear only the positions that the analysis can certify as zero. The use of addition in the provisional sums lets the transfer account for carries. The paper also observes that known bits can establish that the addends have disjoint set bits, allowing the optimizer to treat their addition as OR or exclusive OR for purposes of finding a simplification.

#### Finding which bits matter to uses

The complementary analysis asks which result bits can affect the rest of the program. Its `care` vector uses a set bit for a relevant position and a clear bit for an irrelevant one. The information flows backward, from the uses of a value toward its definition. The analysis starts with all positions irrelevant. Operations that return or store a value mark positions as relevant, and the demands propagate through operands until they stabilize. An AND can make bits of one operand irrelevant when the corresponding bits of the other operand are known to be clear. An OR can do the same when the other operand’s bits are known to be set.

The two analyses interact. If the compiler concludes that a bit of one operand is irrelevant by using a fact about the other operand, it must preserve the bit information on which the conclusion depends. Otherwise it could change the other operand in a way that invalidates the inference. The paper uses this combined information to relax the addend-and-mask pattern. An addition can be replaced when the relevant bits of its result are unaffected, including in contexts where the restriction on relevant bits comes from a use other than an immediate AND.

```
((zeros(y) | −zeros(y)) & care(x + y)) == 0 ⇒ x + y → x
```

Here `x` and `y` are the addends, `zeros(y)` is the analysis vector that is clear wherever `y` is guaranteed to be clear, and `care(x + y)` describes the relevant bits of the sum. The operators `−`, `+`, `|`, and `&` denote fixed-width negation, addition, OR, and AND. The equality test `== 0` requires the potentially affected positions and the relevant positions to be disjoint. When that holds, the implication `⇒` allows the rewrite `→`. This rule was derived manually using the analyses. It extends the earlier rule in both directions, by accepting information about an expression used as the addend and accepting information from users of the result.

The paper also uses the analyses to discover an occult constant, a value that can be replaced by a constant because all of its relevant bits are known.

```
((zeros(x) ⊕ ones(x)) & care(x)) == 0 ⇒ x → eval(zeros(x) & care(x))
```

Here `x` is the value considered for replacement. The functions `zeros` and `ones` supply the analysis vectors for its guaranteed clear and set bits, and `care` identifies positions that influence its uses. Exclusive OR `⊕` marks where the vectors disagree, and AND `&` restricts that disagreement to relevant positions. The test `== 0` requires agreement at every relevant position. If the condition holds, `⇒` permits the rewrite `→` and `eval` computes the literal consisting of the known relevant bits, with irrelevant positions cleared. A value used in several places may have more relevant bits than any single use requires. The analysis must account for those uses before changing the value.

Optgen can output the discovered rules as text or graphics and can emit a test suite for checking an existing compiler. These are outputs of the enumeration and verification process. Random inputs and concrete examples are generated during the search, and no training corpus is used to choose the identities. The separate libFirm experiment exercises the rewrites and manually derived analysis-based extensions in a compiler pass.

### Experiments and results

#### The cost of constructing the rule set

The evaluation addresses the cost of running Optgen, which of its small rewrites existing compilers perform, and how repeated local simplification behaves in a full compiler. The generation runs use the same operation vocabulary: complement and negation, addition and subtraction, and the three binary bitwise operations. The paper ran Optgen with Z3 4.3.1 on an Intel Core i7-3770 at 3.40 GHz with 16 GB RAM. It varies the number of operations in the patterns, whether constants are included, and the width used to discover the rules. Its runtime table also reports maximum memory use. The destination verification width is 32 bits throughout that table.

For the configuration with two operations, constants, and 8-bit generation, Optgen took 6 h 7 min 0 s and used at most 1,046,568 kB. This is the configuration from which the compiler coverage tests were generated. A run at the same pattern bound and generation width without constants took 1 s and used 7456 kB. Constant handling makes a large difference to the work in that comparison even though the search already uses the narrow generation domain.

The paper also ran the two-operation search without constants directly at 32 bits. Its runtime was 6 min 21 s with maximum memory use of 19,892 kB. This compares with the 1 s run that also omitted constants but generated at 8 bits and then verified at 32 bits. Since the expressions contain no literals to multiply in number with the wider domain, this comparison lets the paper focus on the cost of wider solver checks during discovery.

The remaining runs without constants also generated at 8 bits. With three operations the runtime was 36 s and maximum memory use was 17,900 kB. With four operations it was 8 h 27 min 16 s and maximum memory use was 686,104 kB. The timing is for constructing the bounded rule set, an activity that can take place before compilation. It also gives a practical reason to treat the pattern bound as an explicit part of the experiment.

#### How the generated suite tests compilers

For the coverage study, Optgen produces a small input for each optimization being tested. The evaluated compiler generates x86-64 assembly. The test counts arithmetic instructions and compares the count with what is expected from the simplified expression. If the output contains more instructions than expected, the paper records a missed optimization. The question is whether the compiler reaches a sufficiently short result on that input. A compiler could meet the expected count through another sequence of simplifications.

The suite found 63 optimizations that were missing in at least one of GCC 4.9, LLVM 3.5, and ICC 15. The result is a count of different optimizations represented in the comparison, with a separate support entry for each compiler. The examples span a rule without constants, such as the OR around exclusive OR described earlier, rules with literal constants that have a special relationship to the word width, and rules that compute a replacement constant or have a precondition on symbolic constants. The paper notes that the conditions for rules 16, 21, 22, and 59 were supplied by hand. Those cases are included in the comparison and show where the generalizer’s existing pool of expressions needed help.

Some compiler-specific outcomes are particularly easy to interpret from the paper’s examples. GCC 4.9 and ICC 15 miss the simplification of the OR around the exclusive OR. LLVM 3.5 misses the regrouping that removes the outer negation from the expression involving a subtraction and an addition. The paper also identifies a 32-bit rule using `0x7FFFFFFF` and `0x80000000` that all the compared compilers miss. The counts measure synthetically isolated opportunities. The differences between these examples concern both the shape of the calculation and the presence or absence of constants.

A separate suite tests cases where applying a valid rewrite increases the cost because intermediate values are shared. It uses patterns with three operations and no constants. The authors explain that the relevant sharing cases did not occur in their tests with two operations. At least one compiler applied an unfavorable rewrite in each of the ten cases reported in the sharing comparison. In the example with complement around OR, GCC and LLVM both recognize the identity. GCC withholds the rewrite when another operation needs the inner OR, whereas LLVM still applies it. Recognizing the equality and deciding whether to apply it in a given surrounding graph are therefore separately testable compiler behaviors.

#### The effect on executed instructions

The benchmark experiment uses libFirm on SPEC CINT2000. It first compares generated binaries with and without a dedicated phase that repeatedly applies local simplifications to a fixpoint. Next, with the phase still enabled, it compares builds that use the constant-bit and don’t care analyses against builds that omit them. The reported metric is the number of instructions executed by the resulting program. The benchmark name identifies the workload, and each with-and-without comparison holds that workload fixed.

Executed instructions for 197.parser in SPEC CINT2000 by local optimization setting Repeating local simplifications accounts for most of the lower instruction count on this workload.

**The numbers**

| System or setting | executed instructions |
| --- | --- |
| Without local phase | 313,187,450,212 |
| With local phase, without analyses | 291,055,655,200 |
| With local phase and analyses (this paper) | 291,053,327,116 |

The paper reports an average improvement of 3.22 % for the fixpoint phase. Its benchmark table expresses the same comparison as an average ratio of 103.22 %, with the count without the phase as the numerator and the count with the phase as the denominator. For 197.parser, the table reports a ratio of 107.60 %. The difference between its counts is visible in the first comparison above. The separate comparison with the analyses enabled still reports 100.00 % for that benchmark at the table’s precision, although the printed instruction counts differ.

Executed instructions for 186.crafty in SPEC CINT2000 by local optimization setting The instruction count falls with the fixpoint phase and falls further when the bit analyses are enabled.

**The numbers**

| System or setting | executed instructions |
| --- | --- |
| Without local phase | 192,013,840,675 |
| With local phase, without analyses | 184,861,683,227 |
| With local phase and analyses (this paper) | 179,226,675,963 |

Across the analysis comparison, the paper reports an average improvement of 0.64 %, with 100.64 % printed for the average ratio of counts without analyses to counts with analyses. The largest reported improvement from the analyses is 3.14 % on 186.crafty. The paper attributes it to an occult constant found in a workload with many bit operations. The results also include changes elsewhere. The analysis comparison reports 101.77 % for 164.gzip and 102.05 % for 176.gcc, using the same ratio. Several rows display 100.00 %, and in those rows the displayed ratios and the raw counts answer questions at different levels of precision.

Executed instructions for 181.mcf in SPEC CINT2000 by local optimization setting The instruction count rises with the local phase and rises again with the analyses for this workload.

**The numbers**

| System or setting | executed instructions |
| --- | --- |
| Without local phase | 48,034,571,679 |
| With local phase, without analyses | 48,924,041,098 |
| With local phase and analyses (this paper) | 48,969,263,250 |

For 181.mcf, the first comparison reports 98.18 %, and the subsequent analysis comparison reports 99.91 %. Each ratio is below the equal-count value and indicates that enabling the relevant change increased the instruction count. This workload illustrates the difference between aggregate behavior on the benchmark suite and the effect for a particular program. The instructions counted here are executed at runtime. The earlier test that counts arithmetic instructions in the assembly for a small rewrite measures something different, namely whether a compiler simplifies an isolated static pattern to the expected size.

### What the ablations show

#### Constants, width, and the size of the search

The generation timings contain several controlled comparisons. At the same two-operation bound, with generation at 8 bits and verification at 32 bits, the configuration with constants takes hours while the one without constants takes seconds. This supports the paper’s identification of constants as a central obstacle. Literal operands add concrete combinations during enumeration and create families that the generalizer has to examine. The experiment compares the full configurations, so it gives the cost of including constants in the process as a whole.

The runs without constants provide a separate comparison of generation widths. They hold the two-operation bound and final verification width fixed, while changing discovery from 8 bits to 32 bits. The larger width makes the run substantially longer. The paper attributes this to wider solver checks during generation. That is why narrow generation has value even for a rule family that will ultimately be used on wider operands. The verifier still has to handle the wide identity once it becomes a candidate. It can avoid using that wide domain for all the comparisons involved in finding the candidate.

The runs with different operation bounds further show how sharply the cost can grow even in the absence of constants. All of those narrow-generation runs use the same instruction vocabulary. Increasing the bound allows larger compositions of the same operations. The four-operation run taking 8 h 27 min 16 s is a result about this enumeration setup. It supports doing the search offline and choosing a scope. The table gives no separate time breakdown for hashing, witness evaluation, matching, and solver work, so it cannot quantify the individual time savings from the matcher or witness index.

The comparison between 3-bit and 4-bit generation for the selected bitwise operations answers a different question from the timing comparisons. Its outcome is equality of the resulting 32-bit rule sets, instead of a runtime or memory measurement. It shows empirical stability across the widths tested for that operation vocabulary and cost limit. The result illustrates how a user can check whether increasing the discovery width changes the rules while relying on the destination-width proof for validity.

#### Applicability changes when expressions are shared

In the shared-subexpression suite, the mathematical identity stays the same while the surrounding use of an intermediate value changes. The compiler may be able to eliminate the old operations completely in an isolated pattern. If another expression still consumes an intermediate result, some of those operations must remain. The replacement can then add a new operation without removing the one that its local cost calculation counted as eliminated.

In the complement-and-OR example, the paper can distinguish a compiler that recognizes the rewrite and suppresses it in the shared case from a compiler that recognizes it and applies it anyway. That is a more informative comparison than testing only whether a rewrite exists in a compiler. It also explains why the global cost of an application depends on the use graph. A shared intermediate may keep the old expression live, and a value already computed elsewhere may make a replacement cheaper to introduce. The paper suggests conservative suppression for shared subexpressions as one response and leaves more deliberate rearrangement and sharing choices open.

#### Repeated simplification and bit information

The first libFirm comparison turns the fixpoint phase on as a unit. Its baseline is the compiler configuration without that phase, so the result estimates the effect of adding a dedicated pass that repeatedly looks for local opportunities. A rewrite can expose a calculation of a form that another rule recognizes, and a repeated pass gives the optimizer a chance to take advantage of that interaction. The benchmark counts give an aggregate outcome for the whole phase. They do not separate direct applications from applications unlocked by earlier changes.

The second comparison adds the constant-bit and don’t care analyses together while keeping the phase. It shows the incremental effect of supplying both kinds of information to the optimizer in that setting. In 186.crafty the paper identifies a specific mechanism, the discovery of a value that can be replaced by a constant on its relevant bits. The paired comparison does not assign a separate share of the aggregate gain to each analysis. The result on 181.mcf also shows that neither the phase nor the analysis combination reduces the executed instruction count on every workload. Together these comparisons let the reader distinguish the effects of adding the phase, supplying it with more information, and inspecting a particular application in the presence of sharing.

### Limitations

#### Limits identified by the paper

Optgen’s generalizer looks for constant computations and rule conditions among previously enumerated expressions. A valid condition can fall outside that pool even when the rewrite it enables is short. The conditions supplied by hand for rules 16, 21, 22, and 59 show that this constraint affects the evaluation directly. The proposed search over partial functions would make a wider range of candidates available. The paper notes that such a search could require bounds on the cost of the expressions it tries so that it terminates.

The authors qualify the transfer from narrow to wide integers. They verify extended candidates at the destination width. They also acknowledge that completeness at the destination depends on the operations and the width used for discovery. A family that does not appear in the narrow search has to be found through some other route. Similarly, padding represents a particular family of ways to extend a literal. The paper reports favorable experience with this approach and a comparison in which changing the generation width leaves the result unchanged. Those observations establish the behavior of the tested cases.

The rules using global bit information are manually derived. Optgen does not itself infer them in the implementation described. The paper explains that generating them would require adapting the solver formulas to encode the analysis information. It would also need a way to determine which conservative bit information is required for a candidate rule, and the rules’ expressions would have to be examined for the relevance of their result bits. The benchmark result for those rules consequently supports a compiler design that uses the analyses, with automatic derivation left open.

#### Limits of the evidence

The search vocabulary and cost function define what an exhaustive run can establish. The implemented integer operations cover a useful intersection of bitwise and arithmetic expressions. A verified rule set for that vocabulary gives no coverage result for operations outside it. Similarly, the cost bound confines the generator to small expressions. The discovery timings already vary substantially across the tested configurations. They offer direct evidence for those bounds and widths, with wider patterns and additional operations requiring their own measurements.

A proof of equal results concerns the specified fixed-width semantics and, for a conditional rule, its precondition. Using the rule in a particular compiler also requires the compiler’s operations and matching conditions to agree with that specification. The paper’s separate shared-expression experiments address one aspect of the next decision, whether a correct rewrite lowers cost in the actual context. They illustrate why a proof about the value of a calculation cannot establish that the original operations will disappear from the program.

The coverage comparison tests named compiler versions on x86-64 using generated examples and an arithmetic-instruction count. It gives a snapshot for that target, those versions, and the tested patterns. The suite cannot say how frequently an optimization arises in ordinary code, or how much it would contribute to the complete-program instruction counts on its own. The SPEC CINT2000 experiment presents those counts for particular configurations of libFirm, instead of installing each missing rule in each compiler and benchmarking the results.

Executed instruction counts are the quantitative basis for the reported benchmark improvements. They provide a measure of dynamic work that can distinguish the effects of the phase across workloads. Elapsed execution time, code size, and the compilation cost of running the phase are distinct outcomes. Likewise, the with-and-without analyses experiment estimates the effect of enabling both analyses together. The evidence about 186.crafty gives one explanation for a specific outcome without providing separate measurements for the effects of each analysis across the suite.

### What came after

The paper’s documented follow-up directions are proposals from its conclusion. One is to make rule generalization a search problem in its own right. In the implementation, a condition or constant computation must already have been enumerated. The proposed extension would search for expressions that agree with the available instances, check each proposed general rule, and use any counterexample to refine the search. The paper also suggests using superoptimization to find implementations for the transfer functions of constant-bit analysis.

A second direction is to automate the derivation of rewrites that rely on known and relevant bits. The paper’s manually derived addition rule demonstrates what such a generator would need to express. The precondition depends on a fact about the addend and on how the sum is used. Searching for such rules would bring the analysis facts into the same process of candidate discovery and verification used for simpler local identities.

The final direction concerns how a compiler arranges and shares intermediate calculations. The sharing tests show why a locally cheaper expression can increase overall cost. The paper proposes exploring reassociation, which rearranges how operations are grouped, to expose local rewrites or increase reuse of intermediates that already exist. That would extend the decision from applying a matched identity to considering which surrounding expression structure makes the identity worthwhile.

## Cite

Cite as Sebastian Buchwald. 2015. Optgen: A Generator for Local Optimizations. Lecture notes in computer science.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.1007/978-3-662-46663-6_9](https://doi.org/10.1007/978-3-662-46663-6_9)

```bibtex
@inproceedings{buchwald2015optgen,
  title = {{Optgen: A Generator for Local Optimizations}},
  author = {Sebastian Buchwald},
  booktitle = {Lecture notes in computer science},
  year = {2015},
  doi = {10.1007/978-3-662-46663-6\_9},
  url = {https://doi.org/10.1007/978-3-662-46663-6_9}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
