Skip to content
ImagineWorld

Scalar Optimization

node_idnode-book_engineering-a-compiler_chapter-10-scalar-optimization
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleScalar Optimization
pillar_membershipF — compiler_trinity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

An optimizing compiler improves the quality of the code that it generates by applying transformations to rewrite the code. “Quality” might be measured in runtime speed, in code size, or in more complex metrics, such as the energy expended by the processor at runtime. This chapter builds on the introduction to optimization provided in Chapter 8 and the material on static analysis in Chapter 9 to focus on optimization of the code for a single thread of control—so-called scalar optimization. The chapter introduces a selection of machine-independent scalar transformations that address a variety of inefficiencies in compiled code.

Optimization, Transformation, Machine Independent, Machine Dependent, Redundancy, Dead Code, Constant Propagation

A compiler’s optimizer analyzes and transforms the IR form of the code in an attempt to improve that code’s performance. It uses static analyses (see Chapter 9) to discover opportunities for transformations and to prove their safety. It then transforms the code, or rewrites it, in ways that are expected to produce better code in the compiler’s back end.

Code optimization has a history that is as long as the history of compilers. The first FORTRAN compiler included careful optimization with the intent to provide performance that rivaled hand-written assembly code. Since that first optimizing compiler in the late 1950s, the literature on optimization has grown to include thousands of papers that describe analyses and transformations. Deciding which transformations to use and selecting an order in which to apply them remains one of the most daunting decisions that a compiler writer faces.

This chapter focuses on scalar optimization, that is, optimization of code along a single thread of control. It identifies five key sources of inefficiency in compiled code and presents optimizations that help to remove those inefficiencies. The chapter is organized around these five effects; we expect that

Scalar optimization code improvement techniques that focus on a single thread of control a compiler writer choosing optimizations might use the same organizational scheme.

Compiler-based optimization is the process of analyzing the code to determine its properties and using the results of that analysis to rewrite the code into a more efficient or more effective form. Such improvement can be measured in many ways, including decreased running time, smaller code size, or lower processor energy use at runtime. Every compiler has some set of input programs for which it produces highly efficient code. A good optimizer should make that performance available on a much larger set of inputs. The optimizer should be robust, that is, small changes in the input should not produce wild changes in performance.

Machine independent

A transformation that improves code on most target machines is considered machine independent.

Machine dependent

A transformation that relies on specific knowledge of the target processor is considered machine dependent.

An optimizer achieves these goals through two primary mechanisms. It eliminates unnecessary overhead introduced to support programming language abstractions and it matches the needs of the resulting program to the available hardware and software resources of the target machine. In the broadest sense, transformations can be classified as either machine independent or machine dependent. For example, replacing a redundant computation with a reuse of the previously computed value is usually faster than recomputing the value; thus, redundancy elimination is considered machine independent. By contrast, implementing a character string copy operation with the “scatter-gather” hardware on a vector processor is clearly machine dependent. Rewriting that copy operation with a call to the hand-optimized system routine memmove might be more broadly applicable.

Most optimizers are built as a series of passes that share common infrastructure for analysis and manipulation of the IR, as shown in the margin. Each pass takes code in IR form as its input. Each pass produces a rewritten version of the IR code as its output. This structure breaks the implementation into smaller pieces and avoids some of the complexity that arises in large, monolithic programs. It allows the passes to be built and tested independently, which simplifies development, testing, and maintenance. It creates a natural way for the compiler to provide different levels of optimization;each level specifies a set of passes to run. The pass structure allows the compiler writer to run some passes multiple times, if desirable. In practice, some passes should run once, while others might run several times at different points in the sequence.

In the design of an optimizer, the selection of transformations and the ordering of those transformations play a critical role in determining the overall

The choice of specific transformations and the order of their application have a strong impact on the effectiveness of an optimizer. To make the problem harder, individual transformations have overlapping effects (e.g., local value numbering versus superlocal value numbering) and different programs have different sets of inefficiencies.

Equally difficult, transformations that address different effects interact with one another. A given transformation can create opportunities for other transformations. Symmetrically, a given transformation can obscure or eliminate opportunities for other transformations.

Classic optimizing compilers provide several levels of optimization (e.g., -0, -01, -02, …) as one way of providing the end user with multiple sequences that they can try. Research has looked at techniques to derive custom sequences for specific application codes, selecting both a set of transformations and an order of application (see also Section 10.7.3).

effectiveness of the optimizer. The selection of transformations determines what specific inefficiencies in the IR program the optimizer discovers and how it rewrites the code to reduce those inefficiencies. The order in which the compiler applies the transformations determines how the passes interact.

For example, in the appropriate context (e.g., r₂ > 0 and r₅ = 4), an optimizer might replace mult r₂, r₅⇒r₁₇ with lshiftI r₂, 2⇒r₁₇. This change replaces a multicycle integer multiply with a single-cycle shift operation and reduces demand for registers. In most cases, this rewrite is profitable. If, however, the next transformation that the compiler applies uses commutativity to rearrange expressions, then replacing a multiply with a shift may foreclose opportunities. To the extent that a transformation makes later passes less effective, it may hurt overall code quality. Deferring the replacement of multiplies by shifts may avoid this problem; the context needed to prove safety and profitability for this rewrite is likely to survive the intervening passes.

The first hurdle in the design and construction of an optimizer is conceptual. The optimization literature describes hundreds of distinct algorithms to improve IR programs. The compiler writer must select a subset of these transformations to implement and apply. While reading the original papers may help with the implementation, it provides little insight for the decision process; most of the papers advocate the use of their own transformations.

Compiler writers need to understand both what inefficiencies arise in applications translated by their compilers and what impact those inefficiencies

Recall that multiplication is commutative but a shift is not.

The distinction between the categories can be unclear. We call a transformation machine independent if it deliberately ignores target machine considerations, such as its impact on register allocation.

have on the application’s performance. Given a set of specific flaws to address, they can then select specific transformations to address them. Many transformations, in fact, address multiple inefficiencies, so careful selection can reduce the number of passes needed. Since most optimizers are built with limited resources, the compiler writer can prioritize transformations by their expected impact on the final code.

As mentioned in the conceptual roadmap, transformations fall into two broad categories: machine-independent transformations and machine-dependent transformations. Examples of machine-independent transformations from earlier chapters include local value numbering (LVN), inline substitution, and constant propagation. Machine-dependent transformations often fall into the realm of code generation. Examples include peephole optimization (see Section 11.3), instruction scheduling, and register allocation. Other machine-dependent transformations fall into the realm of the optimizer. Examples include tree-height balancing, global code placement, and procedure placement. Some transformations resist classification; loop unrolling has diverse effects that include reduction of loop overhead (machine independent) and provision of more independent instructions to the scheduler (machine dependent).

Chapters 8 and 9 present a number of optimization techniques selected to illustrate specific points in those chapters. Chapters 11 to 13 focus on code generation, which is inherently machine dependent. This chapter presents a broad selection of transformations, most of which are machine-independent. The transformations are organized around the effect that they have on the final code. We will concern ourselves with five specific effects.

  • Eliminate Useless and Unreachable Code The compiler can discover that an operation is either useless or unreachable. In most cases, removing such operations produces faster, smaller code.
  • Move Code The compiler can move an operation to a point where it executes less often but produces the same answer. In most cases, code motion reduces runtime. It sometimes reduces code size.
  • Specialize a Computation The compiler can specialize a code sequence to the context around it. Specialization reduces the cost of generic code sequences.
  • Eliminate a Redundant Computation The compiler can prove that a value has already been computed and reuse the earlier value. In many cases, reuse costs less than recomputation.
  • Enable Other Transformations The compiler can rewrite the code to expose new opportunities for other optimizations. Inline substitution, for example, enables many other optimizations. OPTIMIZATION AS SOFTWARE ENGINEERING Including an optimizer can simplify the design and implementation of a compiler. It simplifies the front end; the front end can generate general-purpose code and ignore special cases. It simplifies the back end; the back end can focus on mapping the IR version of the program to the target machine. Without an optimizer, both the front and back end must pay attention to opportunities to improve the code.

In a pass-structured optimizer, each pass contains a transformation and the analysis required to support it. In principle, each task that the optimizer performs can be implemented once. This provides a single point of control and lets the compiler writer implement complex functions once, rather than many times. For example, deleting an operation from the IR can be complicated. If the deleted operation leaves a basic block empty, except for the block-ending branch or jump, then the transformation should also delete the block and reconnect the block’s predecessors to its successors, as appropriate. Building this functionality once simplifies implementation, understanding, and maintenance.

From a software engineering perspective, the pass structure makes sense. It focuses each pass on a single task. It creates a clear separation of concerns—value numbering ignores register pressure and register allocation ignores redundancy. It lets the compiler writer test passes independently and thoroughly, and it simplifies fault isolation.

This set of categories covers most machine-independent effects that the compiler can address. In practice, many transformations attack effects in more than one category. LVN, for example, eliminates redundant computations, specializes computations with known constant values, and uses algebraic identities to identify and remove some kinds of useless computations.

The rest of this chapter explores these five opportunities: dead code elimination, code motion, specialization, redundancy elimination, and enabling other transformations. It includes multiple transformations in each category. The Advanced Topics section presents an algorithm that combines constant propagation and dead code elimination, along with an algorithm for operator strength reduction.

Sometimes, programs contain computations that have no externally visible effect. If the compiler can determine that a given operation does not affect the program’s results, it can eliminate the operation. Most programmers do

An operation is useless if no operation uses its result, or if all uses of the result are themselves dead.

An operation that does not change any value, such as a ←a+0, is also useless.

An operation is unreachable if no valid control-flow path contains the operation.

not write such code intentionally. However, it arises in most programs as the direct result of other optimizations or from naive translation in the compiler’s front end.

Two distinct effects can make an operation eligible for removal as dead code. The operation can be useless, meaning that its result has no externally visible effect. Alternatively, the operation can be unreachable, meaning that it cannot execute. If an operation falls into either category, it can be eliminated. The term dead code is often used to mean either useless or unreachable code.

Removing useless or unreachable code shrinks the IR form of the code, which leads to a smaller executable program, to faster compilation, and, often, to faster execution. It may also increase the compiler’s ability to improve the code. For example, unreachable code may have effects that show up in the results of static analysis and prevent the application of some transformations. In this case, removing the unreachable block may change the analysis results and allow further transformations (see, e.g., sparse conditional constant propagation in Section 10.7.1).

Some forms of redundancy elimination also remove useless code. As we saw in Section 8.4.1, LVN applies algebraic identities to simplify the code. Examples include a ←a+0, b ←b×1, and c ←max(c,c). Each of these simplifications eliminates a useless operation—by definition, an operation that, when removed, makes no difference in the program’s externally visible behavior.

Because the algorithms in this section modify the program’s control-flow graph (CFG), we carefully distinguish between the terms branch, as in an ILOC cbr, and jump, as in an ILOC jump. Close attention to this distinction will help the reader understand the algorithms.

The classic algorithms for eliminating useless code operate in a manner similar to mark-sweep garbage collectors with the IR code as data (see Sec-tion 6.6.2). Like mark-sweep collectors, they perform two passes over the code. The first pass starts by clearing all the mark fields and marking “critical” operations as “useful.” An operation is critical if it sets a return value for the procedure, it is an input/output statement, or it affects the value in a storage location that may be accessible from outside the current procedure. Examples of critical operations include a procedure’s prolog and epilog code and the precall and postreturn sequences at calls. Next, the algorithm traces the operands of useful operations back to their definitions and marks

An operation can set a return value for a procedure in several ways, including assignment to a call-by-reference parameter or a global variable, assignment through an ambiguous pointer, or passing a return value via a return statement. Mark( ) WorkList ← ∅ for each operation i do clear i’s mark if i is critical then mark i WorkList ← WorkList ∪ {i} while (WorkList ≠ ∅) do remove an operation i from WorkList (assume i is x ← y op z) if def(y) is not marked then mark def(y) WorkList ← WorkList ∪ {def(y)} if def(z) is not marked then mark def(z) WorkList ← WorkList ∪ {def(z)} for each block b ∈ RDF(block(i)) do let x be the branch that ends b if x is unmarked then mark x WorkList ← WorkList ∪ {x} (a) The Mark Phase (b) The Sweep Phase

■ FIGURE 10.1 Useless Code Elimination.

those operations as useful. This process continues, in a simple worklist iterative scheme, until no more operations can be marked as useful. The second pass walks the code and removes any operation not marked as useful.

Fig. 10.1 makes these ideas concrete. The algorithm, which we call Dead, assumes that the code is in SSA form. SSA simplifies the process because each use refers to a single definition. Dead consists of two passes. The first, called Mark, discovers the set of useful operations. The second, called Sweep, removes useless operations. Mark relies on control dependence, which is closely related to dominance frontiers (see Section 9.3.2).

The treatment of operations other than branches or jumps is straightforward. The marking phase determines whether an operation is useful. The sweep phase removes operations that have not been marked as useful.

The treatment of control-flow operations is more complex. Every jump is considered useful. Branches are considered useful only if the execution of a useful operation depends on their presence. As the marking phase discovers

Postdominance In a CFG, j postdominates i if and only if every path from i to the exit node passes through j. See also the definition of dominance on page 452.

useful operations, it also marks the appropriate branches as useful. To map from a marked operation to the branches that it makes useful, the algorithm relies on the notion of control dependence.

The definition of control dependence relies on postdominance. In a CFG, node j postdominates node i if every path from i to the CFG’s exit node passes through j. Using postdominance, we can define control dependence as follows: in a CFG, node j is control-dependent on node i if and only if

  1. There exists a nonnull path from i to j such that j postdominates every node on the path after i. Once execution begins on this path, it must flow through j to reach the CFG’s exit (from the definition of postdominance).
  2. j does not strictly postdominate i. Another edge leaves i and control may flow along a path to a node not on the path to j. There must be a path beginning with this edge that leads to the CFG’s exit without passing through j.

