Elamur Research

Taming Control Divergence in GPUs through Control Flow Linearization

Paper · 2014 · Jayvant Anantpur and R. Govindarajan

Summary

A branch can leave some threads on a GPU waiting while others run. The cost grows when different groups of threads reach the same instructions at different times and the processor issues those instructions separately for each group. Anantpur and Govindarajan trace this behavior to the way the GPU decides where threads should rejoin. Its usual reconvergence point works well for structured control flow. When a program has several routes into a shared block, some threads could rejoin sooner. The paper proposes a compiler transformation that gives them that opportunity. GPU & parallel computing

The transformation, called control flow linearization, gives each thread a variable that records which original block it should run next. The compiler lays out the blocks behind a sequence of checks. A thread enters a block when its recorded destination matches that block, and the threads meet again at the next check. Each original block has a single copy, and every thread still performs its original operations in the order dictated by its own branch decisions. The authors give a linear bound on code growth and describe how the compiler can restrict the transformation to regions that need it.

The same representation lets the compiler change when groups of threads run relative to one another. It can place work from one branch arm between a memory load and its use in the other arm. It can let threads that finish an inner loop early start their next outer iteration and rejoin peers still running the inner loop. Flattening nested branches into successive checks can also reduce the number of pending branches that the hardware reconvergence stack must track. The paper explains these applications through control flow examples and evaluates the basic transformation in the Ocelot compiler framework at the PTX intermediate-code level.

The benchmark results show both sides of the tradeoff. In mum, the authors report a 17.5% improvement in the number of executed instructions, a 48.5% decrease in global loads, and a 68.7% decrease in global stores. Its average kernel time moves from 2242 to 2224 microseconds as its register use rises and occupancy falls. mcx also executes fewer global loads and stores, yet runs slower after the transformation. The compiler generates extra guard work, and the resulting register demand can offset the benefit of bringing threads together sooner. In the benchmarks where the authors could also run an earlier code-copying transformation, linearization produced a smaller increase in PTX instructions.

Deep dive: Taming Control Divergence in GPUs through Control Flow Linearization

Control flow linearization gives GPU threads earlier chances to rejoin after a branch, with trade-offs in code size and register use. · about 37 minutes to read

The problem and its context

When a shared instruction stream splits

A GPU kernel describes the work that many threads will perform. The threads have their own data and can make their own decisions, while the hardware issues instructions to groups called warps. The arrangement makes it possible to express a computation as independent threads and still use a processor that applies a common instruction to several data values. The paper describes this organization in the context of CUDA and OpenCL. The machine can also switch among warps to keep working while an instruction in one warp waits for a result.

Inside a warp, an ordinary data-dependent branch puts pressure on that arrangement. Some threads may satisfy the condition and others may fail it. The machine can run the first path with only its threads enabled, then run the second path with a different set enabled. An active mask records which threads participate in each instruction. A lane whose thread belongs to the other path sits out that instruction. This preserves the individual branch decisions, while the warp spends time issuing work for each participating subset.

To recover full participation, the machine needs a point at which to put the subsets back together. The approach described in the paper uses the immediate postdominator, abbreviated IPDOM, of a branch block. A basic block is a straight-line piece of code with control entering at its start and leaving at its end. A block postdominates another block when every path from the latter to the exit passes through the former. The immediate postdominator is the closest such point downstream. For a conventional conditional with separate arms that meet at a common continuation, that continuation is the natural place to wait for both groups before issuing the following work.

A whole-warp rendezvous answers a question about all paths from the branch. An earlier point may answer a different question about only some of those paths. If a few groups could share an instruction stream before the full warp can rejoin, waiting for the IPDOM leaves them separate for longer than necessary. One group can run a block and move past it, and a later group can arrive and cause that block's instructions to be issued again. Each thread may have done the right amount of work. The duplicate work is at the level of instruction issue for different masks.

The authors illustrate this with a short-circuit Boolean expression. The first condition can make a second condition unnecessary. Threads that take the shortcut proceed directly to a third condition, while those that evaluate the second condition may reach the third one later. Some threads can also go directly to the code for the false outcome. The code after the conditional is common to every path, so it provides the outer branch's IPDOM. The third condition and the false outcome each have incoming routes along which a proper subset of the warp could have met earlier.

The example uses a warp with 4 threads, labeled T1 through T4. T1 and T2 go from B1 directly to B3. T3 goes from B1 through B2 and also reaches B3. T4 goes through B2 to the false outcome. Reconverging at B6, the code after the conditional, leaves B3 to run separately for the group that bypassed B2 and the thread that reached it through B2. In the scenario described by the authors, the false-outcome block B5 runs separately for T2, T3, and T4. The example makes the distinction between a shared block in the program and a shared act of executing it on the GPU concrete.

What makes the graph unstructured

A control flow graph, or CFG, uses blocks as nodes and possible transfers of control as edges. Structured conditionals have well-marked entries and joins. A structured loop has a header through which its body is entered. A CFG can depart from this arrangement in ways that remain perfectly meaningful to a program. The paper points to goto, break, short-circuit expressions, and compiler transformations such as function inlining as sources of these shapes. According to the authors, Wu and colleagues found in an earlier study that 40% of the benchmarks they examined across Parboil, Rodinia and Optix contained unstructured CFGs.

