Introduction to Optimization
local graph
Chapter 8 — Introduction to Optimization
Section titled “Chapter 8 — Introduction to Optimization”ABSTRACT
Section titled “ABSTRACT”To improve the quality of code that a compiler generates, its optimizer analyzes that code and rewrites it into a more efficient form. This chapter introduces the problems and techniques of code optimization and presents key concepts through a series of example optimizations. Chapter 9 expands on this material with a deeper exploration of program analysis. Chapter 10 provides a broader coverage of optimizing transformations.
This chapter examines how optimization can improve code. It discusses the safety and profitability of optimizations, along with the kinds of opportunities for improvement that a compiler writer should seek. It lays out the various scopes at which optimization is performed and presents two examples at each scope.
KEYWORDS
Section titled “KEYWORDS”Optimization, Safety, Profitability, Scope of Optimization, Analysis, Transformation
8.1 INTRODUCTION
Section titled “8.1 INTRODUCTION”The compiler’s front end translates the source-code program into some intermediate representation (IR). The back end translates the IR program into a form where it can execute directly on the target machine, either a hardware platform such as a commodity microprocessor or a virtual machine as in JAVA. Between these processes sits the compiler’s middle section, its optimizer. The optimizer’s task is to transform the IR program from the front end in a way that will improve the quality of the code that the back end produces. Our focus is on scalar optimization—that is, the optimization of single-threaded computations. Optimization of parallel programs is a complex and valuable subject that is beyond the scope of this book.
This chapter introduces the subject of code optimization and provides examples of several different techniques that attack distinct kinds of inefficiencies and operate on different regions in the code. Chapter 9 provides a deeper treatment of some of the techniques of program analysis that are used to support optimization. Chapter 10 describes additional code-improvement transformations. Instruction scheduling, in Chapter 12, and register alloca-tion, in Chapter 13, can be considered as problems in either optimization or code generation.
Conceptual Roadmap
Section titled “Conceptual Roadmap”The goal of code optimization is to discover, at compile time, information about the runtime behavior of the program and to use that information to improve the code that the compiler generates. Improvement can take many forms. The most common goal of optimization is to make the compiled code run faster. In some applications, however, the size of the compiled code outweighs its speed; consider, for example, an application that will be committed to read-only memory, where code size affects the cost of the system. Other optimization objectives include reducing the energy cost of execution, improving the code’s response to real-time events, and reducing total memory traffic.
Optimizers use many different techniques to improve code. A proper discussion of optimization must consider the inefficiencies that can be improved and the techniques that can improve them. For each source of inefficiency, the compiler writer must choose from multiple techniques that try to address it; each technique has its own advantages and disadvantages. The compiler writer needs to understand how those techniques identify opportunities for improvement, how they determine that it is safe to rewrite the code, and why the rewrite represents an improvement. Each of these issues plays a role in successful code optimization.
Overview
Section titled “Overview”Opportunities for optimization arise from many sources, but the primary one is the implementation of source-language abstractions. Because the translation from source code into IR is a local process-it occurs without extensive analysis of the surrounding context-it typically generates IR to handle the most general case of each construct. With more context, the optimizer can often determine that the code does not need that full generality; when that happens, it can rewrite the code in a more restricted and more efficient way.
A second significant source of opportunity for the optimizer lies with the target machine. The compiler must understand, in detail, the properties of the target machine that affect performance. Issues such as the number of functional units and their capabilities, the latency and bandwidth to various levels of the memory hierarchy, the various address modes supported in the instruction set, and the availability of unusual or complex operations all affect the shape of the code that the compiler should generate for a given adou Optimization is a large and detailed subject whose study has filled complete courses and books. This chapter introduces the subject. Section 8.2 explores the concepts of safety and profitability; an optimization should only be applied when it is safe and it is expected to be profitable. Section 8.3 lays out the different granularities, or scopes, over which optimization occurs. The remainder of the chapter uses select examples to illustrate different sources of improvement and different scopes of optimization. This chapter has no Advanced Topics section; instead Chapters 9 and 10 serve that purpose. Chapter 9 delves into static analysis, describing the kinds of analytical problems that an optimizing compiler must solve and practical techniques that have been used to solve them. Chapter 10 examines scalar optimizations—those intended for a uniprocessor—in a more systematic way.
A Few Words About Time
Section titled “A Few Words About Time”Chapter 8 provides an introduction to the subject of code optimization: both analysis and transformation. The optimizations described in this chapter occur entirely at compile time. Conceptually, each optimization reads the IR form of the program, analyzes it, transforms it, and writes it.
To decide whether or not to apply the optimization in a specific location in the code being compiled, the compiler will analyze the code. In essence, the compiler reasons about the runtime flow of values and control. It uses that information to decide whether it is safe to apply the transformation and whether the transformation is likely to improve the code. The compile-time analysis supports compile-time decision-making in order to improve runtime behavior.
8.2 BACKGROUND
Section titled “8.2 BACKGROUND”Until the early 1980s, many compiler writers considered optimization as a feature that should be added to the compiler only after its other parts were working well. This fact led to a distinction between debugging compilers and optimizing compilers. A debugging compiler emphasized quick compilation at the expense of code quality. Debugging compilers did a simple translation, so the compiled code retained a strong resemblance to the source code. This correspondence simplified the task of mapping a runtime error to a specific line of source code; hence the term debugging compiler. By contrast, an optimizing compiler focused on improving the running time of the executable code at the expense of compile time. Spending more time in compilation can produce better code. With optimization, however, the mapping from source code to executable code is more complex and debugging might be, accordingly, harder.
Safety A transformation is safe when it does not change the results of running the program.
Profitability A transformation is profitable to apply at some point when the result is an actual improvement.
OPTIMIZATION, ANALYSIS, AND TRANSFORMATION
Section titled “OPTIMIZATION, ANALYSIS, AND TRANSFORMATION”The compiler construction community often uses the three terms optimization, analysis, and transformation as interchangeable. We make a distinction between these subtly different ideas.
Optimization refers to a broad scheme for improving program performance, such as code motion. Many algorithms exist for code motion. They differ in how they identify code that can move and how they choose its destination.
Analysis refers to compile-time techniques that derive knowledge about the runtime behavior of the compiled code. In code optimization, such analysis reveals opportunities where rewriting the code is safe and, potentially, profitable.
Transformation refers to compile-time techniques that rewrite the code to implement an optimization, usually based on the results of some analysis.
In some simple contexts, an optimization can be implemented in a single pass that combines analysis and transformation. In contexts that include complex control flow, the analysis typically must be completed before transformation can begin.
As RISC processors moved into the marketplace and as RISC implementation techniques were applied to CISC architectures, more of the burden for runtime performance shifted to compilers. To increase performance, processor architects turned to features that require more compiler support. These features include delay slots after branches, nonblocking memory operations, deeper pipelines, and more functional units. These features make processors more performance sensitive both to high-level issues of program layout and structure and to low-level details of scheduling and resource allocation. As the gap between processor speed and application performance has grown, optimization has become a routine part of every compiler.
The routine inclusion of an optimizer, in turn, changes the environment in which both the front end and the back end operate. Optimization further insulates the front end from performance concerns, which simplifies the task of translation in the front end. At the same time, optimization changes the code that the back end processes. Modern optimizers assume that the back end will handle resource allocation; thus, they typically target an idealized machine that has an unlimited supply of registers, memory, and functional units. This change, in turn, gives both more freedom and more responsibility to the compiler’s back end.
If compilers are to shoulder their share of responsibility for runtime performance, they must include optimizers. As we shall see, the tools of optimization also play a large role in the compiler’s back end. For these reasons, it is important to introduce optimization and explore some of the issues that it raises before discussing the techniques used in a compiler’s back end.
8.2.1 Examples
Section titled “8.2.1 Examples”To provide focus, we will explore two examples in depth. The first, a simple two-dimensional array-address calculation, shows the role that knowledge and context play in code optimization. The second, a loop nest from the routine dmxpy in the widely used LINPACK numerical library, provides insight into the transformation process itself and into the challenges that transformed code can present to the compiler.
Improving an Array-Address Calculation
Section titled “Improving an Array-Address Calculation”Consider the IR that a compiler’s front end might generate for an array reference m(i,j) in FORTRAN. Without specific knowledge about the values of m,i, and j, the compiler must generate the complete address polynomial for a two-dimensional array in column-major order:
where@m is the runtime address of the first element of m, lowi and highi are the lower and upper bounds of m’s i th dimension, and w is the size of an element of m. The compiler’s ability to reduce the cost of this computation depends on its ability to analyze the code and its surrounding context.
If m is a local array with low1=low2=1 and the value of high1 is known, then the compiler can simplify the calculation to
where hw=high1xw. If the reference occurs in a loop where j runs from 1 to k, the compiler might use operator strength reduction to replace the term with a sequence , where and If i is also a loop induction variable and i runs from 1 to l, then strength reduction can replace(i-1)xw with the sequence , , where and After these changes, the address calculation is just
Under the right circumstances, the addition in@m+j’ can be moved out of the inner loop(see Sections 10.3.1 and 10.7.2).
The access method for an array in row-major order appears in Section 7.3.2.
The discussion assumes that the compue has not transformed@m into the “false-ze form@m0.
Strength reduction
Section titled “Strength reduction”a transformation that rewrites a series of operations, such as
with an equivalent series
where and
See Section 10.7.2.
Code motion
Section titled “Code motion”moving a computation to a point where it executes less often
After these transformations, the j loop must increment j’ by hw and the i loop must increment i’ by w. In this form, the address computation consists of the increment to i’ and, perhaps, an add in the inner loop and the increment to j’ and an add in the outer loop. Knowing the context around the reference to m(i,j) allows the compiler to significantly reduce the cost of the array-element address expression.
If m is passed in as an actual parameter, then the compiler may not know its upper and lower bounds at compile time. In fact, the dimensions for m might change in different calls to the procedure. In such cases, the compiler may be unable to simplify the address calculation, another example of the role that context plays in performance.
Improving a Loop Nest in LINPACK
Section titled “Improving a Loop Nest in LINPACK”As a more dramatic example of context, consider the loop nest shown in Fig. 8.1. It is the central loop nest of the FORTRAN routine dmxpy from the LINPACK numerical library. The code wraps two loops around a single long assignment. The loop nest forms the core of a routine to compute mx+y, for a matrix m and vectors x and y. We will consider the code from two different perspectives: first, the transformations that the author hand-applied to improve performance, and second, the challenges that the compiler faces in translating this loop nest to run efficiently on a specific processor.
Before the author hand-transformed the code, the loop nest performed the following simpler version of the same computation:
\begin{array}[]{l}\text{do 60 j= 1, n2}\\ \text{do 50 i= 1, n1}\\ \text{y(i)= y(i)+ x(j)* m(i,j)}\\ \text{50 continue}\\ \text{60 continue}\end{array}Loop unrolling Unrolling replicates the loop body for distinct iterations and adjusts the index calculations to match.
To improve performance, the author unrolled the outer loop, the j loop,16 times. That rewrite created 16 copies of the assignment statement with distinct values for j, ranging from j through j-15, and changed the outer loop increment from 1 to 16. Next, the author merged the 16 assignments into one statement, eliminating 15 occurrences of y(i)=y(i)+…; that eliminates 15 additions and most of the loads and stores of y(i). Unrolling the loop eliminates 15 branches and some other operations. It may also improve cache locality.
To handle the cases where the array bounds are not integral multiples of 16,the full procedure has four versions of the loop nest that precede the one shown in Fig. 8.1. These “setup loops” process up to 15 columns of m,
Figure 8.1 Excerpt from dmxpy in LINPACK.
subroutine dmxpy (n1, y, n2, ldm, x, m)double precision y(*), x(*), m(ldm,*)...jmin = j + 16do 60 j = jmin, n2, 16 do 50 i = 1, n1 y(i) = (((((((((((((( y(i)) $ + x(j-15)*m(i,j-15)) + x(j-14)*m(i,j-14)) $ + x(j-13)*m(i,j-13)) + x(j-12)*m(i,j-12)) $ + x(j-11)*m(i,j-11)) + x(j-10)*m(i,j-10)) $ + x(j- 9)*m(i,j- 9)) + x(j- 8)*m(i,j- 8)) $ + x(j- 7)*m(i,j- 7)) + x(j- 6)*m(i,j- 6)) $ + x(j- 5)*m(i,j- 5)) + x(j- 4)*m(i,j- 4)) $ + x(j- 3)*m(i,j- 3)) + x(j- 2)*m(i,j- 2)) $ + x(j- 1)*m(i,j- 1)) + x(j)*m(i,j)50 continue60 continue...endThe setup loops allow the final loop nest shown in Fig. 8.1 to process 16 columns at a time. Ideally, the compiler would transform the original loop nest into this more efficient version, or into the most appropriate form for a given target machine. In the case of dmxpy, the author performed the optimizations by hand to produce good performance across a wide range of target machines and compilers.
From the compiler’s perspective, mapping the loop nest shown in Fig. 8.1 onto the target machine presents hard challenges. The loop nest contains many distinct array-address expressions. Unless the compiler can simplify those address calculations, the loop will be awash in integer arithmetic. reference such as x(j-12), the address calculation is@x+(j-12-1)xw. To simplify further, the compiler can refactor all 16 references to x into the form@x+jw-ck, where jw is jxw and ck is(k+1)xw for each . In this form, each load uses the same base address,@x+jw, with a distinct constant offset, ck.
Mapping this calculation efficiently onto the target machine requires knowledge of the available address modes. If the target machine has a load operation with an address-immediate address mode(e.g.,loadAI), then it can rewrite the accesses to x so that they use a single induction variable that starts at@x+jminxw; the j loop increments it by .
Each iteration of the inner loop uses a different set of locations in m. Thus, the inner loop must compute new addresses and load new values for each of the 16 elements of m on each iteration. Careful refactoring of the address expressions, combined with strength reduction, can reduce the overhead of accessing m. The compiler can arrange to compute the address of m(1,j) in the j loop. It can then use distinct constant offsets in the load operations for each of the 15 other loads.
To achieve this code shape, the compiler must refactor the address expressions, perform strength reduction, recognize loop-invariant calculations and move them out of inner loops, and choose the appropriate address mode for the loads. Even with these improvements, the inner loop must perform 17 loads, 16 floating-point multiplies, and 16 floating-point adds, plus one store. The resulting block of code will challenge both the instruction scheduler and the register allocator.
Memory bound
A loop where loads and stores take more cycles than does computation is considered memory bound.
To determine if a loop is memory bound requires detailed knowledge about both the loop and the target machine.
If the compiler fails in some part of this transformation sequence, the resulting code might be substantially worse than the original. For example, if the compiler cannot refactor the address expressions around common base addresses for x and m, the code might need 33 distinct induction variables-one for each distinct location of x,m, and y. If the resulting demand for registers forced the register allocator to spill, that would insert more loads and stores into the memory-bound inner loop. In cases such as this one, the quality of code produced by the compiler depends on an orchestrated series of transformations that all must work; when one fails to achieve its purpose, the overall sequence may produce lower quality code than the user expects.
8.2.2 Considerations for Optimization
Section titled “8.2.2 Considerations for Optimization”In dmpy, the programmer applied the transformations by hand in the belief t the would make the program run faster.(They did.) The programmer to know that the changes would preserve the program’s meaning.
DEFINING SAFETY
Section titled “DEFINING SAFETY”Correctness is the single most important criterion that a compiler must meet—the code that the compiler produces must have the same meaning as the input program. Each time the optimizer applies a transformation, that action must preserve the correctness of the translation.
Typically, meaning is defined as the program’s observable behavior—that is, the state of its memory just before it halts, along with any output it generates. If the program terminates, the values of all visible variables immediately before it halts should be the same under any translation scheme. For an interactive program, behavior is more complex and difficult to capture.
Plotkin formalized this notion as observational equivalence.
For two expressions, M and N, we say that M and N are observationally equivalent if and only if, in any context C where both M and N are closed (that is, have no free variables), evaluating C[M] and C[N] either produces identical results or neither terminates [295].
Thus, two expressions are observationally equivalent if their impacts on the visible, external environment are identical.
In practice, compilers use a simpler and looser notion of equivalence, namely, that if, in their actual program context, two different expressions M and N produce identical results, then the compiler can substitute N for M. This standard deals only with contexts that actually arise in the program. Tailoring code to context is the essence of optimization. It does not mention what happens when a computation goes awry, or diverges.
In practice, compilers take care not to introduce divergence; that is, they avoid creating code that either loops indefinitely or throws an exception such as division by zero. The opposite case, where the original code would diverge, but the optimized code does not, is rarely mentioned.
Safety, profitability, and risk each play a critical role in the compiler’s decision to apply a given transformation at a specific location in the code.
The compiler needs a mechanism to prove that each application of the transformation is safe—that is, the transformation preserves the program’s meaning. The compiler must have a reason to believe that applying the transformation is profitable—that is, the transformation will improve the program’s performance. Finally, the compiler must understand the ways in which a rewrite might make the code worse—the risk that it is not profitable. The compiler writer needs to consider all three factors when designing and building the decision mechanisms that choose where to transform the code.
Safety
Section titled “Safety”How did the LINPACK programmer know that the transformations were safe? That is, why did the programmer believe that the transformed code would produce the same results as the original code? Close examination of the loop nest shows that the only interaction between successive iterations occurs through the elements of y.
A value computed as y(i) is not reused until the next iteration of the outer loop. The iterations of the inner loop are independent of each other, because each iteration defines precisely one value and no other inner-loop iteration references that value. Thus, the iterations can execute in any order.(For example, reversing the inner loop would produce the same results.)
The interaction through y is limited in its effect. The i th element of y accumulates the sum of all the i th iterations of the inner loop. The unrolled loop reproduces this pattern.
A large part of the analysis done in optimization goes toward proving the safety of transformations.
Profitability
Section titled “Profitability”Why did the LINPACK programmer think that loop unrolling would improve performance? That is, why is the transformation profitable? Several different effects of unrolling might speed up the code.
The number of loop iterations decreases by a factor of 16, which reduces the number of operations used to control the loop: adds, jumps, and branches. These savings can be significant.
This effect might suggest unrolling by an even larger factor. Finite resource limits probably dictated the choice of 16.(See the discussion of demand for registers on the next page.)
The array-address calculations contain duplicated work. Consider the use of y(i). The original code computed y(i)‘s address once per multiplication of x and m. The transformed code computes it once per 16 multiplications; it does 1 as much work. The 16 references to m, and to a lesser extent x, also include common portions that the loop can compute once and reuse.
The transformed loop performs more floating-point operations per memory operation. The original loop performed two floating-point operations per three memory operations; the unrolled loop performs 32 floating-point operations for 18 memory operations, assuming that all the x values reside in registers. Thus, the unrolled loop is less likely to be memory
The argument assumes that x(j) resides in a register. bound. It has enough independent arithmetic to overlap the loads and hide some of their latencies.
Unrolling can help with other machine-dependent effects. It increases the amount of code in the inner loop, which may provide the instruction scheduler with more opportunities to hide latencies. If the end-of-loop branch has a long latency, the longer loop body may let the compiler fill more of that branch’s delay slots. On some processors, unused delay slots must be filled with nops, in which case loop unrolling can decrease the number of nops fetched, reduce memory traffic, and, perhaps, reduce the energy used to execute the program.
If transformations intended to improve performance can make it harder for the compiler to generate good code, those issues should factor into the profitability decision. The hand transformations to dmxpy created new challenges for a compiler, including the following:
Demand for Registers The original loop needs only a handful of registers to hold its active values. It needs floating-point registers for y(i), x(j), and m(i,j). It needs general purpose registers for the address calculations for x, y, and m. The loop index variables need registers across loop iterations. By contrast, the transformed loop needs floating-point registers for the 16 elements of x, the 16 values of m, and one value of y(i), along with the same general purpose registers.
Form of Address Calculation The original loop deals with three addresses, one each for y, x, and m. Because the transformed loop refers to more distinct locations in each iteration, the compiler must shape the address calculations carefully to avoid repeated calculations and excessive demand for registers. In the worst case, the code could compute complete addresses for all 16 elements of x, all 16 elements of m, and one element of y.
If the compiler carefully shapes the address calculations, it can use a single base address, or pointer, for m and another for x, each with 16 constant-valued offsets. It can rewrite the loop to use one of those pointers in the end-of-loop test, obviating the need for another register and eliminating another update (see Section 10.7.2). Planning and optimization make the difference.
Other problems of a machine-specific nature arise as well. For example, the 17 loads and one store, the 16 multiplies, the 16 adds, plus the address calculations and loop-overhead operations in each iteration must be scheduled with care. The compiler may need to use software pipelining to schedule some of the load operations so that they issue in a previous iteration to allow the initial arithmetic operations in the iteration to run in a timely fashion(see Section 12.5).
8.2.3 Opportunities for Optimization
Section titled “8.2.3 Opportunities for Optimization”As we have seen, the task of optimizing a simple loop can involve complex considerations. In general, optimizing compilers capitalize on opportunities that arise from several distinct sources.
-
Reducing the Overhead of Abstraction As we saw in dmxpy, data structures and types introduced by programming languages introduce runtime address calculations. Optimizers use analysis and transformation to reduce this overhead.
-
Taking Advantage of Special Cases Often, the compiler can use knowledge about the context in which an operation executes to specialize that operation. As an example, a C++ compiler can sometimes determine that a call to a virtual function always uses the same implementation. In that case, it can convert the virtual call to a less expensive static call.
-
Matching the Code to System Resources If a program’s resource requirements differ from the processor’s capacities, the compiler may transform the code to align its needs more closely with available resources. The transformations applied to dmxpy have this effect; they decrease the number of memory accesses per floating-point operation.
These are broad areas, described in sweeping generality. As we discuss specific analysis and transformation techniques, in Chapters 9 and 10, we will fill in these areas with more detailed examples.
SECTION REVIEW
Section titled “SECTION REVIEW”Most compiler-based optimization works by specializing general purpose code to its actual context. For some transformations, the benefits accrue from local effects, as with the improvements in array-address calculations. Other transformations require broad knowledge of larger regions in the code and accrue their benefits from effects that occur over larger swaths of the code.
The implementation of any optimization must address three key issues.(1) How can the compiler efficiently find opportunities to apply the transformation?(2) Is the optimization safe in this context?(3) Will the optimization improve the code?
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”-
In the code fragment from dmxpy, why did the programmer unroll the outer loop rather than the inner loop? How would the results differ had she unrolled the inner loop rather than the outer loop?
-
In the C fragment shown below, what facts would the compiler need to discover before it could improve the code beyond a simple byte-oriented, load/store implementation?
MemCopy(charsource, chardest, int length){int i;for(i=1;i≤length;i++){*dest++=*source++;}}
8.3 SCOPE OF OPTIMIZATION
Section titled “8.3 SCOPE OF OPTIMIZATION”Optimizations operate at different granularities or scopes. In the previous section, we looked at optimization of a single array reference and of an entire loop nest. These different scopes presented different opportunities to the optimizer. Reformulating the array reference improved performance of the code for that one reference. Rewriting the loop nest improved performance across a larger region. In general, transformations and the analyses that support them operate on one of four distinct scopes: local, regional, global, or interprocedural.
Local Methods
Section titled “Local Methods”Local methods operate over a single basic block: a maximal-length sequence of branch-free code. In an ILOC program, a basic block begins with a labeled operation and ends with a branch or a jump. In ILOC, the operation after a branch or jump must be labeled or else it cannot be reached; other notations allow a “fall-through” branch so that the operation after a branch or jump need not be labeled. The behavior of straight-line code is easier to analyze and understand than is code that contains branches and cycles.
Inside a basic block, two important properties hold. First, statements are executed sequentially. Second, if any statement executes, the entire block executes, unless a runtime exception occurs. These two properties let the compiler prove, with relatively simple analyses, facts that may be stronger than those provable for scopes that contain conditional or cyclic control
Scope of optimization
Section titled “Scope of optimization”The region of code that an optimization analyzes and transforms is its scope of optimization.
flow(if statements and loops). Thus, local methods sometimes make improvements that cannot be obtained for larger scopes. At the same time, local methods can only improve code sequences that occur entirely inside the same block.
Regional Methods
Section titled “Regional Methods”Regional methods operate over scopes larger than a single block but smaller than a full procedure. In the example control-flow graph(CFG) in the margin, the compiler might consider the entire loop, ,as a single region. In some cases, considering a subset of the code produces sharper analysis and better transformation results than would occur with information from the full procedure. For example, inside a loop nest, the compiler may be able to prove that a heavily used pointer is invariant(single-valued), even though it is modified elsewhere in the procedure. Such knowledge can enable optimizations such as keeping the value referenced through that pointer in a register throughout the loop nest.
The compiler can choose regions in many different ways. A region might be defined by some source-code control structure, such as a loop nest. The compiler might look at the subset of blocks in the region that form an extended basic block(EBB). The example CFG contains three EBBs: , and . While the two single-block EBBs provide no advantage over a purely local view, the large EBB may offer opportunities for optimization(see Section 8.5.1). Finally, the compiler might consider a subset of the CFG defined by some graph-theoretic property, such as a dominator relation or a strongly connected component in the CFG.
Extended basic block
Section titled “Extended basic block”a set of blocks(B0,B1,…,Bk) where either B0 is the entry node or B0 has multiple CFG predecessors, and every other has just one predecessor, which is in the set
Dominator
Section titled “Dominator”In a CFG, x dominates y if and only if every path from the root to y includes x.
Regional methods have several strengths. Focusing on a region smaller than the entire procedure lets the compiler concentrate its efforts on heavily executed regions, such as the body of a loop.(A key observation in code optimization is that the body of a loop almost always executes more frequently than the surrounding code.) With regional methods, the compiler can apply different optimization strategies to distinct regions. Finally, the focus on a limited area in the code can let the compiler derive sharper information about program behavior which, in turn, may expose opportunities for improvement.
Intraprocedural Methods
Section titled “Intraprocedural Methods”These methods, also called global methods, use an entire procedure as context. The motivation for global methods is simple: decisions that are locally optimal may have bad consequences larger contexts. The procedure provides the compiler with a natural boundary for analysis and transformation.
INTRAPROCEDURAL VERSUS INTERPROCEDURAL
Section titled “INTRAPROCEDURAL VERSUS INTERPROCEDURAL”Few terms in compilation create as much confusion as the word global. Global optimizations operate on an entire procedure. The modern connotation, however, suggests an all-encompassing scope, similar to that of a global variable. In optimization, however, global means “pertaining to a single procedure.”
As interest in analysis and optimization across procedure boundaries grew, the community needed terminology to differentiate between global analysis and analysis over larger scopes. Interprocedural was introduced to describe analysis that ranged from two procedures to a whole program. Accordingly, authors began to use intra procedural for single-procedure techniques. Since these words are so close in spelling and pronunciation, they are easy to confuse and awkward to use.
One company, Perkin-Elmer Corporation, introduced the term universal to describe whole-program optimization. The term never gained popularity. We prefer the term whole program and use it whenever possible. It conveys the right distinction and reminds the reader that “global” is not “universal.”
Procedures are abstractions that encapsulate and insulate runtime environments. They also serve as units of separate compilation in many systems.
Global methods typically operate by building a representation of the procedure, analyzing that representation, and transforming the underlying code. If the CFG has cycles, the compiler must analyze the entire procedure before it understands what facts hold on entrance to any specific block. Thus, most global optimizations have separate analysis and transformation phases. The analysis phase gathers facts and reasons about them. The transformation phase uses those facts to determine the safety and expected profitability of the transformations. By virtue of their global view, these methods can discover opportunities that neither local nor regional methods can.
Interprocedural Methods
Section titled “Interprocedural Methods”These methods, sometimes called whole-program methods, consider scopes larger than a single procedure. We consider any transformation that involves more than one procedure to be an interprocedural transformation. Just as moving from a local scope to a global scope exposes new opportunities, so moving from single procedures to multiple procedures can expose new opportunities. It also raises new challenges. For example, name scope rules limit interactions between expressions in different procedures, and parameter binding complicates static analysis across procedure boundaries.
The term “whole program” clearly implies that the technique considers all of the code. We prefer the term “interprocedural” for techniques that analyze some, but not all, of the procedures and “whole program” for those that examine the entire program.
Interprocedural analysis and optimization occurs, at least conceptually, on the program’s call graph. In some cases, these techniques analyze the entire program; in other cases, they may examine a subset of the program. Two classic examples of interprocedural optimizations are inline substitution, which replaces a call with a copy of the code for the callee, and interprocedural constant propagation, which propagates information about constants across the whole program.
SECTION REVIEW
Section titled “SECTION REVIEW”Compilers perform both analysis and transformation over a variety of scopes, ranging from single basic blocks (local methods) to entire programs (whole-program methods). The set of available opportunities changes at different scopes; intuition suggests more opportunities in larger scopes. However, analyzing larger scopes often produces less precise knowledge about the code’s behavior. Thus, no simple relationship exists between scope of optimization and code quality. It would be intellectually pleasing if larger optimization scopes led, in general, to better code. Unfortunately, that relationship does not necessarily hold true.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- Basic blocks have the property that if one operation executes, every operation in the block executes in a specified order (unless an exception occurs). State the weaker property that holds in an extended basic block.
- The PL/I Optimizing Compiler was one of the first compilers to perform interprocedural analysis and optimization. However, it limited its scope to the set of procedures found in a single file. Justify this decision. What problems might arise if the compiler optimized a scope with multiple files?
8.4 LOCAL OPTIMIZATION
Section titled “8.4 LOCAL OPTIMIZATION”Local optimizations are among the simplest methods that the compiler can use. The simple execution model of a basic block, with serial execution of a single path, leads to reasonably precise analysis in support of optimization. Thus, these methods are surprisingly effective.
This section presents two local methods as examples. The first, value numbering, finds redundant expressions in a basic block and replaces the redundant evaluations with reuse of a previously computed value. The second,
Redundant
Section titled “Redundant”An expression e is redundant at p if it has already been evaluated on every path that leads to p. tree-height balancing, reorganizes expression trees to expose more opportunities to the scheduler.
8.4.1 Local Value Numbering
Section titled “8.4.1 Local Value Numbering”Consider the four-statement basic block shown in the margin. An expression, such as b+c or a-d, is redundant in a block if and only if it has been previously computed in the block and no intervening operation redefines one of its constituent arguments. In the example, the occurrence of b+c in the third operation is not redundant because the second operation redefines b. The occurrence of a-d in the fourth operation is redundant because the block does not redefine either a or d between the second and fourth operations.
The compiler can rewrite this block so that it computes a-d once, as shown. The second evaluation of a-d is replaced with a copy from b. An alternative strategy would replace subsequent uses of d with uses of b. However, that approach requires analysis to determine whether or not b is redefined before each later use of d. In practice, it is simpler to have the optimizer insert a copy and let later passes determine whether or not the copy is needed (see the discussion of copy coalescing in Section 13.4.3).
In general, replacing redundant evaluations with references to previously computed values is profitable—that is, the resulting code runs more quickly than the original. However, profitability is not guaranteed. Replacing d←a-d with d←b has the potential to extend the lifetime of b and to shorten the lifetimes of either a or d or both—depending, in each case, on where the value’s last use lies. Depending on the precise details, each rewrite can increase, decrease, or leave unchanged the demand for registers. Replacing a redundant computation with a reference is likely to be profitable unless the rewrite causes the register allocator to spill additional values.
In practice, the optimizer cannot consistently predict the behavior of the register allocator, in part because the code will be further transformed before allocation. Therefore, most redundancy elimination algorithms assume that rewriting to avoid redundancy is profitable.
In the previous example, the redundant expression was textually identical to the earlier instance. Assignment can, of course, produce a redundant expression that differs textually from its predecessor. Consider the block shown in the margin. The assignment d←b makes the expression dxc produce the same value as bxc. To recognize this case, the compiler must track the flow of values through names. Techniques that rely on textual identity do not detect such cases.
a←b+c b←a-d c←b+c d←a-d Original Block a←b+c b←a-d c←b+c d←b Rewritten Block
Coalescing a method that removes an unneeded copy. a←b, by combining a and b
Lifetime In the context of optimization, a value’s lifetime is the region of code between its definitions and its uses. In a block, a value’s lifetime is the interval from its definition to its last use.
a←bxc d←b e←dxc Effect of Assignment The assignment to y(i) in Fig. 8.1 will create multiple redundant subexpressions from the various address polynomials.
for i ← 1 to n, where the block has n operations in the form “Tᵢ ← Lᵢ Opᵢ Rᵢ” do get the value numbers V₁ and V₂ for Lᵢ and Rᵢ if Tᵢ has no table entry then create a table entry for Tᵢ construct a hash key, k, as (V₁,Opᵢ,V₂) if k is already present in the table then replace operation i with “Tᵢ ← x”, where x is the name stored under the key k else create a table entry for k generate a new value number for k and store it in k’s table entry store the name Tᵢ in k’s table entry store k’s value number in the table entry for Tᵢ
■ FIGURE 8.2 Value Numbering a Single Block.
Programmers will protest that they do not write code that contains redundant expressions similar to those in the example. In practice, redundancy elimination finds many opportunities. Translation from source code to IR elaborates many details, such as address calculations, and introduces redundant expressions.
Many techniques have been developed to find and eliminate redundancies. Local value numbering (LVN) is one of the oldest and most powerful of these transformations. It discovers redundancies within a basic block and rewrites the block to avoid them. It provides a simple and efficient framework for other local optimizations, such as constant folding and simplification using algebraic identities.
The Algorithm
The idea behind LVN is simple. The algorithm traverses a basic block and assigns a distinct number to each value that the block computes. It chooses the numbers so that two expressions, M and N, have the same value number if and only if M and N have provably equal values for all possible executions of the block.
Fig. 8.2 shows the basic LVN algorithm. LVN takes as input a block with n binary operations, each of the form Tᵢ ← Lᵢ Opᵢ Rᵢ. LVN examines each operation, in order. It uses a hash table to map names, constants, and expressions into distinct value numbers. The hash table is initially empty.
To process the ith operation, LVN obtains value numbers for Lᵢ and Rᵢ by searching for them in the hash table. If it finds an entry, LVN uses the value
THE IMPORTANCE OF ORDER
Section titled “THE IMPORTANCE OF ORDER”The specific order in which expressions are written has a direct impact on the ability of optimizations to analyze and transform them. Consider the application of local value numbering to two distinct encodings of v←a x b x c:
The encoding on the left assigns value numbers to a,b,a x b,c,(a x b)x c and v, while the encoding on the right assigns value numbers to b,c, bxc,a,a x(bxc) and v. Depending on the surrounding context, one of these may be preferable. For example, if bxc occurs later in the block but axb does not, then the right-hand encoding produces redundancy while the left does not.
In general, using commutativity, associativity, and distributivity to reorder expressions can change the results of optimization. Similar effects can be seen with constant folding; if we replace a with 3 and c with 5, neither ordering produces the constant operation 3x5, which can be folded.
Because the number of ways to reorder expressions is prohibitively large, compilers use heuristic techniques to find good orderings for expressions. For example, the IBM FORTRAN H compiler generated array-address computations in an order that tended to improve other optimizations. Other compilers have sorted the operands of commutative and associative operations into an order that corresponds to the loop nesting level at which they are defined. Because so many solutions are possible, heuristic solutions for this problem often require experimentation and tuning to discover what is appropriate for a specific language, compiler, and coding style.
number of that entry. If not, it creates a new entry and assigns it a new value number.
Given value numbers for Li and Rj, denoted V1 and V2, LVN constructs a hash key from and looks up that key in the table. If an entry exists, the expression is redundant and can be replaced by a reference to the previously computed value. If not, then operation i is the first computation of Op R in the block, so LVN creates an entry for its hash key and assigns that entry a new value number. It also assigns the hash key’s value number, whether new or preexisting, to the table entry for . Because LVN uses value numbers to construct the expression’s hash key, rather than names, it can effectively track the flow of values through copy and assignment operations, such as the small example labeled “Effect of Assignment” on page 395.Extending LVN to expressions of arbitrary arity is simple.
a+0=a a-0=a a-a=0 2xa=a+a a x1=a a x0=0 a÷1=a a÷a=1,a≠0 a1=a a2=a xa a》0=a a《0=a a AND a=a a OR a=a MAX(a,a)=a MIN(a,a)=a
Example with Value Numbers
Example After Rewrite
a2←b0+c1 b4←a2-d3 c5←b4+c1 d4←a2-d3
To see how LVN computes value numbers, consider our example, repeated in the margin. Each name is annotated with the value number that LVN assign to it, shown as a superscript. In the first operation, with an empty value table,b and c get new value numbers, 0 and 1, respectively. LVN constructs the textual string “0+1” as a hash key for the expression b+c and performs a lookup. It does not find an entry for that key, so the lookup fails. Accord-ingly, LVN creates a new entry for “0+1” and assigns it value number 2.LVN then creates an entry for a and assigns it the value number of the expression, namely 2. Repeating this process for each operation, in sequential order, produces the rest of the value numbers shown in the margin.
The value numbers reveal, correctly, that the two occurrences of b+c produce different values, due to the intervening redefinition of b. They also show that the two occurrences of a-d produce the same value. In both occurrences of a-d, a has the same value number; d does, as well. LVN discovers this fact and records it by assigning b and d the same value number, namely 4. That knowledge lets LVN rewrite the fourth operation with a d←b as shown in the margin. Subsequent passes may coalesce and eliminate the copy operation.
Extending the Algorithm
Section titled “Extending the Algorithm”LVN provides a framework for several other local optimizations.
Commutative Operations Variants of a commutative expression, such as axb and bxa, should receive the same value number. As LVN constructs a hash key for the right-hand side of the current operation, it can sort the operands using some convenient scheme, such as ordering them by value number. This simple action will ensure that variants of a commutative expression receive the same value number.
Constant Folding If all the operands of an operation have known constant values, LVN can perform the operation at compile time and fold the answer directly into the code. LVN can mark hash table entries as constants and store their values alongside their value numbers. When LVN discovers a constant expression, it can evaluate the expression and replace the expression with a literal constant value. for i←1 to n, where the block has n operations in the form “T;←L;Op;R;” do get the value numbers V1 and V2 for L; and R; if T; has no table entry then create a table entry for T; if Op; commutes and V1 > V2 then swap V1 and V2 construct a hash key, k, as (V1,Op;V2) if k is already present in the table then replace operation i with “T;←x,” where x is the constant value or name stored under the key k else create a table entry for k generate a new value number for k and store it in k’s table entry store the name T; in k’s table entry if V1 and V2 are both marked as constant then evaluate L; Op; R; into c replace operation i with “T;←c” store c in the table entries for k and T; else if L; Op; R; matches an algebraic identity then replace operation i with the simplified version store k’s value number in the table entry for T;
■ FIGURE 8.4 Local Value Numbering with Extensions.
Algebraic Identities LVN can use algebraic identities to simplify the code. For example, x+0 and x should receive the same value number. Unfortunately, LVN needs special-case code for each identity. A series of tests, one per identity, would significantly slow down LVN. To ameliorate this problem, LVN should organize the tests into operator-specific decision trees. Since each operator has just a few identities, this approach keeps the overhead low. Fig. 8.3 shows some of the identities that can be handled in LVN.
A clever implementor will discover other identities, including some that are type specific. The exclusive-or of two identical values should yield a zero of the appropriate type. Numbers in IEEE floating-point format have their own special cases introduced by the explicit representations of ∞ and NaN; for example, ∞-∞=NaN; ∞-NaN=NaN; and ∞÷NaN=NaN.
Fig. 8.4 shows LVN with these extensions. To handle commutative operations, it sorts the operands by their value numbers before it constructs the hash key. It evaluates constant expressions and applies algebraic identities.
NaN Not a Number is a defined constant that represents an invalid or meaningless result in the IEEE standard for floating-point arithmetic.
Even with these extensions, the cost per IR operation remains extremely low because each step has an efficient implementation.
The Role of Naming
Section titled “The Role of Naming”The choice of names for variables and values can limit the effectiveness of value numbering. Consider what happens when LVN is applied to the block shown in the margin. Again, the superscripts indicate the value numbers assigned to each name and value.
a2←x0+y1 b2←x0+y1 a3←17 3 c2←x0+y1 Example with Value Numbers
In the first operation, LVN assigns 0 to x, 1 to y, and 2 to both x+y and a. At the second operation, it discovers that x+y is redundant, with value number 2; thus, LVN can rewrite b←x+y with b←a. The third operation is not redundant. At the fourth operation, LVN again discovers that x+y has value number 2. It cannot, however, rewrite the operation as c←a because a no longer holds value number 2.
Example After Renaming
a2←x0+y0 1 b2←x0+y0 1 a3←17 3 c2←x0+y0 1
LVN can address this problem in two distinct ways. It can keep a map from value numbers to names. At each operation, it must update the map. Say the operation defines t. LVN must remove t from the list for its old value number and add t to the list for its new value number. At a replacement,LVN can use any name currently in the map for that value number. This approach adds some cost to the processing of each operation. It also clutters up the basic algorithm.
As an alternative, the compiler can rewrite the code so that each operation defines a unique name. Adding a subscript to each name for uniqueness, as shown in the margin, is sufficient. With these new names, the code defines each value exactly once. Thus, no value is ever redefined and lost, or killed. If we apply LVN to this block, it produces the desired result. It proves that the second and fourth operations are redundant; each can be replaced with a copy from a0.(Notice that, after renaming, a0 is live over a longer region in the code than a was.)
However, the compiler must now reconcile these subscripted names with the names in surrounding blocks to preserve the meaning of the original code. In our example, the original name a should refer to the value from the subscripted name a1 in the rewritten code. A clever implementation would map the new a1 to the original a,b0 to the original b, and c0 to the original c;it would also rename a0 to a new temporary name. That solution reconciles the name space of the transformed block with the surrounding context without introducing copies.
This naming scheme approximates one property of the name space created or static single-assignment form, or SSA(see Sections 4.6.2 and 9.3). From
8.4 Local Optimization 401
Section titled “8.4 Local Optimization 401”RUNTIME EXCEPTIONS AND OPTIMIZATION
Section titled “RUNTIME EXCEPTIONS AND OPTIMIZATION”Some abnormal runtime conditions can raise exceptions. Examples include out-of-bounds memory references, undefined arithmetic operations such as division by zero, and illegal operations. (One way for a debugger to trigger a breakpoint is to replace the instruction with an illegal one and to catch the exception.) Some languages include features for handling exceptions, for both predefined and programmer-defined situations.
Typically, a runtime exception causes a transfer of control to an “exception handler,” code designed to deal with the exception. The handler may cure the problem, reexecute the offending operation, and return control to the block. Alternatively, it may transfer control elsewhere or terminate execution.
The optimizer must understand which operations can raise an exception and must consider the impact of an exception on program execution. Because an exception handler might modify the values of variables or transfer control, the compiler must treat exception-raising operations conservatively. For example, every exception-raising operation might end the current basic block. Such treatment can severely limit the optimizer’s ability to improve the code.
To optimize exception-laden code, the compiler needs to understand and model the effects of exception handlers. To do so, it needs access to the code for the exception handlers and it needs to understand which handlers might be in place when a specific exception-raising operation executes.
a design perspective, the simple solution is to apply LVN to code that is already in SSA form.
The Impact of Indirect Assignments
Section titled “The Impact of Indirect Assignments”The previous discussion assumes that assignments are direct and obvious, as in a ← b×c. Many programs contain indirect assignments, where the compiler may not know which values are modified because the reference is ambiguous. Examples include (1) assignment through a pointer, such as *p=0; in C; (2) assignment to a structure element or an array element, such as a(i,j)=0 in FORTRAN; or (3) assignment through a call-by-reference parameter. Indirect assignments complicate value numbering and other optimizations because they create imprecisions in the compiler’s understanding of the flow of values.
Assume, without loss of generality, that the names in our examples are memory addresses. Consider the impact that an indirect assignment, such as *p=0, must have on the state of LVN. Unless the compiler knows the address contained in p, it must assume that any location that p might address
Ambiguous reference A reference is ambiguous if the compiler cannot isolate it to a single memory location.
(a) Left-Associative Tree (b) Right-Associative Tree (c) Balanced Tree
■ FIGURE 8.5 Potential Tree Shapes for a+b+c+d+e+f+g+h.
has been changed. In an implementation of LVN where names represent memory locations, an ambiguous assignment would give each name its own new value number.
While this sounds drastic, it shows the true impact of an ambiguous assignment on the set of facts that the compiler can derive. The compiler can try to disambiguate references. For pointer-based references, it can perform analysis to narrow the set of variables that the compiler believes a pointer can address. A variety of techniques help the compiler understand the patterns of element access in an array—again, to shrink the set of locations that it must assume might be modified by an assignment to one element. Interprocedural alias analysis can resolve some of the ambiguities caused by interactions between parameter binding and name scoping rules.
8.4.2 Tree-Height Balancing
Section titled “8.4.2 Tree-Height Balancing”Expression optimization for multiple functional units demonstrates the impact that code shape can have on the compiler’s ability to improve a computation. Most processors have several functional units; those units can execute independent operations in each cycle. If the compiler can express the computation so that it presents independent operations, the scheduler and the processor may be able to execute them concurrently; if, instead, the compiler introduces unnecessary sequential constraints, the scheduler and the processor may not find enough concurrency to occupy the functional units.
Consider the expression a+b+c+d+e+f+g+h. The code in the margin encodes a left-to-right evaluation, which is equivalent to a postorder walk of the left-associative tree in Fig. 8.5(a). A right-to-left evaluation of the expression would correspond to the tree in panel (b). Each tree constrains the execution order in ways that are more restrictive than the rules of addition. The left-associative tree forces the code to evaluate a+b before it can add either g or h. The right-associative tree requires that g+h precede additions
Left-to-Right Evaluation of a+b+c+d+e+f+g+h
| Adder 0 | Adder 1 |
|---|---|
| 1 t1←a+b | |
| 2 t2←t1+c | |
| 3 t3←t2+d | |
| 4 t4←t3+e | |
| 5 t5←t4+f | |
| 6 t6←t5+g | |
| 7 t7←t6+h | |
| 1 t1←a+b t2←c+d | |
| 2 t3←e+f t4←g+h | |
| 3 t5←t1+t2 t6←t3+t4 | |
| 4 t7←t5+t6 | |
| 5 5 | |
| 6 6 | |
| 7 7 |
(a) Left-Associative Tree
(b) Balanced Tree
■FIGURE 8.6 Schedules from Trees in Fig. 8.5.
involving a or b. The balanced tree in panel(c) imposes fewer constraints, but it still restricts evaluation order more than addition does.
If the processor can perform multiple concurrent additions, then the balanced tree should lead to a shorter schedule for the computation. Fig. 8.6 shows the shortest possible schedules for the balanced tree and the left-associative tree on a computer with two single-cycle adders. The balanced tree can execute in four cycles, with one unit idle in the fourth cycle. By contrast, the left-associative tree takes seven cycles to execute because it serializes the additions. It leaves one adder completely idle. The right-associative tree produces similar results.
This small example suggests an important optimization: using commutativ-ity and associativity to expose additional parallelism in expression evaluation. The rest of this section presents an algorithm that rewrites a single block to improve balance across its forest of expression trees. This transformation exposes more instruction-level parallelism(ILP) to the instruction scheduler.
Candidate Trees
Section titled “Candidate Trees”As a first step, the algorithm must identify trees that are promising candidates for rebalancing. A candidate tree, or subtree, must contain only one kind of operator, such as+ or x. That operator must be both associative and commutative to allow rearrangement of the operands. The tree should be as large as possible, to maximize ILP. If the tree is too small, the optimization will make no difference.
To ensure that the rewritten code works in its surrounding context, that code must preserve any values that are used outside of the expression. A value
Instruction-level parallelism
Section titled “Instruction-level parallelism”Operations that are independent can execute in the same cycle. This kind of concurrency is called instruction-level parallelism.
// All operations have the form “T1←L1 Op1 R1” // Phase 1: build a queue, Roots, of the candidate trees Roots←new empty queue for i←0 to n-1 do Rank(Ti)←-1 if Op is commutative and associative and Ti is exposed then mark Ti as a root Enqueue(Roots, Ti, precedence of Op) // Phase 2: remove a tree from Roots and rebalance it while(Roots is not empty) do var←Dequeue(Roots) Balance(var)
■FIGURE 8.7 Tree-Height Balancing Algorithm.
is exposed if it is used after the block, if it is used more than once within the block, or if it appears as an argument to an operator of another type. Exposed values must be preserved-that is, the rewritten computation must produce the same result for the exposed value as the original computation. This restriction can constrain the algorithm’s ability to rearrange code.
The code fragment shown in the margin computes two large expressions:m←(a+b+c+d), and n←(a+b+c)xexfxg. Assume that m and n are used later, so they are exposed values. t2 is also exposed; it must be preserved for its use in the computation of t3.
The fact that t2 is exposed affects the code in two distinct ways. First, the compiler cannot rewrite(a+b+c+d) as(a+b)+(c+d) because the latter expression never computes the value of t2. Second, the computation of t2 must precede the computation of t3, which, again, restricts the order of operations.
The algorithm to find candidate trees must treat each exposed value as the root of a tree. In the example, this produces the forest shown in the margin. Notice that t2 is defined once and used twice. The trees for t2 and m are too small to benefit from tree-height balancing, while the tree for n, with four operands, can be balanced.
If the compiler’s definitive IR is not a collection of expression trees, it can either build the expression trees for the block as a derivative IR, or it can interpret the definitive IR as expression trees to drive the algorithm. The latter approach requires some simple data structures to link each use in the block with either the definition in the block that reaches it or a notation to
Upward exposed
A name x is upward exposed in block b if the first use of x in b refers to a value computed before entering b.
at the use is upward exposed.
High-Level Sketch of the Algorithm
Section titled “High-Level Sketch of the Algorithm”The tree-height balancing algorithm, shown in Fig. 8.7, consists of two phases. The first phase finds the roots of the candidate expression trees in the block. It ignores operators unless they are both commutative and associative. If a value T is both an exposed value and the result of a commutative and associative operator, then it adds T to a queue of roots, ordered by the operator’s arithmetic precedence.
The second phase takes the roots, in precedence order from lowest to highest, and creates a balanced tree by flattening the tree into a single n-ary operator and then rebuilding it in balanced form. The n-ary tree for n in our continuing example appears in the margin.
Phase 1: Finding Candidate Trees
Section titled “Phase 1: Finding Candidate Trees”Phase 1 of the algorithm is straightforward. The algorithm walks over the operations in the block, in order, and tests each operation to see if it should be the root of a candidate tree. The test relies on observations made earlier. A candidate tree root must be the result of using a commutative and associative operator to create an exposed value.
To determine if the value defined by operation i is exposed, the compiler must understand where is used. The compiler can compute LIVEOUT sets for each block and use that information to determine if is used after the current block(see Section 8.6.1). As part of computing the initial information for that computation, the compiler can also determine how many times is used within the block.
The test for a candidate-tree root, then, can be expressed concisely. For an operation T←L Op R in block B, T is a root if and only if:
Op is both commutative and associative and(T is used more than once in B or T∈LIVEOUT(B))
Phase 1 initializes the ranks of each defined in the block. For each root that it finds, it marks the name as a root and adds it to a priority queue of the roots. The queue for the continuing example appears in the margin; it assumes precedence of one for+ and two for x.
Phase 2: Rebuilding the Block in Balanced Form
Section titled “Phase 2: Rebuilding the Block in Balanced Form”Phase 2 takes the queue of candidate-tree roots and builds, from each root, an approximately balanced tree. Phase 2 starts with a while loop that calls Balance on each candidate tree root. Balance, Flatten, and Rebuild implement Phase 2, as shown in Figs. 8.8 and 8.9.
n-ary Tree for n
Balance(root) // Create balanced tree from its root, T_i if Rank(root) ≥ 0 then return // already processed this tree q ← new empty queue // Flatten the tree, then rebuild it Rank(root) ← Flatten(L_i, q) + Flatten(R_i, q) Rebuild(root, q, Op_i)
Flatten(node, q) // Flatten computes a rank for node & builds the queue if node is a constant then // Constant is a leaf in the tree Rank(node) ← 0 Enqueue(q, node, Rank(node)) else if node is upward exposed then // UE is a leaf in the tree Rank(node) ← 1 Enqueue(q, node, Rank(node)) else if node is a root // Root of another tree is a leaf Balance(node) // Balance sets Rank(node) Enqueue(q, node, Rank(node)) else // interior node for T_i ← L_i Op_i R_i Rank(node) ← Flatten(L_j, q) + Flatten(R_j, q) return Rank(node)
Figure 8.8 Tree-Height Balancing Algorithm: Balance and Flatten.
Recall that Phase 1 ranked the Roots queue by arithmetic precedence, which forces Flat-ten to follow the correct evaluation order.
Balance is invoked on each candidate-tree root in increasing priority order. If the tree has not already been balanced, Balance calls Flatten to create a new priority queue that holds all the operands of the current tree. In essence, the queue represents the single-level, n-ary version of the candidate tree. Once Flatten has created the queue, Balance invokes Rebuild to emit code for the approximately balanced tree.
Flatten is straightforward. It recursively walks the candidate tree, assigns each node a rank, and adds it to the queue. Flatten assigns ranks directly to leaf nodes: zero for a constant and one for a leaf. If Flatten encounters a root, it calls Balance on that root; Balance creates a new queue, flattens the root’s candidate tree, and rebuilds it. The root keeps the priority assigned to it by that recursive call.
When Balance calls Rebuild, the queue contains all of the leaves from the candidate tree, in rank order. Intermediate results, represented by interior nodes in the original expression trees are gone.
Rebuild uses a simple algorithm to rewrite the code. It repeatedly removes the two lowest-ranked items from the tree. If they are constant, then it evaluates
Balance, in effect, gathers the constants together so that Rebuild can combine them. Rebuild(root, q, op) // Build a balanced expression while (q is not empty) do NewL ← Dequeue(q) // Get a left operand NewR ← Dequeue(q) // Get a right operand if NewL and NewR are both constants then // evaluate and fold the result NewT ← Fold(op, NewL, NewR) if q is empty then create the op “root ← NewT” Rank(root) = 0 else Enqueue(q, NewT, 0) Rank(NewT) = 0 else if q is empty then // not a constant; name the result NewT ← root else NewT ← new name create the op “NewT ← NewL op NewR” Rank(NewT) ← Rank(NewL) + Rank(NewR) if q is not empty then // More ops in q ⇒ add NewT to q Enqueue(q, NewT, Rank(NewT))
■ FIGURE 8.9 Tree-Height Balancing Algorithm: Rebuild.
the operation and pushes the result back onto the queue with priority zero. Since all constants have rank zero, Rebuild will fold them all into a single constant term. If one or more of the items has nonzero rank, Rebuild creates an operation to combine the two items. It assigns the operation a new rank. Finally, it pushes the new operation onto the queue. This process continues until the queue is empty.
The expression trees and Roots queue that Phase 1 produces for the ongoing example are shown in the margin. Phase 2 pulls each root from the queue and passes it to Balance. Neither m nor t₂ have enough operands for the algorithm to create a balanced tree.
When Phase 2 pulls n from the Roots queue, Flatten builds a queue that holds all four operands, each with rank one. Rebuild then creates operations to compute g×f and t₂×e, enters those operations into the queue with rank two, and then pulls them and combines them into the root, n. The rebuilt tree for n appears in the margin.
Figure 8.10 gives a larger example for tree-height balancing. Constants have been folded and redundant computations eliminated, as local value numbering might do. All of s, t, u, v, w, x, y, and z are upward exposed, so all are live on exit from the block.
(a) Original code (b) Trees in the code (c) Finding roots
t1 <- 13 + s roots include t6 and t10 boxed roots: t6, t10, t11, t3, t7t2 <- t1 + tt3 <- t2 + 4t4 <- t3 * ut5 <- 3 * t4t6 <- v * t5t7 <- w + xt8 <- t7 + yt9 <- t8 + zt10 <- t9 * t7t11 <- t3 + t9Figure 8.10: Detailed Example of Tree-Height Balancing.
Phase 1 finds roots in reverse order. It colors the roots and their defining trees so that later balancing can reduce tree height without changing required value uses. The roots appear in boxes in panels (b) and (c).
Phase 2 processes the root queue. It removes a node from the queue and calls Balance to process it. When Balance returns, it may append newly exposed roots to the queue. Applying the algorithm to the example first calls Balance on t11, which recursively balances the expression rooted at t11.
17+t; assigns the result to a new name, say n0; and enqueues (n0,1). Finally. Rebuild dequeues (n0,1) and (s,1) and creates the operation n0+s. Since the queue is now empty, Rebuild assigns the result to the tree’s root, t3. The code is shown in the margin.
Rebuild returns; Balance returns; and control is back in the call to Flatten on t11. Flatten continues, until it hits t7, and recurs on Balance(t7).
For t7, Flatten produces the queue: {(x,1),(w,1)}. Rebuild dequeues (x,1) and(w,1); creates the operation x+w; and, since the queue is empty, assigns the result to the root, t7, as shown in the margin.
Rebuild returns; Balance returns; and control returns to Flatten(t11). Flatten returns the queue: {(z,1),(y,1),(t7,2)(t3,2)}. Rebuild creates the operation z+y and assigns its value to n1. Next, it creates the operation n1+t7 and assigns its value to n2. Finally, it creates the operation n2+t3 and assigns its value to the tree’s root, t11.
Rebuild returns; Balance returns; and control flows back to the while loop. Phase 2 calls Balance(t7), which finds that t7 has been processed. It then calls Balance(t3), which finds that t3 has been processed.
Next, the while loop invokes Balance(t10). Flatten recurs on Balance for both t3 and t7. In both cases, the tree has already been processed. At that point, Flatten returns the queue: {(t7,2),(t3,2)}. Rebuild creates the operation t7xt3 and, since the queue is now empty, assigns it to the tree’s root, t10. Rebuild returns. Balance returns.
The next, and final, iteration of the while loop invokes Balance(t6). Flat-ten encounters t3, which causes it to recur with Balance(t3); since t3 has been processed, the call returns immediately. Flatten returns the queue:{〈3,0〉,〈v,1〉,〈u,1〉,〈t3,2〉}. From this queue, Rebuild creates the operations shown in the margin. Rebuild returns; Balance returns; and the while loop terminates. Fig. 8.11 shows the final result.
The difference between the forests of expression trees in Figs. 8.10(b)and 8.11.b may not be obvious. To appreciate the restructured tree, compare the height of the tree for t6, including the tree for t3. In the original code, the tree has height seven where the restructured tree has height four. Similarly, the original tree for t11 has height five where the restructured tree has height four.
As a final point, the reader may observe that the individual trees in Fig. 8.11(b) do not look balanced. The algorithm creates balance across the entire block, rather than across the individual trees. This effect is a simple
n9←17+t
t7←n9+s
t7←x+w
n1←z+y
n2←n1+t7
t11←n2+t3
t10←t7xt3
n3←3xv
n4←n3xu
t6←n4xt3
(a) Transformed Code n0 ← 17 + t t3 ← n0 + s t7 ← x + w n1 ← z + y n2 ← n1 + t7 t11 ← n2 + t3 t10 ← t7 × t3 n3 ← 3 × v n4 ← n3 × u t6 ← n4 × t3
(b) Trees in the Transformed Code t7 x t10 t3 z y t7 x w t6 x u t3 v t3 3 v 17 t s
■ FIGURE 8.11 Code Structure After Balancing.
and clear example of the difference between optimizing for a local effect and optimizing over a larger context.
The balance across the block is the result of a single line of code in Flatten from Fig. 8.8. For a root x, Flatten enqueues x with the rank it was previously assigned in Balance. If we modified that line of code to enqueue it with a rank of one, each of the subtrees would be balanced. The drawing might look better, but the overall height of trees that reference shared subtrees would be taller and the code would expose less ILP.
SECTION REVIEW
Section titled “SECTION REVIEW”Local optimization operates on the code for a single basic block. These techniques rewrite the block based on information derived from that block. In the process, they must maintain the block’s interactions with the surrounding execution context. In particular, they must preserve any observable values computed in the block.
Because they limit their scope to a single block, local optimizations can rely on properties that only hold true in straight-line code. For example, local value numbering relies on the fact that all the operations in the block execute in an order that is consistent with straight-line execution. Thus, it can build a model of prior context that exposes redundancies and constant-valued expressions. Similarly, tree-height balancing relies on the fact that a block has just one entry and one exit to determine which subexpressions in the block it must preserve and which ones it can reorder.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- Naming plays a key role in the effectiveness of LVN. Sketch an algorithm to rename the values in a basic block so that each definition in the block creates a unique name and that each use refers to the correct new name.
- The tree-height balancing algorithm ranks a node n in the final expression tree with the number of nonconstant leaves below it in the final tree. How would you modify the algorithm to produce ranks that correspond to the height of n in the tree? Would that change the code that the algorithm produces?
8.5 REGIONAL OPTIMIZATION
Section titled “8.5 REGIONAL OPTIMIZATION”Inefficiencies are not limited to single blocks. Code in one block may provide the context for improving code in another block. Thus, many optimizations examine contexts larger than a single block.
Regional techniques operate over subsets of the control-flow graph that include multiple blocks but do not, typically, extend to the entire procedure. The primary complication that arises in the shift from local optimization to these regional methods is the need to handle multiple control-flow paths. An if-then-else construct introduces conditionally executed paths. Loops introduce cyclic control flow. Because regional methods examine more context than local methods, they can discover opportunities that local methods cannot see. Because they focus on a subset of the procedure’s CFG, these methods can often be simpler than a global approach to the same problem.
This section presents two regional techniques as illustrations. The first, superlocal value numbering, extends LVN to multiple blocks. The second, loop unrolling, operates over a single loop nest; unrolling played a role in the discussion of dmxpy in Section 8.2.1.
8.5.1 Superlocal Value Numbering
Section titled “8.5.1 Superlocal Value Numbering”To improve the results of LVN, the compiler can expand its scope from a single basic block to an extended basic block, or EBB (see Section 8.3). To process an EBB, the algorithm should value number each path through the EBB. Consider, for example, the CFG shown in Fig. 8.12(a). It contains three EBBs. The nontrivial EBB is (B0,B1,B3,B4,B6). The other two EBBs are trivial: (B2) and (B5). The regional version of value numbering, which we call superlocal value numbering (SVN), processes one EBB at a time and propagates information down each path in the EBB.
(a) Control-Flow Graph (b) Corresponding Low-Level Code
B0: m0 ← a0 + b0 n0 ← a0 + b0 (a0 > b0) → B1, B3 B1: p0 ← c0 + d0 r0 ← c0 + d0 → B2 B2: r2 ← φ(r0,r1) y0 ← a0 + b0 z0 ← c0 + d0 → exit B3: q0 ← a0 + b0 r1 ← c0 + d0 (a0 > b0) → B4, B6 B4: e0 ← b0 + 18 s0 ← a0 + b0 u0 ← e0 + f0 → B5 B5: e2 ← φ(e0,e1) u2 ← φ(u0,u1) v0 ← a0 + b0 w0 ← c0 + d0 x0 ← e2 + f0 → B2 B6: e1 ← a0 + 17 t0 ← c0 + d0 u1 ← e1 + f0 → B5
■ FIGURE 8.12 Example for Superlocal Value Numbering.
The nontrivial EBB contains three paths: ⟨B0,B1⟩, ⟨B0,B3,B4⟩, and ⟨B0,B3,B6⟩. SVN treats each of these paths as if it were straight-line code. To process ⟨B0,B1⟩, the compiler can apply LVN to B0 and use the resulting hash table as a starting point when it applies LVN to B1. The same approach can handle ⟨B0,B3,B4⟩ and ⟨B0,B3,B6⟩ by processing the blocks for each in order and carrying the hash tables forward. Blocks that have multiple predecessors, such as B2 and B5, start new EBBs and, therefore, inherit no context from their predecessors.
This scheme achieves the results of LVN over longer paths by treating each EBB path as if it were a single block. To make the example concrete, consider the code for each block shown in Fig. 8.12(b). Applying LVN to EBB paths exposes opportunities that are hidden when considering just the individual blocks.
- In ⟨B0,B1⟩, LVN discovers that the assignments to n0 and r0 are redundant. SVN discovers the same redundancies.
- In ⟨B0,B3,B4⟩, LVN finds that the assignment to n0 is redundant. SVN also finds that the assignments to q0 and s0 are redundant.
- In ⟨B0,B3,B6⟩, LVN finds that the assignment to n0 is redundant. SVN also finds that the assignments to q0 and t0 are redundant.
- In B5 and B2, SVN degenerates to LVN.
The difficulty in this approach lies in making the process efficient. The obvious would treat each path as if it were a single block, pretending,
// Start the process WorkList ←{entry block} Empty←new table for Block while(WorkList is not empty) do remove Block from WorkList SVN(Block, Empty) free Empty
// Superlocal value numbering algorithm SVN(Block, Table) t←new table for Block link Table as the surrounding scope for t LVN(Block, t) for each successor s of Block do if|preds(s)|=1 then SVN(s,t) else if s has not been processed then add s to WorkList free t
■FIGURE 8.13 Superlocal Value Numbering Algorithm.
for example, that the code for(B0,B3,B4) looks like the code shown in margin. Unfortunately, this approach analyzes a block once for each path that includes it. In the extended block(B0,B1 B3 B4,B6), the algorithm would analyze B0 three times and B3 twice. While we want the optimization benefits that come from examining increased context, we also want to minimize compile-time costs. The key to achieving these conflicting goals is to capitalize on the tree structure of the EBB.
To make SVN efficient, the compiler must reuse the results of blocks that occur as prefixes on multiple paths through the EBB. After processing(B0,B3,B4), it needs a mechanism to recreate the state for the end of(B0,B3) so that it can reuse that state to process B6. The compiler can accomplish this effect in several ways:
■ It can record the state of the table at each block boundary and restore that state when needed.
■ It can unwind the effects of a block by walking the block backward and, at each operation, undoing the work of the forward pass.
■ It can use a sheaf of linked hash tables to implement the value table(see Section 4.5.1). As it enters a block, it creates a new table. To retract the block’s effects, it deletes that block’s table.
While all three schemes will work, the sheaf of tables can produce a simple and fast implementation, particularly if the compiler writer can reuse a table implementation from the compiler’s front end.
Fig. 8.13 shows a high-level sketch of the SVN algorithm, using a sheaf of value tables. It assumes that the LVN algorithm has been parameterized to accept a block and a sheaf of tables. At each block b, SVN allocates a value table for b, links it to the value table of the predecessor block as if SVN can easily estimate the size of each table from the block sizes.
Treating a Path as a Single Block
Example’s CFG
- Create scope for B0
- Apply LVN to B0
- Create scope for B1
- Apply LVN to B1
- Add B2 to WorkList
- Delete B1’s scope
- Create scope for B3
- Apply LVN to B3
- Create scope for B4
- Apply LVN to B4
- Add B5 to WorkList
- Delete B4’s scope
- Create scope for B6
- Apply LVN to B6
- Delete B6’s scope
- Delete B3’s scope
- Delete B0’s scope
- Create scope for B5
- Apply LVN to B5
- Delete B5’s scope
- Create scope for B2
- Apply LVN to B2
- Delete B2’s scope
Actions Taken by SVN on the Example
it were a surrounding scope, and invokes LVN on block b with this new table. When LVN returns, SVN must decide how to process each of b’s successors.
For a successor s of b, two cases arise. If s has only one predecessor, b, then SVN should use the accumulated context from b. Thus, SVN recurs on s with the table from b. If s has multiple predecessors, then SVN must start s with a new context, so SVN adds s to the WorkList. The outer loop will find it later and invoke SVN on s with an empty table. It is important to implement Worklist as a set to ensure that each block is processed exactly once (see Section B.2).
One complication remains. A name’s value number is recorded in the value table associated with the first operation in the EBB that defines it. This effect can defeat our use of the scoping mechanism. In our example CFG, if a name x were defined in each of B0, B4, and B6, its value number would be recorded in the scoped table for B0. When SVN processed B4, it would record x’s new value number from B4 in the table for B0. When SVN deleted the table for B4 and created a new table for B6, the value number from the definition in B4 would remain.
To avoid this complication, the compiler can run SVN on a representation that defines each name once. As we saw in Section 4.6.2, SSA form has the requisite property; each name is defined at exactly one point in the code. Using SSA form ensures that SVN records the value number for a definition in the table that corresponds to the block that contains the definition. With SSA form, SVN can undo all of a block’s effects by deleting its value table. This action reverts the set of tables to their state on exit from the block’s CFG predecessor. As discussed in Section 8.4.1, using SSA form can also make LVN more effective.
Applying the algorithm from Fig. 8.13 to the code shown in Fig. 8.12 produces the sequence of actions shown in the margin. The algorithm begins with B0 and proceeds down to B1. At the end of B1, it visits B2, realizes that B2 has multiple predecessors, and adds it to the worklist. Next, it backs up and processes B3 and then B4. At the end of B4, it adds B5 to the worklist. It then backs up to B3 and processes B6. At that point, control returns to the while loop, which invokes SVN on the two singleton blocks from the worklist, B5 and B2.
SVN discovers and removes redundant computations that LVN cannot. In the example, it finds that the assignments to q0, s0, and t0 are redundant because of definitions in earlier blocks. LVN, with its purely local scope, cannot find these redundancies. do 60 j = 1, n2 nextra = mod(n1,4) if (nextra .ge. 1) then do 49 i = 1, nextra y(i) = y(i) + x(j) * m(i,j) continue
do 50 i = nextra + 1, n1, 4 y(i) = y(i) + x(j) * m(i,j) y(i+1) = y(i+1) + x(j) * m(i+1,j) y(i+2) = y(i+2) + x(j) * m(i+2,j) y(i+3) = y(i+3) + x(j) * m(i+3,j) continue
50 continue 60 continue
nextra = mod(n2,4) if (nextra .ge. 1) then do 59 j = 1, nextra do 49 i = 1, n1 y(i) = y(i) + x(j) * m(i,j) continue
do 60 j = nextra+1, n2, 4 do 50 i = 1, n1 y(i) = y(i) + x(j) * m(i,j) y(i) = y(i) + x(j+1) * m(i,j+1) y(i) = y(i) + x(j+2) * m(i,j+2) y(i) = y(i) + x(j+3) * m(i,j+3) continue
60 continue
(a) Unroll Inner Loop by Four (b) Unroll Outer Loop by Four, Fuse Inner Loops
Figure 8.14 Unrolling dmxpy’s Loop Nest.
On the other hand, SVN has its own limitations. It fails to find redundancies in B5 and B2. The reader can tell, by inspection, that the assignments in those blocks are redundant. Because the blocks have multiple predecessors, SVN cannot carry context into them. Thus, it misses those opportunities. An algorithm would need more context to discover them.
8.5.2 Loop Unrolling
Section titled “8.5.2 Loop Unrolling”Loop unrolling is, perhaps, the oldest, simplest, and best-known loop transformation. To unroll a loop, the compiler replicates the loop’s body and adjusts the logic that controls the number of iterations performed. To see this, consider the loop nest from dmxpy used as an example in Section 8.2.
do 60 j = 1, n2 do 50 i = 1, n1 y(i) = y(i) + x(j) * m(i,j) continue
60 continue
The compiler can unroll either the inner loop or the outer loop. The result of unrolling the inner loop by four is shown in Fig. 8.14(a). Unrolling the outer loop by four produces four inner loops; if the compiler then combines those inner-loop bodies—a transformation called loop fusion—it will produce code similar to that shown in Fig. 8.14(b). The combination of outer-loop unrolling followed by inner-loop fusion is often called unroll-and-jam.
Loop fusion
The process of combining two loop bodies into one is called fusion.
Fusion is safe when each definition and each use in the resulting loop has the same value that it did in the original loops.
In each case, the transformed code needs a short prolog loop to peel off enough iterations so that the unrolled loop processes an integral multiple of four iterations. If the loop bounds are known at compile time, the compiler can determine if the prolog is necessary.
Inner-loop unrolling and outer-loop unrolling produce different results for this particular loop nest. Inner-loop unrolling reduces the number of test-and-branch sequences that the inner loop executes. By contrast, outer-loop unrolling followed by inner-loop fusion not only reduces the number of test-and-branch sequences, but also produces reuse of y(i) and sequential access to both x and m. The increased reuse fundamentally changes the ratio of arithmetic operations to memory operations in the loop; undoubtedly, the author of dmxpy had that effect in mind when he hand-optimized the code, as shown in Fig. 8.1. As discussed below, each approach may also accrue indirect benefits.
Sources of Improvement and Degradation
Section titled “Sources of Improvement and Degradation”Loop unrolling has both direct and indirect effects on the code that the compiler can produce for a given loop. The final performance of the loop depends on all of the effects, direct and indirect.
In terms of direct benefits, unrolling should reduce the number of operations required to complete the loop. The control-flow changes reduce the total number of test-and-branch sequences. Unrolling can create reuse within the loop body, reducing memory traffic. Finally, if the loop contains a cyclic chain of copy operations, unrolling can eliminate the copies as shown in Exercise 8.6.
Unrolling a loop can, however, increase the code size, both in the IR form and in the final form as executable code. Growth in IR increases compile time; growth in executable code has little effect until the loop overflows the instruction cache-at which time the degradation probably overwhelms any direct benefits.
The compiler can also unroll for indirect effects. A key side effect of unrolling is to increase the number of operations in the loop body. Other optimizations can capitalize on this change in several ways:
■ Increasing the amount of ILP in the loop body can lead to better instruction schedules. With more independent operations, the scheduler has a better chance of keeping multiple functional units busy and of hiding the latency of multicycle operations such as branches and memory accesses. ■ Unrolling can move consecutive memory accesses into the same iteration, where the compiler can schedule them together. That may improve locality or allow the use of multiword operations. ■ Unrolling can expose cross-iteration redundancies that are harder to discover in the original code. Both versions of the code in Fig. 8.14 reuse address expressions across iterations of the original loop. In the unrolled loops, local value numbering would find and eliminate those redundancies. In the original, it would miss them. ■ The unrolled loop may optimize differently than the original loop. For example, increasing the number of appearances of a variable in a loop can change the weights used in spill code selection within the register allocator (see Section 13.4). Changing the pattern of register spills can radically affect the running time of the loop.
Note, however, that the unrolled loop body may need more registers than the original loop body. If the increased demand for registers induces additional register spills and restores, then the resulting memory traffic may overwhelm the potential benefits of unrolling.
These indirect interactions are much harder to characterize and understand than the direct effects. They can produce significant performance improvements. They can also produce performance degradations. The difficulty of predicting such indirect effects has led some researchers to advocate an adaptive approach to choosing unroll factors; in such systems, the compiler tries several unroll factors and measures the performance characteristics of the resulting code.
SECTION REVIEW
Section titled “SECTION REVIEW”Optimizations that focus on regions larger than a block and smaller than an entire procedure can find and capitalize on opportunities that a purely local algorithm cannot. These regional techniques have a long history in the literature and in practice.
In some cases, such as SVN, the extension to a regional scope provides increased optimization for little additional cost. Both SVN and superlocal instruction scheduling (see Section 12.4.1) have efficient implementations.
In other cases, regional optimizations apply more aggressive techniques to small regions in the code where the payoff may be large. Loop optimizations fit this mold. Many loop optimizations require extensive analysis to prove safety. Because so many programs spend a large part of their execution time inside loops, compiler writers have found these techniques to be profitable.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- Superlocal value numbering extends local value numbering to extended basic blocks through clever use of a scoped hash table. Consider the issues that might arise in extending the tree-height balancing algorithm to a superlocal scope.
a. How would your algorithm handle a single path through an EBB,such as(B0,B3,B4) in the control-flow graph shown in the margin?
b. What complications arise when the algorithm tries to process(B0,B3,B6) after processing(B0,B3,B4)?
- Loop unrolling always decreases loop overhead. Despite this fact, compilers do not unroll every loop. What factors should the compiler consider in deciding whether or not to unroll a given loop?
8.6 GLOBAL OPTIMIZATION
Section titled “8.6 GLOBAL OPTIMIZATION”Global optimizations operate on an entire procedure or method. Because their scope includes cyclic control-flow constructs such as loops, these methods typically complete an analysis phase before they rewrite the code.
This section presents two examples of global analysis and optimization. The first, finding uninitialized variables with live information, is not strictly an optimization. Rather, it uses global data-flow analysis to discover useful information about the flow of values in a procedure. We will use the discussion to introduce the notion of liveness, which plays a role in many optimization techniques, including tree-height balancing(Section 8.4.2), the construction of SSA form(Section 9.3), and register allocation(Chapter 13). The second, global code placement, uses profile information gathered from running the compiled code to rearrange the layout of the executable code.
8.6.1 Finding Uninitialized Variables with Live Sets
Section titled “8.6.1 Finding Uninitialized Variables with Live Sets”If a procedure can use some variable v before v has been assigned a value, we say that v is potentially uninitialized at that use. Use of an uninitialized variable almost always indicates a logical error in the procedure being compiled. If the compiler discovers such situations, it should alert the programmer to their existence.
We can find potential uses of uninitialized variables by computing information about liveness. A variable v is live at point p if and only if there exists a path in the CFG from p to a use of v along which v is not redefined. We e variable ariable v is live at point p if there exists th from p to a use of v along which v is edefined.
encode live information by computing, for each block b in the procedure, a set LIVEOUT(b) that contains all the variables that are live on exit from b.
Conceptually, the compiler can find uninitialized variables by adding an artificial entry node, n0, to the CFG and an edge from n0 to each actual entry node in the CFG. Then, LIVEOUT(n0) contains precisely those variables that can be used before they are defined.
In practice, since n0 would have no effect on the sets of the other nodes in the CFG, the compiler need not represent n0. It can solve for LIVEOUT ignoring n0. After that computation, it can calculate the value that LIVEOUT(n0)would have, if n0 existed. This approach should be marginally faster, since it avoids iterative evaluations of LIVEOUT(n0).
The computation of LIVEOUT sets is an example of global data-flow analysis, a family of techniques for reasoning, at compile time, about the flow of values at runtime. Problems in data-flow analysis are typically posed as a set of simultaneous equations over sets associated with the nodes and edges of a graph.
Defining the Data-Flow Problem
Section titled “Defining the Data-Flow Problem”Live variable analysis is a classic problem in global data-flow analysis. The compiler computes, for each node n in the procedure’s CFG, a set LIVEOUT(n) that contains all the variables that are live on exit from the block corresponding to n.
Data-flow problems are often defined by an equation over sets associated with the nodes of the CFG. For live variables, the following equation defines the LIVEOUT set for a node n:
LIVEOUT(n)=\bigcup_{m\in succ(n)}\left(\begin{array}[]{c}UEVAR(m)\cup\\ (LIVEOUT(m)\cap\overline{VARKILL(m)})\end{array}\right)where succ(n) refers to the set of CFG successors of n. The analysis should initialize LIVEOUT(n)= 0, .
Here, UEVAR(m) contains the upward-exposed variables in m-variables that are used in m before being defined in m. VARKILL(m) contains any variables defined in m; the overline on VARKILL(m) indicates its logical complement, the set of all variables not defined in m. The compiler must compute both UEVAR and VARKILL sets for each node in the CFG before it can solve the equations for LIVEOUT.
The equation encodes the definition of liveness in an intuitive way.LIVEOUT(n) is just the union of those variables that are live at the head
Data-flow analysis
a form of compile-time analysis for reasoning about the flow of values at runtime
// each block has k operations // of the form”x←y op z” for each block b do // Initialize the sets for b UEVAR(b)←∅ VARKILL(b)←∅ for i←1 to k do if y≠VARKILL(b) then add y to UEVAR(b) if z≠VARKILL(b) then add z to UEVAR(b) add x to VARKILL(b)
// assume the CFG has N blocks // numbered 0 to N-1 for i←0 to N-1 do LIVEOUT(i)←∅ changed←true while(changed) do changed←false for i←0 to N-1 do recompute LIVEOUT(i) if LIVEOUT(i) changed then changed←true
(a) Gathering Initial Information
(b) Solving the Equations
■ FIGURE 8.15 Iterative Live Analysis.
of some block m that immediately follows n in the CFG. The definition requires that a value be live on some path, not on all paths. Thus, the contributions of the successors of n in the CFG are combined to form LIVEOUT(n).The contribution of a specific successor m of n is:
UEVAR(m)∪(LIVEOUT(m)∩VARKILL(m))
A variable, v, is live on entry to m under one of two conditions. It can be used in m before it is defined in m: v∈UEVAR(m). It can be live on exit from m and pass unscathed through m because m does not redefine it: v∈LIVEOUT(m)∩VARKILL(m). Combining these two terms gives the contribution of m to LIVEOUT(n). To compute LIVEOUT(n), the analyzer computes the contribution of each of n’s successors, denoted m∈succ(n),and combines them with a union operation.
Solving the Data-Flow Problem
Section titled “Solving the Data-Flow Problem”To compute the LIVEOUT sets for a procedure and its CFG, the compiler can use a three-step algorithm.
-
Build a CFG The compiler steps through the blocks and builds the graph(see Section 4.4.4). Each node represents a block.
-
Gather Initial Information For each block b, the compiler computes UEVAR(b) and VARKILL(b), as shown in Fig. 8.15(a).
-
Solve the Equations for LIVEOUT(b) Fig. 8.15(b) shows a simple iterative fixed-point algorithm that will solve the equations.
| Iteration | B₀ | B₁ | B₂ | B₃ | B₄ |
|---|---|---|---|---|---|
| - | Ø | Ø | Ø | Ø | Ø |
| 1 | {i} | {s,i} | {s,i} | {s,i} | Ø |
| 2 | {s,i} | {s,i} | {s,i} | {s,i} | Ø |
| 3 | {s,i} | {s,i} | {s,i} | {s,i} | Ø |
■ FIGURE 8.16 Example LIVEOUT Computation.
The rest of this section works through an example LIVEOUT computation. Section 9.2 explores iterative data-flow analysis in more depth.
Gathering Initial Information
To compute LIVEOUT, the analyzer needs UEVAR and VARKILL sets for each block. A single pass can compute both. For each block, the analyzer initializes these sets to Ø. Next, it walks the block, in order from top to bottom, and updates both UEVAR and VARKILL to reflect the impact of each operation. Fig. 8.15(a) shows the details of this computation for operations of the form x ← y ⟨op⟩ z.
Consider the CFG shown in the margin. It consists of a simple loop that contains an if-then construct. The code abstracts away the details of the compares and branches. The table below the CFG shows the initial UEVAR and VARKILL sets.
Solving the LIVEOUT Equations
Given UEVAR and VARKILL sets for each node in the CFG, the compiler applies the algorithm from Fig. 8.15(b) to compute LIVEOUT sets for each node. It initializes all of the LIVEOUT sets to Ø. Next, it computes the LIVEOUT set for each block, in order. It repeats the process, computing LIVEOUT for each node in order until the LIVEOUT sets no longer change.
The table in Fig. 8.16 shows the values of the LIVEOUT sets at each iteration of the solver. Iteration zero shows the initial values. Iteration one computes an initial approximation to the LIVEOUT sets. Because it processes the blocks in ascending order of their labels, B₀, B₁, and B₂ receive values based solely on the UEVAR sets of their CFG successors. When the algorithm reaches B₃, it has already computed an approximation for LIVEOUT(B₁), so the value that it computes for B₃ reflects the contribution of the new value for LIVEOUT(B₁). LIVEOUT(B₄) is empty, as befits the exit block.
In the second iteration, the value s is added to LIVEOUT(B₀) as a consequence of its presence in the approximation of LIVEOUT(B₁). No other
UEVAR VARKILL
B₀ Ø (i) B₁ (i) Ø B₂ Ø (s) B₃ (s,i) (s,i) B₄ (s) Ø
Initial Sets
The theory of iterative data-flow analysis guarantees that the solution to this set of equations is unique(see also Section 9.2).
changes occur. The third iteration does not change the values of the LIVEOUT sets and the algorithm halts.
The order in which the algorithm processes the blocks affects the values of the intermediate sets. If the algorithm visited the blocks in descending order of their labels, it would require one fewer pass. However, the final values of the LIVEOUT sets are independent of the evaluation order. The iterative solver in Fig. 8.15 computes a fixed-point solution to the equations for LIVEOUT.
This iterative data-flow solver is a fixed-point algorithm. It halts because (1) the LIVEOUT sets are finite and (2) the recomputation of LIVEOUT for a block can either produce the same set or a larger set. The VARKILL and UEVAR sets are constant across all the iterations. The LIVEOUT sets increase monotonically; since their size is bounded, the algorithm must halt.
Finding Uninitialized Variables
Section titled “Finding Uninitialized Variables”Once the compiler has computed LIVEOUT sets for each node in the CFG, it must compute the set of variables that are live on entry to any of the CFG’s entry nodes. This set is equivalent to LIVEOUT(n0), if n0 were an artificial entry node with an edge to each actual entry node.
The example CFG has just one entry node, B0, so LIVEOUT(n0) is:
Inspection shows that s is uninitialized along the path .
This approach identifies variables that have a potentially uninitialized use. The compiler should recognize that situation and report it to the programmer. However, this approach may yield false positives for several reasons.
If a variable v is ambiguous, it could be initialized through another name. Live analysis will not connect the initialization and the use. This situation can arise when a pointer is set to the address of a local variable, as in the code fragment shown in the margin.
If a variable v exists before the current procedure is invoked, then it may have been previously initialized in a manner invisible to the analyzer. This case can arise with static variables of the current scope or with variables declared outside the current scope.
The equations for live analysis may discover a path from the procedure’s entry to a use of v along which v is not defined. If that path is not feasible at runtime, then v will still appear in LIVEOUT(n0) even though no execution will ever use the uninitialized value. For example, the C program in the margin always initializes s before its use, yet main(){ int s,i=1; while(i<=80){ if(i==1) s=0; s=s+i++; } printf(“%d”,s); } The marginal example with the while loop illustrates one of the fundamental limits of data-flow analysis: it assumes that all paths through the CFG are feasible at runtime. In the example, that assumption is too conservative. The only CFG path that leads to an uninitialized use runs from the entry of main into the loop, bypasses the initialization of s, and executes the increment of s. That path can never occur, because i must have the value 1 on the loop’s first iteration. The LIVEOUT solver cannot discover that fact because it has no mechanism to understand that the path is infeasible.
The assumption that all paths in the CFG are feasible greatly reduces the cost of the analysis. At the same time, the assumption produces a loss of precision in the computed sets. To discover that s is initialized on the first iteration of the while loop, the compiler would need to combine an analysis that tracked individual paths with some form of constant propagation and with live analysis. To solve the problem in a general way would require symbolic evaluation of parts of the code during the analysis, a much more expensive prospect.
Another kind of complication arises at a procedure call. If a procedure contains a call site, the analyzer must account for any side effects of that call. At a call site s, some global variable v might be either used or modified as the result of a call to s. (Similar issues arise if v is passed as a call-by-reference parameter or if the callee is nested inside the caller.) In the absence of specific information about the callee, the analyzer must assume that every variable that might be modified is modified and that any variable that might be used is used. Such assumptions are safe, in that they represent the worst-case behavior.
Other Uses for Live Variables
Section titled “Other Uses for Live Variables”Compilers use liveness in many other contexts.
■ The compiler can use live information to discover useless store operations. An operation that stores an unambiguous scalar variable v to memory is useless unless v is live at the store. A useless store can be deleted.
■ Live information can improve the speed and precision of the SSA construction; a value only needs a φ-function in a block where it is live. Eliminating nonlive φ-functions can significantly reduce the number of φ-functions that the compiler inserts.
■ Live-variable information plays a critical role in global register allocation (see Section 13.4). The allocator need not preserve values in regions where they are not live. Live information forms the basis for reasoning about which values to keep in registers.
Live range The live range of a value is the set of operations that lie between its definitions and its uses.
In different contexts, liveness is calculated for different sets of names. We have discussed LIVEOUT with an implicit domain of variable names. In global register allocation, the compiler computes LIVEOUT sets over a carefully constructed set of values, called live ranges.
8.6.2 Global Code Placement
Section titled “8.6.2 Global Code Placement”Many processors have asymmetric branch costs; the cost of the fall-through path is less than the cost of the taken branch. Each branch has two successor basic blocks; the compiler can choose which block lies on the fall-through path and which lies on the taken path. The global code-placement optimization relies, implicitly, on the twin observations that branches have asymmetric costs and that some decisions in the code have lopsided execution frequencies.
Consider the CFG shown in the margin. (B0,B3) executes 100 times more often than (B0,B1). If branch costs are asymmetric, the compiler should use the less expensive branch for (B0,B3). If (B0,B1) and (B0,B3) have roughly equal execution frequencies, then that choice would have little impact for this example.
Two different layouts for this code are shown in the margin. The “slow” layout uses the fall-through branch to implement (B0,B1) and the taken branch for (B0,B3). The “fast” layout reverses this decision. If the fall-through branch is faster than the taken branch, then the “fast” layout uses the less expensive branch 100 times more often.
The compiler can take advantage of asymmetric branch costs. If the compiler knows the expected relative execution frequencies of the branches in a procedure, it can lay out the code for faster execution.
To perform global code placement, the compiler reorders the basic blocks of a procedure according to two principles: First, the compiler should make the most likely execution paths use fall-through branches. Thus, whenever possible, a block should be followed immediately by its most frequent successor. This placement has two benefits. A larger portion of executed branches take the faster (fall-through) path, directly reducing execution time. Placing consecutive blocks in consecutive virtual memory addresses should also improve instruction cache locality. Second, the compiler should move infrequently executed code (cold code) to the end of the procedure. This action places frequently executed code (hot code) near other hot code and cold code away from the hot code.
GATHERING PROFILE DATA Profile data plays an important role in optimizations such as global code placement or inline substitution (see Section 8.7.1). Several approaches are used to gather profile data.
■ Instrumented Executables The compiler can generate code to count specific events, such as procedure entries and exits or taken branches. At the end of execution, the data is written to an external file and processed offline by another tool.
■ Timer Interrupts The profile tool can interrupt program execution at regular, frequent intervals. The tool constructs a histogram of program counter locations where the interrupts occurred. Again, postprocessing constructs a profile.
■ Performance Counters Most processors support hardware counters that record specific events, such as taken branches. The runtime system can use counters to construct accurate profile-like data.
Each approach produces slightly different data. An instrumented executable can measure many different runtime properties. A timer-interrupt system may have lower overhead, but only finds frequently executed statements (not the paths taken to reach them). Hardware counters are accurate and efficient, but depend in idiosyncratic ways on the specific processor.
Each of these approaches works. Each of them requires cooperation between the compiler and the profiling tool on issues such as data formats, code layout, and methods for mapping runtime locations back to locations in the source code or the IR.
This placement can reduce the working-set size of the hot code, which can, in turn, improve locality in cache and virtual memory.
After placement, the code should execute longer sequences of operations without disruption—a taken branch, a stall due to an instruction cache fault, or a stall due to a page fault.
Code placement, like most global optimizations, has separate analysis and transformation phases. The analysis phase constructs branch execution frequency estimates. The transformation phase uses that data, expressed as weights on CFG edges, to discover the frequently executed paths. It then reorders the basic blocks from that model.
Obtaining Profile Data For global code placement, the compiler needs estimates of the relative execution frequency of each edge in the CFG. It can obtain that information
E←|edges|
for each block b do
create a degenerate chain, d, for b
priority(d)←E
P←0
for each CFG edge(x,y),x≠y, in decreasing frequency order do
if x is the tail of chain a and y is the head of chain b then
t←priority(a)
append b onto a
priority(a)←min(t, priority(b),P++)
else priority(b)←min(priority(b),P++)
FIGURE 8.17 Building Hot Paths.
Section titled “FIGURE 8.17 Building Hot Paths.”from a profiling run of the code: compile the entire program, run it under a profiling tool on representative data, and give the compiler access to the resulting profile data. It can obtain that information from a model of program execution; such models range from simple to elaborate, with a range of accuracies.
Specifically, the compiler needs execution counts for the CFG edges. The CFG in the margin illustrates why edge counts are superior to block counts for code placement. From the execution counts, shown as labels on the edges, we see that blocks B0 and B3 each execute ten times. The path(B0,B1,B2,B3) executes more than any other path in this CFG fragment. The edge counts suggest, for example, that making B2 the fall-through case of the branch at the end of B1 is better than making it the taken case.
Using execution counts for blocks rather than edges can be misleading; a block’s count can combine counts from multiple paths. In the CFG, the block counts for B2 and B4 would each be 5. For the branch at the end of B1, those block counts suggest that the paths to B2 and B4 are of equal importance, while the edge counts show that(B1,B2) executes more often than(B1,B4). The code-placement algorithm ranks edges by frequency of execution; thus, the increased accuracy from the edge counts has a direct effect on the quality of the results.
Constructing Chains as Hot Paths in the CFG
Section titled “Constructing Chains as Hot Paths in the CFG”To determine the code layout, the compiler finds hot paths through the CFG-paths that contain the most frequently executed edges. Each path is a chain of one or more blocks. The algorithm assigns a priority to each path;the priorities drive the code reordering process.
Example CFG
(a) Example CFG
(b) Steps of the Hot-Path Building Algorithm on the Example
| Edge | Set of Chains | P |
|---|---|---|
| (B0,E.(B1)E.(B2)E.(B5)E.(B4)E | 0 | |
| (B0,B1) | (B0,B1)0.(B2)E.(B5)E.(B5)E.(B4)E | 1 |
| (B2,B3) | (B0,B1)0.(B2,B3)1.(B5)E.(B4)E | 2 |
| (B4,B3) | (B0,B1)0.(B2,B3)1.(B5)E.(B4)E | 3 |
| (B1,B2) | (B0,B1,B2,B3)0.(B5)E.(B4)E | 4 |
| (B0,B5) | (B0,B1,B2,B3)0.(B5)4.(B4)E | 5 |
| (B5,B4) | (B0,B1,B2,B3)0.(B5,B4)4 | 6 |
| (B1,B4) | (B0,B1,B2,B3)0.(B5,B4)4 | 7 |
■FIGURE 8.18 Example of the Hot-Path Building Algorithm.
The compiler can use a greedy algorithm to find hot paths, as shown in Fig. 8.17. To begin, it creates a degenerate chain for each block that contains exactly that block. It sets the priority for each degenerate chain to a large number, such as the number of edges in the CFG or the largest integer.
Next, the algorithm iterates over the edges in the CFG and builds up chains to model the hot paths. It takes the edges in order of decreasing execution frequency. For an edge,(x,y), the algorithm merges the chain containing x with the chain containing y if and only if x is the last node in its chain and y is the first node in its chain. If either condition is not true, it leaves the chains that contain x and y alone.
If the algorithm merges the chains for x and y, it must assign the new chain an appropriate priority. It computes that priority as the minimum of the priorities of the chains for x and y. If both x and y are degenerate chains with their initial high priority, the algorithm sets the priority of the new chain to the ordinal number of merges that it has considered, denoted as P. The effect of this choice is to place the new chain behind chains constructed from higher-frequency edges and ahead of those constructed from lower-frequency edges.
The algorithm halts after it examines every edge. It produces a set of chains that model the hot paths in the CFG. Each node belongs to exactly one chain. Edges in chains execute more often than edges that cross from one chain to another. The priority values of the chains approximate an order that would maximize the number of executed forward branches.
To illustrate the algorithm’s operation, consider its behavior when applied to the example CFG from the previous section, which appears in Fig. 8.18(a).
The algorithm ignores self loops.(x,x).because they do not affect placement decisions.
Forward branch
A forward branch is one whose target has a higher address than its source. In some ISAs, forward branches are faster than backward branches.
t ← chain headed by the CFG entry node WorkList ← {(t, priority(t))} while (Worklist ≠ ∅) do remove a chain c of lowest priority from WorkList for each block x in c in chain order do place x at the end of the executable code for each block x in c do for each edge ⟨x, y⟩ where y is unplaced do t ← chain containing y if (t, priority(t)) ≠ WorkList then WorkList ← WorkList ∪ {(t, priority(t))}
■ FIGURE 8.19 Code-Layout Algorithm.
Panel (b) shows the algorithm’s progress on the example. Priorities are shown as subscripts on chains. E is |edges|.
Tie breaking among equal-priority chains can lead to different layouts. For example, if the algorithm chooses (B₄, B₃) before (B₂, B₃), then it builds the chains: ⟨B₀, B₁, B₂⟩₀ and ⟨B₅, B₄, B₃⟩₁. Different chains may produce different layouts. The algorithm still produces good results, even with a nonoptimal ordering for the equal-weight edges.
Performing Code Layout
Section titled “Performing Code Layout”The set of chains produced by the hot-path algorithm constitutes a partial order on the set of basic blocks. To produce the executable code, the compiler must place all of the blocks into a fixed linear order. Fig. 8.19 shows an algorithm that computes a linear layout from the set of chains. It encodes two simple heuristics: (1) place the blocks of a chain in order, so that fall-through branches implement the chain’s edges, and (2) place chains in priority order, lowest to highest.
The implementation can use a sparse set for the worklist (see Appendix B.2.3).
The algorithm represents a chain as a pair, (l, p) where l is a list of blocks and p is the chain’s priority. Each chain should enter the worklist exactly once. The following table shows the algorithm’s behavior on the set of chains derived in Fig. 8.18(b):
Step WorkList Code Layout --- ⟨B₀, B₁, B₂, B₃⟩₀ 1 ⟨B₅, B₄⟩₄ B₀, B₁, B₂, B₃ 2 ∅ B₀, B₁, B₂, B₃, B₅, B₄ The first line shows the initial state; the worklist starts with the chain that contains . The algorithm removes that chain from the worklist and places all its blocks, in order. Next, it processes the edges that leave the already placed blocks. These edges add the chain to the worklist.
The second iteration removes from the worklist and places and at the end of the layout. It finds no edges that lead to unplaced blocks, so the algorithm halts.
If, instead, the algorithm had produced the chains and , the final layout would have been different.
Step WorkList Code Layout
1 2
If we assume that the estimated execution frequencies are correct, there is no reason to prefer one layout over the other.
A Final Example As a final example, consider the CFG shown in the margin. The first step in the placement algorithm is to apply the hot-path algorithm. It proceeds as follows:
Edge Set of Chains P
1 0 2 1 3 2 4 3 5 4 6 6
The algorithm halts with one multinode chain and two degenerate chains. It captures the fact that accounts for most of the executions and that both and execute infrequently.
The layout algorithm first places . When it processes the outbound edges from those nodes, it adds both of the degenerate blocks to the worklist. The next two iterations remove and place and then .
SECTION REVIEW
Section titled “SECTION REVIEW”Optimizations that examine an entire procedure have opportunities for improvement that are not available at smaller scopes. Because the global, or whole-procedure, scope includes cyclic paths, global optimizations usually need global analysis. As a consequence, these algorithms typically have an offline flavor; they analyze the code before they transform it.
This section highlighted two distinct kinds of analysis: global data-flow analysis and runtime collection of profile data. Data-flow analysis is a compile-time technique that accounts, mathematically, for the effects along all possible paths through the code. By contrast, profile data records what actually happened on a single run of the code, with a single set of input data. Data-flow analysis is conservative, in that it accounts for all possibilities. Runtime profiling is aggressive, in that it assumes that future runs will share runtime characteristics with the profiling run. Both kinds of information can play an important role in optimization.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- In some situations, the compiler needs to know that a variable is live along all paths that leave a block, rather than live along some path. Re-formulate the equations for LIVEOUT so that they compute the set of names that are used before definition along every path from the end of the block to the CFG’s exit node, .
- To collect accurate edge-count profiles, the compiler can instrument each edge in the profiled procedure’s CFG. A clever implementation can instrument a subset of those edges and deduce the counts for the rest. Devise a scheme that derives accurate edge-count data without instrumenting each branch. On what principles does your scheme rely?
8.7 INTERPROCEDURAL OPTIMIZATION
Section titled “8.7 INTERPROCEDURAL OPTIMIZATION”As discussed in Chapter 6, procedure calls form boundaries in software systems. The division of a program into multiple procedures has both positive and negative impacts on the compiler’s ability to generate efficient code. On the positive side, it limits the amount of code that the compiler considers at any one time. This effect keeps compile-time data structures small and limits the cost of compile-time algorithms by limiting the problem sizes.
On the negative side, procedure calls make compile-time knowledge less precise. For example, consider a call from fee to fie that passes a variable x as a call-by-reference parameter. If the compiler knows that x has the value 15 before the call, it cannot use that fact after the call, unless it knows that the call cannot change x. To use x’s value after the call, the compiler must prove that the formal parameter corresponding to x is not modified by fie or any procedure fie calls, directly or indirectly.
Procedure calls also introduce direct costs in the precall, postreturn, prolog, and epilog sequences (see Section 6.5). These sequences consist of multiple operations, each of which takes time to execute. The transitions between these sequences require jumps. In the general case, all of these operations are needed. For any specific call, however, the compiler may be able to tailor either the sequences or the body of the callee to the actual context and achieve better performance.
Procedures and procedure calls introduce inefficiencies that intraprocedu-ral optimization cannot address. To reduce some of these inefficiencies, the compiler can analyze and transform multiple procedures together, using interprocedural analysis and optimization. These techniques are equally important in Algol-like languages and in object-oriented languages.
This section presents two different interprocedural optimizations: inline substitution of procedure calls and procedure placement for improved code locality. Because whole-program optimization requires that the compiler has access to the code being analyzed and transformed, the decision to perform whole-program optimization has implications for the structure of the compiler. Thus, the final subsection discusses the structural issues that arise in a system that includes interprocedural analysis and optimization.
8.7.1 Inline Substitution
Section titled “8.7.1 Inline Substitution”As we saw in Chapters 6 and 7, procedure linkage code involves a significant number of operations. The linkage code allocates an activation record, evaluates each actual parameter, preserves the caller’s state, creates the callee’s environment, transfers control from the caller to the callee and back, restores the caller’s state, and, if necessary, returns values from the callee to the caller. These runtime actions are part of the overhead of using a high-level language; they maintain programming-language abstractions but are not strictly needed to compute the results. Optimizing compilers try to reduce the cost of such overheads.
In some cases, the compiler can improve the efficiency of the final code by replacing a call site with a copy of the callee’s body, appropriately tailored to the context at the call site. This transformation, called inline substitution, lets the compiler eliminate much of the code in the linkage sequences and tailor the new copy of the callee’s body to the caller’s context. Because Interprocedural data-flow analysis is discussed in Sections 9.2.4 and 9.4.
Inline substitution a transformation that replaces a call site with a copy of the callee’s body, rewritten to reflect the parameter bindings
(a) Original Code
(b) After Inlining foe into fie
Figure 8.20 Inline Substitution Example.
inline substitution moves code from one procedure to another and alters the program’s call graph, it is inherently an interprocedural transformation.
The implementation of inline substitution partitions naturally into two sub-problems: the actual transformation and a decision procedure that chooses which call sites to inline. The transformation itself is relatively simple. The decision procedure is more complex. The specific choices have a direct impact on the transformation’s effectiveness.
The Transformation
Section titled “The Transformation”To perform inline substitution, the compiler rewrites a call site with the body of the callee, while making appropriate modifications to model the effects of parameter binding. Fig. 8.20(a) shows two procedures, fee and fie, both of which call a third procedure, foe. Panel (b) depicts the control flow after inlining the call from fie to foe. The compiler has created a copy of foe and moved it inside fie, connected fie’s precall sequence directly to the prolog of its internal copy of foe and connected the epilog to the postreturn sequence in a similar fashion. Some of the resulting blocks can be merged, enabling improvement with subsequent optimization. Of course, the compiler must use an IR that can represent the inlined procedure. Some source-language constructs can create arbitrary and unusual control-flow constructs in the resulting code. For example, a callee with multiple premature returns may generate a control-flow graph (CFG) that is hard to represent in a near-source IR.
In the transformation, the compiler writer should pay attention to the proliferation of local variables. A simple implementation would create one new local variable in the caller for each local variable in the callee. If the compiler inlines several procedures, or several call sites to the same callee, the local name space can grow quite large. While growth in the name space is not a correctness issue, it can significantly increase the compile time of transformed code.
The Decision Procedure
Section titled “The Decision Procedure”Choosing which call sites to inline is a complex task. Inlining a given call site can improve performance; unfortunately, it can also degrade performance. To make intelligent choices, the compiler must consider a broad range of characteristics of the caller, the callee, and the call site. The compiler must also understand its own strengths and weaknesses.
The primary sources of improvement from inlining are direct elimination of operations and improved effectiveness of other optimizations. The former effect can occur when parts of the linkage sequence can be eliminated; for example, register save and restore code might be eliminated in favor of allowing the register allocator make those decisions. Knowledge from the caller may prove code in the callee to be dead or useless. More precise knowledge may also expose constant values or redundancies.
The primary source of degradation from inline substitution is decreased effectiveness of code optimization on the resulting code. Inlining the callee can increase code size and name space size. It can increase demand for registers in the neighborhood of the original call site. Eliminating the register save and restore code changes the problem seen by the register allocator. In practice, any of these can lead to a decrease in optimization effectiveness.
At each call site, the compiler must decide whether or not to inline the call. To complicate matters, a decision made at one call site affects the decision at other call sites. For example, if a calls b which calls c, choosing to inline c into b changes both the characteristics of the procedure that might be inlined into a and the call graph of the underlying program. Furthermore, inlining has effects, such as code size growth, that must be viewed across the whole program; the compiler writer may want to limit the overall growth in code size.
If the compiler uses data-flow analysis, growth in the name space appears as growth in the sizes of the sets used to solve data-flow problems. A typical data-flow problem uses several sets per node in the CFG. Inline any call site that matches one of the following:
(1) The callee uses more than t0 percent of execution time, and (a) the callee contains no calls, or (b) the static call count is one, or (c) the call site has more than t1 constant-valued parameters
(2) The call site represents more than t2 percent of all calls, and (a) the callee is smaller than t3, or (b) inlining the call will produce a procedure smaller than t4
■ FIGURE 8.21 A Typical Decision Heuristic for Inline Substitution.
Decision procedures for inline substitution examine a variety of criteria at each call site. These include:
■ Callee Size If the callee is smaller than the code in the linkage sequence, then inlining the callee should reduce both the code size and the number of operations executed. This situation arises surprisingly often.
■ Caller Size The compiler may limit the overall size of any procedure to mitigate increases in compile time and decreases in optimization effectiveness.
■ Dynamic Call Count An improvement to a frequently executed call provides greater benefit than the same improvement to a rarely executed call. In practice, compilers use either profile data or simple estimates, such as 10 times the call site’s loop nesting depth.
■ Constant-Valued Actual Parameters If some actual parameters have known constant values, the transformed code can fold those constants directly into the callee’s body.
■ Static Call Count Compilers often track the number of distinct sites that call a procedure. Any procedure called from just one call site can be inlined without any code space growth.
■ Parameter Count The number of parameters can serve as a proxy for the cost of the procedure linkage, as the compiler must generate code to evaluate and store each actual parameter.
■ Calls in the Procedure Tracking the number of calls in a procedure provides an easy way to detect leaves in the call graph. Leaf procedures are often good candidates for inlining.
■ Loop Nesting Depth Call sites in loops execute more frequently than call sites outside loops. They also disrupt the compiler’s ability to schedule the loop as a single unit(see Section 12.4).
■ Fraction of Execution Time Computing the fraction of execution time spent in each procedure from profile data can prevent the compiler from inlining routines that cannot have a significant impact on performance.
As inlining proceeds, the compiler may need to update these metrics. For example, inlining b into a will change both the static call count metric for b and the calls in the procedure metric for a.
In practice, compilers precompute some or all of these metrics and then apply a set of heuristics to determine which call sites to inline. Fig. 8.21 shows a typical heuristic. It relies on a series of threshold parameters, named t0 through t4. The specific values chosen for the parameters will govern much of the heuristic’s behavior; for example, t3 should have a value greater than the size of the standard precall and postreturn sequences. The best settings for some of these parameters are almost certainly program specific.
8.7.2 Procedure Placement
Section titled “8.7.2 Procedure Placement”The global code placement technique in Section 8.6.2 rearranged blocks within a single procedure. The analogous whole-program problem is to rearrange the procedures in an executable:
Given the call graph for a program, annotated with execution frequencies for each call site, rearrange the procedures to reduce virtual-memory working-set sizes and to limit the potential for call-induced conflicts in the instruction cache.
The principle is simple. If procedure p calls procedure q and the compiler places them next to each other in memory, then they should not conflict in the instruction cache unless size(p)+size(q) is greater than the cache size. Adjacent placement also increases the likelihood that p and q are located in the same virtual memory page, which can reduce working set size and page faults. Thus, the algorithm tries to maximize the number of calls for which the caller and callee are adjacent.
To compute a placement, the algorithm treats the program’s call graph as a set of constraints on the relative placement of procedures in the executable code. Each call-graph edge,(p,q), specifies an adjacency that should occur in the executable code. Unfortunately, the compiler cannot satisfy all of those adjacencies. For example, if p calls q,r, and s, the compiler cannot place all three of them next to p. The algorithm uses a greedy approximate technique to find a good placement, rather than trying to compute an optimal placement.
Procedure placement differs subtly from the global code placement problem discussed in Section 8.6.2. The global algorithm improves the code by ensuring that hot paths can be implemented with fall-through branches. Thus, the chain-construction algorithm in Fig. 8.17 ignores any CFG edge unless Virtual-to-physical address mapping may complicate that statement, but cache asso-ciativity should mitigate the issue.
Recall that a program’s call graph has a node for each procedure and an edge(r,y)for each call from x to y.
// Initialization work build the call multi-graph G initialize Q as a priority queue // Order Q highest to lowest for each edge(x,y)∈G do // Add weights to the edges if(x=y) then // Self loop is irrelevant delete(x,y) from G else weight((x,y))← estimated execution frequency for (x,y) for each node x∈G do list(x)←(x) // Initialize placement lists if multiple edges exist from x to y then combine them and their weights for each edge(x,z)∈G do // Put each edge into Q Enqueue(Q,(x,z), weight((x,z))) // Iterative reduction of the graph while Q is not empty do (x,y)←Dequeue(Q) // Take highest priority edge for each edge(y,z)∈G do // Move source from y to x ReSource((y,z),x) for each edge(z,y)∈G do // Move target from y to x ReTarget((z,y),x) append list(y) to list(x) // Update the placement list delete y and its edges from G // Clean up G
■ FIGURE 8.22 Analysis Phase of the Procedure Placement Algorithm.
it runs from the tail of one chain to the head of another. By contrast, as the procedure placement algorithm builds chains of procedures, it can use edges that run between procedures that lie in the middles of their chains because its goal is simply to place procedures near each other-to reduce working set sizes and to reduce interference in the instruction cache. If p calls q and the distance from p to q is less than the cache size, placement achieves its objectives. Thus, in some sense, the procedure placement algorithm has more freedom than the block-layout algorithm.
Procedure placement consists of two phases: analysis and transformation. The analysis operates on the program’s call graph. It repeatedly selects two call graph nodes that are connected by an edge and combines them. The order of combination is driven by execution frequency data, either measured or estimated. The order of combination determines the final layout. The layout phase is straightforward; it simply rearranges the code for the procedures into the order chosen by the analysis phase. Fig. 8.22 shows a greedy algorithm for the analysis phase of procedure placement. It constructs a placement by considering call-graph edges in order of decreasing execution frequency. As a first step, it builds the call graph, annotates each edge with its estimated execution frequency, and combines all the edges between two nodes into a single edge. As the final part of its initialization work, it builds a priority queue of the call-graph edges, ordered by their weights.
The second half of the algorithm iteratively constructs an order for procedure placement. The algorithm associates with each node in the graph an ordered list of procedures. These lists specify a linear order among the named procedures. When the algorithm halts, the lists will specify a total order on the procedures in each node that can be used to place them in the executable code.
The algorithm uses the call-graph edge weights to guide the process. It repeatedly selects the highest-weight edge, say (x,y), from the priority queue and combines its source x and its sink y. Next, it must update the call graph to reflect the change.
-
For each edge (y,z), it calls ReSource to replace (y,z) with (x,z) and to update the priority queue. If (x,z) already exists, ReSource combines the execution counts of (y,z) and the existing (x,z).
-
For each edge (z,y), it calls ReTarget to replace (z,y) with (z,x) and to update the priority queue. If (z,x) already exists, ReTarget combines the execution counts of (z,y) and the existing (z,x).
To force the placement of y after x, the algorithm appends list(y) to list(x). Finally, it deletes y and its edges from the call graph.
The algorithm halts when the priority queue is empty. The final graph has one node for each of the connected components of the original graph. If all nodes are reachable from the program’s entry, the final graph consists of a single node. If some nodes are not reachable, either because no path in the program calls them or because those paths are obscured by ambiguous calls, then the final graph will consist of multiple nodes. Either way, the compiler and linker can use the lists associated with nodes in the final graph to specify the relative placement of procedures.
Figure 8.23 shows the steps of the procedure placement algorithm. Each row shows the remaining graph, the current lists of merged procedures, and the priority queue of weighted edges.
Initial: List(x): {P0} {P1} {P2} {P3} {P4} {P5} {P6} Q: (P5,P6)104, (P5,P4)52, (P1,P2)20, (P1,P4)10, (P1,P3)10, (P0,P1)10, (P0,P5)2
1: List(x): {P0} {P1} {P2} {P3} {P4} {P5,P6} Q: (P5,P4)52, (P1,P2)20, (P1,P4)10, (P1,P3)10, (P0,P1)10, (P0,P5)2
2: List(x): {P0} {P1} {P2} {P3} {P5,P6,P4} Q: (P1,P2)20, (P1,P5)10, (P1,P3)10, (P0,P1)10, (P0,P5)2
3: List(x): {P0} {P1,P2} {P3} {P5,P6,P4} Q: (P1,P5)10, (P1,P3)10, (P0,P1)10, (P0,P5)2
4: List(x): {P0} {P1,P2,P5,P6,P4} {P3} Q: (P0,P1)12, (P1,P3)10
5: List(x): {P0,P1,P2,P5,P6,P4} {P3} Q: (P0,P3)10
6: List(x): {P0,P1,P2,P5,P6,P4,P3} Q: emptyFigure 8.23: Steps of the Procedure Placement Algorithm.
frequencies. A self-loop cannot affect placement since its source and sink are identical.
Panel 0 shows the state of the algorithm immediately before the iterative reduction begins. Each node has the trivial list that contains its own name. The priority queue has every edge, except the self loop, ranked by execution frequency.
Panel 1 shows the state of the algorithm after the first iteration of the while loop. The algorithm collapsed P6 into P5, and updated both the list for P5 and the priority queue.
In panel 2, the algorithm has collapsed P4 into P5. It retargeted(P1,P4) onto P5 and changed the corresponding edge name in the queue. It also removed P4 from the graph and updated the list for P5.
The other iterations proceed in a similar fashion. Panel 4 shows a situation where the algorithm combined edges. When it collapsed P5 into P1, it retar-geted(P0,P5) onto P1. Since(P0,P1) already existed, it simply combined their weights and updated the priority queue by deleting(P0,P5) and changing the weight on(P0,P1).
At the end of the iterations, the graph has been collapsed to a single node, P0.While this example constructed a layout that begins with the entry node, that happened because of the edge weights rather than by algorithmic design.
8.7.3 Pragmatics of Interprocedural Optimization
Section titled “8.7.3 Pragmatics of Interprocedural Optimization”Building a compiler that performs analysis and optimization across two or more procedures fundamentally changes the relationship between the compiler and the code that it produces. Traditional compilers have compilation units of a single procedure, a single class, or a single file of code; the resulting code depends solely on the contents of that compilation unit. Once the compiler uses knowledge about one procedure to optimize another, the correctness of the resulting code depends on the state of both procedures.
Consider the impact of inline substitution on the validity of the optimized code. Assume that the compiler inlines fie into fee. Any subsequent editing change to fie will necessitate recompilation of fee-a dependence that results from an optimization decision rather than from any relationship exposed in the source code.
If the compiler collects and uses interprocedural information, similar problems can arise. For example, fee may call fie, which calls foe; assume that the compiler relies on the fact that the call to fie does not change the known constant value of the global variable x. If the programmer subsequently edits Compilation unit The portion of a program presented to the compiler is often called a compilation unit.
foe so that it modifies x, that change can invalidate the prior compilations of both fee and fie by changing the facts upon which optimization relies. Thus, a change to foe can necessitate a recompilation of other procedures in the program.
To make interprocedural optimization practical, manage recompilation, and provide the necessary source code access, researchers have proposed a variety of different scenarios. These include using larger compilation units, integrating the compiler into a development environment, performing link-time optimization, and relying on just-in-time compilation for interprocedu-ral optimizations.
Enlarging Compilation Units
Section titled “Enlarging Compilation Units”The simplest solution to the practical problems introduced by interpro-cedure optimization is to enlarge the compilation units. If the compiler only considers optimization and analysis within a compilation unit, it can sidestep the issue of recompilation. It can limit its analysis and optimization to code that is compiled together; then, it will not introduce dependences between compilation units and it should not require access to information about other units. The IBM PL/I optimizing compiler took this approach;code quality improved as related procedures were aggregated into the same file.
Of course, this approach limits the opportunities for interprocedural optimization. It also encourages the programmer to create larger compilation units and to group together procedures that call one another. Both of these may introduce practical problems in a system with multiple programmers. Still, as a practical matter, this organization is attractive because it is a minor change from traditional models of compilation.
Integrated Development Environments
Section titled “Integrated Development Environments”If the compiler is embedded inside an integrated development environment(IDE), the compiler can access code as needed through the IDE. The IDE can notify the compiler when source code changes so that the compiler can determine if recompilation is needed. This model shifts ownership of both the source code and the compiled code from the developer to the IDE. Col-laboration between the IDE and the compiler then ensures that appropriate actions are taken to guarantee consistent and correct optimization.
Link-Time Optimization
Section titled “Link-Time Optimization”The compiler writer can shift interprocedural optimization into the linker, where it will have access to all of the statically linked code. To obtain the full benefits of this approach, the linker may also need to perform subsequent global optimization. Since the results of link-time optimization are recorded in the executable, and that executable is discarded on the next compilation, this strategy sidesteps the recompilation problem. It almost certainly performs more analysis and optimization than the other approaches, but it offers both simplicity and obvious correctness.
Just-In-Time Compilation
Section titled “Just-In-Time Compilation”An environment that performs runtime optimization faces a different set of opportunities and constraints (see Chapter 14). At runtime, all of the code for the application is available; there is no issue with access. The just-in-time compiler can optimize across procedure boundaries. The system discards JIT-compiled code at the end of execution, so recompilation concerns only arise from changes in the code made during execution—changes that can be handled through careful deoptimization (see the discussion on page 742).
At the same time, JITs operate under time constraints that almost certainly prevent the JIT from applying classic whole-program analyses such as computing summary information or performing interprocedural constant propagation. Runtime optimization systems tend to be profile driven; they are more likely to find and optimize specific hot calls than they are to discover that some subpart of the call tree is side-effect free. Despite these limitations, JIT-based systems can profit from selective application of interprocedural optimizations. These systems do use interprocedural methods; they do so precisely because it is profitable.
A hot-trace optimizer can easily build traces that cross procedure calls (see Section 14.3). Hot-method optimizers often include inline substitution to lower the cost of dynamic dispatch (see Section 14.4).
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”-
Suppose procedure a invokes b and c. If the compiler inlines the call to b, what code space and data space savings might arise? If it inlines c as well, are further data-space savings possible?
-
In procedure placement, what happens to a procedure whose incoming edges all have estimated execution frequencies of zero? Where should the algorithm place such a procedure? Does the treatment of such a procedure affect execution time performance? Can the compiler eliminate them as useless?
8.8 SUMMARY AND PERSPECTIVE
Section titled “8.8 SUMMARY AND PERSPECTIVE”The optimizer in a typical compiler contains a collection of techniques that try to improve the performance of the compiled code. While most optimizations try to improve runtime speed, optimizations can also target other measures, such as code size or energy consumption. This chapter has shown a variety of techniques that operate over scopes that range from single basic blocks through entire programs.
Optimizations improve performance by tailoring general translation schemes to the specific details of the code at hand. The transformations in an optimizer try to remove the overhead introduced in support of source-language abstractions, including data structures, control structures, and error checking. They try to recognize special cases that have efficient implementations and rewrite the code to realize those savings. They try to match the resource needs of the program against the actual resources available on the target processor, including functional units, the capacity and bandwidth of each level in the memory hierarchy(registers, cache, translation lookaside buffers, and memory), and instruction-level parallelism.
Before the optimizer can apply a transformation, it must determine that the proposed rewrite of the code is safe-that it preserves the code’s original meaning. Typically, the optimizer must analyze the code to prove safety. In this chapter, we saw a number of approaches to proving safety, ranging from the bottom-up construction of the value table in local value numbering through computing LIVEOUT sets to detect uninitialized variables.
Once the optimizer has determined that it can safely apply a transformation, it must decide whether or not the rewrite will improve the code. Some techniques, such as local value numbering, simply assume that the rewrites they use are profitable. Other techniques, such as inline substitution, require complicated decision procedures to determine when a transformation might improve the code.
This chapter provided a basic introduction to the field of compiler-based code optimization. It introduced many of the terms and issues that arise in optimization. It does not include an “Advanced Topics” section; instead, the interested reader will find additional material on static analysis in support of optimization in Chapter 9 and on optimizing transformations in Chapter 10.
CHAPTER NOTES
Section titled “CHAPTER NOTES”The field of code optimization has a long and detailed literature. For a deeper treatment, the reader should consider some of the specialized books on the subject [21,277,279]. It would be intellectually pleasing if code optimization had developed in a logical and disciplined way, beginning with local techniques, extending them first to regions, then to entire procedures, and finally to entire programs. As it happened, however, development occurred in a more haphazard fashion. For example, the original Fortran compiler [28] performed both local and global optimization—the former on expression trees and the latter for register allocation. Interest in both regional techniques, such as loop optimization [260], and interprocedural techniques, such as inline substitution, crops up early in the literature, as well [17].
Local value numbering, with its extensions for algebraic simplifications and constant folding, is usually credited to Balke in the late 1960s [17,94], although it is clear that Ershov achieved similar effects in a much earlier system [150]. Similarly, Floyd mentioned the potential for both local redundancy elimination and application of commutativity [160]. The extension to EBBs in superlocal value numbering is natural and has, undoubtedly, been invented and reinvented in many compilers. Our treatment derives from Simpson [59].
The tree-height balancing algorithm is due to Hunt and McKinley [105]; it uses a rank function inspired by Huffman codes, but is easily adapted to other metrics. The classic algorithm for balancing instruction trees is due to Baer and Bovet [30]. In practice, the tree-height balancing algorithm might be best applied just before scheduling.
Loop unrolling is the simplest loop nest optimization. It has a long history in the literature [17]. Several authors have studied selection of unroll factors [130,337]. The use of unrolling to eliminate register-to-register copy operations as in Review Question 2 for Section 8.5 is from Kennedy [225]. Unrolling can have subtle and surprising effects [118].
The ideas that underlie live analysis have been around as long as compilers have been automatically allocating storage locations for values[250].Beatty first defined live analysis in an internal IBM technical report[16].Lowry and Medlock discuss “busy” variables[260] and the use of this information in both dead-code elimination and reasoning about interference(see Chapter 13). The formulation of liveness as a global data-flow problem appeared by 1971[14,224]. It plays a key role in many optimizations(see, for example, Sections 9.3 and 13.4).
The code-placement algorithms, at both the global and whole-program scopes, are taken from Pettis and Hansen[293]. Subsequent work on this problem has focused on collecting better profile data and improving the placements[171,194]. Later work includes work on branch alignment[72,369] and code layout[85,100,171].
Interprocedural optimization has been discussed in the literature for decades[17,334]. While inline substitution, as a transformation, is straightforward, its profitability has been the subject of many studies[34,108,129,309]. Hall reports on one study where increased name space size led directly to a decrease in effectiveness of optimization[108]. All of the scenarios mentioned in Section 8.7.3 have been explored in real systems[114,334,354]. Interpro-cedural analysis has a long and rich history[19,35,37,334]. Recompilation analysis is treated in depth by Burke and Torczon[70,347]. See the notes for Chapter 9 for more references on interprocedural analysis. The interproce-dural aspects of JIT compilation are discussed in more depth in Chapter 14.
EXERCISES
Section titled “EXERCISES”- Apply the algorithm from Fig. 8.4 to blocks and .
sed value is defined on page 404.
- Design an algorithm to convert a block of three-address code into a forest of expression trees, with the specification that each exposed value is the root of its own tree. You may assume that you have LIVEOUT and LIVEIN sets for the block.
- Consider a basic block b, such as B0 or B1 in Exercise 8.1. It has n operations, numbered from 1 to n.
a. For a name x, USES(x) contains the index in b of each operation that uses x as an operand. Write an algorithm to compute the USES set for every name mentioned in block b.
b. Apply your algorithm to blocks B0 and B1 from Exercise 8.1.
c. For a reference to x in operation i of block b, DEF(x,i) is the index in b of the operation that defines the value of x visible at operation i. Write an algorithm to compute DEF(x,i) for each reference x in b. If x is upward exposed at i, then DEF(x,i) should be -1.
d. Apply your algorithm to blocks B0 and B1 from Exercise 8.1.
- Apply the tree-height balancing algorithm from Section 8.4.2 to blocks B0 and B1 from Exercise 8.1.
Assume LIVEOUT(B0)={t3, t9} and LIVEOUT(B1)={t7, t8, t9}. The names a through f are upward-exposed in the blocks.
- For the control-flow graph shown in Fig. 8.24:
Section 8.5
a. Find the extended basic blocks and list their distinct paths.
b. Apply local value numbering (LVN) to each block.
c. Apply superlocal value numbering (SVN) to the EBBs. Note any improvements that it finds beyond those found by LVN.
- Consider the following simple five-point stencil computation:
do 20 i = 2, n-1, 1 t1 = A(i,1) t2 = A(i,2) do 10 j = 2, m-1, 1 t3 = A(i,j+1) A(i,j) = 0.2 × (t1 + t2 + t3
- A(i-1,j) + A(i+1,j)) t1 = t2 t2 = t3 10 continue 20 continue
Each iteration of the loop executes two copy operations.
a. Loop unrolling can eliminate the copy operations. What unroll factor is needed to eliminate all copy operations in this loop?
SECTION 8.6
Section titled “SECTION 8.6”b. In general, if a loop contains multiple cycles of copy operations, how can you compute the unroll factor needed to eliminate all of the copy operations?
- At some point p, LIVE(p) is the set of names that are live at p.LIVEOUT(b) is just the LIVE set at the end of block b.
a. Develop an algorithm that takes as input a block b and its LIVEOUT set and produces as output the LIVE set for each operation in the block.
b. Apply your algorithm to blocks and in Exercise 8.1. Assume that LIVEOUT(B0)={t3,t9} and LIVEOUT(B1)={t7,t8,t9}.
-
Compute LIVEOUT sets for each of the blocks in the control-flow graph shown in Fig. 8.24.
-
Fig. 8.17 shows an algorithm for finding the hot paths in a CFG.
a. Devise an alternative hot-path construction that pays attention to ties among equal-weight edges.
b. Construct two examples where your algorithm leads to a code layout that improves on the layout produced by the book’s algorithm.
■ FIGURE 8.24 Control-Flow Graph for Question 8.5.
Section titled “■ FIGURE 8.24 Control-Flow Graph for Question 8.5.”Use the code-layout algorithm from Fig. 8.19 with the chains constructed by your algorithm and those built by the book’s algorithm.
- Consider the following pseudocode fragment. It shows a procedure fee and two call sites that invoke fee.
static int A[1000,1000], B[1000], sum; x = A[i,j] + y; call fee(i,j,1000); call fee (1,1,0); fee(int row; int col; int ub) int i; sum = A[row, col]; for (i=0; i<ub; i++) sum = sum + B[i];
a. What benefits would you expect from inlining fee at each of the call sites? Estimate the fraction of fee’s code that would remain after inlining and subsequent optimization. b. Based on your experience in part a, sketch a high-level algorithm to estimate the benefits of inlining a specific call site. Your method should consider the impact on both the caller and the callee.
- In the previous problem, features of the call site and its context determined the extent to which the optimizer could improve the inlined code. Sketch, at a high level, a procedure for estimating the improvements that might accrue from inlining a specific call site. (With such an estimator, the compiler could inline the call sites with the highest estimated profit, stopping when it reached some threshold on procedure size or total program size.)
- When the procedure placement algorithm, shown in Fig. 8.22, considers an edge (p,q) it always places p before q. a. Formulate a modification of the algorithm that would consider placing the sink of an edge before its source. b. Construct an example where this approach places two procedures closer together than the original algorithm. Assume that all procedures are of uniform size.
- In the example from Fig. 8.23, there are three equal weight edges: (P0,P1), (P1,P3), and (P1,P4). Show how the algorithm would proceed if it took those edges in another order.
← node-book_engineering-a-compiler_chapter-07-code-shape | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-09-data-flow-analysis →