In other words, two or more edges leave block i. One or more edges lead to j and one or more edges do not. Thus, the decision made at the branch that ends block i can determine whether or not j executes. If an operation in j is useful, then the branch that ends i is also useful.

This notion of control dependence is captured precisely by the reverse dominance frontier of j, denoted RDF(j). Reverse dominance frontiers are simply dominance frontiers computed on the reverse CFG. When Mark marks an operation in block b as useful, it visits every block in b’s reverse dominance frontier and marks their block-ending branches as useful. As it marks these branches, it adds them to the worklist. It halts when that worklist is empty.

Sweep replaces any unmarked branch with a jump to the first postdominator block that contains a marked operation. If the branch is unmarked, then its successors, down to its immediate postdominator, contain no useful operations.(Otherwise, when those operations were marked, the branch would have been marked.) A similar argument applies if the immediate postdominator contains no marked operations. To find the nearest useful postdominator, the algorithm can walk up the postdominator tree until it finds a block that contains a useful operation. Since, by definition, the exit block is useful, this search must terminate.

After Dead runs, the code contains no useless computations. It may contain empty blocks, which can be removed by the next algorithm.

Optimization can rewrite the IR form of the program so that it has useless control flow. If the compiler includes optimizations that create useless control flow as a side effect, then it should include a pass that simplifies the CFG by eliminating useless control flow. This section presents a simple algorithm called Clean that handles this task.

Clean operates directly on the procedure’s CFG. It uses four transformations shown in the margin, applied in the following order:

  1. Fold a Redundant Branch If Clean finds a block that ends in a branch. and both sides of the branch target the same block, it replaces the branch with a jump. This situation arises as the result of other simplifications. For example, B_{i} might have had two successors, each with a jump to B_{j}.If another transformation had already emptied those blocks, then empty-block removal, discussed next, might produce the inital graph shown in the margin.

  2. Remove an Empty Block If Clean finds a block that contains only a jump, it can merge the block into its successor. This situation arises when other passes remove all of the operations from a block B_{i}. Consider the initial graph shown in the margin. Since B_{i} has only one successor, B_{j},the transformation retargets the edges that enter B_{i} to B_{j} and deletes B_{i}from B_{j}’s set of predecessors. This transformation simplifies the graph. It should also speed up execution. In the original graph, the paths through B_{i} needed two control-flow operations to reach B_{j}. In the transformed graph, those paths use one operation to reach B_{j}.

  3. Combine Blocks If Clean finds a block B_{i} that ends in a jump to B_{j} and B_{j} has only one predecessor, it can combine B_{i} and B_{j}, as shown in the margin. This situation can arise in several ways. Another transformation might eliminate other edges that entered B_{j}, or B_{i} and B_{j} might be the result of folding a redundant branch. In either case, the two blocks can be combined into a single block. This eliminates the jump at the end of B_{i}.

  4. Hoist a Branch If Clean finds a block B_{i} that ends with a jump to an empty block B_{j} and B_{j} ends with a branch, Clean can replace the block-ending jump in B_{i} with a copy of the branch from B_{j}. The effect, is to hoist the branch into B_{i}, as shown in the margin. This situation arises when other passes eliminate the operations in B_{j}, leaving a jump to a branch. The rewritten code achieves the same effect with one fewer jump. It adds one edge to the CFG.

Notice that B_{i} cannot be empty, or Clean would have removed it. Neither can it be B_{j}’s sole predecessor; Clean would have combined B_{I} and B_{j}.(After hoisting, B_{j} still has at least one predecessor.)

Some bookkeeping is required to implement these transformations. Some of the modifications are trivial. To fold a redundant branch in a program represented with ILOC and a graphical CFG, Clean simply overwrites the block-ending branch with a jump and adjusts the successor and predecessor

MakeAPass()

for each block i, in postorder do

if i ends in a conditional branch then

if both targets are identical then

replace the branch with a jump

/* case 1*/

if i ends in a jump to j then

if i is empty then

replace transfers to i with transfers to j

/* case 2*/

if j has only one predecessor then

combine i and j

/* case 3*/

if j is empty and ends in a conditional branch then

overwrite i’s jump with a copy of j’s branch

/* case 4*/

Clean()

while the CFG keeps changing do

compute postorder

MakeAPass()

Many compilers and assemblers have included an ad-hoc pass that eliminates a jump to a jump or a jump to a branch. Clean achieves the same effect in a systematic way.

lists of the blocks. Others are more difficult. Merging two blocks may involve allocating space for the merged block, copying the operations into the new block, adjusting the predecessor and successor lists of the new block and its neighbors in the CFG, and discarding the two original blocks.

Clean applies these four transformations in a systematic fashion. It traverses the graph in postorder, so that B’s successors are simplified before B,unless the successor lies along a back edge with respect to the postorder numbering. In that case, Clean will visit the predecessor before the successor. This traversal order is unavoidable in a cyclic graph. Simplifying successors before predecessors reduces the number of times that the implementation must move some edges.

In some situations, more than one of the transformations may apply. Careful analysis of the various cases leads to the order shown in Fig. 10.2, which corresponds to the order in which they were presented. The algorithm may apply multiple transformations to a block in a single visit.

If the CFG contains back edges, then a pass of Clean may create additional opportunities-unprocessed successors along the back edges. These, in turn, may create other opportunities. Thus, Clean repeats the transformation sequence iteratively until the CFG stops changing. It must compute a new postorder numbering between calls to MakeAPass because each pass changes the underlying graph. Fig. 10.2 shows pseudocode for Clean. Clean cannot, by itself, eliminate an empty loop. Consider the CFG shown in the margin. Assume that block B2 is empty. None of Clean’s transformations can eliminate B2 because the branch that ends B2 is not redundant. B2 does not end with a jump, so Clean cannot combine it with B3. Its predecessor ends with a branch rather than a jump, so Clean can neither combine B2 with B1 nor fold its branch into B1.

However, cooperation between Clean and Dead can eliminate the empty loop. Dead used control dependence to mark useful branches. If B1 and B3 contain useful operations, but B2 does not, then the Mark pass in Dead will decide that the branch ending B2 is not useful because B2 ≠ RDF(B3). Because the branch is useless, the code that computes the branch condition is also useless. Thus, Dead eliminates all of the operations in B2 and converts the branch that ends it into a jump to its closest useful postdominator, B3. This eliminates the original loop and produces the CFG labeled “After Dead” in the margin.

In this form, Clean folds B2 into B1, to produce the CFG labeled “Remove B2” in the margin. This action makes the branch at the end of B1 redundant. Clean rewrites it with a jump, producing the CFG labeled “Fold the Branch” in the margin. At this point, if B1 is B3’s sole remaining predecessor, Clean coalesces the two blocks into a single block.

This cooperation is simpler and more effective than adding a transformation to Clean to handle empty loops. Such a transformation might recognize a branch from Bi to itself and, for an empty Bi, rewrite it with a jump to the branch’s other target. The problem lies in determining when Bi is truly empty. If Bi contains no operations other than the branch, then the code that computes the branch condition must lie outside the loop. Thus, the transformation is safe only if the self-loop never executes. Reasoning about the number of executions of the self-loop requires knowledge about runtime values, a task that is, in general, beyond a compiler’s ability. If the block contains operations, but only operations that control the branch, then the transformation would need to recognize the situation with pattern matching. In either case, this new transformation would be more complex than the four included in Clean. Relying on the combination of Dead and Clean achieves the desired result in a simpler, more modular fashion.

Sometimes the CFG contains unreachable code. The compiler should find such blocks and remove them. A block can be unreachable for two distinct reasons: there may be no path through the CFG that leads to the block, or

Original CFG

After Dead

Remove B2

Fold the Branch

If the source language allows arithmetic on code pointers or labels, the compiler must preserve all blocks. Otherwise, it can limit the preserved set to blocks whose labels are referenced.

The former case is easy to handle. The compiler can perform a simple mark-sweep-style reachability analysis on the CFG. First, it initializes a mark on each block to the value “unreachable.” Next, it starts with the entry and marks each CFG node that it can reach as “reachable.” If all branches and jumps are unambiguous, then all unmarked blocks can be deleted. With ambiguous branches or jumps, the compiler must preserve any block that the branch or jump can reach. This analysis is simple and inexpensive. It can be done during traversals of the CFG for other purposes or during CFG construction itself.

Handling the second case is harder. It requires the compiler to reason about the values of expressions that control branches. Section 10.7.1 presents an algorithm that finds some blocks that are unreachable because the paths leading to them are not executable.

Code transformations often create useless or unreachable code. Many transformations simply leave the dead operations in the IR form of the code and rely on specialized transformations, such as Dead and Clean, to remove such operations. Most optimizing compilers include a set of transformations to excise dead code. Often, these passes run several times during the transformation sequence.

Dead and Clean do a thorough job of eliminating useless and unreachable code. However, limitations in the precision of the underlying analyses can prevent the transformations from proving that some code is dead. In particular, limits on the analysis of pointer-based values and on the precision of control-flow analysis can obscure useless or unreachable code.

  1. Experienced programmers are often certain that they do not write code that is useless or unreachable. What transformations from Chapter 8 might create useless code?
  2. How might the compiler, or the linker, detect and eliminate unreachable procedures? What benefits might accrue from using your technique?

Moving a computation to a point in the code where it executes less frequently than it executed in its original position should reduce the total operation count of the running program. The first transformation presented in this section, lazy code motion, uses code motion to speed up execution. Because loops tend to execute many more times than the code that surrounds them, much of the work in this area has focused on moving loop-invariant expressions out of loops. Lazy code motion performs loop-invariant code motion. It extends the notions originally formulated in the available expressions data-flow problem to include operations that are redundant along some, but not all, paths. It inserts code to make such expressions redundant on all paths and then removes the newly redundant expression.

Some compilers, however, optimize for other criteria. If the size of the executable code is a concern, the compiler can perform code motion to reduce the number of copies of a specific operation. The second transformation presented in this section, hoisting, uses code motion to eliminate duplicate instructions. It finds locations where it can insert a single operation that makes multiple copies of the same operation redundant.

Lazy code motion(LCM) uses data-flow analysis to discover both operations that are candidates for code motion and locations where it can place those operations. The algorithm operates on the IR form of the program and its CFG, rather than on SSA form. The algorithm solves three different sets of data-flow equations and derives additional sets from those results. It produces, for each edge in the CFG, a set of expressions that should be evaluated along that edge and, for each node in the CFG, a set of expressions whose upward-exposed evaluations should be removed from the corresponding block. A simple rewriting strategy interprets these sets and modifies the code.

LCM combines code motion with elimination of both redundant and partially redundant computations. Redundancy was introduced in the discussion of LVN and SVN in Chapter 8. A computation is partially redundant at point p if it occurs on some, but not all, paths that reach p and none of its constituent operands changes between those evaluations and p.

Fig. 10.3 shows two ways that an expression can be partially redundant. In panel(a), the expression bxc occurs on one path leading to the join point but not on the other. To make the second computation redundant, LCM inserts an evaluation of bxc on the other path as shown in panel(b). In panel(c),LCM operates on a CFG and IR rather than on the SSA form of the code. SSA can complicate code motion algorithms. Moving an operation that defines x, may require renaming and, perhaps, insertion of one or more ϕ\phi -functions.

Redundant

An expression e is redundant at p if it has already been evaluated on every path that leads to p.

Partially redundant

An expression e is partially redundant at p if it occurs on some, but not all, paths that reach p.

LCM moves expression evaluations, not assignments. It will create a name, t, to hold bxc and rewrite a←bxc with a←t.

In this context, earliest means the position in the CFG closest to the entry node.

These rules are consistent with the register-naming rules from Section 4.6.1.

bxc is redundant along the loop’s back edge but not along the edge that enters the loop. It is also invariant in the loop. Inserting an evaluation of bxc before the loop makes the evaluation inside the loop redundant, as shown in panel(d). By making the loop-invariant computation redundant and eliminating it, LCM moves it out of the loop, an optimization also called loop-invariant code motion.

The fundamental ideas that underlie LCM were introduced in Section 9.2.4.LCM computes both available expressions and anticipable expressions. Next, LCM uses the results of these analyses to annotate each CFG edge(i,j)with a set Earliest(i,j) that contains the expressions for which this edge is the earliest legal placement. LCM then solves a third data-flow problem to find later placements, that is, situations where evaluating an expression after its earliest placement has the same effect. Later placements are desirable because they can shorten the lifetimes of values defined by the inserted evaluations. Finally, LCM computes its final products, two sets INSERT and DELETE, that guide its code-rewriting step.

LCM relies on several implicit assumptions about the code shape. Textually identical expressions always define the same name. Thus, each instance ofri+rjr_{i}+r_{j} always defines the same rkr_{k} , and the algorithm can use rkr_{k} as a proxy for ri+rjr_{i}+r_{j} . This naming scheme simplifies the rewriting step; the optimizer can simply replace a dundam evaluation of ri+rjr_{i}+r_{j} with a copy from rkr_{k} ,

B1:loadI 1⇒r10 i2i r10⇒r4 loadAI rorg, On⇒r11 i2i r11⇒r5 cmp_LE r4,r5⇒r12 cbr r12→B2,B3

Variable VR Name a b c i n x r1 r2 r3 r8 r5 r5

(b) Mapping from Variables to Virtual Registers

B2: mult r2,r3⇒r15 add r1,r15⇒r16 i2i r16⇒r6 addI r4,1⇒r13 i2i r13⇒r4 cmp_GT r4,r5⇒r14 cbr r14→B3,B2