Dominance is the entry-side counterpart to postdominance. A block dominates another when every path from the graph's entry to the latter goes through the former. Together the two relations let the authors identify edges that cross the usual boundaries of a branch or a loop. Their definition first flags an edge from a block with several successors into a block with several predecessors when neither endpoint dominates or postdominates the other. Such an edge can enter shared code without every route to that code going through its source, and without every route out of its source going through its destination. The short-circuit example contains edges of this kind.

A second case concerns an edge into a loop from outside it. If the destination fails to dominate every block in the loop, the edge enters somewhere other than a header through which all paths to the body must pass. The third case concerns an edge out of a loop. The source of the edge is inside the loop and fails to postdominate the rest of it. The source therefore cannot serve as the common point through which control passes after those other loop blocks. The paper calls a graph unstructured when it has an edge of any of these kinds. The authors base the coverage of the definition on prior transformations and their examination of benchmark CFGs.

Unstructured control flow and divergence are related through execution. A block can be unstructured in the graph even if every thread currently follows the same path through it. A structured branch can diverge whenever its condition varies across threads. Structuring the graph changes where a diverged warp can rejoin and the order in which its subsets can be scheduled. The branch conditions from the original computation still determine which operations each thread performs.

Other costs of keeping paths separate

Separate execution can hurt even when the paths end at a sensible common join. Consider two branch arms with several blocks apiece. A load in the first arm delivers a value needed a little later on that arm. When the use is reached before the value is ready, the processor may have to wait. If the hardware runs that arm to its reconvergence point before starting the second, instructions on the other arm cannot fill the interval. Other ready warps can help hide the delay. The paper is concerned with the case where there is too little other work ready and the current warp already has independent instructions on its deferred path.

Nested loops present a different kind of wait. A thread that leaves an inner loop early can be held at the inner loop's join while others continue. It may have work ready in the remainder of the outer iteration or at the start of the next one. It might even be able to run the same inner-loop body again, with its local loop variables now belonging to a later invocation. A path schedule that keeps the warp together at the inner loop's exit gives up that opportunity. The gap between the threads' trip counts determines which lanes have work left in the current invocation.

There is also a cost to tracking pending paths. The stack mechanism discussed in the paper records the next program counter for a path, its active mask, and a reconvergence program counter. A program counter identifies where execution resumes. As divergent branches nest, the machine can encounter a new split while it still holds the pending work and reconvergence state for the enclosing split. The paper follows an example with 4 threads in which one thread takes the alternative path at each nested branch. With the assumed push order, the stack reaches 7 entries at the innermost statement. The shape of the control flow determines how many unresolved decisions the machine needs to remember simultaneously.

Earlier approaches described by the authors

Previous compiler work had already addressed graph structure. The paper discusses transformations by Zhang and colleagues, which Wu and colleagues implemented at the PTX level in equivalent form. Forward copying handles cross-edges in acyclic regions by duplicating code. Backward copying can create a copy of a loop to peel an iteration and handle an incoming edge. A separate transformation deals with an outgoing edge from a loop. A copy gives paths distinct versions of code so the graph can have cleaner branch and loop boundaries. The cost is that those versions occupy space even when the original contained a single block.

The authors also discuss a result by Carter and colleagues about converting irreducible graphs to reducible ones by splitting nodes. An irreducible graph can contain cyclic control flow with several ways into the cycle, preventing a single original header from dominating the body. Node splitting can require an exponential expansion for this conversion. The paper notes that the result concerns that family of transformations and leaves room for schemes that represent control decisions in variables. This distinction motivates keeping the original blocks and spending instructions on dispatch.

Several other approaches change how the machine manages divergent threads. Thread Frontier, by Diamos and colleagues, combines compiler information about where other groups could be with hardware that looks for waiting threads and prioritizes execution. Rhu and colleagues proposed keeping the paths of a branch available in a dual-path stack so their work could be interleaved. Dynamic warp formation groups threads according to their next program counters. Dynamic warp subdivision lets parts of a warp advance separately, and thread block compaction can form warps from threads across a block using a common stack. These approaches change the machinery that chooses which threads run together.

The related work also includes compiler analyses for detecting branches that will be uniform across threads. The authors point out that such analyses could help decide where linearization can be skipped. They describe Han and colleagues' existing compiler transformation for combining a divergent loop with enclosing loops, and they mention a technique for flattening C++ control flow for obfuscation by determining jump targets dynamically. Linearization shares the broad idea of putting control information into a value. Its particular concern is the layout of the guard checks and the opportunities that layout creates for warp reconvergence.

The method, step by step

Give each thread a next destination

The compiler starts with the CFG and assigns identifiers to the basic blocks it will transform. It introduces a variable, called gv in the paper, whose value is the identifier of the next original block to execute. The entry initializes the variable to the correct starting destination. Original branch conditions still get evaluated. Their outcome now chooses what value goes into gv. An unconditional successor needs only a fixed assignment, and a fall-through in the original graph likewise has a known destination. The variable does the part of a program counter's job that concerns the next block of user code.

Each original block gets a guard before it. The guard checks whether the current thread is supposed to run that block. Threads with a matching value execute the body. Other threads skip it. At the continuation of the guard, both groups are available for the next check. That next check might select some threads that just ran the preceding body and some that skipped it. The machine's reconvergence stack can service each small conditional using the rewritten control flow.

