Instruction Scheduling
local graph
Chapter 12 — Instruction Scheduling
Section titled “Chapter 12 — Instruction Scheduling”ABSTRACT
Section titled “ABSTRACT”The elapsed running time of a set of operations depends heavily on the order in which those operations are presented for execution. Instruction scheduling reorders the operations in a procedure to reduce the code’s execution time. The set of legal orders for the operations is constrained by the need to preserve the flow of values from the original code. The goal is to reduce the number of cycles, start to finish, required to execute the code.
This chapter introduces the dominant technique for scheduling in compilers: greedy list scheduling in single basic blocks. Compiler writers use a variety of schemes to apply list scheduling to larger scopes. The chapter presents several of these, including superlocal scheduling, trace scheduling, and loop scheduling.
KEYWORDS
Section titled “KEYWORDS”Instruction Scheduling, Dependence Graph, List Scheduling, Trace Scheduling, Software Pipelining
12.1 INTRODUCTION
Section titled “12.1 INTRODUCTION”On many processors, the order in which operations are presented for execution has a significant effect on the length of time it takes for a sequence of operations to execute. Different operations take a different number of machine cycles to complete. On a typical commodity microprocessor, integer addition and subtraction require fewer cycles than integer division; similarly, floating-point division takes more cycles than floating-point addition or subtraction. Multiplication usually falls between the corresponding addition and division operations. The cost of a load from memory depends on where in the memory hierarchy the loaded value resides at the time that the load issues.
To help the compiler manage this complex situation, most processors allow for overlapped execution of operations, albeit under constraints that ensure predictable answers. To allow operations to execute concurrently, most processors provide distinct and independent functional units. To decrease the time interval between the start of distinct operations, most processors use a pipelined execution model. Both of these concurrency support mechanisms increase the complexity of the execution model.
Instruction scheduling is the process of systematically reordering the operations in a block or a procedure so that they execute in fewer cycles. The scheduler takes in a partially ordered list of operations in the target machine’s assembly language; it produces a fully ordered list of the same operations. It assumes that the code has already been optimized. It does not try to duplicate the optimizer’s work. Instead, the scheduler packs operations into the available cycles and functional unit issue slots to reduce idle, or wasted, cycles.
Conceptual Roadmap
The order in which the processor issues operations has a direct impact on the speed of execution of that code. Thus, most compilers include an instruction scheduler to reorder the final operations in a way that improves performance. The scheduler’s choices are constrained by the flow of data, by the delays associated with individual operations, and by the capabilities of the target processor. The scheduler must account for all these factors if it is to produce a correct and efficient schedule for the compiled code. Scheduling for single basic blocks is NP-complete under almost any realistic scenario.
The dominant technique for instruction scheduling is a greedy heuristic called list scheduling. List schedulers operate on straight-line code and use a variety of priority ranking schemes to guide their choices. Compiler writers have invented a number of frameworks to schedule over larger regions in the code than basic blocks; these regional and loop schedulers simply create conditions where the compiler can apply list scheduling to a longer sequence of operations.
A Few Words About Time
Instruction scheduling is a compile-time activity that tries to improve the quality of the code that the compiler produces. Like most optimizations, the scheduler runs at compile time. It analyzes the code and reorders the operations before they are emitted by the compiler. The benefits of that rearrangement accrue at runtime.
Overview
To speed up program execution, processor architects added features such as pipelined execution, multiple functional units, and out-of-order execution. These features make processors and their execution models more complex. They make higher performance possible; they also make realized performance more sensitive to the order in which operations are issued. Thus, they make the instruction scheduler an important factor in the performance of the final compiled code.
Informally, instruction scheduling is the process whereby a compiler reorders the operations in the final code to decrease the number of cycles required for it to run. The instruction scheduler takes as input a partially ordered list of instructions; it produces as output an ordered list of instructions constructed from the same set of operations. The scheduler assumes a fixed set of operations; it does not optimize the code. The scheduler assumes that values in registers remain in registers and values in memory remain in memory; it does not change storage allocation or storage placement decisions.
The scheduler’s primary goal is to compute an issue order for the operations in a block such that (1) operands are available when needed, (2) the functional units are well utilized, and (3) the number of cycles required to execute the block is minimized.
Example
Section titled “Example”Consider the example in Fig. 12.1(a) that computes (a+a) x b x c x d; this example first appeared in Section 1.3.3. We have substituted concrete numbers for the offsets @a, @b, @c, and @d. The column labeled “Start” shows the cycle in which each operation issues. Assume that the processor has one functional unit; loads and stores take three cycles; a multiply takes two cycles; and all other operations complete in a single cycle. The original code, shown in panel (a), executes in 22 cycles, known as it schedule length.
The scheduled code, shown in panel (b), executes in 13 cycles. It separates long-latency operations from operations that reference their results. This separation allows operations that do not depend on the results of those long-latency operations to execute in parallel before those operations finish. The scheduled code issues load operations in the cycles 1, 2, and 3; the results are available in cycles 4, 5, and 6, respectively. The overlap among operations effectively hides the latency of the memory operations. The same approach hides the latency of the first multiply. The reordered code has a schedule length of 13 cycles, a 41 percent improvement while executing the same operations. The increased concurrency requires one extra register.
Roadmap
Section titled “Roadmap”This chapter examines both the instruction scheduling problem and the algorithms that compilers use to solve it. Section 12.2 discusses both the processor features that make scheduling hard and the ideas that underlie scheduling
The scheduler tries to minimize the block’s running time. It cannot, in practice, guarantee an optimal schedule.
| Start | Operations |
|---|---|
| 1 | loadAI rarp,4 ⇒ r1 |
| 4 | add r1,r1 ⇒ r1 |
| 5 | loadAI rarp,8 ⇒ r2 |
| 8 | mult r1,r2 ⇒ r1 |
| 10 | loadAI rarp,12 ⇒ r2 |
| 13 | mult r1,r2 ⇒ r1 |
| 15 | loadAI rarp,16 ⇒ r2 |
| 18 | mult r1,r2 ⇒ r1 |
| 20 | storeAI r1 ⇒ rarp,4 |
| Start | Operations |
|---|---|
| 1 | loadAI rarp,4 ⇒ r1 |
| 2 | loadAI rarp,8 ⇒ r2 |
| 3 | loadAI rarp,12 ⇒ r3 |
| 4 | add r1,r1 ⇒ r1 |
| 5 | mult r1,r2 ⇒ r1 |
| 6 | loadAI rarp,16 ⇒ r2 |
| 7 | mult r1,r3 ⇒ r1 |
| 9 | mult r1,r2 ⇒ r1 |
| 11 | storeAI r1 ⇒ rarp,4 |
(a) Original Code
(b) Scheduled Code
■ FIGURE 12.1 Example Block from Chapter 1.
algorithms. Section 12.3 introduces list scheduling, the standard framework that most compilers use. Section 12.4 examines techniques that compiler writers use to apply that framework to larger domains. The Advanced Top-ics section examines software pipelining, a technique for scheduling loops.
12.2 BACKGROUND
Section titled “12.2 BACKGROUND”Schedule length (again)
To compensate for the complex execution models of modern processors and A block’s schedule length is the number of cycles that elapse from when the first operation issues until the last operation completes.
To capitalize on them, compilers systematically reorder the operations in the code that they generate. The compiler has multiple goals in this process. Dependence graph
It tries to decrease the number of empty or wasted operation issue slots. It The dependence graph D for block b has a node for each operation in b and an edge (x,y) if operation y uses the result of x-that is, y depends on x.
It tries to decrease idle time on the individual functional units. Finally, it tries to reduce the overall schedule length.
An instruction scheduler analyzes the code to determine how the flow of values constrains the order of execution. It builds a dependence graph, D, to represent the order constraints induced by the flow of values. The scheduler reorders the operations, within the constraints expressed in D, to capitalize on processor and system resources while hiding, to the extent possible, processor and system latencies.
To design and implement a scheduler, the compiler writer must understand the processor’s feature set, the impact that those features have on the performance of compiled code, and the ways in which those features present either challenges or opportunities to the scheduler. This section describes some of the processor features that complicate scheduling. It then introduces the scheduling problem.
12.2.1 Architectural Features That Affect Performance
Section titled “12.2.1 Architectural Features That Affect Performance”Computer architects have explored and implemented myriad features intended to increase peak processor performance. Some features, such as pipelined execution, both affect scheduling and rely on scheduling. Others, such as register windows, have a negligible impact on the design and effectiveness of a scheduler. This section describes three processor features that interact with scheduling: pipelined execution, variable latency operations, and multiple functional units.
Unless otherwise stated, we assume that all operations are nonblocking operations-the processor can issue operations to a functional unit in each cycle, even if earlier operations are not yet complete. Operations begin execution when issued, unless the processor detects that the operation uses a value that will be defined by another operation that is still executing. When the processor detects such a pipeline data hazard, it stalls the operation until its operand is available.
Pipelined Execution
Section titled “Pipelined Execution”The fundamental unit of time in scheduling is one cycle of the processor’s clock. Many operations, such as an integer add, an immediate load, or a logical shift, operate in a single cycle. More complex operations, such as multiply, divide, branch, jump, and most memory operations, need more than one cycle to complete. A typical processor can issue one operation per cycle to each functional unit, so a short cycle time leads to more operations issued per second.
Multicycle operations are often pipelined; that is, the operation is decomposed into a series of simpler, single-cycle steps that, in sequence, perform the complex operation. The pipeline resembles an assembly-line: each pipeline stage performs part of the operation; at the end of the cycle, the result passes to the next pipeline stage.
To exploit pipelined execution, the scheduler must understand when in the pipeline an operation reads the values that it uses and when it writes the values that it defines. Ideally, the scheduled code issues each operation after its operands are available. To allow the scheduler to fill all of the issue slots while delaying each operation until its arguments are ready, the code must have sufficient instruction-level parallelism (ILP).
Variable Latency Operations
Section titled “Variable Latency Operations”Some operations have unpredictable latencies. The latency of a load operation or a store operation, for example, depends on the state of the processor’s memory hierarchy. Some implementations of multiplication and division
This section provides an overview of features that affect scheduling. For more detail the reader should consult a textbook on computer architecture [200].
A typical operation reads its operands at the start of the cycle in which it issues and writes its results at the end of the cycle in which it completes.
The optimizer can increase the amount of exposed instruction level parallelism in code. See, for example, Section 4
WHAT HAPPENS WHEN AN OPERAND IS NOT READY?
In some situations, a processor will try to execute an operation before all of its operands are ready. The following sequence demonstrates the problem. Assume that the processor issues the mul t and the add in consecutive cycles.
mul t r₁, r₂ ⇒ r₃ add r₁, r₃ ⇒ r₄
If add takes one cycle and mul t takes three cycles, then the value of r₃ is not available when the add issues. The processor can detect such a data hazard before it issues an operation by comparing the names of the arguments to the names that will be defined by operations that are still in execution.
Most processors stall the new operation until the argument is available. Processors differ, however, on the impact of a stall.
-
Statically Scheduled, or In-Order, Processors Once the need for a stall is detected, these processors stop issuing additional operations until the hazard clears. Some processors stall just the one functional unit; others stall all the functional units.
-
Dynamically Scheduled, or Out-of-Order, Processors These processors maintain a window into the instruction stream and issue operations as their arguments become ready, with preference to operations early in the window.
The scheduler should place operations into cycles where they can execute without a stall. In the example, it could schedule two independent operations between the mul t and the add, if such operations were available.
A few processors have relied on the compiler to detect and mitigate data hazards. While this approach may simplify the hardware, it can complicate the scheduler. In such a scheme, the compiler may need to insert nops to enforce temporal separation between operations.
have small variations in latency based on the bit-patterns of their arguments. If the operation has a maximum latency, the scheduler can use that latency and produce a safe schedule.
For memory operations, the maximum latency is often impractically long for use in scheduling. Consider a tight eight-operation loop that contains a load operation. If the load can take anywhere from two cycles (a hit in the first-level cache) to 100 cycles (a miss to RAM), then using the 100 cycle latency will produce many idle cycles if the load operations exhibit even modest locality. Thus, the scheduler should estimate some reasonable expected latency and rely on the hardware to detect incomplete operations and stall their successors.
Multiple Functional Units
Section titled “Multiple Functional Units”To increase the number of operations per second that the processor can execute, architects build processors with multiple functional units. Each functional unit can initiate execution of an operation in each cycle. To keep multiple functional units busy, the compiler must issue multiple independent operations in the same cycle, again exploiting ILP. The scheduler must understand both the resources available—the number of functional units and the sets of operations that each can execute—and the dispatch discipline that determines how the processor issues operations.
Superscalar processors have a single instruction stream. At each cycle, the processor looks at the instruction stream and issues as many consecutive operations as it can. Consider a simple two functional unit, in-order processor. At each cycle, it would pick the first operation in the window and issue it. It would then examine the next operation; if that operation can issue on the unused functional unit, the processor issues it. If not, the functional unit remains idle in the current cycle. An out-of-order processor has a larger window and looks at successive operations until it finds one that can issue without a hazard.
By contrast, a very-long instruction-word (VLIW) processor manages the operation issue process by encoding one operation per functional unit into each instruction. This strategy simplifies the process of selecting and issuing operations. Instead, the compiler must fully specify the operation-issue behavior of the program. A VLIW instruction may represent idle operations (nops) implicitly or explicitly.
Many variations exist between these two endpoints. Superscalar processors vary from strictly in-order processors to out-of-order processors with large lookahead windows. Some VLIW processors have long instruction words, but allow the instructions to vary in length to save code space. In order to plan execution time behavior, the scheduler must understand the processor’s instruction dispatch discipline.
The diversity of dispatch mechanisms blurs the distinction between an operation and an instruction. On VLIW and packed VLIW machines, an instruction contains multiple operations. On superscalar machines, we usually refer to a single operation as an instruction and describe these machines as issuing multiple instructions per cycle. Throughout this book, we use the term operation to describe a single opcode and its operands. We use the term instruction to refer to an aggregation of one or more operations that all issue in the same cycle. In deference to tradition, we still refer to this chapter’s problem as instruction scheduling, although it might be more precisely called operation scheduling.
Superscalar a processor that has one instruction stream and multiple functional units, and that issues multiple operations per cycle
VLIW processor A very-long instruction-word processor has an instruction format with a slot for each functional unit in each cycle. A packed VLIW processor has a variable-length instruction word that can hold up to one operation for each functional unit.
(a) Example Code
a:loadAI rarp,4→r1 b:add r1,r1→r1 c:loadAI rarp,8→r2 d:mult r1,r2→r1 e:loadAI rarp,12→r2 f:mult r1,r2→r1 g:loadAI rarp,16→r2 h:mult r1,r2→r1 i:storeAI r1→rarp,4
(b) Its Dependence Graph
■ FIGURE 12.2 Dependence Graph for the Example.
12.2.2 The Instruction Scheduling Problem
Section titled “12.2.2 The Instruction Scheduling Problem”The instruction scheduling problem is defined over a basic block and its dependence graph,D. Nodes in D represent operations in the block. Edges in D represent the flow of values between those operations. Edges are directed; the edge(x,y) indicates that operation y uses the value produced by operation x. Additionally, each node has two attributes, a type and a delay. For a node n, the operation corresponding to n must execute on a functional unit specified by type(n). That operation requires delay(n) cycles to complete. Fig. 12.2 shows the code for our running example and its dependence graph.
Edges in D show the flow of values. If we reversed the edges, D would form a forest of DAGs.
We draw D with roots at the bottom, so that the drawing reflects the order of the code.
D is a forest of reversed directed acyclic graphs(DAGs). Thus, we use DAG terminology to describe D. Nodes without predecessors, such as a,c,e, and g in the example, are leaves. Leaves can be scheduled as early as possible, because they depend on no other operations. Nodes without successors, such as node i in the example, are roots. Roots can only be scheduled after all of their predecessors have completed.
Assume, for the moment, that all operations have known delays. A discussion of scheduling with variable delays starts on page 636.
Given a dependence graph D for a block, a schedule S maps each node n to a nonnegative integer that denotes the cycle in which it should be issued, assuming that the first operation issues in cycle 1. Thus, the i th instruction contains the set of operations{n|S(n)=i}. A valid schedule must meet three constraints.
-
S(n)≥1, for each n∈N. This constraint forbids operations that issue before execution starts. A schedule that violates this constraint is not well formed. For the sake of uniformity, the schedule must also have at least operation n’ with S(n’)=1.
-
If then . This rule enforces correctness. An operation should not issue until its operands have been defined. Some processors expect the compiler to insert nops to enforce this constraint. Others relax it and use hardware interlocks to delay an operation until its operands are available.
-
Each instruction contains no more operations of each type t than the target machine can issue in a cycle. This constraint enforces feasibility. It ensures that no instruction over-subscribes the functional units.
Given a well-formed, correct, and feasible schedule, the schedule length is simply the cycle number in which the last operation completes, assuming the first instruction issues in cycle 1. Schedule length can be computed as:
If delay accurately captures the operation latencies, schedule S should execute in L(S) time.(Variable latency operations might introduce inaccuracies into delay.) A schedule is time optimal if for all other schedules that contain the same set of operations.
Schedule Quality
Section titled “Schedule Quality”Schedule length is the classic measure of schedule quality. With fixed latency operations, schedule length accurately reflects execution time. With variable latency operations, the actual cost of the operation depends on dynamic factors. As long as the scheduler uses consistent assumptions, the lengths of different schedules should be comparable.
Schedules can be measured in terms other than time. Two schedules and for the same block might produce different demands for registers If the processor requires the scheduler to insert nops for idle functional units, then two schedules may differ in the number of operations fetched. Finally, Sj might require less energy than S; to execute on the target system because it never uses one of the functional units, it fetches fewer instructions, or it causes fewer bit transitions in the processor’s fetch and decode logic.
What Makes Scheduling Hard?
Section titled “What Makes Scheduling Hard?”The fundamental task of a scheduler is to assign each operation in the block a cycle in which it will issue. For each cycle, it builds a set of operations. As it does so, the scheduler must ensure that each operation issues only when its operands are available. If the processor has hardware interlocks to prevent an operation from reading an undefined value, then the schedule can issue an operation earlier-once all the operations that compute its operands have issued. That operation, however, will stall until the operands are ready.
MEASURING RUNTIME PERFORMANCE
Section titled “MEASURING RUNTIME PERFORMANCE”The primary goal of instruction scheduling is to improve the running time of the generated code. Because this chapter covers scheduling algorithms, our focus is on schedule length. However, discussions of performance use many different metrics.
- Instructions per Second This metric measures operations retired per second. Its common use is to state hardware peak performance; it can be used to state application performance.
- Cycles per Instruction (CPI) This metric divides elapsed time, in cycles, by operations retired. For a fixed stream of operations, a smaller CPI indicates better performance.
- Benchmarks These metrics measure the elapsed time to complete a known set of tasks. They provide information about overall system performance on a particular workload.
Performance measures provide insight into the quality of code generated by the compiler. They do not, in general, provide enough detail to allow compiler writers to determine where to focus their effort. A high CPI value might arise from the structure of the code, from a poor scheduling heuristic, or from insertion of excessive spill code by the register allocator. (Spill operations often have multicycle latencies.)
To manage processor resources, the scheduler faces conflicting goals. To achieve high performance it should keep the functional units busy. To hide the latencies of multicycle operations, it should overlap the execution of independent operations. The scheduler should schedule variable-latency operations, such as loads, early relative to their uses. Each of these goals is important; all consume the same finite resource: available ILP in the code. The scheduler must tradeoff between these competing goals.
When the scheduler places an operation i in cycle c, that decision affects the earliest possible placement of any operation that relies on the result of i—any operation in D that is reachable from i. If more than one operation can legally execute in cycle c, then the scheduler’s choice can change the earliest placement of many operations—all those operations dependent (either directly or transitively) on each of the possible choices.
Local instruction scheduling is NP-complete for all but the simplest architectures. In practice, compilers approximate good solutions to scheduling problems using greedy heuristics. Most of the scheduling algorithms used in compilers are based on a single family of heuristic techniques, called list scheduling. The following section describes list scheduling in detail. Subsequent sections show how to extend the paradigm to larger scopes.
SECTION REVIEW
Section titled “SECTION REVIEW”The advent of pipelined execution, nonblocking operations, variable latency operations, and multiple functional units makes code performance sensitive to the order in which operations are issued. The compiler’s instruction scheduler analyzes the dependence and latency structure of the code and reorders operations to improve execution time while preserving the code’s original meaning.
Instruction scheduling is a hard problem that involves low-level details of the target architecture. It is also a computationally complex problem. Instruction scheduling straight-line code is NP-complete for almost any realistic architecture. Thus, most compilers use a greedy heuristic technique, list scheduling, to solve the problem.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- The Texas Instruments C6X series of processors introduced a multicycle nop. The operation took a single argument: the number of consecutive cycles that it should idle the functional unit. What advantages might a multicycle nop provide? How might the scheduler capitalize on the availability of this operation?
- Assume that load operations are nonblocking with latency k, so that one load takes k cycles, but two loads, issued in successive cycles, take k + 1 cycles. Should this observation affect instruction selection? How might the algorithms in Chapter 11 account for this effect?
12.3 LOCAL SCHEDULING
Section titled “12.3 LOCAL SCHEDULING”List scheduling is a greedy, heuristic paradigm. Since the late 1970s, it has been the dominant technique that compilers use to schedule instructions, largely because it discovers reasonable schedules and it adapts easily to new ISAs. However, list scheduling is an approach rather than a specific algorithm. Wide variation exists in both implementations and detailed heuristics. This section explores the basic list scheduling framework, as well as a couple of variations on the scheme.
List scheduling operates on a block’s dependence graph. It annotates D with latency and priority information. It then uses the annotated graph to construct, cycle by cycle, a schedule for the block that the graph represents.
Critical path the longest latency path through D Dependence Graph Annotated with Latencies
To fix this conflict, the code in Fig. 12.1(b) renamed the value defined by e and used by f from r₂ to r₃.
Antidependence Operation x is antidependent on operation y if x precedes y and y defines a value used in x. Reversing their order of execution could cause x to compute a different value.
SSA form creates a name space that avoids kills and, thus, many antidependences.
The dependence graph captures most of the schedule-critical properties of a block. The figure in the margin repeats the graph from Fig. 12.2(b). For a node n, the path length from n to the root is shown as a superscript on n. (If D had multiple roots, the scheduler would use the maximal path length to a root.) The superscripts show that the path abdfhi is the critical path through D; it determines the block’s minimal execution time.
How, then, should the compiler schedule this computation? Each operation should be placed in a cycle where its operands are available. Since a, c, e, and g are leaves, they are the initial candidates for scheduling. The fact that a lies on the critical path suggests that it be scheduled into the first cycle. Once a has been scheduled, the longest path remaining in D is cdfhi, suggesting that c issue in the second cycle. Given the prefix ac, b and e tie for latency. However, b depends on the result of a, which will not be available until cycle four. Thus, eb is a better suffix to ac than is be. Continuing in this fashion leads to the schedule acebdgfhi, the schedule shown in Fig. 12.1(b).
Simply choosing that schedule, however, is not enough The operations for nodes c and e both define r₂; d, in turn, uses the value from c. The scheduler cannot move e before d unless it renames the result of e to avoid the conflict with c’s definition of r₂. The dependence graph fails to capture this conflict because it arises from the fact that executing e overwrites the value, rather than from the flow of a value.
Ordering constraints such as the one between c and e are called antidependences. We denote the antidependence between e and d as e→A.d. The scheduler must respect the antidependences in the original code. The example contains four antidependences, namely, e→Ac, e→Ad, g→Ae, and g→Af. All of them involve redefinition of r₂. (Constraints exist based on r₁ as well, but each antidependence on r₁ duplicates a dependence based on the flow of values.)
The scheduler has two options to handle this kind of antidependence. It can either represent antidependences explicitly and respect them in the same way that it handles dependences from the flow of values, or it can rename around them. The former approach restricts the set of schedules that the compiler can discover. The latter approach increases the size of the name space, which may force the register allocator to insert spill code into the block. The local scheduling algorithm that we present assumes that the scheduler will rename register-based values in the code. The section on dependence graph construction will provide more details on detecting and representing antidependences. 12.3.1 The Algorithm
Classic list scheduling operates on a single basic block. To schedule a single block, the scheduler follows a four-step plan.
-
Rename To avoid antidependences on register-based values, the compiler renames them. This step is not strictly necessary, but it simplifies the scheduler’s implementation.
-
Build a Dependence Graph The scheduler walks the block from bottom to top. At each operation, it builds a node that represents both the operation and the value it defines. It then connects that node to the node for each operation that uses the value.
-
Assign Priorities to Each Operation To guide the choice of operations, the scheduler computes one or more priorities for each node in D. Priorities are typically computed in a walk over D. The maximum latency-weighted distance to a root is a common priority scheme.
-
List Scheduling The scheduler starts in the block’s first cycle and chooses as many operations as possible to issue in that cycle. It then increments its cycle counter, updates its notion of which operations are ready to execute, and schedules the next cycle. It repeats this process until each operation has been scheduled.
The following subsections explore each of these steps in more detail.
12.3.2 Renaming
Section titled “12.3.2 Renaming”The first step in the algorithm renames all unambiguous scalar values in the block so that each name corresponds to a single definition. As a matter of code shape, we assume that values in registers are unambiguous from their definition to their last use. The renaming algorithm operates on these register names. To denote the different name spaces, a name in the original code is a source name while a name created by renaming is a virtual name.
The compiler can create a virtual-name space with properties that simplify the task at hand. For example, local value numbering creates a virtual name space where name identity implies value identity. For scheduling, the renaming algorithm creates a name space that eliminates antidependences between unambiguous scalar values. That name space, in turn, simplifies the later phases of scheduling.
In a single block, each definition creates a new value. Renaming finds each such value and assigns it a new virtual name. Within the span between the value’s definition and its last use, the algorithm rewrites references to the source name with its virtual name. This process creates a one-to-one correspondence between values and names.
VName ← 0 for i ← 0 to max source-register number do SToV[i] ← invalid // initialization for each Op in the block, bottom to top do for each definition, O, in Op do // do defs first if SToV[O] = invalid then // invalid def indicates SToV[O] ← VName++ // an unused value O ← SToV[O] // O gets its new name SToV[O] ← invalid // next ref is a new name for each use, O, in OP do // do uses second if SToV[O] = invalid then // start a new value SToV[O] ← VName++ // O gets its new name O ← SToV[O]
■ FIGURE 12.3 Renaming for List Scheduling.
This algorithm also appears in local register allocation (see Section 13.3).
In the example, note that all of the names in a store are uses, not definitions.
loadAI r_orp,4 ⇒ r7 add r7,r7 ⇒ r5 loadAI r_orp,8 ⇒ r6 mult r5,r6 ⇒ r3 loadAI r_orp,12 ⇒ r4 mult r3,r4 ⇒ r1 loadAI r_orp,16 ⇒ r2 mult r1,r2 ⇒ r0 storeAI r0 ⇒ r_orp,4
Example Attention
The algorithm, shown in Fig. 12.3, discovers values, assigns virtual names, and rewrites references in a single backward pass over the block. Its central data structure is a map, SToV, from source names to virtual names. The algorithm begins by setting all the SToV entries to invalid and initializing the first virtual name to zero. It then iterates over each operation in the block, from bottom to top.
At each operation, the algorithm processes definitions before uses. It rewrites defined names with their virtual names; if a defined name has no virtual name, its value is not used in the block. It invalidates a virtual name when it encounters the name’s definition, which forces the next use of that source name to have its own virtual name. For each of the used names, it checks SToV to determine if the value has a virtual name; if not, it assigns the value the next virtual name and rewrites it.
The algorithm processes definitions before uses to ensure correct behavior when a single operation uses a name and then redefines it. For example, in an operation such as addI r₁₈,12 ⇒ r₁₈, the algorithm will first rewrite the definition with SToV[r₁₈]. Next, it will invalidate SToV[r₁₈]. Then, it will create a new virtual name and update SToV[r₁₈] with the new name. Finally, it will rewrite the use with the new name, from SToV[r₁₈].
After renaming, each live range has a unique virtual name. A source name that was defined in multiple operations will be rewritten with multiple distinct virtual names. The renamed version of the example block appears in the margin. The antidependences that arose from order of operations in the input program have been broken; the actual flow of values remains the same. As discussed in the next subsection, rarp has not been renamed because it is live across the block boundaries.
The renaming algorithm also plays an important role in local register allocation (see Section 13.3).
End-of-Block Conditions
Section titled “End-of-Block Conditions”The algorithm in Fig. 12.3 assumes that the block has no surrounding context-that is, the block is the entire program. In most situations, a block b has both predecessors and successors in the control-flow graph. For the generated code to function correctly in that context, the renaming algorithm must preserve source names that are live across those boundaries.
Before renaming, the compiler can compute LIVE information (see Sec-tions 8.6.1 and 9.2.2). The algorithm then needs three modifications to deal with the boundary conditions. It should initialize VName to a value higher than the maximum source-register number. To handle successor blocks, it should initialize SToV to i for any name i∈LIVEOUT(b). These two steps ensure that values in LIVEOUT have the names expected by successor blocks.
Handling boundaries with predecessor blocks is slightly more complex. Before the algorithm assigns a new VName to some source name, it must determine whether that value is defined in the current block or in some predecessor block. Because the input code can define names multiple times, checking LIVEIN(b) is insufficient. Instead, the compiler must determine whether the current use is upward exposed.
During LIVE analysis, the compiler computes the set of upward exposed variables in b, UEVAR(b). As it does so, it can mark any upward exposed uses. Then, when the renaming algorithm encounters a use of name i such that SToV[i] is invalid, it can assign i to SToV[i] if the use is upward exposed, rather than VName.
12.3.3 Building the Dependence Graph
Section titled “12.3.3 Building the Dependence Graph”The second step in the local scheduling process builds a dependence graph,D, for the basic block. The algorithm, shown in Fig. 12.4 is straightforward. It creates an empty map, M, that takes virtual names from the code into nodes in D. It then iterates over the operations in the block, from top to bottom. For each operation, O, it creates a node n in D. It updates M so that M(d)=n, for each name d defined by O. It then adds edges from n to the nodes that define the values used in O.
The final step adds edges to represent antidependences through memory locations and ensure that the final schedule respects them. The idea is simple.
Names are assumed to be represented as integers. The compiler can use as many virtual names as it needs.
If names are small integers, M mented as a vector.
Recall that renaming eliminated antidepe dences among unambiguous scalar name create an empty map, M // definitions to nodes create a node, undef, in D // for an undefined value for each operation O, top to bottom do // walk the block create a node n for O, in D // n represents O for each name, d, defined in O do set M(d) to n for each name, u, used in O do // true dependence if M(u) is undefined then set M(u) to undef add an edge (n,M(u)) to D if O is a memory operation then // antidependences add serialization edges as needed
Figure 12.4 Building the Dependence Graph After Renaming.
If an operation might change the contents of memory, the scheduler must ensure that the operation does not affect values seen by other operations. The details are slightly complex.
Consider, for example, the three operation code fragment shown in the margin. The scheduler can reorder the two loads; neither modifies the contents of the memory so changing their relative issue order has no effect on the values placed in r5 and r6. The store, however, changes the contents of memory. In the absence of information about the addresses in the loads and stores, the scheduler must ensure that the loads read from memory before the store writes to memory. The compiler may need to add edges to D to serialize these operations.
The first load uses the same address as the store; the compiler must schedule these operations so that the load reads its value before the store overwrites that value. The second load uses a different register as its address. If the compiler can prove that r17 and r18 always have distinct values, then the scheduler can reorder the store and the second load. If the compiler cannot prove those values distinct, it must preserve the relative ordering of the second load and the store, as well.
The table in Fig. 12.5 summarizes the situations that can arise. The scheduler can always swap the order of two loads. With a load and a store, it must preserve their original order; it must serialize the operations. The table denotes this delay as serial. With a store followed by a load, the scheduler must ensure that the store completes before the load issues; in general, it must allow the full latency of the store.
Conflict Type First Op Second Op Delay Read After Read(RAR) 1oad 1oad none Write After Read(WAR) 1oad store serial Read after Write(RAW) store 1oad store Write after Write(WAW) store store serial
■ FIGURE 12.5 Serialization Latencies for Memory Operations.
Given a pair of memory references, the compiler must enforce the appropriate delay, unless it can prove that the two operations refer to disjoint locations in memory. In terms of dependence graph construction, the compiler must add an edge to represent these constraints, weighted with the appropriate latency. The compiler can reduce the number of antidependences that it must represent by analyzing the values of the memory addresses.
12.3.4 Computing Priorities
Section titled “12.3.4 Computing Priorities”To guide scheduling decisions, the compiler computes one or more priority values for each operation. When the scheduler confronts a choice, it takes the operation with the highest priority value. The scheduler needs a tie-breaking strategy; a common approach uses a second or third priority value. The literature discusses many priority schemes; one often used scheme is the operation’s maximum latency-weighted distance to a root in D.
Priorities such as latency-weighted depth, number of descendants, breadth-first order, and depth-first order can be computed in a traversal of D. The scheduler can incorporate other heuristics, such as a preference for loads over stores, with simple numerical manipulations of the priority scores.
Multiple priorities can be accommodated as a linear combination. If p1 and p2 are scores from different priority metrics, the scheduler can combine them as to create a single value. If , the effect is to use p2 to break ties in the p1 metric. Alternatively, the compiler can restrict and tune the values of and for the best result across a training set of codes.
Using lower-weight priorities to break ties can push the schedule toward specific goals. For example, using the operation’s latency as a lower-weight priority pushes long latency operations earlier in the block. Using the number of operands that are last uses as a lower-weight priority can decrease demand for registers.
Some priority schemes are hard to encode as numerical weights. For example, if the processor restricts certain operations to specific functional units, Cycle ← 1 Ready ← leaves of D Active ← Ø while (Ready ∪ Active ≠ Ø) do for each functional unit, f, do if there is an op in Ready for f then let O be the highest priority op // choose O by priority in Ready that can execute on f remove O from Ready // schedule O in Cycle S(O) ← Cycle Active ← Active ∪ {O} Cycle ← Cycle + 1 // start next Cycle for each O ∈ Active do if S(O) + delay(O) ≤ Cycle then // update Ready list remove O from Active for each successor s of O in D do if s is ready then add s to Ready
Figure 12.6 The List-Scheduling Algorithm.
the compiler writer may want to boost the priority of those operations on their respective units. Rather than manipulate the priority numbers, the compiler writer can track the restricted and unrestricted operations separately. The scheduler can first draw from the restricted list and then, if needed, from the unrestricted list.
12.3.5 List Scheduling
Section titled “12.3.5 List Scheduling”The final step in scheduling is to construct the actual schedule for the block. The most widely used algorithm for this part of the process is the list-scheduling algorithm-a greedy heuristic that, in practice, constructs good schedules. Fig. 12.6 shows the basic algorithm.
The algorithm performs an abstract simulation of the block’s execution. It ignores the details of values and operations to focus on the timing constraints imposed by edges in D. To track time, it maintains a simulation clock, in the variable Cycle. It initializes Cycle to 1 and increments Cycle as it proceeds through the block.
The algorithm uses two lists to track operations. The Ready list holds all the operations that are “ready” to execute in the current cycle; that is, their operands have already been computed. Initially, Ready contains all the leaves
of D, since they do not depend on other operations in the block. The Active list holds all operations that were issued in an earlier cycle but have not yet completed execution.
The list-scheduling algorithm follows a simple discipline. Each iteration of the scheduler begins in some specific cycle. It examines the Ready list and tries to select an operation for each functional unit. If more than one operation is available for some unit, it chooses the operation with the highest priority score. After it has considered all units, the scheduler increments Cycle and updates the Ready list.
To update Ready for the new cycle, the scheduler first finds all of the operations in Active that completed in the previous cycle. For each such completed operation, the scheduler checks each successor s in D to determine if s is now ready to execute. More precisely, it determines if all of the operands used by s are available-that is, the operation that produced the operand has, itself, completed execution.
The process terminates when the simulated clock reaches the first cycle where every operation has completed. If all operands of the leaves of D are available in the first cycle, and delay(op) accurately reflects the execution time of op, then the simulated clock should match the actual execution time, in cycles. A simple postpass can emit the operations in order and insert nops if needed.
The algorithm must respect one final constraint. Any block-ending branch or jump must be scheduled so it does not complete execution before the block ends. If i is the block-ending branch, it cannot be scheduled earlier than cycle Thus, a single-cycle branch must be scheduled in the last cycle of the block, and a two-cycle branch must appear no earlier than the second to last cycle.
The quality of the schedule produced by this algorithm depends primarily on the mechanism used to pick an operation from the Ready list. Consider the simplest scenario, where the Ready list contains at most one item in each iteration. In this restricted case, the algorithm must generate an optimal schedule. Only one operation can execute in the first cycle.(There must be at least one leaf in D, and our restriction ensures that there is exactly one.) At each subsequent cycle, the algorithm has no choices to make-either Ready contains an operation and the algorithm schedules it, or Ready is empty and the algorithm schedules nothing to issue in that cycle.
The difficulty arises when, in some cycle, the Ready list contains multiple operations. Then, the scheduler must choose among several ready operations and that choice is critical. The algorithm takes the operation with
Operation O completes at the end of cycle - first+ delay(O).
INTERACTIONS BETWEEN SCHEDULING AND ALLOCATION
Section titled “INTERACTIONS BETWEEN SCHEDULING AND ALLOCATION”Antidependences between operations can limit the scheduler’s ability to reorder operations. The scheduler can avoid antidependences by renaming; however, renaming creates a need for the compiler to perform register allocation after scheduling. This example is but one of the interactions between instruction scheduling and register allocation.
The core function of the scheduler is to reorder operations. Since most operations both use and define values, changing the relative order of two operations can change the lifetimes of values. Moving an operation x ← y + z forward can increase the lifetimes of y and z and decrease the lifetime of x. Symmetrically, moving the operation backward can shrink the lifetimes of y and z while lengthening the lifetime of x. The net impact of reordering operations on register demand depends on detailed information about the lifetimes of the definitions and uses.
In a similar way, register allocation can change the instruction-scheduling problem. The core functions of a register allocator are to rename references and to insert spill code. Both of these functions affect the scheduler’s ability to produce fast code. When the allocator maps a large virtual name space to the smaller name space of target-machine registers, it can introduce antidependences that constrain the scheduler. Similarly, when the allocator inserts spill code, it adds operations to the code that must, themselves, be scheduled into instructions.
We know, mathematically, that solving these problems together might produce solutions that cannot be obtained by running the scheduler followed by the allocator or the allocator followed by the scheduler. However, both problems are complex enough that most real-world compilers treat them separately.
the highest priority score. A well-designed priority scheme incorporates lower-priority tie-breaking criteria. The metric suggested earlier, maximum latency-weighted distance to a root, corresponds to always choosing the operation on the critical path for the current cycle in the schedule being constructed. To the extent that the impact of a scheduling priority is predictable, this scheme should provide balanced pursuit of the longest paths.
Scheduling Operations with Variable Delays
Section titled “Scheduling Operations with Variable Delays”The latency of memory operations often depends on the current state of the memory hierarchy. Thus, the latency of a specific load operation might vary from a couple of cycles to hundreds of cycles. Worse yet, a given operation—that is, the instruction in some specific slot in some specific lock—may have different latencies on successive executions. for each load operation, I, in the block do delay(I) ← 1
for each operation i in D do let D_i be the nodes and edges in D independent of i for each connected component C of D_i do find the maximal number of loads, N, on any path through C for each load operation I in C do delay(I) ← delay(I) + delay(i) ÷ N
■ FIGURE 12.7 Computing Delays for Load Operations.
In the absence of detailed knowledge about the addresses being accessed and the state of the memory hierarchy, the scheduler may not have an accurate estimate of the delay. If it assumes the worst case, it risks idling the processor for long periods. If it assumes the best case, it will stall the processor on a cache miss. In practice, the scheduler must seek some middle ground.
The compiler can obtain good results by calculating an individual latency for each load based on the amount of instruction-level parallelism available to cover the load’s latency. This approach, called balanced scheduling, schedules the load with regard to the code that surrounds it rather than the hardware on which it will execute. It distributes the locally available parallelism across loads in the block. This strategy mitigates the effect of a cache miss by scheduling as much extra delay as possible for each load. It will not slow down execution in the absence of cache misses.
Fig. 12.7 shows the computation of delays for individual loads in a block. The algorithm initializes the delay for each load to one. Next, it considers each operation i in the block’s dependence graph, D. It finds the nodes in D that are independent of i, called Di. Conceptually, this task is a reachability problem on D. We can find Di by removing from D every node that is a transitive predecessor of i or a transitive successor of i, along with any edges associated with those nodes.
The algorithm then finds the connected components of Di. For each component C, it finds the maximum number N of loads on any single path through C. N is the number of loads in C that can share operation i’s delay, so the algorithm adds delay(i)/N to the delay of each load in C. For a given load l, the operation sums the fractional share of each independent operation i’s delay that can be used to cover the latency of l. Using this value as delay(l) produces a schedule that shares the slack time of independent operations evenly across all loads in the block.
Figure 12.8 Dependence Graph for a Block from go.
12.3.6 Forward Versus Backward List Scheduling
Section titled “12.3.6 Forward Versus Backward List Scheduling”The list-scheduling algorithm, as presented in Fig. 12.6, moves through the dependence graph from its leaves to its roots and creates the schedule from the first cycle in the block to the last. An alternate formulation of the algorithm operates in the opposite direction, moving from roots to leaves and scheduling from last cycle to first cycle. This version of the algorithm is called backward list scheduling, and the original version is called forward list scheduling.
List scheduling, itself, is not particularly expensive. Thus, some compilers have run the scheduler several times with different combinations of heuristics and kept the best schedule.(The scheduler can reuse the preparatory work-renaming, building the dependence graph, and computing priorities.) In such a scheme, the compiler should consider using both forward and backward scheduling.
In practice, neither forward scheduling nor backward scheduling always wins. The difference between forward and backward list scheduling lies in the order in which the scheduler considers operations. If the schedule depends critically on the careful ordering of some small set of operations, the two directions may produce noticeably different results. If the critical operations occur near the leaves, forward scheduling might consider them together, while backward scheduling would need to work its way through the remainder of the block to reach them. Symmetrically, if the critical operations occur near the roots, backward scheduling might examine them together, while forward scheduling sees them in an order dictated by decisions made starting at the other end of the block.
| Integer | Integer | Memory |
|---|---|---|
| 1 loadI1 | lshift | — |
| 2 loadI2 | loadI3 | — |
| 3 loadI4 | add1 | — |
| 4 add2 | add3 | — |
| 5 add4 | addI | store1 |
| 6 cmp | — | store2 |
| 7 — | — | store3 |
| 8 — | — | store4 |
| 9 — | — | store5 |
| 10 — | — | — |
| 11 — | — | — |
| 12 — | — | — |
| 13 cbr | — | — |
(a) Forward Schedule
(b) Backward Schedule
■ FIGURE 12.9 Schedules for the Block from go.
To make this point concrete, consider the example shown in Fig. 12.8.It shows the dependence graph for a basic block found in the SPEC 95 benchmark program go. The compiler added dependences from the store operations to the block-ending branch to ensure that the memory operations complete before the next block begins execution. Superscripts on nodes in the dependence graph give the latency from the node to the end of the block;subscripts differentiate among similar operations. The example assumes the operation latencies shown in the margin.
This example came to our attention during a study of list scheduling that targeted an ILOC machine with two integer functional units and one unit to perform memory operations. The five store operations take most of the time in the block. To minimize execution time, the schedule must place the stores as early as possible.
Forward list scheduling, using latency to the end of the block for priority, executes the operations in priority order, except for the comparison. It schedules the five operations with rank eight, then the four rank seven operations and the rank six operation. It begins on the operations with rank five, and slides the cmp in alongside the stores, since the cmp is a leaf. If ties are broken arbitrarily by taking left-to-right order, this produces the schedule shown in Fig. 12.9(a). Notice that the memory operations begin in cycle 5,producing a schedule that issues the branch in cycle 13.
| Opcode | De |
|---|---|
| loadI | 1 |
| lshift | 1 |
| add | 2 |
| addI | 1 |
| cmp | 1 |
| cbr | 1 |
| store | 4 |
WHAT ABOUT OUT-OF-ORDER EXECUTION?
Section titled “WHAT ABOUT OUT-OF-ORDER EXECUTION?”Dynamically scheduled processors, with their support for out-of-order (000)execution, can improve on the static schedule that a compiler produces. Does OOO execution eliminate the need for compiler-based scheduling?
To understand this issue, it is important to recognize when an OOO processor can improve on the static schedule. If runtime circumstances are better than the assumptions made by the scheduler, then OOO hardware can issue an operation earlier than its position in the static schedule. This situation can arise at a block boundary if an operand is available before its worst-case time. It can arise with variable-latency operations, such as loads and stores. Because the processor can look at actual runtime addresses, an OOO processor can also disambiguate some load-store dependences that the scheduler cannot.
However, OOO execution does not eliminate the need for the compiler to schedule instructions. Because the lookahead window is finite, bad schedules can defy improvement. For example, a lookahead window of 50 instructions will not let the processor execute a string of 100 integer instructions followed by 100 floating-point instructions in interleaved(integer, floating point) pairs. It should, however, interleave shorter strings of operations. OOO execution helps the compiler by improving good, but nonoptimal, schedules.
Using the same priorities with backward list scheduling, the compiler first places the branch in the last slot of the block. The cmp precedes it by one cycle, determined by delay(cmp). The next operation scheduled is store1(by the left-to-right tie-breaking rule). It is assigned the issue slot on the memory unit that is four cycles earlier, determined by delay(store). The scheduler fills in successively earlier slots on the memory unit with the other store operations, in order. It begins filling in the integer operations, as they become ready. The first is add1, two cycles before store1. When the algorithm terminates, it has produced the schedule shown in Fig. 12.9(b).
The backward schedule takes one fewer cycle than does the forward schedule. It places the addI earlier in the block, which allows store5 to issue in cycle 4-one cycle earlier than the first memory operation in the forward schedule. By considering the problem in a different order, using the same underlying priorities and tie breakers, the backward algorithm finds a different result.
Why does this happen? The forward scheduler places all the rank-eight operations in the schedule before any rank-seven operations. Even though the add1 operation is a leaf, its lower rank causes the forward scheduler to defer it. By the time the scheduler runs out of rank-eight operations, other rank-seven operations are available. By contrast, the backward scheduler places the addI earlier than three of the rank-eight operations—a result that the forward scheduler could not consider.
SECTION REVIEW
Section titled “SECTION REVIEW”List scheduling has been the dominant paradigm that compilers have used for many years. It computes, for each operation, the cycle in which that operation should issue. The algorithm is reasonably efficient; its complexity relates directly to the underlying dependence graph. This greedy heuristic approach, in its forward and backward forms, produces excellent results for single blocks.
The key data structure for instruction scheduling is the dependence graph. It represents the flow of data in the block. It is easily annotated with information about operation-by-operation delays. The dependence graph directly represents both the constraints and the critical paths in the block.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- The Ready list is one of the most heavily accessed data structures in a list scheduler. Compare and contrast the costs of implementing Ready as an ordered list versus a priority queue. How does the expected length of the Ready list affect the tradeoff?
- For each of the following tie-breakers, suggest a rationale. a. Prefer operations with operands in registers over ones with immediate operands. b. Prefer the operation with the most recently defined operands. c. Prefer a load before an operation that computes a value.
12.4 REGIONAL SCHEDULING
Section titled “12.4 REGIONAL SCHEDULING”To extend list scheduling to larger regions, compiler writers use the same kinds of strategies that work with value numbering. They construct multi-block regions that they can treat as a single block and, then, apply the local scheduling algorithm to those regions. As with superlocal value numbering, the compiler must take care on the borders between the multiblock region and the rest of the procedure being compiled. This section examines three schemes that compiler writers have used to improve schedule quality:
superlocal scheduling, trace scheduling, and superblock cloning. Each expands the context to which the compiler applies list scheduling.
12.4.1 Superlocal Scheduling
Section titled “12.4.1 Superlocal Scheduling”Recall from Section 8.3 that an extended basic block(EBB) consists of a set of blocks in which has multiple predecessors and every other block has exactly one predecessor, some in the EBB. The compiler can identify EBBs in a simple pass over the CFG. The CFG shown in the margin has one large EBB,{ }, and two trivial EBBs, and The large EBB has two paths, , and ,The paths share as a common prefix.
Example CFG with Execution Frequencies
Both(B0,B4) and(B1,B5) are premature exits relative to(B0,B1,B2).
Compensation code
code inserted into a block to counteract the effects of cross-block code motion along a path that does not include
Because is an EBB path, we know has only one predecessor.
To obtain a larger context, the scheduler can treat paths in an EBB, such as , as if they are single blocks, provided that it accounts for the shared path prefixes and for any premature exits from those paths. This approach lets the compiler apply list scheduling to longer sequences of operations. The effect is to increase the fraction of code that is scheduled together, which may improve execution times.
To see how shared prefixes and premature exits complicate list scheduling, consider the ways that the scheduler might move operations across block boundaries in the path in the example. Such code motion may require the scheduler to insert compensation code to maintain correctness.
The compiler can move an operation forward-that is, later on the path. For example, it might move an operation i from B0 into B1. While that decision might speed execution along the path , it removes i from the path . Unless i is dead along , the scheduler must correct this situation.
To compensate, the scheduler can insert a copy of i at the head of B4. If it was legal to move i out of B0, it is legal to place it at the head of B4.A dependence that prevents placement of i at the head of B4 would also prevent its placement in B1. The copy of i in B4 does not lengthen the path but it does increase the overall code size.
The compiler can move an operation backward-that is, earlier on the path. For example, it might move an operation j from B1 to B0. While that decision might speed execution along the path , it adds j to the path . That placement lengthens the path . It may also change the values seen in B4.
If j kills some value used in B4, the scheduler must rewrite the code to make the value available at the head of B4. It could insert code at the he recompute the value; renaming might accomplish the same effect. In either case, the presence of both j and compensation code along the path will lengthen that path.
The mechanics of superlocal scheduling are straightforward. The compiler selects an EBB. It performs renaming over the region, if necessary. Next, it schedules each path through the EBB, in order of decreasing execution frequency. It builds a dependence graph for the entire path and schedules it ignoring premature exits and recording all cross-block placements. A post-pass inserts compensation code. It repeats this process until it has scheduled every block in the EBB. Each block is scheduled exactly once.
When the scheduler processes a path with an already-scheduled prefix, it leaves that prefix intact. The effect is to prioritize the schedules of hotter paths over those of cooler paths. If the estimates of future execution frequencies are accurate, this approach may improve overall execution times.
In the example, the scheduler might process . Next, it would schedule B4 relative to the schedule for B0. Finally, it would schedule the trivial EBBs, B3 and B5, as singleton blocks.
Mitigating Compensation Code
Section titled “Mitigating Compensation Code”The scheduler can take steps to limit the impact of compensation code. It can use live information to avoid some of the compensation code suggested by forward motion. If the result of the moved operation is not live on entry to the off-path block, no compensation code is needed on that path. It can avoid compensation code introduced by backward motion if it prohibits backward motion into a block b of any operation that defines a name .This restriction can limit the scheduler’s ability to improve the code, but it avoids lengthening other paths.
12.4.2 Trace Scheduling
Section titled “12.4.2 Trace Scheduling”Trace scheduling extends the approach taken in superlocal scheduling beyond a path through a single EBB. Trace scheduling constructs maximal-length acyclic paths, or traces, through the CFG and applies the list-scheduling algorithm to those traces. Like superlocal scheduling, this approach schedules each block once. Like superlocal scheduling, it may need to insert compensation code. The algorithm consists of two distinct phases: trace construction and scheduling.
The algorithm follows the same basic scheme as superlocal scheduling. It identifies a trace and schedules that trace-keeping track of places where the new schedule will need compensation code. It schedules the hottest paths first, so that the shorter and more constrained schedules execute less often.
Trace
an acyclic path through the CFG selected using profile information
trace ← eligible edge e with highest frequency count x ← hottest eligible edge entering source(trace) or leaving sink(trace) while (x is nonnull) do add x to the appropriate end of the trace x ← hottest eligible edge entering source(trace) or leaving sink(trace)
(a) The Trace Construction Algorithm
(b) A More Complex Example
■ FIGURE 12.10 Trace Construction Algorithm.
Trace Construction
Section titled “Trace Construction”Fig. 12.10(a) shows the algorithm to construct a single trace. It uses a greedy heuristic to find the hottest acyclic path through the CFG. It begins with a trace that consists of the hottest remaining edge in the graph—the one with highest execution frequency—and repeatedly adds edges to either the start or the end of the trace. At each step, it takes the hottest edge among the available choices—those that would extend either the start or the end of the trace. When no such edge remains, the trace is finished.
Recall that an edge (x,y) is a loop-closing edge in the CFG if y∈DOM(x).
The algorithm excludes some edges. It considers an edge ineligible for use in the current trace if either the edge closes a loop or both its source and sink already appear in the current trace or an earlier one.
The first restriction prevents the scheduler from moving code out of a loop. We assume that the optimizer already performed loop-invariant code motion(see Section 10.3.1) and that the scheduler should not insert compensation code that splits a loop-closing branch.
To find successive traces, the compiler removes the on-trace edges from the graph and invokes the trace construction algorithm on the remaining graph. It repeats this process until no eligible edges remain.
Examples
Section titled “Examples”Consider the CFG shown in the margin. The algorithm starts with the hottest edge, . It extends with and , in order. At that point, it cannot extend the trace any further. The first trace is . It removes those edges from the graph.
Example CFG with Execution Frequencie
or the second trace, the algorithm starts with . It extends the trace B5) and . It cannot extend the trace further. The second trace is . It removes those edges. The only remaining edge. , is ineligible.
Fig. 12.10(b) shows a more complex CFG. Its hottest edge is(B5,B6). It extends the trace with, in order,(B6,B7),(B7,B8), and(B0,B5), to form the trace .
The second trace begins with a tie for the hottest remaining edge. It chooses one of(B6,B9) or(B9,B8). It uses the other edge to extend the trace, to form . At that point, no eligible edge remains to extend the second trace.
The third trace begins with(B4,B3). The algorithm adds(B5,B4) to form . No eligible edge remains to extend this trace.
The fourth trace begins with(B0,B1). The algorithm extends the trace with and . At that point, no eligible edges remain. The fourth trace is . The only edge left in the graph is , which runs between two traces and is, therefore, ineligible.
Scheduling
Section titled “Scheduling”Given a trace, the scheduler applies the list-scheduling algorithm to the entire trace, in the same way that superlocal scheduling does. With a trace, one additional opportunity for compensation code occurs; the trace may have interim entry points-block in mid-trace that have multiple predecessors, such as B4 in Fig. 12.10(b).
Forward motion of an operation i on the trace across an interim entry point may add i to the off-trace path. If i redefines a value that is also live across the interim entry, some combination of renaming or recom-putation may be necessary. The alternative is to either prohibit forward motion across the interim entry or to use cloning to avoid this situation(see Section 12.4.3).
Backward motion of an operation i across an interim entry point may force the compiler to add i to the off-trace path. The change is straightforward, since i already occurred on the off-trace path. The scheduler must already correct for any name conflict introduced by the on-trace backward motion; the off-trace compensation code can simply define the same name.
If the interim entry comes from a previously scheduled block, the scheduler may need to split the entering edge, unless the specific situation can be handled with renaming. The alternative is to prohibit code motion across interim entries if it forces compensation code into an already scheduled trace.
Note that(B8,B5) is a loop-closing edge and, therefore, ineligible.
To schedule an entire procedure, the scheduler first performs renaming over the entire procedure. Next, it repeatedly discovers a new trace and schedules it, until it cannot construct another trace. To schedule an individual trace, it builds a dependence graph for the trace, computes priorities, and performs list scheduling on the trace. The process continues until all the blocks have been scheduled.
Superlocal scheduling can be considered a degenerate case of trace scheduling in which interim entries to the trace are prohibited.
12.4.3 Cloning for Context
Section titled “12.4.3 Cloning for Context”Join points in the control-flow graph can limit the opportunities for either superlocal scheduling or trace scheduling. To improve the results, the compiler can clone blocks to create longer join-free paths. Superblock cloning has exactly this effect (see Section 10.6.1). For superlocal scheduling, it increases the size of the EBBs and the length of some of the paths through the EBBs. For trace scheduling, it avoids the complications caused by interim entry points in the trace. In either case, cloning also eliminates some of the branches and jumps in the EBBs.
For the example CFG shown in the margin, cloning would produce the CFG labeled “Example After Cloning.” Block B5 has been cloned to create separate instances for the path from B1 and the path from B4. Similarly, B3 has been cloned twice to create a unique instance for each path that enters it. Taken together, these actions eliminate all join points in the CFG.
At this point, the compiler can combine some of the blocks, to produce the final CFG, “Example After Combining Blocks.” This step eliminates some control-flow operations, such as the jump from B4 to B5.
Now, the entire graph forms one single EBB. The compiler can select the hottest path, say and schedule it. It can then use as a prefix to schedule B5& 3. Finally, it can use B0 as a prefix to schedule B4& 5& 3. Cloning the CFG eliminates most of the interference between these distinct paths.
Contrast this result with the result of superlocal scheduling on the original CFG. The superlocal algorithm scheduled B4 with respect to B0, as happens with the cloned graph. However, the superlocal algorithm scheduled both B3 and B5 with no prior context. In the cloned graph, each is duplicated and scheduled to a set of specific prefixes. The price of this specialization is increased code size.
Tail-recursive programs can also benefit from cloning. Recall from Sec-tious 7.5.2 and 10.4.1 that a program is tail recursive if its last action is a tail call—a recursive self-invocation. When the compiler detects a tail call, it can convert the call into a jump back to the procedure’s entry. As shown in the margin, cloning blocks in the tail-recursive procedure may create a code shape that gives the scheduler a longer block and a more restricted context with which to work.
The first diagram shown in the margin shows the abstracted CFG graph for a tail-recursive routine, after the tail call has been optimized. Block is entered along two paths, the path from the procedure entry and the path from . The scheduler must use worst-case assumptions about what precedes . By cloning as shown in the lower drawing, the compiler can make control enter along only one edge, which may improve the results of regional scheduling. To further simplify the situation, the compiler might coalesce onto the end of , creating a single-block loop body. The resulting loop can be scheduled with either a local scheduler or a loop scheduler, as appropriate.
Tail Call After Tail-Call Optimization
Tail Call After Cloning and Optimization
SECTION REVIEW
Section titled “SECTION REVIEW”Regional scheduling techniques build longer segments of straight-line code to which they apply list scheduling. The infrastructure of regional scheduling simply provides more context and more operations to the list scheduler, in an attempt to provide that scheduler with more freedom and more opportunities. The quality of the code that the regional scheduler produces is, to some extent, determined by the quality of the underlying scheduler.
Superlocal scheduling, trace scheduling, and superblock cloning before superlocal scheduling can each introduce compensation code. The compensation code takes additional space. It may introduce additional operations along some of the paths. However, experience has shown that the benefits of regional scheduling often outweight the costs.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”-
In regional scheduling, cross-block code motion can necessitate the insertion of compensation code. How can the compiler identify situations in which moving an operation across a block boundary will not require compensation code?
-
Both trace scheduling and cloning try to improve on the results of superlocal scheduling. Compare and contrast these approaches and their expected results.
12.5 ADVANCED TOPICS
Section titled “12.5 ADVANCED TOPICS”Compiler optimization has, since the first FORTRAN compiler, focused on improving code in loops. The reason is simple: code inside loops executes more frequently than code outside of loops. This observation has led to the development of specialized scheduling techniques that attempt to decrease the total running time of a loop. These loop-schedulers can create better schedules than a regional scheduler for one simple reason: they account for the flow of values across the entire loop, including the loop-closing branch.
Loop scheduling comes into play when the default scheduler cannot produce compact and efficient code for a loop. If the scheduled loop has no unused issue slots, loop scheduling is unlikely to help. If, on the other hand, it has a significant number of empty issue slots, then loop scheduling may increase functional unit utilization and decrease the loop’s overall running time.
Software pipelining schedules a loop by mimicking the behavior of a hardware pipeline. It overlaps the executions of successive iterations of the loop so that operations from two or more iterations execute concurrently. The pipelined loop decreases the lag between the start of the ith and(i+1)st iterations-the initiation interval of the loop. A smaller initiation interval leads to faster overall execution for the entire loop.
12.5.1 The Strategy Behind Software Pipelining
Section titled “12.5.1 The Strategy Behind Software Pipelining”The speed advantage of software pipelining is simple. For a nonpipelined loop, the initiation interval is simply the number of cycles, c, that it takes to execute one iteration of the loop. If a loop executes n iterations, the total execution time of the loop is n·c.
After software pipelining, the loop starts the(i+1)st iteration before the i th iteration has finished. This strategy produces a smaller initiation interval, ii, which reduces the overall execution time of the loop.
The pipelined loop starts a new iteration every ii cycles. The first n-1 iterations each incur a cost of just ii cycles. The rest is overlapped with later iterations. The final iteration incurs the full cost, c, because the final part of the loop executes on its own. Thus, the total cost of the pipelined loop is(n-1)·ii+c cycles. We can guarantee, by construction, that ii≤c.
From a code shape perspective, the transformed loop consists of a pipelined kernel that performs the steady-state computation, along with a prolog and an epilog to handle the initialization and finalization of the loop. The combined effect is analogous to that of a hardware pipeline, which executes multiple distinct operations concurrently.
p kernel central portion of a software pipelined the kernel, executes most of the loop’s ns in an interleaved fashion.
| Cycle | Functional Unit 0 | Comments |
|---|---|---|
| -4 | loadI | θx ⇒ rθx |
| -3 | loadI | θy ⇒ rθy |
| -2 | loadI | θz ⇒ rθz |
| -1 | addI | rθx, 796 ⇒ rub |
| 1 | L₁: loadAO | rarp, rθx ⇒ rx |
| 2 | loadAO | rarp, rθy ⇒ ry |
| 3 | addI | rθx, 4 ⇒ rθx |
| 4 | addI | rθy, 4 ⇒ rθy |
| 5 | mult | rx, ry ⇒ rz |
| 6 | cmp_LE | rθx, rub ⇒ rcc |
| 7 | storeAO | rz ⇒ rarp, rθz |
| 8 | addI | rθz, 4 ⇒ rθz |
| 9 | cbr | rcc ⇒ L₁, L₂ |
L₂: …
Figure 12.11 Example Loop, Local Scheduler, One Functional Unit.
When the pipelined loop executes, the prolog fills the pipeline. If the kernel executes operations from three iterations of the original loop, then each kernel iteration processes roughly one-third of each active iteration of the original loop. To start execution, the prolog must perform enough work to prepare for the last third of iteration 1, the second third of iteration 2, and the first third of iteration 3.
After the loop kernel completes, the epilog completes the final iterations, which empty the pipeline. In the hypothetical example, the epilog must execute the last third of the second-to-last iteration and the last two-thirds of the final one. The prolog and epilog increase the loop’s overall code size.
To make this discussion concrete, consider the following loop in C:
for (i=0; i < 200; i++) z[i] = x[i] * y[i];
Assume that x, y, and z all have lower bounds of zero. Fig. 12.11 shows the ILOC code that a compiler might generate for the loop, after optimization and local scheduling. Both operator strength reduction and linear function test replacement have been applied (see Section 10.7.2), so the address expressions for x, y, and z are updated with addI operations and the end of loop test has been rewritten in terms of the offset in x, which eliminates the need for i.
Initiation interval
A loop’s initiation interval is the lag, in cycles, between the start of the i th iteration and the start of the(i+1)st iteration. Software pipelining schedules a loop by mimicking the behavior of a hardware pipeline. It overlaps the executions of successive iterations of the loop so that operations from two or more iterations execute concurrently. The pipelined loop decreases the lag between the start of the i th and(i+1)st iterations-the initiation interval of the loop. A smaller initiation interval leads to faster overall execution for the entire loop.
Loop kernel
Section titled “Loop kernel”The central portion of a software pipelined loop, the kernel, executes most of the loop’s iterations in an interleaved fashion.
| Cycle | Functional Unit 0 | Comments |
|---|---|---|
| -4 | loadI @x → r@x | Set up the loop with initial loads |
| -3 | loadI @y → r@y | |
| -2 | loadI @z → r@z | |
| -1 | addI r@x, 796 → r@ub | |
| 1 | L₁: loadAO r@rp, r@x → r@x | Get x[i] & y[i] |
| 2 | loadAO r@rp, r@y → r@y | |
| 3 | addI r@x, 4 → r@x | Bump the pointers in shadow of loads |
| 4 | addI r@y, 4 → r@y | |
| 5 | mult r@x, r@y → r@z | The actual work |
| 6 | cmp_LE r@x, r@ub → r@cc | Shadow of mult |
| 7 | storeAO r@z → r@rp, r@z | Save the result |
| 8 | addI r@z, 4 → r@z | Bump z’s pointer |
| 9 | cbr r@cc → L₁, L₂ | Loop-closing branch |
| L₂: … |
| Cycle | Functional Unit 0 | Functional Unit 1 |
|---|---|---|
| -2 | loadI @x ⇒ rₑₓ | loadI @y ⇒ rₑᵧ |
| -1 | loadI @z ⇒ rₑᵧ | addI rₑₓ, 796 ⇒ rᵤᵦ |
| 1 | L₁: loadA0 rᵒᵣₚ, rₑₓ ⇒ rₓ | nop |
| 2 | loadA0 rᵒᵣₚ, rₑᵧ ⇒ rᵧ | addI rₑₓ, 4 ⇒ rₑₓ |
| 3 | addI rₑᵧ, 4 ⇒ rₑᵧ | mult rₓ, rᵧ ⇒ rᵧ |
| 4 | cmp_LE rₑₓ, rᵤᵦ ⇒ r₰₰ | nop |
| 5 | storeA0 rᵧ ⇒ rᵒᵣₚ, rₑᵧ | addI rₑᵧ, 4 ⇒ rₑᵧ |
| 6 | stall on rᵧ | cbr r₰₰ ⇒ L₁, L₂ |
| 7 | … start of next iteration … |
The code in Fig. 12.11 has been scheduled for a machine with one functional unit. Operation latencies are shown in the margin. The first column in the figure shows the cycle in which each operation issues, normalized to the start of the loop (at label L₁).
The preloop code initializes a pointer for each array (rₑₓ, rₑᵧ, and rₑᵧ). It computes an upper bound for the range of rₑₓ into rᵤᵦ; the end-of-loop test uses rᵤᵦ. The loop body loads x and y, performs the multiply, and stores the result into z. The schedule uses all of the issue slots in the shadow of long-latency operations. During the load latencies, it updates rₑₓ and rₑᵧ. The comparison executes during the multiply. It fills the slots after the store with the update of rₑᵧ and the branch. This produces a tight schedule for a one-functional-unit machine.
Consider what happens to the same code on a two-functional unit, super-scalar processor with the same latencies. Assume that loads and stores must execute on unit 0, that functional units stall when an operation issues before its operands are ready, and that the processor cannot issue operations to a stalled unit. Fig. 12.12 shows the execution trace of the loop’s first iteration. The mult in cycle 3 stalls because neither rₓ nor rᵧ is ready. It stalls in cycle 4 waiting for rᵧ, begins executing again in cycle 5, and produces rᵧ at the end of cycle 6. The storeA0 must stall until the start of cycle 7. Assuming that the hardware can tell that rₑᵧ contains an address that is distinct from rₑₓ and rₑᵧ, the processor can issue the first loadA0 for the second iteration in cycle 7. If not, then the processor will stall until the store completes.
With two functional units, the code executes more quickly. The preloop is down to two cycles, from four. The initiation interval is down to six cy-ies tron, nine. The critical path executes as quickly as we can expect; the
| Cycle | Functional Unit 0 | Functional Unit 1 |
|---|---|---|
| -6 | loadI | 0x |
| -5 | loadAO | r0rp, r0x |
| -4 | loadAO | r0rp, r0y |
| -3 | loadI | 0z |
| -2 | nop | |
| -1 | mult | rx, ry |
| 1 | L1: | loadAO |
| 2 | loadAO | |
| 3 | cmp_LE | |
| 4 | storeAO | |
| 5 | cbr | |
| +1 | L2: | nop |
| +2 | storeAO | |
| +3 | … |
Figure 12.13 Example Loop, Software Pipelined, Two Functional Units.
multiply issues before ry is available and executes as soon as possible. The store proceeds as soon as r2 is available. Some issue slots are wasted(unit 0 in cycle 6 and unit 1 in cycles 1 and 4).
Reordering the linear code can change the execution schedule. For example, moving the update of rx in front of the load from r0y allows the processor to issue the updates of rx and r0y in the same cycles as the loads from those registers. This lets some of the operations issue earlier in the schedule, but it does nothing to speed up the critical path. The net result is the same-a six-cycle loop.
Pipelining the code can further reduce the initiation interval, as shown in Fig. 12.13. The top portion, above the dotted line, contains the loop’s prolog. The central portion contains its five-cycle kernel. The bottom portion, below the second dotted line, contains the loop’s epilog. The next subsection presents the algorithm that generated the kernel for this pipelined loop.
12.5.2 An Algorithm for Software Pipelining
Section titled “12.5.2 An Algorithm for Software Pipelining”To pipeline the loop, the scheduler first constructs an estimate of the minimum initiation interval that the loop needs. Next, it tries to schedule the loop into a kernel of that length; if that process fails, it increases the kernel size
by one and tries again. This process halts; in the worst case, the scheduler reaches the initiation interval of the original, nonpipelined loop. Once the scheduler has the kernel, it generates a prolog and epilog to match.
Estimating Kernel Size
Section titled “Estimating Kernel Size”To estimate kernel size, the loop scheduler can compute lower bounds on the number of cycles that the kernel must contain.
The first lower bound arises from a simple observation: the schedule must issue every operation in the loop body. The number of cycles required to issue all the operations is bounded by:
where u varies over all functional unit types, Ou is the number of operations of type u in the loop and Nu is the number of functional units of type u.RC represents the resource constraint.
Recurrence
The second lower bound arises from another simple observation: the initiation interval must be large enough to let each recurrence in the loop complete. The scheduler can compute the lower bound from recurrence lengths as follows:
A loop-based computation that creates a cycle in the dependence graph
A recurrence must span multiple iterations.where r ranges over all recurrences in the loop body, dr is the cumulative delay around recurrence r, and k, is the number of iterations that r spans.DC is the dependence constraint.
These two estimates, RC and DC, are lower bounds because the scheduler may not find a schedule that fits within that number of cycles.
The scheduler can use ii=max(RC,DC) as its first estimate for the initiation interval. It tries to schedule the loop into ii. If that attempt fails, it increments ii and tries again. We know that it will succeed for some ii in the range max(RC,DC)≤ii≤c, where c is the length of the schedule found by the local scheduler.
To compute RC, the scheduler must account for two different estimates. The loop has a total of nine operations that are scheduled on two functional units, producing a value for RC of[9/2]=5. It has three memory operations that are restricted to unit zero; these operations produce a value for RC of[3/1]=3. Thus, the RC constraint for the loop is max (5,3)=5.
The computation of DC looks at the dependence graph. It contains three recurrences, one for each of r, r, and r. All three have a cumulative delay of one and span one iteration, so DC=[1/1]=1.
With RC=5 and DC=1,ii=max(RC,DC)=5.
(a) Original Code for Example Loop
b) Dependence Graph
■ FIGURE 12.14 Dependence Graph for the Example Loop.
Scheduling the Kernel
Section titled “Scheduling the Kernel”To schedule the kernel, the compiler uses the list scheduler with a fixed-length schedule of ii slots. Updates to the scheduling clock, Cycle in Fig. 12.6, are performed modulo ii. The cycles in the dependence graph introduce two complications for the scheduler to manage.
First, the scheduler must recognize that loop-carried dependences, such as (g,e), (h,f), and (l,k), do not constrain the first iteration of the loop. The first iteration will use values from before the loop, as indicated by the edges from a,b, and c in the dependence graph from Fig. 12.14(b).
Second, the loop-carried dependences expose critical antidependences. In the example, g both reads and writes r0x. For any given value in rx, g cannot update rx before e uses the value in rx. Thus, g cannot be scheduled before e. (They can issue in the same cycle, because e reads its arguments at the start of the cycle and g writes its result at the end of the cycle.) By similar logic, h cannot precede f and l cannot precede k.
Fig. 12.15 shows the steps that the scheduler takes with the example code. It assumes a two functional-unit processor with memory operations restricted to unit zero, and an initiation interval of five.
Module scheduling List scheduling with a cyclic clock is some times called modulo scheduling.
Loop-carried dependence a dependence that represents a value carried along the CFG edge for the loop-closing branch
Figure 12.15 Steps in Modulo Scheduling the Example.
The figure shows reservation-table panels with columns Cycle, F0, and F1 as the scheduler builds the modulo schedule:
| Panel | Scheduled entries |
|---|---|
| Cycle 1 | F0=e, F1=g |
| Cycle 2 | F0=f, F1=h |
| Cycle 3 | F0=j, F1=-- |
| Cycle 4 | F0=--, F1=-- |
| Cycle 5 | F0=m, F1=i |
| Cycles 1, 2, and 3 | rows 1-3 contain e/g, f/h, j/-- |
| Cycle 4 after wraparound | rows 1-5 contain e/g, f/h, j/--, k/l, m/i |
The accompanying text walks through the ready-list decisions. In cycle 2, both f and j are ready; the scheduler places f on unit 0 and h on unit 1. In cycle 3, only j is ready. In cycle 4, m is ready, but the scheduler must leave the cycle empty so the branch transfers after cycle 5. In cycle 5, both m and i are ready and are placed in cycle 5. When the cycle wraps back to 1, the ready list is empty until operation k becomes ready; k executes on unit 0 and makes l ready, and l is placed on unit 1 in cycle 4.
Cycle Functional Unit 0 Functional Unit 1
1 L1:loadAO r_{orp},r_{\theta x}\Rightarrow r_{x}addI r_{\theta x},4\Rightarrow r_{\theta x}
2 loadAO r_{orp},r_{\theta y}\Rightarrow r_{y}addI r_{\theta y},4\Rightarrow r_{\theta y}
3 cmp_LE r_{\theta x},r_{ub}\Rightarrow r_{cc}nop
4 storeAO rz⇒r_{orp},r_{\theta z}addI r_{\theta z},4\Rightarrow r_{\theta z}
5 cbr r_{cc}\rightarrow L_{1},L_{2}mult r_{x},r_{y}\Rightarrow r_{z}
■FIGURE 12.16 Final Kernel Schedule for the Pipelined Loop.
The scheduler repeatedly bumps the counter(modulo 5) until both the active list and the ready list are empty. Since neither operation k nor operation l has any descendants in the dependence graph, both ready and active become empty and the algorithm halts.
Modulo scheduling fails when it does not find an issue slot for some operation. If that happens, the algorithm increments the initiation interval and tries again. The process must halt; when ii reaches the original schedule length, it will schedule in a single iteration.
Generating Prolog and Epilog Code
Section titled “Generating Prolog and Epilog Code”In principle, generating the prolog and epilog code is simple. The key insight, in both cases, is that the compiler can use the dependence graph to guide the process.
To generate the prolog code, the compiler starts from each upward exposed use in the loop and follows the dependence graph in a backward scheduling phase. For each upward exposed use, it must emit the chain of operations that computes the necessary value, properly scheduled to cover their la-tencies. To generate the epilog, the compiler starts from each downward exposed use in the loop and follows the dependence graph in a forward scheduling phase.
The kernel of our pipelined loop, shown in Fig. 12.16, has upward exposed uses for r_{\theta x},r_{\theta y},r_{\theta z},r_{ub},and r_{z}.The original loop had the first four uses. The exposed reference to rz arose because the scheduler moved the storeAO operation from the kernel’s i th iteration to its(i+1)st iteration.
Thus, the prolog still needs the operations that define r_{\theta x},r_{\theta y},r_{\theta z},and r_{ub}.In addition, it must compute the first value of rz and bump the addresses in r_{\theta x} and r_{\theta y} so that the first iteration of the kernel reads the second values of x and y. These constraints produce the prolog shown in Fig. 12.13.
Changing the address computation can lead to a shorter kernel, as shown in Exercise 9.Similarly, use of an autoincrement on r_{py} and r_{p2} would remove operations from the loop and change the schedule.
In this case, the epilog is simple. The kernel executes the entire final iteration, except for the storeA0. Thus, the epilog contains that operation, placed to ensure that the multiply completes before the store issues.
12.5.3 A Final Example
Section titled “12.5.3 A Final Example”C Loop for Example
C6x processors can bundle up to eight operations in a cycle. The|| sequence at the start of a line indicates that the operation goes into the same instruction bundle as the operation on the previous line. The processor has two register banks, the A and B banks. The codes that begin with a period, such as .S1, dictate where in the VLIW instruction this operation fits. Finally.the doubleword load (LDW) reads two numbers from memory; the multiply low (MPY) and multiply high (MPYH) multiply the low-order and high-order numbers, respectively.
The compiler pipelined the loop and fit it into a single VLIW instruction-the operations between the dashed lines in panel (a). The branch has a five-cycle latency; operations can execute in the delay slots of a branch. Thus.the loop prolog code consists of five instructions, each containing a branch. The last two instructions in the prolog also zero the various registers used in the loop, to create the correct initial conditions.
From a software pipelining perspective, the compiler found the minimal initiation interval-it cannot do better than one cycle. The control flow, shown in panel (b), is counter-intuitive. The prolog fills the pipeline with pending branches, so that every iteration of the kernel executes in the delay slot of a branch issued several cycles earlier. We would not expect a typical human programmer to discover this code shape.
The example arose as part of a study on how to derive accurate representations, including CFGs, from optimized assembly code. Needless to say, the CFG in Fig. 12.17(b) obfuscates the original loop structure. Algorithmically deriving the CFG in panel (b) is complicated. Deriving the CFG for the original loop from the optimized assembly code appears to be much harder. The original CFG appears in the margin.
Several details are missing in the code fragment. We assume that 30, 44, and 34 are initialized earlier.
12.6 SUMMARY AND PERSPECTIVE
Section titled “12.6 SUMMARY AND PERSPECTIVE”To obtain reasonable performance on a modern processor, the compiler must perform instruction scheduling. Most compilers use some form of list scheduling. The algorithm is easily adapted and parameterized by changing priority schemes, tie-breaking rules, and even the direction of scheduling. List scheduling is robust, in the sense that it produces good results across a wide variety of codes. In practice, it often finds a time-optimal schedule.
Variations on list scheduling that work over larger regions address problems that arise, at least in part, from increased processor complexity. Regional and loop scheduling techniques are responses to the increase in both the number of pipelines and their individual latencies. As machines have become more complex, schedulers need more context to discover enough instruction-level parallelism to keep the machines busy. Trace scheduling was developed for VLIW architectures, which provide many functional units. Software pipelining provides a way of increasing the number of operations issued per cycle and decreasing total time for executing a loop.
CHAPTER NOTES
Section titled “CHAPTER NOTES”Scheduling problems arise in many domains, ranging from construction, through industrial production, through package delivery to spaceflight pay-load planning. A rich literature has developed on scheduling, including many specialized variants of the problem. Instruction scheduling has been studied as a distinct problem since the 1960s.
Algorithms that guarantee optimal schedules exist for simple situations. For example, on a machine with one functional unit and uniform operation la-tencies, the Sethi-Ullman labelling algorithm creates an optimal schedule for an expression tree[321]. It can be adapted to produce good code for expression DAGs. Fischer and Proebsting built on the Sethi-Ullman algorithm to derive an algorithm that produces optimal or near optimal results for small memory latencies[299]. Unfortunately, it has trouble as latencies rise or the number of functional units grows.
Much of the scheduling literature deals with variants on the list-scheduling algorithm. Landskov et al. is often cited as the definitive work on list scheduling[248], but the algorithm goes back, at least, to Heller in 1961[198]. Other papers that build on list scheduling include Bernstein and Rodeh[42], Gibbons and Muchnick[169], and Hennessy and Gross[199].Krishnamurthy et al. provide a high-level survey of the literature for pipelined processors[243,332]. Kerns, Lo, and Eggers developed balanced scheduling as a way to adapt list scheduling to uncertain memory laten-cies[232,257]. Schielke’s RBF algorithm explored the use of randomization and repetition as an alternative to multilayered priority schemes[318]. Mot-wani et al. used a-β tuning to blend two heuristics: one that decreases register pressure and another that increases ILP[278].
Many authors have described regional scheduling algorithms. The first automated regional technique appears to be Fisher’s trace-scheduling algorithm[158,159]. It has been used in several commercial systems[148,259]and numerous research systems[330]. Hwu et al. proposed superblock scheduling as an alternative[211]; inside a loop, it clones blocks to avoid join points, as shown in Section 12.4.3.
Click proposed a global scheduling algorithm based on the use of a global value graph[90]; it was used in the original HotSpot Server Compiler for JAVA[288]. Bala and Rubin developed a technique that can efficiently perform aggressive scheduling techniques, such as cross-block code motion and updates to previously scheduled blocks[33]. They applied the ideas in a global schouler for the Kendall Square Research compiler. Several authors have proposed techniques to make use of specific hardware features [311,330]. Other approaches that use replication to improve scheduling include Ebcioğlu and Nakatani [147] and Gupta and Soffa [183]. Sweany and Beaty proposed choosing paths based on dominance information [339]; others have looked at various aspects of that approach [115,210,338].
Software pipelining has been explored extensively. Rau and Glaeser introduced the idea in 1981 [304]. Lam developed the scheme for software pipelining presented here [245]; the paper includes a hierarchical scheme for handling control flow inside a loop. Aiken and Nicolau developed a similar approach, called perfect pipelining [11] at the same time as Lam’s work.
The example for backward versus forward scheduling in Fig. 12.8 was brought to our attention by Philip Schielke [318]. He took it from the SPEC 95 benchmark program go. It captures, concisely, an effect that has caused many compiler writers to include both forward and backward schedulers in their compilers’ back ends.
EXERCISES
Section titled “EXERCISES”-
Some operations, such as a register-to-register copy, can execute on almost any functional unit, albeit with a different opcode. Can the scheduler capitalize on these alternatives? Suggest modifications to the basic list-scheduling framework that allow it to use “synonyms” for a basic operation such as a copy.
-
Most modern microprocessors have delay slots on some or all branch operations. With a single delay slot, the operation immediately following the branch executes while the branch processes; thus, the ideal slot for scheduling a branch is in the second-to-last cycle of a basic block. (Most processors have a version of the branch that does not execute the delay slot, so that the compiler can avoid generating a nop instruction in an unfilled delay slot.)
a. How would you adapt the list-scheduling algorithm to improve its ability to “fill” delay slots?
b. Sketch a postscheduling pass that would fill delay slots.
c. Propose a creative use for the branch-delay slots that cannot be filled with useful operations.
- Maintenance of the Ready and Active lists is a major part of the list scheduling algorithm (see Fig. 12.6). At each cycle, the scheduler must determine which operations in Active have completed, and then check
■ FIGURE 12.18 CFG for Question 7.
each successor of a newly completed operation to see if its operands are now ready.
a. Checking, for each successor s, whether all of the operands that s uses are yet available is an expensive part of list scheduling. Suggest a scheme to reduce the asymptotic cost of those checks.
b. To avoid scanning the entire Active list, the compiler writer could implement Active with a separate list for each cycle. How many lists would be needed? How would this scheme affect the cost of scheduling?
c. A clever implementation of the multiple list scheme from part (b) could reuse the list. Sketch the code needed to recycle the lists.
-
In superlocal scheduling, what data structures must the scheduler preserve at the end of a block with multiple successors? Suggest an efficient way to preserve them.
-
Consider the CFG fragment shown in the margin.
Assume that the scheduler has decided to move c from B1 into B0 between a and b. (If that motion is safe, then c does not change a value used in b.) The scheduler must ensure that c also has no impact on e.
-
If c redefines a value used in e, how might the scheduler use renaming to avoid the impact on e? Which definitions and uses must be renamed?
-
If the value is used again in some block that follows B1, how might the scheduler ensure that those uses receive the correct value? Phrase your answer in terms of the LIVEOUT sets for B1 and B2.
-
Working again with the CFG in the margin, assume that the scheduler has decided to move a into block B2. Under what conditions can it avoid inserting a copy of a into B1? | Cycle | Functional Unit 0 | Comments | |------|------------------|----------| | -5 | addI
r_arp, @x ⇒ r_@x | Set up the loop
with initial loads | | -4 | addI
r_arp, @y ⇒ r_@y | | | -3 | addI
r_arp, @z ⇒ r_@z | | | -2 | loadI
0
⇒ r_ctr | | | -1 | loadI
792
⇒ r_ub | | | 1 | L₁: loadAO
r_ctr, r_@x ⇒ r_x | Get x[i] & y[i] | | 2 | loadAO
r_ctr, r_@y ⇒ r_y | | | 3 | mult
r_x, r_y
⇒ r_z | Will stall on r_x & r_y | | 4 | cmp_LE
r_ctr, r_ub
⇒ r_cc | Shadow of mult | | 5 | storeAO
r_z
⇒ r_ctr, r_@z | Save the result | | 6 | addI
r_ctr, 4
⇒ r_ctr | Bump the offset counter | | 7 | cbr
r_cc
→ L₁, L₂ | Loop-closing branch | | L₂: … | | |
■ FIGURE 12.19 Code for Question 9.
- Using the CFG shown in Fig. 12.18.
a. List the extended basic blocks in the CFG, along with each path through each EBB. In what order should the compiler schedule those paths? b. List the traces that the trace construction algorithm will find in the CFG, in the order that they should be scheduled. c. Show the CFG that would result from applying superblock cloning to the CFG in Fig. 12.18. Label nodes with their estimated execution counts.
- Software pipelining overlaps loop iterations to create an effect that resembles hardware pipelining.
a. Discuss the impact that software pipelining will have on the demand for registers in the pipelined loop (versus the original loop)? b. How can the scheduler use predicated execution to reduce the code-space penalty for software pipelining? (Predicated execution is discussed in Section 7.4.2 on page 352.)
- The example code in Fig. 12.11 generates a five-cycle software pipelined kernel because it contains nine operations. If the compiler
generated addresses for x, y, and z in a different way, as shown in Fig. 12.19, it could further reduce the operation count in the loop body. This scheme uses one more register than the original code.
a. Compute RC and DC for this version of the loop. b. Generate the software pipelined loop body. c. Generate the prolog and epilog code for your pipelined loop body.
← node-book_engineering-a-compiler_chapter-11-instruction-selection | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-13-register-allocation →