B3:…

(a) A Simple Loop

(c) Control-Flow Graph

FIGURE 10.4 Example for Lazy Code Motion.

rather create a new temporary name and insert copies into rk after each prior evaluation or rj+rj. We will add the restriction that i<k and j<k.

LCM moves expression evaluations, not assignments. The naming discipline requires a second rule for program variables because they receive the values of different expressions. Thus, program variables are only set by register-to-register copy operations. The compiler needs a clear way to divide the name space between variables and expressions.

Finally, the compiler first assigns virtual register numbers to variables that are kept in registers, then uses higher virtual register numbers for temporary values and the computed values. Taken together, these rules ensure that a variable is always set with a copy of the form ri←rjr_{i}\leftarrow r_{j} , where i<ji<j . Thus, assignments are easy to distinguish from expression evaluations.

Combining these rules creates a clear distinction between expressions, which can be moved, and assignments, which cannot. Any operation other than a register-to-register copy operation or a control-flow transfer is an expression evaluation. Any copy operation, ri⇒rjr_{i}\Rightarrow r_{j} where i>ji>j is an assignment; if i≤j, it is an expression evaluation.

Fig. 10.4(a) shows the ILOC code for the simple example loop given in the margin. The loop contains a single statement whose entire right-hand side is loop invariant. Panel(b) shows the map from variable names to register numbers; registers with subscripts larger than nine are expressions.

for i=1 to n do x=a+b+c

Code for the Example

The data-flow problems used in LCM start from three distinct sets of local information. For each block b, LCM needs the three sets:

DEExpr(b):the set of downward-exposed expressions in b,

UEExpr(b):the set of upward-exposed expressions in b, and

EXPRKILL(b): the set of expressions killed in b.

These sets were in Section 9.2.4. For the example program shown in Fig. 10.4, these sets have the following values:

B1B2B3
DEExpr{r10,r11,r12}{r14,r15,r16}0
UEExpr{r10,r11}{r13,r15,r16}0
EXPRKILL{r12,r13,r14}{r12,r13,r14}0

We show the sets for B3 as empty, because the example abstracts away all of the code in B3. In most realistic scenarios, B3 would contain code and the sets for B3 would be nonempty.

To simplify the exposition, we assume that the CFG has a unique entry node n0n_{0} and a unique exit node nfn_{f} .

The first step in LCM computes available expressions, as defined in Sec-tion 9.2.4. LCM needs information on the availability at the end of each block-AvailOUT sets. An expression e is available on exit from block b if, along every path from n0 to the end of b,e has been evaluated and none of its arguments has been subsequently defined. LCM can compute AVAILOUT by solving the equations:

AVAILIN(n)=⋂m∈preds(n)AVAILOUT(m)AVAILIN(n)\quad=\bigcap_{m\in preds(n)}AVAILOUT(m) AVAILOUT(n)\quad=\left(\begin{array}[]{c}DEExpr(n)\,\cup\\ (AVAILIN(n)\,\cap\,\overline{EXPRKILL(n)}\end{array}\right)

AVAILOUT(n) contains any expressions that are downward exposed in n, plus any expressions that are available at the end of all of n’s CFG predecessors and not killed in n. The appropriate initial values are:

AVAILIN(n0)=∅AVAILIN(n_{0})\quad=\quad\emptyset AVAILOUT(n) = { all expressions },∀ n≠n0AVAILOUT(n)\,=\,\{\,all\,expressions\,\},\forall\,n\neq n_{0}

an use a standard iterative solver. For the example in ess produces the following sets: B₁ B₂ B₃

AVAILOUT {r₁₀,r₁₁,r₁₂} {r₁₀,r₁₁,r₁₄,r₁₅,r₁₆} …

LCM uses the AVAILOUT sets to determine possible placements for expressions in the CFG. If an expression e ∈ AVAILOUT(b), the compiler can place an evaluation of e at the end of block b and obtain the result produced by e’s most recent evaluation on any path from n₀ to b in the CFG. If e ∤ AVAILOUT(b), then one of e’s constituent subexpressions has been modified along one of these paths, so an evaluation of e at the end of b might produce a different value. Thus, the AVAILOUT sets show the compiler how far forward in the CFG it can move the evaluation of e, ignoring any uses of e.

Anticipable Expressions

To capture information for backward motion of expressions, LCM computes anticipability. Recall, from Section 9.2.4, that an expression is anticipable at point p if and only if it is computed on every path that leaves p and produces the same value at each of those computations. Because LCM needs information about the anticipable expressions at both the start and the end of each block, we have refactored the equation to introduce a set ANTIN(n) that holds the set of anticipable expressions for the entrance of the block corresponding to node n in the CFG:

ANTOUT(n) = ∩ m∈succs(n) ANTIN(m), ∀n ≠ nf ANTIN(n) = (∪ UEXPR(n) ∪ (ANTOUT(n) ∩ EXPRKILL(n))) )

ANTIN(n) contains any expressions that are upward exposed in n, plus any expression that is anticipable at the start of each of n’s CFG successors and not killed in n. The appropriate initial values are:

ANTOUT(nf) = ∅ ANTOUT(n) = {all expressions}, ∀n ≠ nf

For the example, solving these equations yields the following sets:

B₁ B₂ B₃

ANTIN {r₁₀,r₁₁} {r₁₃,r₁₅,r₁₆} ∅ ANTOUT ∅ ∅

ANTOUT provides information about the safety of hoisting an evaluation to either the start or the end of the current block. If x∈ANTOUT(b), then the compiler can place an evaluation of x at the end of b, with two guarantees. First, the evaluation at the end of b will produce the same value as the next evaluation of x along any execution path in the procedure. Second, along any execution path leading out of b, the program will evaluate x before re-defining any of its arguments.

Given solutions to availability and anticipability, the compiler can determine the earliest point in the program at which it can evaluate each expression. To simplify the equations, LCM assumes that evaluations are placed on a CFG edge rather than at the start or end of a specific block. Computing an edge placement lets the compiler defer the decision to insert the evaluation at the start of the edge, at the end of the edge, or in the middle of the edge(see the discussion of critical edges in Section 9.3.5, page 487).

For a CFG edge(i,j), an expression e is in EARLIEST(i,j) if and only if the compiler can legally move e to(i,j), and cannot move it to any earlier edge in the CFG. The EARLIEST equation defines this condition:

EARLIEST(i,j) = ANTIN(j) ∩ AVAILOUT(i)‾∩ (EXPRKILL(i)∪ANTOUT(i)‾)\begin{array}{cc}\text{EARLIEST}(i,j)\,=\,\text{ANTIN}(j)\,\cap\,\overline{\text{AVAILOUT}(i)}\\ \cap\,(\text{EXPRKILL}(i)\cup\overline{\text{ANTOUT}(i)})\end{array}

These terms define an earliest placement for e as follows:

  1. e∈ANTIN(j) means that the compiler can safely move e to the head of j. Anticipability ensures that e will produce the same value as its next evaluation on any path leaving j and that each of those paths evaluates e.

  2. e∈AVAILOUT(i) shows that no prior computation of e is available on exit from i. Were e∈AVAILOUT(i), inserting e on(i,j) would be redundant.

  3. The third condition encodes two cases. If e∈EXPRKILL(i), the compiler cannot move e through block i because of a definition in i. If e∈ANTOUT(i), the compiler cannot move e into i because e∈ANTIN(k)for some edge(i,k). If either is true, then e can move no further than(i,j).

LCM can ignore the third term in EARLIEST(n0,k), for any k. LCM cannot move an expression earlier than n0. The EARLIEST sets for the continuing example are as follows:

(B1,B2)(B1,B3)(B2,B2)(B2,B3)EARLIEST{r13,r15,r16}∅{r13}∅\begin{array}{cccc}\left(B_{1},B_{2}\right)&\left(B_{1},B_{3}\right)&\left(B_{2},B_{2}\right)&\left(B_{2},B_{3}\right)\\ \text{EARLIEST}&\left\{r_{13},r_{15},r_{16}\right\}&\varnothing&\left\{r_{13}\right\}&\varnothing\end{array}

EARLIEST

The final data-flow problem in LCM determines when an earliest placement can be deferred to a later point in the CFG while achieving the same effect. Later analysis is formulated as a forward data-flow problem on the CFG with a set LATERIN(n) associated with each node and another set LATER(i,j)associated with each edge(i,j). This system of equations is defined as:

Note that LATER(i,j) is defined for edges(i,j). not for arbitrary pairs of nodes.

LATERIN(j)=⋂i∈preds(j)LATER(i,j), j≠n0LATERIN(j)\quad=\bigcap_{i\in preds(j)}\quad LATER(i,j),\,j\neq n_{0} LATER(i,j)=EARLIEST(i,j)∪(LATERIN(i)∩UEEXPR(i)‾)LATER(i,j)\quad=\quad EARLIEST(i,j)\quad\cup\quad(LATERIN(i)\cap\overline{UEEXPR(i)})

The appropriate initial values are:

LATERIN(n0) = ∅LATERIN(n_{0})\,=\,\varnothing LATERIN(n)={ all expressions ∣ ,∀n≠n0LATERIN(n)\quad=\quad\{\text{ all expressions}\,|\,,\quad\forall n\neq n_{0}

The compiler can use a standard iterative solver on these equations. These equations have a unique fixed point.

An expression e∈LATERIN(k)e\in LATERIN(k) if and only if every path that reaches k includes an edge(p,q) such that e∈EARLIEST(p,q)e\in EARLIEST(p,q) , and the path from q to k neither redefines e’s operands nor contains an evaluation of e that an earlier placement of e would anticipate. The Earliest term in the equation for LATER ensures that LATER(i,j) includes Earliest(i,j). The rest of that equation puts e into LATER(i,j) if e can be moved forward from i(e∈LATERIN(i))(e\in LATERIN(i)) and a placement at the entry to i does not anticipate a use in i(e∉UEExpr(i)).

Given LATER and LATERIN sets, e∈LATERIN(i)e\in LATERIN(i) implies that the compiler can move the evaluation of e forward through i without losing any benefit-that is, there is no evaluation of e in i that an earlier evaluation would anticipate, and e∈LATER(i,j)e\in LATER(i,j) implies that the compiler can move an evaluation of e in i into j.

For the example, these equations produce the following sets:

B1B2B3LATERIN∅{r13}∅(B1,B2)(B1,B3)(B2,B2)(B2,B3)LATER{r13,r15,r16}∅{r13}∅\begin{array}{cccccccccccc}& B_1& B_2& B_3\\ \hline\\ LATERIN&\varnothing&\{r_{13}\}&\varnothing\\ &&\\ &&(B_1,B_2)&(B_1,B_3)&(B_2,B_2)&(B_2,B_3)\\ LATER&\{r_{13}, r_{15}, r_{16}\}&\varnothing&\{r_{13}\}&\varnothing\end{array}

The final step in performing LCM is to rewrite the code so that it capitalizes on the knowledge derived from the data-flow computations. To drive the rewriting process, LCM computes two additional sets, INSERT and DELETE.

The INSERT set specifies, for each edge, the computations that LCM should insert on that edge.

INSERT(i,j)=LATER(i,j)∩LATERIN(j)‾INSERT(i,j)=LATER(i,j)\cap\overline{LATERIN(j)}

If i has only one successor, LCM can insert the computations at the end of i. If j has only one predecessor, it can insert the computations at the entry of j. If neither condition applies, the edge (i,j)(i,j) is a critical edge and the compiler should split it by inserting a block in the middle of the edge to evaluate the expressions in INSERT(i,j).

The DELETE set specifies, for a block, which computations LCM should delete from the block.

DELETE(i)=UEExpr(i)∩LATERIN(i)‾,i≠n0DELETE(i)=UEExpr(i)\cap\overline{LATERIN(i)},\quad i\neq n_{0}

DELETE(n0) is 0 because n0 has no predecessor. If e∈DELETE(i), then the first computation of e in i is redundant after all the insertions have been made. Any subsequent evaluation of e in i that has upward-exposed uses-that is, the operands are not defined between the start of i and the evaluation-can also be deleted. Because all evaluations of e define the same name, the compiler need not rewrite subsequent references to the deleted evaluation. Those references will naturally refer to earlier evaluations of e that will produce the same result.

For the example, the INSERT and DELETE sets are simple:

(B1,B2)(B1,B3)(B2,B2)(B2,B3)INSERT{r15,r16}∅∅B1B2B3DELETE∅{r15,r16}∅\begin{array}{cccc}\left(B_1, B_2\right)&\left(B_1, B_3\right)&\left(B_2, B_2\right)&\left(B_2, B_3\right)\\ \text{INSERT}&\left\{r_{15}, r_{16}\right\}&\varnothing&\varnothing\\ \left.B_1\right.&\left.B_2\right.&\left.B_3\right.\\ \text{DELETE}&\varnothing&\left\{r_{15}, r_{16}\right\}&\varnothing\end{array}

The compiler interprets the INSERT and DELETE sets and rewrites the code as shown in Fig. 10.5(a). LCM deletes the expressions that define r15 and r16 from B2 and inserts them on the edge(B1,B2).

B1:loadI 1→r10 i2i r10→r4 loadAI rarp,@n→r11 i2i r11→r5 cmp_LE r4,r5→r12 cbr r12→B2a,B3 B2a:mult r2,r3→r15 add r1,r15→r16 jump→B2 B2:i2i r16→r6 addI r4,1→r13 i2i r13→r4 cmp_GT r4,r5→r14 cbr r14→B3,B2 B3:…

(a) The Transformed Code

(b) Its CFG

■FIGURE 10.5 Example After Lazy Code Motion.

Since B1 has two successors and B2 has two predecessors,(B1,B2) is a critical edge. Thus, LCM splits the edge, creating a new block B2a to hold the inserted computations of r15 and r16. Splitting(B1,B2) adds an extra jump to the code. Code generation and block placement should strive to place B2a so that the end-of-block jump becomes a fall-through case.

Notice that LCM leaves the copy defining r6 in B2.(Recall that r6 holds the variable x.) LCM moves expressions, not assignments. If the copy is not needed, subsequent copy coalescing, either in the register allocator or as a standalone pass, should discover that fact and eliminate the copy operation.

Code motion techniques can also be used to reduce the size of the compiled code. Code hoisting provides one direct way to accomplish this goal. It uses the results of anticipability analysis in a particularly simple way.

If an expression e∈ANTOUT(b), for some block b, that means that e is evaluated along every path that leaves b and that an evaluation of e at the end of b would make the first evaluation along each path redundant. To reduce code size, the compiler can insert an evaluation of e at the end of b and replace the first occurrence of e on each path that leaves b with a reference to the previously computed value. The effect of this transformation is to replace multiple copies of the evaluation of e with a single copy, reducing the overall number of operations in the compiled code.

The equations for ANTOUT ensure that none of e’s operands is redefined between the end of b and the next evaluation along each path that leaves b.

Some authors use the name VERYBUSY for ANTOUT when used in hoisting.

To replace those expressions directly, the compiler would need to locate them. It could insert e, then solve another data-flow problem, proving that the path from b to some evaluation of e is clear of definitions for e’s operands. Alternatively, it could traverse each of the paths leaving b to find the first block where e is defined—by looking in the block’s UEXPR set. Each of these approaches seems complicated.

A simpler approach has the compiler visit each block b and insert an evaluation of e at the end of b, for every expression e ∈ ANTOUT(b). If the compiler uses a uniform discipline for naming, as suggested in the discussion of LCM, then each evaluation will define the appropriate name. Either LCM or SVN can then remove the newly redundant expressions.

Compilers perform code motion for two primary reasons. Moving an operation to a point where it executes fewer times than it would in its original position should reduce execution time. Moving an operation to a point where one instance replaces several should reduce code size. This section presented an example of each.

LCM is a classic example of a data-flow driven global optimization. It identifies redundant and partially redundant expressions, computes the best place for them, and moves them. By definition, any loop-invariant expression is either redundant or partially redundant; LCM moves a large class of loop invariant expressions out of loops. Hoisting takes a much simpler approach; it finds operations that are redundant on every path that leaves some point p and replaces the redundant occurrences with one evaluation at p. Thus, hoisting is usually done to reduce code size.

One common form of sinking is called cross jumping.

  1. Hoisting discovers the situation in which some expression e exists along each path that leaves point p and each of those occurrences can be replaced safely with an evaluation of e at p. Formulate the symmetric and equivalent optimization, code sinking, that discovers when multiple expression evaluations can safely be moved forward in the code—from points that precede p to p.
  2. Consider what will happen if you apply your code-sinking transformation at link time, when all the code for the entire application is present. What opportunities might it find in the procedure linkage code?

In most compilers, the front end determines the shape of the IR program before it performs any detailed analysis of the code. Of necessity. this produces general code that works in any context that the running program might encounter. With analysis, however, the compiler can often learn enough to narrow the contexts in which the code must operate. The compiler can then specialize the sequence of operations in ways that capitalize on its knowledge of the context in which that code will execute.

Important techniques that perform specialization appear in other sections of this book. Constant propagation, described in Sections 9.3.6 and 10.7.1,analyzes a procedure to find variables and expressions that have known constant values; it then folds those values directly into the computation. Interprocedural constant propagation, introduced in Section 9.4.2, applies the same ideas at the whole-program scope. Operator strength reduction, presented in Section 10.7.2, replaces inductive sequences of expensive computations with equivalent sequences of faster operations. Peephole optimization, introduced in Section 11.3, uses pattern matching over short instruction sequences to find local improvement. Value numbering, shown in Sec-tions 8.4.1 and 8.5.1, systematically simplifies the IR form of the code by applying algebraic identities and local constant folding. Each of these techniques implements a form of specialization.

Optimizing compilers rely on these general techniques to improve code. In addition, most optimizing compilers contain specialization techniques that specifically target properties of the source languages or applications that the compiler writer expects to encounter. The rest of this section presents three such techniques that target specific inefficiencies at procedure calls: tail-call optimization, leaf-call optimization, and parameter promotion.

When the last action that a procedure takes is a call, we refer to that call as a tail call. The compiler can specialize tail calls to their contexts in ways that eliminate much of the overhead from the procedure linkage. To understand how the opportunity for improvement arises, consider what happens when o calls p and p calls q. When q returns, it executes its epilog sequence and jumps back to p’s postreturn sequence. Execution continues in p until p returns, at which point p executes its epilog sequence and jumps to o’s postreturn sequence.

If the call from p to q is a tail call, then no useful computation occurs between the postreturn sequence and the epilog sequence in p. Thus, any code that preserves and restores p’s state, beyond what is needed for the return from p to o, is useless. A standard linkage, as described in Section 6.5,spends much of its effort to preserve state that is useless in the context of a tail call.

At the call from p to q, the minimal precall sequence must evaluate the actual parameters at the call from p to q and adjust the access links or the display if necessary. It need not preserve any caller-saves registers, because they cannot be live. It need not allocate a new AR, because q can use p’s AR,provided that p’s local data area is large enough for q.(If not, the compiler can arrange for p’s prolog to allocate a larger data area.) It must leave intact the context created for a return to o, namely the return address and caller’s ARP that o passed to p, and any callee-saves registers that p preserved in its own AR. Finally, the precall sequence must jump to a tailored prolog sequence for q.

That context will cause the epilog code for q to return control directly to o.

In this scheme, q needs a custom prolog sequence to match the custom pre-call sequence in p. It only needs to save the parts of p’s state that allow a return to o. q’s prolog does not preserve callee-saves registers, for two reasons. First, values computed by p into those registers are dead. Second, the callee-saves values that p saved must be restored on return to o from q. Thus,q’s custom prolog should simply initialize local variables and values that q needs and branch into the code for q.

With these changes to p’s precall sequence and the q’s prolog, the tail call avoids saving and restoring p’s state, which eliminates much of the overhead of the call. Of course, once p’s precall has been tailored in this way, p’s sequences are unreachable. Standard techniques such as Dead and Clean will not discover that fact, because they assume that the interprocedural jumps to their labels are executable. As the optimizer tailors the call, it can eliminate these dead sequences.

With a little care, the optimizer can arrange for the operations in the tailored prolog for q to appear as the last operations in its more general prolog. In this scheme, the tail call from p to q simply jumps to a point farther into the prolog sequence than would a normal call from some other routine.

If the tail call is a self-recursive call-that is, p and q are the same procedure-then tail-call optimization can produce particularly efficient code. In a self-recursive tail call, the entire precall sequence devolves to argument evaluation and a branch back to the top of the routine. An eventual return out of the recursion requires one branch, rather than one branch per recursive

The resulting code can rival a traditional loop for efficiency.

Some of the overhead involved in a procedure call arises from the need to prepare for calls that the callee might make. A procedure that makes no calls, called a leaf procedure, creates opportunities for specialization. The compiler can easily identify a leaf procedure; it makes no calls.

During translation of a leaf procedure, the compiler can avoid inserting operations whose sole purpose is to set up for subsequent calls. For example, the procedure prolog code may save the return address from a register into a slot in the AR. That action is unnecessary unless the procedure itself makes another call. If the register that holds the return address is needed for some other purpose, the register allocator can spill the value. Similarly, if the implementation uses a display to provide addressability for nonlocal variables, as described in Section 6.4.3, a leaf procedure can avoid the display update in the prolog sequence.

The register allocator should use caller-saves registers before callee-saves registers in a leaf procedure. To the extent that it can avoid the callee-saves registers, it can eliminate saves and restores in the prolog and epilog. In small leaf procedures, the compiler may be able to avoid all use of callee-saves registers. If the compiler has access to both the caller and the callee, it can do better; for leaf procedures that need fewer registers than the caller-save set includes, it can avoid some of the register saves and restores in the caller as well.

In addition, the compiler can avoid the runtime overhead of activation-record allocation for leaf procedures. In an implementation that heap allocates ARs, that cost can be significant. In an application with a single thread of control, the compiler can allocate statically the AR of any leaf procedure. A more aggressive compiler might allocate one static AR that is large enough to work for any leaf procedure and have all the leaf procedures share that AR.

If the compiler has access to both the leaf procedure and its callers, it can allocate space for the leaf procedure’s AR in each of its callers’ ARs. This scheme amortizes the AR allocation cost over at least two calls—the invocations of the caller and the leaf procedure. If the caller invokes the leaf procedure multiple times, the savings are multiplied.

Ambiguous memory references prevent the compiler from keeping values in registers. Sometimes, the compiler can employ the results of special case analysis, analysis of pointer values, or analysis of array subscript

Promotion a category of transformations that move an ambiguous value into a local scalar name to expose it to register allocation

expressions to prove that a potentially ambiguous value refers, in reality, to just one memory location. In such cases, the compiler can rewrite the code to move that value into a scalar local variable, where the register allocator can keep it in a register. This kind of transformation is often called promotion. The analysis to promote array references or pointer-based references is beyond the scope of this book. However, a simpler case can illustrate these transformations equally well.

Call-by-reference parameters can be ambiguous. The call site may pass the same variable in two or more parameter slots. It might pass a global variable as an actual parameter. Unless the compiler performs interprocedural analysis to rule out such possibilities, it must treat every call-by-reference formal parameter as ambiguous inside the callee. The potential ambiguity forces the compiler to keep the parameter’s value in memory rather than in a register.

The compiler can create a new name to hold the promoted value: a local scalar value in a near-source IR or a virtual register in a lower-level IR.

If the compiler can prove that the actual parameter must be unambiguous in the callee, it can promote the parameter’s value. It can copy the value into its temporary name at the start of the procedure and copy it back before the procedure returns. The temporary name can then compete for registers with the other unambiguous scalar values. If the callee cannot modify the parameter, the compiler could convert the parameter to use call-by-value.

To apply this transformation to a procedure p, the optimizer must identify all of the call sites that can invoke p. It can either prove that the transformation applies at all of those call sites or it can clone p to create a copy that handles the promoted values (see Section 10.6.2).

SECTION REVIEW Specialization includes many techniques that tailor general-purpose computations to their detailed contexts. Other chapters and sections present powerful global and regional specialization techniques, such as constant propagation, peephole optimization, and operator strength reduction.

This section focused on optimizations that the compiler can apply to the code that implements procedure calls. Tail-call optimization is a valuable tool that converts tail recursion to a form that rivals conventional iteration for efficiency; it applies to nonrecursive tail calls as well. Leaf procedures offer special opportunities for improvement because the callee can omit major portions of the standard linkage sequence. Parameter promotion is one example of a class of important transformations that remove inefficiencies related to ambiguous references.

  1. Parameter promotion transforms the code to move an unambiguous call-by-reference parameter in a local scalar variable. An analogous transformation could look at a loop and move a pointer-based value (e.g., *p in C) into a local scalar variable throughout the loop. What safety conditions would the compiler need to prove to perform such scalar promotion on pointer-based values?

  2. Inline substitution might be an alternative to the procedure-call optimizations in this section. How might you apply inline substitution in each case? How might the compiler choose the more profitable alternative?

A computation x+y is redundant at some point p in the code if, along every path that reaches p, x+y has already been evaluated and x and y have not been modified since the evaluation. Redundant computations typically arise as artifacts of translation or optimization.

We have already presented three effective techniques for redundancy elimination: local value numbering (LVN) in Section 8.4.1, superlocal value numbering (SVN) in Section 8.5.1, and lazy code motion (LCM) in Section 10.3.1. These algorithms cover the span from simple and fast (LVN) to complex and comprehensive (LCM). While all three methods differ in scope, the primary distinction between them lies in the way that they establish that two values are identical. Section 10.5.1 explores this issue in detail. Section 10.5.2 presents one more version of value numbering, a dominator-based technique.

10.5.1 Value Identity Versus Name Identity

Section titled “10.5.1 Value Identity Versus Name Identity”

LVN introduced a simple mechanism to prove that two expressions had the same value. LVN relies on two principles. It assigns each value a unique identifying number—its value number. It assumes that two expressions produce the same value if they have the same operator and their operands have the same value numbers. These simple rules allow LVN to find a broad class of redundant operations—any operation that produces a preexisting value number is redundant.

With these rules, LVN can prove that 2+a has the same value as a+2 or as 2+b when a and b have the same value number. It cannot prove that a+a and 2×a have the same value because they have different operators.

Similarly, it cannot prove the a+0 and a have the same value. Thus, we extended LVN with algebraic identities to handle many well-defined cases not covered by the original rule. The table in Fig. 8.3 on page 398 shows the range of identities that LVN can handle. SVN extends the optimization to larger scopes.

By contrast, LCM relies on names to prove that two values have the same number. If LCM sees a+b and a+c, it assumes that they have different values because b and c have different names. It relies on a lexical comparison-name identity. The underlying data-flow analyses cannot directly accommodate the notion of value identity; data-flow problems operate over a predefined name space and propagate facts about those names over the CFG. The kind of ad-hoc comparisons used in LVN do not fit into the data-flow framework.

The compiler can improve the effectiveness of LCM by encoding value identity into the code’s name space before applying LCM. The compiler first applies a value numbering technique, such as DVNT from the next subsection, to find value numbers. Next, it rewrites the code in terms of the value numbers. Finally, it applies LCM to the transformed code. The resulting code should reflect the strengths of both approaches. It can find improvements that neither technique could find on its own.

Chapter 8 described two value numbering algorithms, LVN and SVN. While SVN discovers more redundancies than LVN, it still misses some opportuni-nities because it only propagates information along paths through extended basic blocks(EBBs). For example, in the CFG fragment shown in the margin, SVN will process the paths ⟨B0,B1,B2⟩\langle B_{0},B_{1},B_{2}\rangle and ⟨B0,B1,B4⟩\langle B_{0},B_{1},B_{4}\rangle . Thus, it optimizes both B2 and B4 in the context of the prefix path ⟨B0,B1⟩\langle B_{0},B_{1}\rangle . Because B3B_{3}forms its own degenerate EBB, SVN optimizes B3B_{3} without any prior context.SVN cannot propagate information across the join point and into B3.

From an algorithmic point of view, SVN begins each block with a table that includes the results of all predecessors on its EBB path. Block B3 forms a degenerate EBB with no predecessors, so it has no prior context. To improve on that situation, we must answer the question: on what state could B3 rely?

B3 cannot rely on values computed in either B2 or B4, since neither lies on every path that reaches B3. By contrast, B3 can rely on values computed inB0B_{0} and B1B_{1} , since they occur on every path that reaches B3B_{3} . Thus, we might extend value numbering for B3 with information about computations in B0B_{0}and B1. We must, however, account for the impact of assignments in the intervening blocks, B2 or B4.

CFG Fragment(118,543),(230,670) Consider an expression, x+y, that occurs at the end of B1 and again at the start of B3. If neither B2 or B4 redefines x or y, then the evaluation of x+y in B3 is redundant and the optimizer can reuse the value computed in B1. On the other hand, if either of those blocks redefines x or y, then the evaluation of x+y in B3 computes a distinct value from the evaluation in B1 and the evaluation is not redundant. We need an algorithmic way to ensure that the algorithm can distinguish between these two cases.

Fortunately, the SSA name space encodes precisely this distinction. In SSA, a name that is used in some block Bi can only enter Bi in one of two ways. Either the name is defined by a φ-function at the top of Bi, or it is defined in some block that dominates Bi. Thus, an assignment to x in either B2 or B4 creates a new name for x and forces the insertion of a φ-function for x at the head of B3. That φ-function creates a new SSA name for x and the renaming process changes the SSA name used in the subsequent evaluation of x+y in B3. Thus, SSA form encodes the presence or absence of an intervening assignment in B2 or B4 directly into the name space. A value-numbering algorithm that uses SSA names can avoid the complications posed by those intervening assignments.

The other major question that we must answer before we can extend SVN is: given a block such as B3, how do we locate the most recent predecessor with information that the algorithm can use? The IDOM relation, discussed in Section 9.2.1, captures precisely this effect. B1 is IDOM(B3), so it is the closest node that occurs on every path from the entry node to B3. For a block b, the algorithm can use the tables from IDOM(b) as an initial state.

The dominator-based value numbering technique (DVNT) builds on the ideas in SVN. It uses a sheaf of tables to map expressions to value numbers. It creates a new table for each block and discards that table when it is no longer needed. To simplify bookkeeping, DVNT simply uses the SSA names as value numbers. Thus, if tk ← ai ×bj is the first evaluation of ai ×bj, then the value number for ai ×bj is tk.

Fig. 10.6 shows the algorithm. It takes the form of a recursive procedure that the optimizer invokes on a procedure’s entry block. It follows both the CFG for the procedure, represented by the dominator tree, and the flow of values in the SSA form. For each block B, DVNT takes three steps: it processes any φ-functions that exist in B; it value numbers the assignments; and it propagates information into B’s successors and recurs on B’s children in the dominator tree.

This discussion has a subtle consequence. Data-flow problems that use KILL sets, such as VARKILL or EXPRKILL, can be reformulated over SSA names to eliminate those sets. The resulting framework can be noticeably cheaper to solve. The SSA name refers uniquely to the result of one definition point.

DVNT(B) allocate a new table for B and link it into the sheaf for each ϕ\phi -function p of the form “n←φ(…)” in B do if p is meaningless then VN[n]←the value number for p’s first argument delete p from the code if p is redundant with some ϕ\phi -function q in B then VN[p]←VN[q] delete p from the code else VN[n]←n Add p to the hash table with value number n for each assignment “x←y op z” in B, in order, do overwrite y with VN[y] overwrite z with VN[z] let expr←“y op z” if expr can be simplified to expr’ then rewrite the assignment as “x←expr’” expr←expr’ if expr has a value number v in the hash table then VN[x]←v delete the assignment from the code else VN[x]←x add expr to the hash table with value number x for each successor s of B do adjust the ϕ\phi -function inputs in s for each child c of B in the dominator tree DVNT(c) free the scope for B

■ FIGURE 10.6 Dominator-Based Value Numbering Technique.

DVNT must assign each ϕ\phi -function p a value number. If p is meaningless-that is, all its arguments have the same value number-DVNT sets its value number to the value number for one of its arguments and deletes p. If p is redundant-that is, it produces the same value number as another ϕ\phi -function q in B-DVNT assigns p the value number of q. DVNT then deletes p.

Otherwise, the ϕ\phi -function computes a new value. DVNT assigns it a value number-the SSA number of its target. If the code reaches this point, then either the φ-function has a unique combination of arguments, or some of its arguments do not yet have a value number. In either case, DVNT cannot simplify the φ-function.

DVNT iterates over the assignments in B and processes them in a manner analogous to LVN and SVN. One subtlety arises from the use of SSA names as value numbers. When the algorithm encounters a statement x ← y op z, it can simply replace y with VN[y] because the name in VN[y] holds the same value as y.

Once DVNT has processed all the φ-functions and assignments in B, it visits each of B’s CFG successors s and updates φ function arguments that correspond to values flowing across the edge (B,s). It records the current value number for the argument in the φ-function by overwriting the argument’s SSA name. Next, the algorithm recurs on B’s children in the dominator tree. Finally, it frees the hash table that it used for B.

This recursive scheme takes DVNT on a preorder walk of the dominator tree, which ensures that the appropriate tables have been constructed before it visits a block. This order can produce a counterintuitive traversal; for the CFG in the margin, the algorithm could visit B₃ before either B₂ or B₄. Since the only facts that the algorithm can use in B₃ are those discovered processing B₀ and B₁, the relative ordering of B₂, B₄, and B₃ is not only unspecified, it is also irrelevant.

Redundancy elimination assumes that it is faster to reuse a value than to recompute it. LCM and DVNT find redundant computations and eliminate duplicate evaluations. LCM uses name-based identity while DVNT uses value-based identity. These different notions of identity can find different redundancies.

Both LCM and DVNT eliminate redundant computations. LCM removes the evaluation of redundant and partially redundant expressions; it does not eliminate assignments. Value numbering also removes assignments; it does not find partial redundancies. To combine the strengths of both techniques, some compilers use value-numbering to encode value identity into the name space and a name-based technique such as LCM to rewrite the code.

  1. DVNT does not propagate a value along a loop-closing edge—a back edge in the call graph. LCM will propagate information along such edges. Write several examples of redundant expressions that a true “global” technique such as LCM can find that DVNT cannot.

  2. The DVNT algorithm resembles the renaming phase of the SSA construction algorithm. Can you reformulate the renaming phase so that it performs value numbering as it renames values? What impact would this change have on the size of the SSA form for a procedure?

Often, an optimizer includes passes whose primary purpose is to create or expose opportunities for other transformations. In some cases, a transformation changes the shape of the code to make it more amenable to optimization. In other cases, the transformation creates a point in the code where specific conditions hold that make another transformation safe or profitable. By directly creating the necessary code shape, these enabling transformations reduce the sensitivity of the optimizer to the shape of the source program.

Several enabling transformations are described in other parts of the book. Both loop unrolling (Section 8.5.2) and inline substitution (Section 8.7.1) obtain most of their benefits by creating context for other optimizations. (In each case, the transformation eliminates some overhead, but the larger effect comes from subsequent application of other optimizations.) The tree-height balancing algorithm (Section 8.4.2) does not eliminate any operations, but it creates a code shape that can produce better results from instruction scheduling. This section presents four enabling transformations: superblock cloning, procedure cloning, loop unswitching, and renaming.

Often, the optimizer’s ability to transform the code is limited by path-specific information in the code. Imagine using SVN on the CFG shown in the margin. The fact that blocks B3B_{3} and B7B_{7} have multiple predecessors may limit the optimizer’s ability to improve those blocks. If, for example, B6B_{6} assigned x the value 7 and B8B_{8} assigned x the value 13, a use of x in B7B_{7} would appear to receive the value ⊥\bot, even though the value is known and predictable along each path leading to B7B_{7}.

CFG for Superblock Cloning In such circumstances, the compiler can clone blocks to create code that is better suited for the transformation. In this case, it might create two copies of B7, say B7a and B7b, and redirect the incoming edges as (B6,B7a) and (B8,B7b). With this change, the optimizer could propagate the value 7 for x into B7a and the value 13 for x into B7b.

As an additional benefit, since B7a and B7b both have unique predecessors, the compiler can merge the blocks to create one block from B6 and B7a and another from B8 and B7b. This change eliminates the block-ending jump in B6 and B8 and, potentially, allows for further improvement in optimization.

An issue in this kind of cloning is, when should the compiler stop cloning? One technique, called superblock cloning, is widely used to create additional context for instruction scheduling inside loops. In superblock cloning, the optimizer starts with a loop head—the entry to a loop—and clones each path until it reaches a backward branch.

Applying this technique to the example CFG produces the modified CFG shown in the margin. B1 is the loop header. Each of the nodes in the loop body has a unique predecessor. If the compiler applies a superlocal optimization (one based on EBBs), every path that it finds will encompass a single iteration of the loop body. (To find longer paths, the optimizer could need to unroll the loop before superblock cloning.)

Superblock cloning enables other optimizations in three principal ways:

  1. It creates longer blocks. Longer blocks let local and superlocal optimization see more context. While LVN extends nicely from one block to larger regions, other optimizations do not. In the transformed CFG, local techniques can be applied directly to the merged blocks. For example, the compiler could apply the tree-height balancing algorithm to (B6,B7a,B3b), rather than balancing B6, B7a, and B3b, by themselves.

  2. It eliminates branches. Combining two blocks eliminates a branch between them. Branches take time to execute. They also can disrupt performance-critical mechanisms in the processor, such as instruction prefetch. The net effect is to reduce the number of operations that execute and to make hardware prediction mechanisms more effective.

  3. It creates points where optimization can occur. When cloning eliminates a join point in the CFG, it creates new points in the program where the compiler can derive more precise knowledge about the runtime context. The transformed code may present opportunities for optimization that exist nowhere in the original code.

Of course, cloning has costs, too. It duplicates individual operations, which causes code growth. The larger code may run more quickly because it avoids backward branch a CFG edge (i,j) where the depth-first number of i is less than or equal to the depth-first number of j

Loop-closing branch a CFG edge (i,j) where j ∈ DOM(i).

CFG After Superblock Cloning some end-of-block jumps. It may run more slowly if its size causes more in-struction cache misses. In applications where the user cares more about code space than runtime speed, superblock cloning may be counterproductive.

Inline substitution, described in Section 8.7.1, has effects similar to su-perblock cloning. For a call from p to q, it creates a unique copy of q and merges it with the call site in p. It achieves the same effects as superblock cloning, including specialization to a particular context, elimination of some control-flow operations, and increased code size.

In some cases, cloning a procedure can achieve some of the benefits of inline substitution with less code growth. The key observation is that procedure cloning need not create a separate clone for each call site. Rather, it should create a clone for each interesting optimization context. The compiler creates multiple copies of the callee and assigns calls with similar context to the same clone.

Consider, for example, the simple call graph in the margin. Assume that P3’s behavior depends strongly on one of its input parameters; for a value of one, the compiler can generate code that provides efficient memory access, while for other values, it produces much larger, slower code. Further, assume that P0 and P1 both pass the value 1 to P3, while P2 passes it the value 17.

Constant propagation across the call graph does not help here because it must compute P3’s parameter as 1∧1∧17=⊥, which does not allow specialization in P3. Procedure cloning can create a place where the parameter is always 1, as with P3a in the graph in the margin. The call that inhibits optimization,(P2,P3) in the original call graph, is assigned to P3b.The compiler can generate optimized code for P3a and generic code for P3b.

Loop unswitching hoists loop-invariant control-flow operations out of a loop. If the predicate in an if-then-else construct is loop invariant, then the compiler can rewrite the loop to pull the if-then-else out of the loop and generate a tailored copy of the loop inside each half of the new if-then-else. Fig. 10.7 shows a brief example.

Unswitching is an enabling transformation; it allows the compiler to tailor loop bodies in ways that are otherwise hard to achieve. After unswitching, the remaining loops contain less control flow. They execute fewer branches and other operations to support those branches. This can lead to better scheduling, better register allocation, and faster execution. If the original

do i = 1 to n if (x > y) then a(i) = b(i) * x else a(i) = b(i) * y

if (x > y) then do i = 1 to n a(i) = b(i) * x else do i = 1 to n a(i) = b(i) * y

(a) Original Loop (b) Unswitched Version

FIGURE 10.7 Unswitching a Short Loop.

loop contained loop-invariant code that was inside the if-then-else, then LCM could not move it out of the loop. After unswitching, LCM easily finds and removes such redundancies.

Unswitching also has a simple, direct effect that can improve a program: it moves the branch from the loop-invariant conditional out of the loop. Moving control flow out of loops is difficult. Techniques based on data-flow analysis, like LCM, have trouble moving such constructs because the transformation modifies the CFG on which the analysis relies. Techniques such as SVN and DVNT can recognize cases where the predicates controlling if-then-else constructs are constant or redundant but can neither simplify the control flow nor move the construct out of a loop.

Most scalar transformations rewrite or reorder operations in the code. We have seen, in several contexts, that the choice of names can either obscure or expose opportunities for improvement. For example, in LVN, converting the names in a block to SSA names exposed some opportunities for reuse that would otherwise be difficult to capture.

For many transformations, careful construction of the “right” name space can expose additional opportunities, either by making more facts visible to analysis or by avoiding some of the side effects that arise from reuse of storage. As discussed in Section 10.5.1, the compiler writer can improve the effectiveness of LCM by encoding value identity into the name space, where LCM’s name-based, data-flow approach will discover the redundancy and perform the appropriate redundancy elimination and code motion. Careful renaming exposes more opportunities to LCM and makes it more effective.

In a similar way, names matter to instruction scheduling. In a scheduler, names encode the data dependences that constrain the placement of operations in the scheduled code. When the reuse of a name reflects the actual flow of values, that reuse provides critical information required for The illusion of a constraint introduced by naming is often called false sharing.

correctness. If reuse of a name occurs because a prior pass has compressed the name space, then the reuse may unnecessarily constrain the schedule. For example, the register allocator places distinct values into the same physical register to improve register utilization. If the compiler performs allocation before scheduling, the allocator can introduce apparent constraints on the scheduler that are not strictly required by the original code.

Renaming is a subtle issue. Individual transformations can benefit from name spaces with different properties. Compiler writers have long recognized that moving and rewriting operations can improve programs. In the same way, they should recognize that renaming can improve optimizer effectiveness. As SSA has shown, the compiler need not be bound by the name space introduced by the programmer or by the compiler’s front end. Renaming is a fertile ground for future work

As we saw in Chapter 7, the shape of the IR affects the code that the compiler can generate. The techniques in this section rewrite the code to create opportunities for other optimizations. They use replication, selective rewriting, and renaming to create places in the code that can be improved by specific transformations.

Cloning, at either the block or procedure level, achieves its effects by eliminating control-flow merge points. It can simplify paths and combine blocks or procedures. Loop unswitching moves control structures out of a loop to make them both more amenable to optimization. Renaming is a powerful idea with widespread application, including redundancy elimination, strength reduction, scheduling, and register allocation.

  1. Superblock cloning creates new opportunities for other optimizations. Consider tree-height balancing. How much can superblock cloning help? Can you envision a transformation to follow superblock cloning that would expose more opportunities for tree-height balancing? For SVN, how might the results of using SVN after cloning compare to the results of running LCM on the same code?

  2. Procedure cloning attacks some of the same inefficiencies as inline substitution. Is there a role for both of these transformations in a single compiler? What are the potential benefits and risks of each transformation? How might a compiler choose between them?

In some algorithms, viewing the SSA form of the code as a graph simplifies either the discussion or the implementation. Both sparse conditional constant propagation (SSCP) and the strength reduction algorithm operate on SSA form viewed as a graph.

In SSA form, each name corresponds to exactly one definition. A use of that name in operation i can be interpreted as a chain from i back to the name’s definition. The compiler can easily construct maps from uses to their definitions and definitions to their uses during the SSA construction. These maps can be interpreted as a graph, with edges that connect definitions to uses and reflect the flow of values in the original code.

We draw SSA graphs with edges that run from a use to its corresponding definition, which indicates the relationship implied by the SSA names. The compiler may need to traverse the edges in both directions. SCCP propagates values from definitions to uses. OSR moves, primarily, from uses to definitions. The compiler writer can easily build the graph to allow traversal in either direction.

Most of the examples in this chapter have been chosen to illustrate a specific effect that the compiler can use to speed up the executable code. Sometimes, performing two optimizations together can produce results that cannot be obtained with any combination of applying them separately. The next subsection shows one such example: combining constant propagation with unreachable code elimination. Section 10.7.2 presents a second, more complex example of specialization: operator strength reduction with linear-function test replacement (LFTR). The algorithm that we present, OSR, is simpler than previous algorithms because it relies on properties of SSA form. Finally, Section 10.7.3 discusses some of the issues that arise in choosing a specific application order for the optimizer’s set of transformations.

Sometimes, reformulating two distinct optimizations in a unified framework and solving them jointly can produce results that cannot be obtained by any combination of the optimizations run separately. As an example, consider the sparse simple constant propagation (SSCP) algorithm from Section 9.3.6. It assigns a lattice value to the result of each operation in the SSA form of the program. When it halts, it has tagged every definition with a lattice value that is either T, ⊥\perp, or a known constant. CFGWorkList ← { edges leaving n₀ } SSAWorkList ← Ø for each edge e in the CFG do mark e as unexecuted for each def and each use, x, in the procedure do Value(x) ← T while (CFGWorkList ≠ Ø or SSAWorkList ≠ Ø) do if CFGWorkList ≠ Ø then remove an edge e = (m,n) from CFGWorkList if e is marked as unexecuted then mark e as executed EvaluateAllPhisInBlock((m,n)) if no other edge entering n is marked as executed then if n is an assignment then EvaluateAssign(n) let o be n’s CFG successor add (n,o) to CFGWorkList else EvaluateConditional(n) if SSAWorkList ≠ Ø then remove an edge e = (s,d) from SSAWorkList c ← CFG node that uses d if any edge entering c is marked as executed then if d is a φ function argument then EvaluatePhi((s,d)) else if c is an assignment then EvaluateAssign(c) else EvaluateConditional(c) ■ FIGURE 10.8 Sparse Conditional Constant Propagation.

SSCP assigns a lattice value to the operand used by a conditional branch. If the value is ⊥, then either branch target is reachable. If the value is neither ⊥ nor T, then the operand must have a known value and the compiler can rewrite the branch with a jump to one of its two targets, simplifying the CFG. Since this removes an edge from the CFG, it may make the block that was the branch target unreachable. Constant propagation can ignore any effects of an unreachable block. SSCP has no mechanism to take advantage of this knowledge.

We can extend the SSCP algorithm to capitalize on these observations. The resulting algorithm, called sparse conditional constant propagation (SCCP), appears in Figs. 10.8 to 10.10. EvaluateAssign(m) /* m is a CFG node */ for each value y used by the expression in m do let (x,y) be the SSA edge that supplies y Value(y) ← Value(x) let d be the name of the value produced by m if Value(d) ≠ ⊥ then v ← evaluation of m over lattice values if v ≠ Value(d) then Value(d) ← v for every SSA edge (d,u) do add (d,u) to SSAWorklist

EvaluateConditional(m) /* m is a CFG node */ let (s,d) be the SSA edge referenced in m if Value(d) ≠ ⊥ then if Value(d) ≠ Value(s) then Value(d) ← Value(s) if Value(d) = ⊥ then for each CFG edge (m,n) do add (m,n) to CFGWorkList else let (m,n) be the CFG edge that matches Value(d) add (m,n) to CFGWorkList

■ FIGURE 10.9 Evaluating Assignments and Conditionals.

In concept, SCCP operates in a straightforward way. It initializes the data structures. It iterates over two graphs, the CFG and the SSA graph. It propagates reachability information on the CFG and value information on the SSA graph. It halts when the value information reaches a fixed point; because the constant propagation lattice is so shallow, it halts quickly. Combining these two kinds of information, SCCP can discover both unreachable code and constant values that the compiler simply could not discover with any combination of SSCP and unreachable code elimination.

To simplify the explanation of SCCP, we assume that each CFG node, n, holds one statement plus some optional φ-functions. If n has one predecessor, it holds an assignment or a branch. If n has multiple predecessors, it may also have φ-functions before the assignment or branch.

In detail, SCCP is more complex than either SSCP or unreachable code elimination. Using two graphs introduces more bookkeeping. Making the flow of values depend on reachability adds work to the algorithm. The result is a powerful but complex algorithm. EvaluatePhi((s,d)) /(s,d) is an SSA graph edge/ let p be the φ function that uses d EvaluateOperands(p) EvaluateResult(p)

EvaluateAllPhisInBlock((m,n)) /(m,n) is a CFG edge/ for each φ function p in block n do EvaluateOperands(p) for each φ function p in block n do EvaluateResult(p)

EvaluateOperands(phi) let w be the name defined by φ function phi if Value(w) ≠ ⊥ then for each parameter p of φ function phi do let c be the CFG edge corresponding to p let (x,y) be the SSA edge whose use is in p if c is marked as executed then Value(x) ← Value(y)

EvaluateResult(phi) let x be the name defined by φ function phi if Value(x) ≠ ⊥ then v ← evaluation of phi over lattice values if Value(x) ≠ v then Value(x) ← v for each SSA graph edge (x,y) do add (x,y) to SSAWorkList

■ FIGURE 10.10 Evaluating φ Functions.

To start, the algorithm initializes each Value field to T and marks each CFG edge as “unexecuted.” It initializes a worklist for CFG edges to hold the set of edges that leave the procedure’s entry node, n0. It initializes a worklist for SSA edges to the empty set.

In this discussion, a block is reachable if and only if some CFG edge that enters it is marked as executable.

After initialization, the algorithm repeatedly picks an edge from one of the worklists and processes that edge. For a CFG edge (m,n), SCCP determines if (m,n) is marked as executed. If so, SCCP takes no further action for (m,n). If (m,n) is marked as unexecuted, then SCCP marks it as executed and evaluates all of the φ-functions at the start of block n. Next, SCCP checks if block n has already been entered from another edge. If not, then SCCP evaluates the assignment or conditional branch in n. This processing may add edges to either worklist.

For an SSA edge, the algorithm first checks if the destination block is reachable. If the block is reachable, SCCP calls one of EvaluatePhi, EvaluateAssign, or EvaluateConditional, based on the kind of operation that uses the SSA name. When SCCP must evaluate an assignment or a conditional over the lattice of values, it follows the same scheme used in SSCP, discussed in Sec-tion 9.3.6 on page 493. Each time the lattice value for a definition changes, all the uses of that name are added to the SSA worklist.

Because SCCP only propagates values into blocks that it has already proved executable, it avoids processing unreachable blocks. Because each value propagation step is guarded by a test on the executable flag for the entering edge, values from unreachable blocks do not flow out of those blocks. Thus, values from unreachable blocks have no role in setting the lattice values in other blocks.

After the propagation step, a final pass is required to replace operations that have operands with Value tags other than⊥. The final pass can specialize many of these operations. It should also rewrite branches that have known outcomes with the appropriate jump operations. A subsequent pass can remove the unreachable code(see Section 10.2.3). The algorithm cannot rewrite the code until the propagation completes.

Subtleties in Evaluating and Rewriting Operations

Section titled “Subtleties in Evaluating and Rewriting Operations”

Some subtle issues arise in modeling individual operations. For example, if the algorithm encounters a multiply operation with operands T and⊥, it might conclude that the operation produces⊥. Doing so, however, is premature. Subsequent analysis might lower the T to the constant 0, so that the multiply produces a value of 0. If SCCP uses the rule Tx⊥→⊥, it introduces the potential for nonmonotonic behavior-the multiply’s value might follow the sequence T,⊥,0, which would increase the running time of SCCP. Equally important, it might incorrectly drive other values to⊥ and cause SCCP to miss opportunities for improvement.

To address this, SCCP should use three rules for multiplies that involve⊥,as follows: Tx⊥→T,αx⊥→⊥ for a≠T and a≠0, and 0x⊥→0. This same effect occurs for any operation for which the value of one argument can completely determine the result. Other examples include a shift by more than the word length, a logical AND with zero, and a logical OR with all ones.

Some rewrites have unforeseen consequences. For example, replacing 4xs, for nonnegative s, with a shift replaces a commutative operation with a non-commutative operation. If the compiler subsequently tries to rearrange expressions using commutativity, this early rewrite forecloses an opportunity.

This kind of interaction can have noticeable effects on code quality. To choose when the compiler should convert 4xs into a shift, the compiler writer must consider the order in which optimizations will be applied.

SCCP can find constants that the SSCP algorithm cannot. Similarly, it can discover unreachable code that no combination of the algorithms in Sec-tion 10.2 can discover. It derives its power from combining reachability analysis with the propagation of lattice values. It can eliminate some CFG edges because the lattice values are sufficient to determine which path a branch takes. It can ignore SSA edges that arise from unreachable operations(by initializing those definitions to T) because those operations will be evaluated if the block becomes marked as reachable. The power of SCCP arises from the interplay between these analyses-constant propagation and reachability.

If reachability did not affect the final lattice values, then the same effects could be achieved by performing constant propagation(and rewriting constant-valued branches as jumps) followed by unreachable-code elimination. If constant propagation played no role in reachability, then the same effects could be achieved by the other order-unreachable-code elimination followed by constant propagation. The power of SCCP to find simplifications beyond those combinations comes precisely from the fact that the two optimizations are interdependent.

Operator strength reduction is a transformation that replaces a series of expensive(“strong”) operations with a series of inexpensive(“weak”) operations that compute the same values. The classic example replaces integer multiplications based on a loop index with equivalent additions. This particular case arises routinely from the expansion of array and structure addresses in loops. Fig. 10.11(a) shows the ILOC that might be generated for the following loop:

\begin{array}[]{l}\text{sum}\leftarrow 0\\\text{for}i\leftarrow\text{1 to}100\\\text{sum}\leftarrow\text{sum}+\text{a(i)}\\\end{array}

The code is in semipruned SSA form; the purely local values(r1,r2,r3,r4,and r5) have neither subscripts nor φ-functions. Notice how the reference to a(i) expands to four operations-the subI,multI,and addI that compute(i-1)x4+@a and the load that defines r4. loadI 0 ⇒ rs0 loadI 1 ⇒ ri0 loadI 100 ⇒ r100 l1: phi ri0,r12 ⇒ r11 phi rs0,rs2 ⇒ rs1 subI r11,1 ⇒ r1 multI r1,4 ⇒ r2 addI r2,@a ⇒ r3 load r3 ⇒ r4 add rs1,r4 ⇒ rs2 addI r11,1 ⇒ r12 cmp_LE r12,r100 ⇒ r5 cbr r5 ⇒ l1,l2 l1: phi rt6,rt3 ⇒ rt7 phi rs0,rs2 ⇒ rs1 load rt7 ⇒ r4 add rs1,r4 ⇒ rs2 addI rt7,4 ⇒ rt8 cmp_LE rt8,r11m ⇒ r5 cbr r5 ⇒ l1,l2 l2: …

(a) Original Code (b) Strength-Reduced Code

■ FIGURE 10.11 Strength Reduction Example.

For each iteration, this sequence of operations computes the address of a(i)from scratch as a function of the loop index variable i. Consider the sequences of values taken on by r11,r1,r2,and r3.

r11: { 1, 2, 3, …, 100 } r1: { 0, 1, 2, …, 99 } r2: { 0, 4, 8, …, 396 } r3: { @a, @a+4, @a+8, …, @a+396 }

The only purpose for r1,r2,and r3 is to compute the address for the load operation. If the code could compute each value of r3 from the preceding one, it could eliminate the operations that define r1 and r2. Of course, r3 would then need an initialization and an update; it would also need a φ-function at l1 and, possibly, at l2.

Panel (b) shows the code after strength reduction, LFTR, and dead-code elimination. It computes those values formerly in r3 directly into rt7 and uses rt7 in the load operation. The end-of-loop test, which used r12 in the original code, has been modified to use rt8. This makes the computations of r1,r2,r3,ri0,ri1,and ri2 all dead. They have been removed to produce the final code. Now, the loop contains just five operations, ignoring φ-functions, while the original code contained eight. (Translation out of SSA form rewrites the φ-functions as copy operations; many of those copies can be coalesced.)

loadI 0⇒rs0 loadI 1⇒ri0 loadI 100⇒r100 l1: phi rio, rio⇒ri phi rs0,rs2⇒rs1 subI ri1,1⇒r1 multI r1,4⇒r2 addI r2,@a⇒r3 load r3⇒r4 add rs1,r4⇒rs2 addI ri1,1⇒ri2 cmp_LE ri2,r100⇒r5 cbr r5→l1,l2 l2: …

(b) Corresponding SSA Graph

■ FIGURE 10.12 Relating SSA in ILOC to the SSA Graph.

If a multI is more expensive than an addI, the savings will be larger. Historically, the high cost of a multiply justified strength reduction. However, even if multiplication and addition have equal costs, the strength-reduced form of the loop may be preferred because it creates a better code shape for later phases of the compiler. In particular, if the target machine has an autoincrement address mode, then the addI operation in the loop often can be folded into a load or store. This option does not exist with the multiply.

The rest of this section presents a simple algorithm for operator strength reduction(OSR), followed by a scheme for LFTR that shifts end-of-loop tests away from variables that would otherwise be dead. OSR operates on the SSA form of the code, considered as a graph. Fig. 10.12 shows the code for our example in SSA form alongside its SSA graph.

Region constant

A value that does not vary within a given loop is a region constant for that loop.

Induction variable

A value that increases or decreases by a constant amount in each iteration of a loop is an induction variable.

Strength reduction looks for contexts in which an operation, such as a multiply, executes inside a loop and its operands are (1) a value that does not vary in that loop, called a region constant, and (2) a value that varies systematically from iteration to iteration, called an induction variable. When it finds this situation, it creates a new induction variable to compute the same sequence of values in a more efficient way. The restrictions on the form of the multiply operation’s operands ensure that this new induction variable can be computed using additions, rather than multiplications. An operation that the algorithm can reduce in this way is called a candidate operation. To simplify the presentation of OSR, we only consider candidate operations that have one of the formats shown in the margin. where c is a region constant and i is an induction variable. The key to finding and reducing candidate operations is efficient identification of region constants and induction variables. The restriction to these five forms is critical.

A region constant can either be a literal constant, such as 10, or a loop-invariant value, that is, one not modified inside the loop. With the code in SSA form, the compiler can determine if an argument is loop invariant by checking the location of its sole definition-the block that contains the definition must dominate the entry to the loop that defines the induction variable. OSR can check both of these conditions in constant time. Performing constant propagation and lazy code motion before strength reduction may expose more region constants.

Intuitively, an induction variable is one whose values in the loop form an arithmetic progression. For the purposes of this algorithm, we can use a much more specific and restricted definition: an induction variable is a strongly connected component (SCC) of the SSA graph in which each operation that updates its value is one of (1) an induction variable plus a region constant, (2) an induction variable minus a region constant, (3) a φ-function, or (4) a register-to-register copy from another induction variable. While this definition is much less general than conventional definitions, it is sufficient to enable the OSR algorithm to find and reduce candidate operations. To identify induction variables, OSR finds SCCs in the SSA graph and iterates over each SCC to determine if each operation in each SCC is of one of these four types.

Because OSR defines induction variables in the SSA graph and region constants relative to a loop in the CFG, the test to determine if a value is constant relative to the loop containing a specific induction variable is complicated. Consider an operation o of the form x←i×c, where i is an induction variable. For o to be a candidate for strength reduction, c must be a region constant with respect to the outermost loop in which i varies. To test whether c has this property, OSR must relate the SCC for i in the SSA graph back to a loop in the CFG. To simplify this test, OSR will add a field to each SSA node to hold its “header.”

OSR finds the SSA graph node with the lowest reverse postorder number in the SCC that defines i. It considers this node to be the header of the SCC and records that fact in the header field of each node of the SCC. (Any node in the SSA graph that is not part of an induction variable has its header field set to null.) In SSA form, the induction variable’s header is the φ-function at

the start of the outermost loop in which it varies. In an operation x←ixc, where i is an induction variable, c is a region constant if the CFG block that contains its definition dominates the CFG block that contains i’s header. This condition ensures that c is invariant in the outermost loop in which varies. To perform this test, the SSA construction must produce a map from each SSA node to the CFG block where it originated.

The header field plays a critical role in determining whether or not an operation can be reduced. When OSR encounters an operation x←yxz, it can determine if y is an induction variable by following the SSA graph edge to y’s definition and inspecting its header field. A null header field indicates that y is not an induction variable. If both y and z have null header fields, the operation cannot be strength reduced.

If one of y or z has a nonnull header field, then OSR can use that header to determine if the other operand is a region constant. Assume y’s header is not null. OSR looks in the SSA-to-CFG map, indexed by y’s header, to find the entry to the outermost loop where y varies. If the CFG block containing z’s definition dominates the CFG block of y’s header, then z is a region constant relative to the induction variable y.

To perform strength reduction, OSR must examine each operation and determine if one of its operands is an induction variable and the other is a region constant. If the operation meets these criteria, OSR can reduce it by creating a new induction variable that computes the needed values and replacing the operation with a register-to-register copy from this new induction variable.(It should avoid creating duplicate induction variables.)

Based on the preceding discussion, we know that OSR can identify induction variables by finding SCCs in the SSA graph. It can discover a region constant by examining the value’s definition. If the definition results from an immediate operation, or its CFG block dominates the CFG block of the induction variable’s header, then the value is a region constant. The key is combining these ideas into an efficient algorithm.

OSR is built on Tarjan’s strongly connected region finder. As shown in Fig. 10.13, OSR takes an SSA graph as its argument and repeatedly applies the strongly connected region finder, DFS, to it.(This process stops when DFS has visited every node in G.)

DFS performs a depth-first search of the SSA graph. It assigns each node a number that corresponds to the order in which DFS visits the node. It pushes each node onto a stack and labels the node with the lowest depth-first number on a node that can be reached from its children. When DFS returns from OSR(G) nextNum ← 0 while there is an unvisited n ∈ G do DFS(n)

DFS(n) n. Num ← nextNum++ n. Visited ← true n. Low ← n. Num push(n) for each operand o of n do if o. Visited = false then DFS(o) n. Low ← min(n. Low, o. Low) if o. Num < n. Num and o is on the stack then n. Low ← min(n. Low, o. Num) if n. Low = n. Num then SCC ← ∅ repeat until x = n do x ← pop() SCC ← SCC ∪ {x} Process(SCC)

Process(N) if N has only one member n then if n is a “candidate” then Replace(n, iv, rc) else n. Header ← null else ClassifyIV(N)

ClassifyIV(N) IsIV ← true for each node n ∈ N do if n is not a valid update for an induction variable then IsIV ← false if IsIV then header ← n ∈ N with the lowest RPO number for each node n ∈ N do n. Header ← header else for each node n ∈ N do if n is a “candidate” then Replace(n, iv, rc) else n. Header ← null

■ FIGURE 10.13 Operator Strength Reduction Algorithm.

processing the children, if the lowest node reachable from n has n’s number, then n is the header of an SCC. DFS pops nodes off the stack until it reaches n; all of those nodes are members of the SCC.

DFS removes SCCs from the stack in an order that simplifies the rest of OSR. When an SCC is popped from the stack and passed to Process, DFS has already visited all of its children in the SSA graph. If we interpret the SSA graph so that its edges run from uses to definitions, as shown in the SSA graph in Fig. 10.12, then candidate operations are encountered only after their operands have been passed to Process. When Process encounters an operation that is a candidate for strength reduction, its operands have already been classified. Thus, Process can examine operations, identify candidates, and invoke Replace to rewrite them in strength-reduced form during the depth-first search.

DFS passes each SCC to Process. If the SCC consists of a single node n that has the form of a candidate operation, shown in the margin, Process passes n to Replace, along with its induction variable, iv, and its region

x ← c × i x ← i × c x ← c + i x ← i + c x ← i - c

Candidate Operations

When Process identifies n as a candidate operation, it finds both the induction variable, iv, and the region constant, rc.

Replace(n, iv, rc) result←Reduce(n.op, iv, rc) replace n with a copy from result n.header ← iv.header

Reduce(op, iv, rc) result ← Lookup(op, iv, rc) if result is “not found” then result ← NewName() Insert(op, iv, rc, result) newDef ← Clone(iv, result) newDef.header ← iv.header for each operand o of newDef do if o.header = iv.header then rewrite o with Reduce(op,o, rc) else if op is x or newDef.op is φ then replace o with Apply(op,o, rc) return result

Apply(op,o1,o2) result ← Lookup(op,o1,o2) if result is “not found” then if o1 is an induction variable and o2 is a region constant then result ← Reduce(op,o1,o2) else if o2 is an induction variable and o1 is a region constant then result ← Reduce(op,o2,o1) else result ← NewName() Insert(op,o1,o2,result) find block b dominated by the definitions of o1 and o2 create “op o1,o2⇒result” at the end of b and set its header to null return result

■ FIGURE 10.14 Algorithm for the Rewriting Step.

constant, rc. Replace rewrites the code, as described in the next section. If the SCC contains multiple nodes, Process passes the SCC to ClassifyIV to determine whether or not it is an induction variable.

ClassifyIV examines each node in the SCC to check it against the set of valid updates for an induction variable. If all the updates are valid, the SCC is an induction variable, and Process sets each node’s header field to contain the node in the SCC with the lowest reverse postorder number. If the SCC is not an induction variable, ClassifyIV revisits each node in the SCC to test it as a candidate operation, either passing it to Replace or setting its header to show that it is not an induction variable.

The remaining piece of OSR implements the rewriting step. Both Process and ClassifyIV call Replace to perform the rewrite. Fig. 10.14 shows the code for Replace and its support functions Reduce and Apply.

Replace takes three arguments, an SSA graph node n, an induction variable iv, and a region constant rc. The latter two are operands of n. Replace calls Reduce to rewrite the operation represented by n. Next, it replaces n with a copy operation from the result produced by Replace. It sets n’s header field, and returns. Reduce and Apply do most of the work. They use a hash table to avoid inserting duplicate operations. Since OSR works on SSA names, a single global hash table suffices. It can be initialized in OSR before the first call to DFS. Insert adds entries to the hash table; Lookup queries the table.

The plan for Reduce is simple. It takes an opcode and its two operands and either creates a new induction variable to replace the computation or returns the name of an induction variable previously created for the same combination of opcode and operands. It consults the hash table to avoid duplicate work. If the desired induction variable is not in the hash table, it creates the induction variable in a two-step process. First, it calls Clone to copy the definition for iv, the induction variable in the operation being reduced. Next, it recurs on the operands of this new definition.

These operands fall into two categories. If the operand is defined inside the SCC, it is part of iv, so Reduce recurs on that operand. This forms the new induction variable by cloning its way around the SCC of the original induction variable iv. An operand defined outside the SCC must be either the initial value of iv or a value by which iv is incremented. The initial value must be a φ-function argument from outside the SCC; Reduce calls Apply on each such argument. Reduce can leave an induction-variable increment alone, unless the candidate operation is a multiply. For a multiply, Reduce must compute a new increment as the product of the old increment and the original region constant rc. It invokes Apply to generate this computation.

Apply takes an opcode and two operands, locates an appropriate point in the code, and inserts that operation. It returns the new SSA name for the result of that operation. A few details need further explanation. If this new operation is, itself, a candidate, Apply invokes Reduce to handle it. Otherwise, Apply gets a new name, inserts the operation, and returns the result. (If both o1 and o2 are constant, Apply can evaluate the operation and insert an immediate load.) Apply locates an appropriate block for the new operation using dominance information. Intuitively, the new operation must go into a block dominated by the blocks that define its operands. If one operand is a constant, Apply can duplicate the constant in the block that defines the other operand. Otherwise, both operands must have definitions that dominate the header block, and one must dominate the other. Apply can insert the operation immediately after this later definition.

Consider what happens when OSR encounters the example in Fig. 10.12.Assume that it begins with the node labeled rs2 and that it visits left children before right children. It recurs down the chain of operations that define r4, r3,r2,r1,and r_{i1}.At r_{i1},it recurs on r_{i2} and then r_{i0}.It finds the two single-node SCCs that contain the literal constant one. Neither is a candidate, so Process marks them as noninduction variables by setting their headers to null.

The first nontrivial SCC that DFS discovers contains r_{i1} and r_{i2}. All the operations are valid updates for an induction variable, so Classify/V marks each node as an induction variable and sets its header field to point to r_{i1},the node with the lowest depth-first number in the SCC.

Now, DFS returns to the node for r1. Its left child is an induction variable and its right child is a region constant, so it invokes Reduce to create an induction variable. In this case, r1 is r_{i1}-1, so the induction variable has an initial value equal to one less than the initial value of the old induction variable, or zero. The increment is the same. Fig. 10.15 shows the SCC that Reduce and Apply create, under the label “for r1.” Finally, the definition of r1 is replaced with a copy operation, r1←r_{t1}. The copy operation is marked as an induction variable.

Next, DFS finds the SCC that consists of the node for r2. Process classifies it as a candidate because its left operand (the copy that now defines r1) is an induction variable and its right operand is a region constant. Process invokes Replace to create an induction variable with the value r1x4. Reduce and Apply clone the induction variable for r1, adjust the increment to account for the multiply, and add a copy to r2. DFS next passes the node for r3 to Process. This creates another induction variable with @a as its initial value and copies its value to r3.

Process handles the load, followed by the SCC that computes the sum. It finds that none of these operations are candidates.

Finally, OSR invokes DFS on the unvisited node for the cbr. DFS visits the comparison, the previously marked induction variable, and the constant 100. No further reductions occur.

The SSA graph in Fig. 10.15 shows all of the induction variables created by this process. The induction variables labeled “for r1” and “for r2” are dead. The induction variable for i would be dead, except that the end-of-loop test still uses it. To eliminate this induction variable, the compiler can apply LFTR to transfer the test to the induction variable for r3.

Strength reduction often eliminates all uses of an induction variable except for an end-of-loop test. In that case, the compiler may be able to rewrite the end-of-loop test to use another induction variable found in the loop. If the compiler can remove this last use, it can eliminate the original induction variable as dead code. This transformation is called linear-function test replacement (LFTR).

To perform LFTR, the compiler must (1) locate comparisons that rely on otherwise unneeded induction variables, (2) locate an appropriate new induction variable that the comparison could use, (3) compute the correct region constant for the rewritten test, and (4) rewrite the code. Having LFTR cooperate with OSR can simplify all of these tasks to produce a fast, effective transformation.

The operations that LFTR targets compare the value of an induction variable against a region constant. OSR examines each operation in the program to determine if it is a candidate for strength reduction. It can easily and inexpensively build a list of all the comparison operations that involve induction variables. After OSR finishes its work, LFTR should revisit each of these comparisons. If the induction-variable argument of a comparison was strength reduced by OSR, LFTR should retarget the comparison to use the new induction variable.

To facilitate this process, Reduce can record the arithmetic relationship it uses to derive each new induction variable. It can insert a special LFTR edge from each node in the original induction variable to the corresponding node in its reduced counterpart and label it with the operation and region constant of the candidate operation responsible for creating that induction variable.

■ FIGURE 10.16 Example After Linear Function Test Replacement.

Section titled “■ FIGURE 10.16 Example After Linear Function Test Replacement.”

In Fig. 10.16 these additional edges appear as dashed lines. The sequence of reductions in the example create a chain of labeled edges. Starting from the original induction variable, we find the labels-1,x4,and+@a.

When LFTR finds a comparison that should be replaced, it can follow the edges from its induction-variable argument to the final induction variable that resulted from a chain of one or more reductions. The comparison should use this induction variable with an appropriate new region constant.

The labels on the LFTR edges describe the transformation that must be applied to the original region constant to derive the new region constant. In the example, the trail of edges leads from r1 to rt8 and produces the value (100-1)x4+@a for the transformed test. Fig. 10.16 shows the edges and the rewritten test.

This version of LFTR is simple, efficient, and effective. It relies on close collaboration with OSR to identify comparisons that might be retargeted and to record the reductions as it applies them. Using these two data structures,LFTR can find comparisons to retarget, find the appropriate place to retarget them, and find the necessary transformation for the comparison’s constant argument.

The effectiveness of an optimizer on any given code depends on the sequence of optimizations that it applies to the code-both the specific transformations that it uses and the order in which it applies them. Traditional optimizing compilers have offered the user the choice of several sequences

a set of optimizations and an order for their application (e.g., -0, -01, -02, …) that provide a tradeoff between compile time and optimization. Increased optimization effort, however, does not guarantee improvement.

The optimization sequence problem arises because the effectiveness of any given transformation depends on several factors.

  1. Does the opportunity that the transformation targets appear in the code? If not, the transformation will have no effect.
  2. Has a prior transformation hidden or obscured that opportunity? For example, LVN can convert 2x a into a shift operation. However, multiply is commutative and shift is not. Any transformation that needs commutativity to effect its improvement might see opportunities vanish from prior application of LVN.
  3. Has any other transformation already eliminated the inefficiency? Transformations have overlapping and idiosyncratic effects; for example, LVN achieves some of the effects of global constant propagation and loop unrolling achieves some of the same effects as superblock cloning. The compiler writer might still include both transformations for their nonoverlapping effects.

The interactions between transformations makes it difficult to predict the improvement from the application of any single transformation or any sequence of transformations.

Researchers have looked at automated techniques to find good optimization sequences. The approaches vary in granularity and in technique. The various systems look for sequences at the block level, at the source-file level, and at the program level. Most of these systems use some kind of search over the space of optimization sequences.

In general, these techniques are too expensive to be practical for individual programs because the space of potential sequences is too large. For example, if the compiler chooses a sequence of 10 transformations from a set of 15, it can generate 1015 possible sequences—an impractically large number to explore. Thus, compilers that search for good sequences use heuristic techniques to sample subsets of the search space. In general, these techniques fall into three categories: (1) genetic algorithms adapted to act as intelligent searches, (2) randomized search algorithms, and (3) statistical machine learning techniques. All three approaches have shown promise.

Despite the huge search spaces, well-tuned search algorithms can find good optimization sequences with 100 to 200 probes of the search space. While that number is not yet practical, further refinement may reduce the number of probes to a practical level.

In this context, a good sequence is one that produces results within 5 percent of the best results.

The primary interesting application of these techniques is to derive the sequences used by the compiler’s command line flags, such as -02. The compiler writer can use an ensemble of representative applications to discover good general sequences and then apply those sequences as the compiler’s default sequences. A more aggressive approach, used in several systems, is to derive a handful of good sequences for different application ensembles and have the compiler try each of those sequences and retain the best result.

The design and implementation of an optimizing compiler is a complex undertaking. This chapter has introduced a conceptual framework for thinking about transformations—the taxonomy of effects. Each category in the taxonomy is represented by several examples, either in this chapter or elsewhere in the book.

The challenge for the compiler writer is to select a set of transformations that work well together to produce good code—code that meets the user’s needs. The taxonomy presented in this chapter is a framework for thinking about that decision. The specific transformations implemented in a compiler determine, to a large extent, the kinds of programs for which it will produce good code.

While the algorithms presented in this chapter are modern, many of the basic ideas were well known in the 1960s and 1970s. Dead-code elimination, code motion, strength reduction, and redundancy elimination are all described by Allen [12] and by Cocke and Schwartz [98]. A number of survey papers provide overviews of the state of the field at different points in time [17,29,31,328]. Books by Morgan [277] and Muchnick [279] both discuss the design, structure, and implementation of optimizing compilers. Wolfe [364] and Allen and Kennedy [21] focus on dependence-based analysis and transformations for vector and parallel computation.

Dead implements a mark-sweep style of dead-code elimination that was introduced by Kennedy [226,228]. It is reminiscent of the Schorr-Waite marking algorithm [319]. Dead is specifically adapted from the work of Cytron et al. [120, Section 7.1]. Clean was developed and implemented in 1992 by Rob Shillingsburg [262].

LCM improves on Morel and Renvoise’s classic algorithm for partial redundancy elimination [276]. That paper inspired many improvements [88,141,144,333]. Knoop, Rüthing, and Steffen’s LCM [236] improved code placement; the formulation in Section 10.3 uses equations from Drechsler and Stadel [145]. Bodik, Gupta, and Soffa combined this approach with replication to find and remove all redundant code [47]. The DVNT algorithm is from Simpson’s thesis [59,326]. It has been implemented in a number of compilers.

Hoisting appears in the Allen-Cocke catalogue as a technique for reducing code space [17]. The formulation using anticipability appears in several places, including Fischer and LeBlanc [157]. Sinking or cross-jumping is described by Wulf et al. [368].

Both peephole optimization and tail-recursion elimination date to the early 1960s. Peephole optimization was first described by McKeeman [268]. Tail-recursion elimination is older; folklore tells us that McCarthy described it at the chalkboard during a talk in 1963. Steele’s thesis [335] is a classic reference for tail-recursion elimination.

Superblock cloning was introduced by Hwu et al. [211]. Loop optimizations such as unswitching and unrolling have been studied extensively [21,29]: Kennedy used unrolling to avoid copy operations at the end of a loop [225]. Cytron, Lowrey, and Zadeck present an interesting alternative to unswitching [121]. McKinley et al. give practical insight into the impact of memory optimizations on performance [101,269].

Combining optimizations, as in SCCP [358,359], often leads to improvements that cannot be obtained by independent application of the original optimizations [89,91]. Value numbering combines redundancy elimination, constant propagation, and simplification of algebraic identities [59]. LCM combines elimination of redundancies and partial redundancies with code motion [236]. Click and Cooper [91] combine Alpern’s partitioning algorithm [22] with SCCP [359]. Many authors have combined register allocation and instruction scheduling [44,54,173,278,285,286,294,318]. Not all pairs of optimizations benefit from being combined [89,91].

Operator strength reduction has a rich history. One family of strength-reduction algorithms developed out of work by Allen, Cocke, and Kennedy [20,95,97,227,264]. The OSR algorithm is in this family [117]. Another family of algorithms grew out of the data-flow approach to optimization exemplified by the LCM algorithm; a number of sources give techniques in this family [138,140,142,187,220,231,237]. The version of OSR in Section 10.7.2 only reduces multiplications. Allen et al. show the reduction sequences for many other operators [20]; extending OSR to handle these cases is straightforward. A weaker form of strength reduction rewrites integer multiplies with faster operations [251].

Section 10.1

  1. One of the primary functions of an optimizer is to remove overhead that the compiler introduced during the translation from source language into IR.

a. Give four examples of inefficiencies that you would expect an optimizer to improve, along with the source-language constructs that give rise to them.

b. Give four examples of inefficiencies that you would expect an optimizer to miss. Explain why an optimizer would have difficulty improving them.

Section 10.2

  1. Fig. 10.1 shows the algorithm for Dead. The marking pass is a classic fixed-point computation.

a. Explain why this computation terminates.

b. Is the fixed-point that it finds unique? Prove your answer.

c. Derive a tight time bound for the algorithm.

  1. Consider the algorithm Clean from Section 10.2. It removes useless control flow and simplifies the CFG.

a. Why does the algorithm terminate?

b. Give an overall time bound for the algorithm.

Section 10.3

  1. Redundancy elimination has a variety of effects on the code that the compiler generates.

a. How does LCM affect the demand for registers in the code being transformed? Justify your answer.

b. How does LCM affect the size of the code generated for a procedure?(Assume that demand for registers is unchanged.)

c. How does hoisting affect the demand for registers in the code being transformed? Justify your answer.

d. How does hoisting affect the size of the code generated for a procedure?(Assume that demand for registers is unchanged.)

Section 10.4

  1. A simple form of operator strength reduction replaces a single instance of an expensive operation with a sequence of operations that are less expensive to execute. For example, some integer multiply operations can be replaced with a sequence of shifts and adds.

a. What conditions must hold to let the compiler safely replace an integer operation x←yxz with a single shift operation? b. Sketch an algorithm that replaces a multiplication of a known constant and an unsigned integer with a sequence of shifts and adds. c. How might you fit this transformation into the LVN algorithm?

  1. Both tail-call optimization and inline substitution attempt to reduce the overhead caused by the procedure linkage. a. Can the compiler inline a tail call? What obstacles arise? How might it work around them? b. Contrast the code produced from your modified inlining scheme with that produced by tail-call optimization.

  2. A compiler can find and eliminate redundant computations in many different ways. Among these are DVNT and LCM. a. Show two examples of redundancies eliminated by DVNT that cannot be found by LCM. b. Show an example of a redundancy that LCM finds and improves but that DVNT cannot find.

  3. Sketch an algorithm that renames the values and variables in a procedure so that name identity encodes value identity.

  4. Superblock cloning can cause significant code growth. a. How might the compiler mitigate code growth in superblock cloning while retaining as much of the benefit as possible? b. What problems might arise if the optimizer allowed superblock cloning to continue across a loop-closing branch?

Hint: Think back to the block-placement algorithm in Chapter 8.


← node-book_engineering-a-compiler_chapter-09-data-flow-analysis | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-11-instruction-selection →