Here is the destination update at the end of B1 in the short-circuit example, where the outcome of c1() originally determined the outgoing edge.

gv ← if c1v then B3id else B2id

gv is the thread's next-block variable. The arrow ← assigns a value. c1v is the saved result of the call to c1(). B3id is the identifier for B3, which evaluates the third condition, and B2id is the identifier for B2, which evaluates the second. The two alternatives reproduce the original successors of B1. The guard for B3 subsequently tests that recorded destination.

gv = B3id

Here = tests equality. gv is the current next-block value, and B3id identifies the body protected by the guard. A thread with this value enters B3. The same test is made across the warp, with each thread supplying its own gv.

This is enough to see how the short-circuit example changes. After B1, the group that already wants B3 skips B2. The group that needs B2 executes it. A thread that discovers in B2 that it should also go to B3 writes that destination. The groups come together at the guard for B3, which now admits the direct arrivals and the arrivals from B2 in the same pass. The thread that needs the false-outcome block keeps that destination while passing the check for B3. Other threads may acquire the same destination after evaluating the third condition. When the sequence reaches B5, its guard can admit those threads together.

How the compiler linearizes a control flow region

The steps in order.

How the compiler linearizes a control flow regionStep 1: Find the region and its entry and exit1. Find the region and its entry and exitStep 2: Order its blocks for forward progress2. Order its blocks for forward progressStep 3: Give each block a destination check3. Give each block a destination checkStep 4: Record the original successor after each body4. Record the original successor after each bodyStep 5: Rejoin threads at the next check5. Rejoin threads at the next checkStep 6: Add guarded returns for backward destinations6. Add guarded returns for backward destinationsStep 7: Remove checks made redundant by known destinations7. Remove checks made redundant by known destinations

Choose where to start and stop the sequence

The initial description treats all ordinary blocks of an unstructured CFG as the region to linearize, leaving its entry and exit as boundaries. A smaller transformation needs a way to find the corresponding boundaries inside a larger function. For a set of blocks the compiler looks for the common immediate dominator, or CIDOM. It dominates every block in the set, and it is the closest common dominator in the sense that every other common dominator dominates it. The common immediate postdominator, or CIPDOM, applies the same relationship looking towards the exit. Every block in the set is postdominated by it, and every other common postdominator postdominates it.

These boundaries give the guard sequence a place to begin and a place to continue into the surrounding graph. The first guard is reached from the region's common entry boundary. At the end, the final body and the skip route from its guard go to the common exit boundary, subject to the handling of loop edges. The boundaries also matter when an internal block has a predecessor outside the initial set. If that predecessor can enter the interior through another route, starting a sequence of guards at the proposed entry would leave that route unaccounted for. The region calculation expands the set to establish the desired entry and exit conditions.

Within the boundaries, the default order is reverse postorder. The compiler explores the CFG by depth-first traversal, records blocks as it finishes exploring them, and reverses that finishing order. In acyclic portions this puts predecessors ahead of their successors. A thread can then visit the guards in order and reach the selected successor later on the same pass. A cycle requires some edge to point to a block earlier in the order. The paper calls an edge retreating when its destination precedes its source in the chosen order. This is the case that calls for a guarded return.

The order has a direct execution cost. If B5 were laid out before B3 in the short-circuit example, a thread that chose B5 after running B3 would need a return route. In the paper's forward layout, the existing scan reaches it. The same point applies to a check a thread skips. A long gap between a body and its successor may mean several intermediate guard instructions even though none of those bodies runs for that thread. The order gives the compiler control over a scheduling decision and determines some of the overhead of exercising that control.

Build the front-to-back control flow

For a block in the order, the compiler creates a guard with an edge into the body. The other edge skips the body and goes to the next guard. After the body finishes and sets gv, it also goes to that next guard. Thus the next guard is shared by the route that executed the current body and the route that skipped it. For a chain without cycles, this completes the links in the new graph. In the short-circuit example the compiler creates guards for B1 through B6, adds the destination updates in B1 through B5, and connects the paths at the end of the sequence to the exit.

It helps to follow the two kinds of state separately. The hardware program counter follows the checks and their bodies in the rewritten graph. The value of gv says where a given thread should next perform an original operation. Several checks can execute while gv keeps its value. When the matching original operation runs, it can write a new value. This separation lets threads meet at a guard even when they still have different destinations. Reconvergence makes the full set available to take the check, and the check can immediately select a subset for the next body.

In the straightforward acyclic case, the fall-through successor of a guard is its immediate postdominator. Both the body path and the skip path reach that successor. The divergence associated with choosing the body is therefore short-lived. The proof of structure groups each guard, body, and join into a single-entry, single-exit unit. The join may be empty when it simply hands control to the next guard. In that case it can be removed by connecting its incoming edges directly to its successor. The separate join is useful in reasoning about the graph even where the compiler emits no code for it.

Represent cycles with guarded returns

A forward scan by itself cannot schedule a visit to a destination the scan has already passed. At the source of a retreating edge, the compiler introduces a further guard for taking the return. The body and its skip route meet at that guard. Depending on the encoded destination, the return guard sends execution toward an earlier guard or allows it to continue forward. The original loop decision still comes from the value computed by the body. The new branch reads that decision together with the layout of the sequence.

The paper illustrates this with the retreating edge from B4 to B2 in an example where other edges leave the loop irregularly. An extra guard after B4 provides a back edge to the guard for B2. A thread that should exit the loop can carry the identifier of a later block. A thread that should go around again is enabled for the guarded return. Both paths have explicit structural points in the transformed graph, including the fall-through after the return, where the reconvergence machinery can operate.

Some backward transfers would produce partially overlapping loops if each edge simply returned to the guard for its own destination. The authors describe moving the target of such a return up to an existing loop header. In their example, adding an original edge from B5 to B3 would send the corresponding transformed return to the guard for B2. The thread can still hold the identifier for B3. It passes the test for B2 without running B2, then runs B3 when its guard is reached. This change to the routing of checks keeps the original destination intact and gives the rewritten loop a common entry. The resulting loop intervals are intended to be disjoint or nested.

This is also how an irreducible graph can acquire a reducible structure without copying its loop bodies. A side entrance into a cycle can be represented by an identifier for an interior block. The new graph routes execution through a common header, and the guards enforce that interior destination. The authors show an example for which either B1, B2, B3 or B1, B3, B2 can be chosen as the order. Both layouts can be made reducible. The freedom matters because reverse postorder can differ according to which successor the traversal visits first.

Why the rewritten graph preserves the computation

The structural argument operates at two levels. Within the unit formed by a guard, its body and its join, the guard dominates entry into the body and the join postdominates completion of the alternatives. The unit contains no cycle. Between units, the default links are successive, and the guarded returns form natural loops, with a header that dominates the loop. The arrangement of returns keeps loops nested or disjoint. This lets the authors argue for structure inside each unit and in the graph made by composing the units.

The semantic argument concerns the sequence of original blocks that each thread executes. If a block has no successor, it can assign an unused value so no later original body is selected. If it has one successor, the assignment records that successor. If it has two, the original condition selects the identifier. A thread may then go through intervening checks to get to its destination. Those checks leave the application's values alone. Starting at the assigned entry, each original transfer therefore has a corresponding transition in the rewritten code, with guard operations along the way.

The argument also runs in the reverse direction. Take two consecutive original bodies executed by a thread in the new graph. The second can run only if its identifier matches the destination recorded after the first. That identifier was chosen from the original successors according to the original control decision. Thus the guard sequence cannot introduce a new transition between application blocks. This direction matters for a layout that scans through unrelated bodies or reaches an earlier guard during a loop return. Being physically next in the new graph does not make a body the next part of the thread's computation.

Linearization can change which subsets issue a particular block together, and can change when one subset's work runs relative to another's. Its preservation argument rests on keeping the original path of each thread. Its reconvergence argument rests on the new layout. Ordinary guards bring the executing and skipping threads together at the next check. When the transformation can route several arrivals to the same body in the same pass, that body can issue for the combined group. A loop body can still execute repeatedly for the same thread, as required by its original trip count.

Find the smallest region that contains an irregular edge

Applying the transformation everywhere would add checks to code whose existing structure already gives the hardware a good place to rejoin. The authors therefore give an algorithm that starts from each unstructured edge. The initial set contains the source and destination. From the current set the analysis finds its common immediate dominator and postdominator. It then identifies blocks by looking from the entry boundary towards the exit and from the exit boundary back towards the entry.

UN₂ ← (N₁ ∩ N₂) ∪ (N₃ ∩ N₄)

UN₂ is the next set of blocks being considered for the unstructured region. N₁ contains blocks dominated by the current common entry boundary, while N₂ contains blocks that can reach the current common exit boundary. N₃ contains blocks postdominated by that exit boundary, and N₄ contains blocks reachable from the entry boundary. The symbol ∩ selects elements common to both sets on its sides, ∪ combines the resulting sets, and ← assigns the result. The first intersection finds blocks reached under the entry condition that can continue to the exit. The second finds blocks reachable from the entry for which the exit is the common downstream point.

UN₂ = UN₁

UN₁ is the current set and UN₂ is the set produced by the update. Here = is the equality test used to decide when to stop. If the sets differ, the new set becomes the current one, its boundaries are found again, and the analysis repeats. A newly included block can require wider boundaries, so the algorithm determines the region from a stable set.

The definition keeps the boundary blocks outside the region's interior. Incoming edges to the interior must originate either inside it or from the entry boundary. Outgoing edges must stay inside or reach the exit boundary. These closure conditions express what allows a guard sequence to replace the interior while remaining connected to the rest of the program in the expected way. The authors state that regions found for different irregular edges can be disjoint, equal, or contained within one another. Partial overlap would defeat the simple choice of an independently transformable enclosing region.

An unstructured region can itself contain a well-formed conditional or another structured piece of code. The compiler searches for these pieces using pairs of immediate dominator and postdominator boundaries, then checks the blocks between them for the required relationships and for the absence of unstructured edges. A structured subregion includes its own entry and exit. If the entry is skipped, its interior and exit can be skipped together. When it is entered, the original graph can handle its internal decisions and joins. The transformation guards its entry and leaves the interior in its original form, saving guard work and preserving structure for other compiler passes.

Remove checks that cannot affect a path

After forming the new graph, the compiler analyzes which destination values can arrive at each guard. Original bodies contribute the identifiers they can assign. A guard for a body admits the matching identifier on the edge into that body and passes the remaining values along its skip edge. A retreating-edge guard may accept several destination values on its return edge, since different original destinations can share the same transformed return. The compiler keeps propagating sets of possible values through the graph until the inputs to the guards stop changing.

The termination argument uses the finite supply of block identifiers. During the analysis, a guard's input set can grow when the compiler discovers another way to reach it. A recorded value stays in the set. The test along each outgoing edge depends on the guard, so the analysis can use the stabilized information to tell which predecessor edges are incapable of supplying a match. This is a compile-time analysis of the program's possible destinations. It needs neither example executions nor training data.

The first optimization, O1, redirects incoming paths when their possible destination values allow them to bypass a check. If only one incoming edge can supply the matching value, the other incoming edges can go straight to the following guard. The paper also describes redirecting a sole nonmatching edge past the test. The useful distinction is between a guard that can perform some dispatch for an incoming edge and a guard that would just pass that edge through.

The second optimization, O2, uses dominance in the original graph. If reaching one original block requires passing through another, the compiler can nest the corresponding checks in the circumstances described by the authors. The inner check then runs under the outer check rather than being tested on the full stream of guard visits. The third optimization, O3, merges a guard into its predecessor when the guard has a single predecessor and that predecessor is an original block in the region. The evaluation also reports O4, which adds miscellaneous optimizations to the preceding set.

There is a static cost even after the compiler omits some checks. The paper counts a guard for each transformed body and an additional guard for each retreating edge. Its bound uses the authors' claim about the number of retreating edges in the graphs under consideration. A guard adds a comparison, a fall-through body needs an assignment, and an original branch can be replaced by a destination assignment. The authors conclude that the increase scales linearly with the counts of blocks and instructions. That accounting concerns the representation constructed by the transformation. Once the code runs, the number of visits to its guards can depend on path choices and loop trip counts.

Use the layout to change when paths run

For branch interleaving, the paper starts with a branch whose arms contain independent work for different threads. B2 on one arm loads a value used by B3 and B4. B5 is the first block selected on the other arm. With the usual order, the processor can reach a use in B3 while the value loaded in B2 is pending. The illustrated transformed order puts B5 between B2 and B3. Threads that chose the second arm have a chance to execute their work during the interval. Threads that chose the first arm retain their destination while B5 runs and then enter B3 together when their check arrives.

The extra distance between a load and its use can help when the machine only stalls on reaching a use whose operand is unavailable. The extent of the gain depends on what the inserted work does and whether enough threads reach it. The authors also describe the case in which a block both loads and uses a value. Splitting it into a load portion and a use portion would let the compiler put independent work between them. This extends the layout decision to a pair of operations that originally shared a basic block. The figure illustrates a possible schedule, and the paper leaves the choice of such schedules to future heuristics.

For loop merging, the paper uses two threads with inner-loop trip counts that change across outer iterations. T1 has counts of 10 and 15, while T2 has 15 and 10. In the original execution, the inner loop runs for 15 iterations of the warp on each outer iteration. When T1 finishes its first invocation after 10 iterations, it waits through the remaining 5 iterations of T2. Its next invocation has work ready once it has finished the intervening outer-loop code. The example is designed so that letting it advance would put both threads back in the inner body sooner.

The transformed inner and outer loops share a guarded return. A thread continuing its current inner invocation records B4 as its destination. A thread ready to start the next outer iteration records B2. Both requests use a return to the guard for B2. A thread targeting B4 skips the intervening bodies. A thread targeting B2 can execute B2 and B3, then reach the guard for the inner body. The same issue of that body can now serve threads on different invocations. Their loop state remains local to each thread. The gain the authors seek is fewer intervals in which a ready lane waits for all its peers to finish an invocation.

The third application is to flatten nested divergent branches so fewer reconvergence records accumulate. In the stack example, the original branches can split again before their enclosing branch has rejoined. Under the illustrated linearization, threads that split at the guard for B2 have rejoined by the guard for B4. The pending state for the first split has been resolved before the next one. The authors suggest using this selectively, applying linearization to branches beyond a desired nesting limit. This application makes the depth of pending divergence a reason to linearize even when the compiler is starting from structured code.

Experiments and results

What the authors ran and measured

The evaluation uses an implementation in Ocelot. The compiler front end builds a CFG from PTX version 2.3. The pass rewrites that graph, and the modified PTX is compiled just in time for execution. The main setup uses CUDA toolkit version 4.2 and a Tesla C2070 from the Fermi family, with the default compiler optimization level. Each benchmark is run 10 times, and the reported execution time is the average. The authors use the CUDA profiler to obtain the run time and other counters. There is no data split or training stage in this experiment. The compiler analyzes each input kernel before the measured execution.

The benchmarks are hotspot, heartwall, mcx, mum, nqueen, particlefilter and ray. The core comparison pairs the original kernel with the same kernel after optimized linearization. Static measurements include the number of PTX instructions, the number of basic blocks, allocated registers and SASS instructions. SASS is the assembly representation executed by the GPU. These measures describe different points in the pipeline. A change in the graph can disappear when the downstream compiler simplifies it, or it can produce costs in register allocation and assembly that a count of PTX instructions alone would miss.

The dynamic measurements are average kernel time, executed assembly instructions, executed global loads and executed global stores. The instruction and memory counters are aggregate measurements over threads and streaming multiprocessors. A streaming multiprocessor is the unit on the GPU that executes scheduled warps. An executed instruction count measures work done during the input run. A static instruction count measures the size of the generated program. A guard emitted once can contribute many times to the former, while a body that issues for fewer separated groups can contribute less even if its static code stays the same.

The paper reports ratios for the static measurements as well as the raw counts. Its convention is:

Incr = AfOpt / Bf

Incr is the reported size or resource ratio. AfOpt is the value of the measure after optimization of the linearized code. Bf is its value before linearization. The slash / denotes division, and = defines the ratio. Values in the column express the optimized quantity relative to its original counterpart. The immediate post-transformation counts are separately available for PTX instructions and basic blocks, which lets the authors show how much of the expansion survives optimization.

Code size and register use

After optimization, the PTX increase is under 5% in 6 out of 7 benchmarks according to the authors, with the largest increase, 10%, in mum. In that kernel the static PTX count goes from 232 before linearization to 259 immediately after it and 256 after optimization. The basic-block count changes from 37 to 51 and then to 47. Its reported increase of 27% in basic blocks is the highest in the suite. A guard can account for a block in the CFG while adding relatively little PTX, which is one reason the two size measures need to be read separately.

ray shows a more pronounced difference between the immediate and optimized layouts. It starts with 84 basic blocks, reaches 148 after transformation, and has 90 after optimization. Its PTX counts are 780, 869 and 805, respectively. particlefilter starts with 10 blocks, reaches 17, and returns to 10 after optimization. Its PTX counts are 52, 63 and 54. These measurements show that the guarded sequence constructed by the initial pass can have many features the compiler later removes or combines. An unchanged final number of blocks still allows shifts in their contents, their connections and their execution frequency.

SASS counts increase by up to 12% in the suite, as reported by the authors. The mum kernel moves from 202 to 226 assembly instructions. particlefilter goes from 52 to 51, even though its PTX instruction count rises. Register requirements can move independently of both counts. The paper reports that 4 of the 7 benchmarks require increases of 10% or more in registers. hotspot, heartwall and particlefilter retain their original register counts. Among the cases with increases, ray goes from 43 to 50 registers, and nqueen goes from 16 to 18. The two cases the authors discuss most closely are mum and mcx, where register use affects how to interpret the runtime results.

The runtime results depend on the kernel

The time measurements are mixed. mum moves from 2242 to 2224 microseconds, and nqueen moves from 112 to 110. Among the slower kernels, hotspot moves from 342 to 360 microseconds, particlefilter from 187 to 205, and ray from 163 to 173. The times for heartwall are reported as 4.22× 10⁴ before and 4.23× 10⁴ after optimization, in microseconds. The result for mcx rises from 3.15× 10⁶ to 3.97× 10⁶ microseconds. These are kernel averages for the reported runs on the stated GPU.

Original and linearized mum kernel by mean execution time

Optimized linearization gives mum a slightly shorter mean kernel time.

Original and linearized mum kernel by mean execution timeOriginal mum: 2242Original mum2242Optimized linearization (this paper): 2224Optimized linearization (this paper)2224
The numbers
System or settingmicroseconds
Original mum2242
Optimized linearization (this paper)2224

For mum, the aggregate executed assembly instruction count goes from 7.80× 10⁶ to 6.43× 10⁶, corresponding to the 17.5% improvement reported by the authors. The global-load count goes from 1.69× 10⁵ to 8.76× 10⁴, and the global-store count goes from 5.99× 10⁴ to 1.87× 10⁴. The reported reductions are 48.5% and 68.7%, respectively. Fewer issues of memory operations and fewer executed instructions are consistent with useful work being shared across groups in the transformed graph. The reported run time also reflects the resources available to schedule that work.

The authors follow this through the register allocation. The mum kernel uses 22 registers before the transformation and 32 afterward. Its reported occupancy moves from 0.833 to 0.667. Occupancy describes how much of the GPU's capacity to keep warps resident is being used. More registers per thread can restrict the number of warps the machine can hold ready, limiting its ability to switch away from work that is waiting. In this kernel the authors attribute the modest time improvement, relative to the change in the instruction and memory counters, to the lower occupancy.

The mcx kernel illustrates a distinct effect of register demand. The paper reports a 4.4% decrease in global loads and a 13.3% decrease in global stores. Executed assembly instructions rise from 2.64× 10¹⁰ to 3.05× 10¹⁰, and the kernel takes longer. The register count grows from 57 to 63. The authors identify 63 as the allocator's upper limit on the GPU they used and observe that the generated code spills register values to global memory. Spilling adds work to save and retrieve values that cannot be kept in registers. They attribute the slowdown to the resulting pressure on the memory system and increase in cache misses.

For heartwall, the paper reports a 2.5% decrease in global stores, with the global-load count unchanged at the displayed precision. Its executed instruction count changes from 4.68× 10⁸ to 4.71× 10⁸. In hotspot, both displayed global memory counters are unchanged, while the executed instruction count rises from 4.32× 10⁶ to 4.57× 10⁶. particlefilter also shows unchanged global memory counters and an increase in executed instructions, from 1.02× 10⁵ to 1.49× 10⁵. This part of the suite makes clear why the success of reconvergence as a graph property and the instruction cost of any given kernel execution need separate measurements.

Comparison with a code-copying baseline

The authors also compare static PTX size against the earlier transformation by Wu and colleagues. Both transformations run within the Ocelot framework for the comparison. The authors could get the earlier implementation working for only 3 benchmarks. They used CUDA toolkit version 4.0 for hotspot and particlefilter in this comparison. The baseline PTX counts for those cases belong to this setup. They differ from the counts for the corresponding kernels in the main transformation statistics.

Static PTX instruction counts for particlefilter with CUDA 4.0

Linearization adds fewer PTX instructions than the code-copying transformation.

Static PTX instruction counts for particlefilter with CUDA 4.0Original kernel: 54Original kernel54Wu and colleagues: 78Wu and colleagues78Control flow linearization (this paper): 62Control flow linearization (this paper)62
The numbers
System or settingPTX instructions
Original kernel54
Wu and colleagues78
Control flow linearization (this paper)62

For hotspot, the original code in this comparison contains 237 PTX instructions, the earlier transformation produces 242, and linearization produces 240. For heartwall, the corresponding counts are 1422, 1452 and 1432. The static result favors linearization over copying in all the cases where the comparison ran. Both methods have the purpose of structuring the input. The comparison isolates one practical difference in their output, the PTX size, and the paper gives no corresponding head-to-head runtime figures.

What the ablations show

Unoptimized linearization and successive guard optimizations

The authors provide a sequence of controlled compiler settings. They compare the original program, the program immediately after linearization, and successively optimized versions. The optimization levels are cumulative. O2 includes O1, O3 adds merging a guard with its predecessor where possible, and O4 adds miscellaneous changes beyond the named optimizations. The outcome measured in this comparison is the number of executed assembly instructions. Each transition therefore shows the effect of adding a pass or group of changes to a particular preceding configuration.

mum is the clearest case in which linearization itself reduces dynamic instruction work. Its count moves from 7.80× 10⁶ in the original to 6.90× 10⁶ immediately after the transformation. It then reaches 6.66× 10⁶ at O1, stays at the displayed 6.66× 10⁶ at O2, goes to 6.60× 10⁶ at O3, and reaches 6.43× 10⁶ at O4. The benefit begins with the new graph. The subsequent passes make instruction execution cheaper within that layout, with their visible measured contributions differing across levels.

ray shows what happens when most of the benefit of the added passes goes into recovering the cost of the initial transformation. The original executes 1.82× 10⁶ instructions and the unoptimized transform executes 2.50× 10⁶. O1 brings that to 2.16× 10⁶ and the later levels bring it to 1.89× 10⁶. The approach closes much of the gap introduced by guards, while the final count remains above the original. That outcome is compatible with a better-structured graph whose added checks outweigh the avoided issues in this run.

For mcx, the count rises from 2.64× 10¹⁰ to 3.7× 10¹⁰ with the unoptimized transform. It then falls to 3.36× 10¹⁰ at O1, 3.26× 10¹⁰ at O2, 3.18× 10¹⁰ at O3, and 3.05× 10¹⁰ at O4. The successive passes reduce the observed instruction overhead. The final value still sits above the original, and the runtime diagnosis also implicates effects from register allocation. Guard removal and the number of live registers affect different aspects of execution, so an improvement along the optimization sequence does not by itself predict the final time relative to the baseline.

Why individual optimization levels can go the other way

The optimization sequence is not uniformly decreasing. In particlefilter, the count starts at 1.02× 10⁵ and rises to 1.77× 10⁵ with unoptimized linearization. O1 raises it again to 2.14× 10⁵. The following levels bring it to 1.86× 10⁵, 1.68× 10⁵ and ultimately 1.49× 10⁵. The table establishes the direction of these changes. It leaves open how much comes from a different frequency of guard execution and how much comes from the way the downstream compiler lowers the modified PTX.

hotspot also rises at O1, from 4.90× 10⁶ to 4.98× 10⁶, before falling at later levels. In heartwall, O3 matches the original figure of 4.68× 10⁸ at the displayed precision, and O4 gives 4.71× 10⁸. The paper describes the optimizations as helping reduce executed instructions. The individual measurements support that description as a tendency across the sequence, with reversals and ties in particular kernels. Since the levels build on one another, the table cannot give the cost or benefit of enabling a later optimization by itself on the unoptimized graph.

The static counts help explain what the compiler is capable of removing. For example, the nqueen graph has 37 basic blocks immediately after the transform and 31 after optimization, compared with 30 in the original. The successive dynamic measurements nevertheless stay close to the original, moving from 5.94× 10⁴ originally to 6.01× 10⁴ immediately after transformation and 5.96× 10⁴ at O4. A substantial fraction of the extra static blocks can disappear without yielding a reduction in the executed instruction counter. Static simplification establishes how much code the compiler leaves behind. Dynamic counters also depend on when the surviving code is reached.

What the examples establish separately

The examples control the paths taken by individual threads so the mechanism is visible. In the short-circuit example, the original branch decisions are held fixed and the guard schedule changes which arrivals at B3 and B5 can be combined. In the branch-interleaving example, the order between a load and its dependent use is held fixed, while a block from the other arm is inserted between them. In the loop example, each thread keeps its own trip counts, while the return schedule changes whether their active invocations have to advance together. In the stack example, reconvergence between guards explains why an unresolved inner split need not be added to an unresolved outer split.

These examples establish feasibility at the level of control flow and thread scheduling. The benchmark optimization series measures the cumulative effect of changes to the basic linearization pass. It does not measure branch interleaving, loop merging and selective stack-depth reduction as independently enabled features. The profiler data can show fewer executed instructions or memory operations for a kernel. The paper does not assign a measured share of those changes to each of the illustrative scheduling applications.

Limitations

Limits identified by the authors

The authors identify PTX as a practical place to implement their pass, given the documentation and the Ocelot infrastructure. They also argue that it is earlier in compilation than they would prefer. Changing the program's control flow at that point can affect later analyses, optimizations and register allocation. The effects are visible in the larger register counts, the reduced occupancy for mum, and the spill code for mcx. A static bound on the added instructions in the transformation does not capture all the work that a later allocation or lowering step can introduce.

Their proposed alternative is to perform the rewrite later, at the assembly level. They estimate that the basic scheme would need one extra integer register for the destination and one extra predicate register for the result of the guard check. Loop merging would require an additional predicate register per merged loop. They suggest reserving those registers by giving the allocator a correspondingly lower limit. The authors say they lacked enough public information about the GPU's assembly instructions to implement the pass at that level. The register arrangement and the more accurate cost estimates they expect at that level are therefore proposals.

The authors also leave the choice of where and how to apply the transformation to future heuristics. The examples identify reasons to consider a rewrite, such as repeated issues at shared blocks, a potential memory stall, differing trip counts or a limit on stack depth. Turning these into a compiler decision requires judging how frequently the relevant paths occur, how much guard work the new layout introduces, and how strongly the lower-level code is affected. The experimental pass demonstrates the transformation and its optimizations. It does not provide an empirically validated policy for picking the best regions and schedules.

Limits of the evidence

The results come from one GPU setup and a small collection of benchmark kernels, with a different CUDA toolkit version used for two cases in the comparison with Wu and colleagues. The measurements establish what happened in these runs. They leave open how the balance between reconvergence, code growth, register demand and memory behavior would change on other hardware or in a different compiler. The limited overlap with the earlier baseline also narrows the code-size comparison. The same runtime evaluation against that baseline would be needed to establish how the two strategies compare in elapsed time.

The paper reports averages over repeated runs and gives no measure of the spread. That matters especially for the small changes in mum and nqueen. The means can be reported as observed, while their reproducibility across new runs cannot be judged from a variability estimate in the paper. A much larger shift in a dynamic counter can help diagnose a change in code behavior, but the counters measure different quantities from time. In mum, for instance, the instruction and memory results are compatible with a worthwhile reconvergence change even though the run-time margin is small.

The instruction counter is also an indirect view of reconvergence. It reflects the combined effects of skipped duplicate issues, newly executed guards, and the code produced by the downstream compiler. The paper does not separately count the number of times each original block was issued for different masks or measure the active-lane fraction at each guard. The short-circuit example explains exactly how duplicate issues can be eliminated. The aggregate benchmark counters indicate the net outcome for those runs, with limited attribution at the level of individual blocks.

The correctness sketches address graph structure and the sequence of original blocks a thread follows. They are most direct when read under the paper's assumptions about CFG entry and exit and the scope of the transformation. In particular, the block-order argument reasons about a thread's original operations while allowing their timing relative to other threads to change. It does not provide a separate treatment of synchronization or other operations whose correctness might depend on cross-thread ordering. Similarly, earliest reconvergence refers to the joins of the newly structured control flow. The evaluation does not compare its schedules against every possible way of coordinating threads in the original graph.

The linear size argument is an accounting result for adding guards and destination updates without copying original bodies. It is not a bound on the number of checks executed in a particular run. Retreating transfers can bring execution through the same sequence again, and a thread with an outstanding destination may skip several guards before its next body. The experiments show why the distinction matters. After optimization, some kernels retain modest static size changes while still executing more instructions. Whether a useful shared execution offsets those checks depends on the paths taken together on the GPU.

The individual scheduling applications have different prerequisites. Branch interleaving needs work on the other arm that can be placed between a definition and a use, and the expected gain requires the latency to matter in the first place. Loop merging needs enough overlap in useful work across invocations to justify the extra dispatch and any predicates they require. Lowering the maximum stack depth can be valuable as a control-flow property even if the chosen flattening increases execution work. The paper supplies constructions for these cases, with no separate benchmark series quantifying the range over which each pays off.

What came after

The paper closes by identifying two directions for follow-up work. Moving linearization to a lower intermediate representation would let the compiler estimate costs closer to the code the GPU executes and test whether the extra register demand can be contained. Developing heuristics would turn the examples for branch interleaving, loop merging and stack-depth control into compiler choices that can be evaluated across kernels. These are the authors' proposed next steps. No later studies are documented here that establish how those proposals were taken up or how subsequent implementations changed the results.

Cite

Cite as Jayvant Anantpur and R. Govindarajan. 2014. Taming Control Divergence in GPUs through Control Flow Linearization. Lecture notes in computer science.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1007/978-3-642-54807-9_8

@inproceedings{anantpur2014taming,
  title = {{Taming Control Divergence in GPUs through Control Flow Linearization}},
  author = {Jayvant Anantpur and R. Govindarajan},
  booktitle = {Lecture notes in computer science},
  year = {2014},
  doi = {10.1007/978-3-642-54807-9\_8},
  url = {https://doi.org/10.1007/978-3-642-54807-9_8}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/anantpur-2014-taming-control-divergence-gpus-through/