Algorithmadvanced
Pettis-Hansen code positioning
Also called profile-guided code layout.
Orders basic blocks and procedures by greedily merging chains along the heaviest edges of the profile, to improve instruction cache use.
- Time
- O(E log E + C E) worst
- Space
- Θ(V + E) extra
- Where
- C = the number of chains left after merging; E = the number of CFG edges with a profile weight; V = the number of basic blocks of the procedure
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Pettis-Hansen code positioning puts the basic blocks of each procedure, and the procedures of a program, in an order chosen from a profile. Inside a procedure it builds chains of blocks: it takes the control-flow graph edges from the most frequent to the least frequent, and joins two chains when the edge goes from the end of one to the start of the other. The frequent edges then become fall-throughs, which need no taken jump and keep the hot code dense in the instruction cache. Across procedures it does the same on the call graph, so that a caller and a callee that call each other often end up close in memory. Choosing the best layout is NP-hard, and the greedy merge is a fast approximation of it.
In plain words
A program is stored in memory as one long line of code. When the processor runs one block and the next block it needs is right after it, it just keeps going. When the next block is somewhere else, it has to jump, and the code it fetched around the first block is partly wasted. A profile says which moves from block to block happen most. The method starts with every block on its own and then, from the most common move downwards, glues the two pieces together when one ends where the other begins. The busiest routes become straight lines of code. The same gluing on the procedures puts procedures that call each other often next to each other.
The problem
The input is a CFG with blocks , where is the entry, and a weight for each edge, the number of times the profile run took it. A layout is an order of the blocks with the entry first. An edge is a fall-through in the layout when comes right after . The fall-through weight of a layout is the total weight of its fall-through edges. The goal is a layout with large fall-through weight.
The model is simple on purpose. It ignores the cost of a taken jump that depends on its distance, the cache line boundaries, and the size of each block. In the toy IR every block ends in an explicit jump, br or ret, so any order of the blocks with the entry first has the same meaning. In machine code, a jump to the next block is deleted, and a br gets its condition flipped when its first target is the next block.
Legality. Any layout is legal: moving blocks changes only addresses, and the control flow is given by the terminators. The entry must stay first in the toy IR, because the first block is where a run starts. Profit. Each fall-through edge saves a taken jump on each of its traversals, and chains of hot blocks fill fewer cache lines.
Hardness. Finding a layout of the largest fall-through weight is NP-hard, even with two-way branches only and all weights 1. Decision form: given , is there a layout with fall-through weight at least ?
Reduction. Plesník showed that the Hamiltonian cycle problem stays NP-complete on digraphs where every node has in-degree and out-degree at most 2. Given such a digraph on nodes, pick a node and split it: keeps the arcs out of and becomes the entry, and keeps the arcs into and gets no successors (it ends in ret). Give every arc weight 1 and ask for . The new graph has blocks, so a layout has consecutive pairs, and its fall-through weight is exactly when every consecutive pair is an arc. Such a layout is a Hamiltonian path that starts at . It must end at , the only node with no successor, and so it is a Hamiltonian cycle of through . Conversely, a Hamiltonian cycle of , cut open at , gives such a layout. Out-degrees stay at most 2, so every block ends in a jump, a br or a ret. If some block cannot be reached from the entry, has no Hamiltonian cycle, and that case is easy to detect. The construction is linear, so the decision problem is NP-hard. It is in NP, since a layout is a certificate checked in linear time. In this model, layout is the maximum-weight Hamiltonian path problem with a fixed start, a close relative of the traveling salesman problem.
The algorithm
A chain is a list of blocks. head(c) and tail(c) are its first and last blocks.
PETTIS-HANSEN-BLOCKS(blocks, w)- 1
make one chain [b] for every block b - 2
for each edge a -> b with w(a, b) > 0, by decreasing weight do - 3
if a = b, or b is the entry, or a and b are in the same chain then skip the edge - 4
if a = tail(chain(a)) and b = head(chain(b)) then - 5
append chain(b) to chain(a) - 6
placed <- [the chain whose head is the entry] - 7
while some chain is not placed do - 8
c <- the unplaced chain with the largest total weight of edges from placed blocks into c - 9
append c to placed - 10
return the blocks of placed, chain by chain
Lines L1 to L5 are the bottom-up chain building of Pettis and Hansen. Lines L6 to L9 put the chains in a sequence. Pettis and Hansen order chains with a precedence relation that tries to make conditional branches jump forward. The rule in L8 is a simpler version of the same idea, used by the implementation here: the next chain is the one the placed code jumps into most. Ties go to the earlier chain in the original order.
Procedure positioning ("closest is best"). The call graph is made undirected: the weight of is the number of calls between and in either direction. Each procedure starts as its own group. Repeat: take the heaviest edge between two different groups (the weight between groups is the sum of the edges between them), and join the two groups into one list. Of the four ways to join (each group forwards or reversed), take the one where the two procedures of the heaviest single edge between the groups end up closest. The final groups give the order of the procedures in memory.
Example
A case where the greedy loses. Blocks E (entry), A, B, X, D, C with the profile EA 19, AB 10, AD 9, DC 9, CB 9 and BX 19. A branches to B or D, and the D side joins B again through C.
| step | edge | weight | action | chains |
|---|---|---|---|---|
| 1 | EA | 19 | join | [E A], [B], [X], [D], [C] |
| 2 | BX | 19 | join | [E A], [B X], [D], [C] |
| 3 | AB | 10 | join | [E A B X], [D], [C] |
| 4 | AD | 9 | skip, A is not a tail | |
| 5 | DC | 9 | join | [E A B X], [D C] |
| 6 | CB | 9 | skip, B is not a head |
The layout is E A B X D C, with fall-through weight . Trying all 120 orders that start with E gives the best layout E A D C B X, with weight . The greedy took AB (10) and so lost both AD and CB (18 together).
A loop. Blocks B0 (entry) to B4 with B0B1 1, B1B2 100, B1B4 1, B2B1 90, B2B3 10 and B3B1 10. B1 is the loop test, B2 the body, B3 a rare path in the body and B4 the exit. The merges are B1B2 (100), then B2B3 (10), then B0B1 (1). B2B1 and B3B1 close the loop and are skipped, and B1B4 is skipped because B1 is no longer a tail. The layout B0 B1 B2 B3 B4 has fall-through weight 111, which is also the best of all 24 orders. The back edge B2B1 (90) stays a taken jump: no layout can make both B1B2 and B2B1 fall through.
Procedures. Procedures main, parse, lex, eval, print, gc with calls parse-lex 500, parse-gc 60, eval-gc 40, eval-print 30, main-print 2, main-parse 1 and main-eval 1. The merges, heaviest first:
- parse-lex 500: [parse lex].
- parse-gc 60: joining [parse lex] and [gc] as [lex parse gc] puts parse and gc next to each other.
- eval-gc 40: [eval gc parse lex].
- eval-print 30: [lex parse gc eval print].
- main: the group weight is , and the heaviest single edge is main-print, so main goes next to print.
The final order is main, print, eval, gc, parse, lex. The 500 calls between parse and lex and the 60 between parse and gc cross a distance of one procedure.
Correctness
The output is a layout: each block is in exactly one chain at all times, because L5 moves a whole chain into another and the two chains differ by L3. The entry is never appended to another chain by L3, so it stays the head of its chain, and L6 puts that chain first. Every pair of consecutive blocks inside a chain was joined by L5 along an edge of positive weight, so it is a fall-through. Legality holds for any order, as explained above, so the layout keeps the meaning of the procedure.
The layout is not optimal in general, and cannot be unless P = NP, by the reduction above. The example shows a loss of on a graph with six blocks.
Proof: Pettis-Hansen block positioning returns a legal layout, and optimal layout is NP-hardfull
Setting. A procedure has blocks with entry , and a weight on each CFG edge. A layout is a sequence that holds every block exactly once and starts with . The fall-through weight of a layout is , with for pairs that are not edges. PETTIS-HANSEN-BLOCKS is lines L1 to L10 of the page.
Theorem 1. PETTIS-HANSEN-BLOCKS returns a layout. Each pair of consecutive blocks inside a chain is an edge of positive weight. In the toy IR, the program with its blocks in this order has the same outcome as the original on every input.
Proof. Invariant of lines L1 to L5: the chains are nonempty lists that partition the set of blocks, the entry is the head of its chain, and every two consecutive blocks in a chain form an edge with .
L1 makes it true: each block forms its own chain. Assume it before a step of L2 with edge . If L3 or L4 skips the edge, nothing changes. Otherwise and are in different chains and , is the tail of , is the head of , and is not the entry. L5 replaces the two chains by followed by . The partition is kept, since the two chains were disjoint and both are replaced by their concatenation. The new consecutive pairs are the old ones plus , which is an edge with by L2. The entry was the head of its chain. That chain is not , because the head of is . If it is , the entry is still the head of the joined chain, and otherwise its chain did not change.
So after L5 there is exactly one chain whose head is the entry. L6 places it first, and L7 to L9 place each other chain exactly once, since each round removes one unplaced chain. The concatenation in L10 holds every block exactly once and starts with : it is a layout.
For the toy IR: a run starts at the first block of the dict, which is in both programs. After that, every transfer of control is named by a terminator, by label, and the blocks are unchanged. So by induction on the steps of a run, both programs execute the same block with the same environment and memory at every step, and they have the same outcome.
Theorem 2. The problem "given a CFG with edge weights and a number , is there a layout with ?" is NP-complete, even when every block has at most two successors, every weight is 1, and every block is reachable from the entry.
Proof. It is in NP: a layout is a certificate of linear size, and is computed in linear time.
For hardness, reduce from the Hamiltonian cycle problem on digraphs in which every node has in-degree at most 2 and out-degree at most 2, which is NP-complete (Plesník 1979). Let be such a digraph with nodes, and pick any node . If some node of cannot be reached from , then has no Hamiltonian cycle; map the instance to a fixed "no" instance (for example two blocks with no edge between them and ). Otherwise build :
- the blocks are the nodes of other than , plus two new blocks and ;
- each arc of with stays;
- each arc becomes , each arc becomes , and a loop is dropped;
- the entry is , every arc has weight 1, and .
Every block has at most two successors, has none, and has no predecessor. Every block is reachable from , because every node of is reachable from . has blocks, and the construction takes linear time.
A layout of has consecutive pairs, each contributing 1 if it is an arc and 0 otherwise. So if and only if every consecutive pair is an arc, that is, the layout is a Hamiltonian path of starting at .
If has a Hamiltonian cycle, write it as . Then is a Hamiltonian path of : the first arc comes from , the last from , and the others are arcs of between nodes other than .
Conversely, let be a Hamiltonian path of . The block has no successor, so it can only be last: . Then are the nodes of other than , and is a Hamiltonian cycle of , by reading the arcs back.
So has a Hamiltonian cycle if and only if has a layout with .
Corollary. Unless P = NP, no polynomial-time algorithm returns a layout of maximum fall-through weight on every input. In particular PETTIS-HANSEN-BLOCKS, which runs in polynomial time, is not optimal on every input. The page gives an input where it returns weight 57 and the optimum is 65.
Complexity
Sorting the edges takes . With head and tail markers per block and linked lists for the chains, each test in L4 and each join in L5 takes time, and the "same chain" test in L3 is a find in a disjoint-set forest. The union-find steps cost less than the sort, so L1 to L5 take . The ordering loop L7 to L9 scans all edges for each of the chains, so it takes . The procedure ordering recomputes the group weights after each of at most joins of procedures, which takes for call-graph edges.
Properties
- Greedy and deterministic for a fixed tie rule.
- It only uses edge weights, so an edge profile is enough. A path profile adds nothing for this model.
- It is not optimal: it is a greedy algorithm for an NP-hard problem. It keeps at least one third of the best fall-through weight. The fall-through edges of a layout have at most one edge out of each block, at most one into each block and none into the entry, and no cycle. These are three matroids, L1 to L5 is the greedy algorithm on their intersection, and that greedy keeps at least a third of the best weight. The bound is tight up to : with entry D, edges DB, BA, AC of weight 1 and AB of weight , the greedy joins AB first and lays out D A B C, of weight , while D B A C has weight 3.
- An edge into the entry is never a fall-through, and in each loop at least one edge of the cycle is not a fall-through.
Variants and improvements
- Procedure splitting. Pettis and Hansen also move blocks that never ran in the profile into a separate cold part far away, so the hot part of each procedure is small.
- Extended TSP. Newell and Pupyrev score a layout also by the short jumps it makes, forward and backward, which fit better with real branch costs and cache lines, and give better heuristics for that score.
- Call-chain clustering. For very large binaries, Ottoni and Maher order procedures by merging each one into the cluster of its most frequent caller, with a limit on the cluster size, and report better results than closest-is-best.
- Exact layout for small procedures. For a few blocks, a search over all orders, as in the tests here, finds the optimum in this model.
When to use it
Use it in the back end of a compiler or a post-link optimizer, after the profile is collected, when the hot code of a program is larger than the instruction cache or when taken branches are costly. Inlining should come first, since it changes the CFG. Without a profile, static branch predictions can stand in for the weights, but the gain is smaller.
Pitfalls
- A stale profile. The weights describe the training run. If production inputs take other paths, the layout can be worse than the source order.
- Ties. Many edges have equal weights in small profiles. The result then depends on the tie rule, so the rule must be fixed for builds to be reproducible.
- Moving the entry. In a format where the first block is the entry, as in the toy IR, a chain that puts another block first changes the program. L3 keeps the entry at the head.
- Fall-through is not the whole cost. The model ignores block sizes, cache line boundaries and the distance of jumps. A layout that wins on fall-through weight can still fill more cache lines.
- Greedy is not optimal. The example above loses 8 of 65. Do not report the result as the best layout.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
"""Pettis-Hansen code positioning.
Basic block positioning: a control-flow graph is a list of blocks (the
first one is the entry) and a dict from edge (a, b) to its profile weight.
chain_blocks merges blocks into chains along the heaviest edges first,
order_chains puts the chains in a sequence, and layout gives the final
order. fallthrough_weight is the weight of the edges that become fall
throughs, the quantity the layout tries to make large.
Procedure positioning: closest_is_best orders the procedures of a call
graph by merging groups along the heaviest call edges first, and joins two
groups so that the two procedures of the edge end up as close as possible.
apply_layout puts the blocks of a toy IR program (toyir.py) in a new order.
"""
from itertools import permutations
import toyir
def chain_blocks(blocks, weight):
"""The chains of Pettis and Hansen's bottom-up block positioning.
An edge a -> b joins the chain that ends in a to the chain that starts
with b, when the two chains differ and b is not the entry. Edges are
taken in order of decreasing weight, ties in the order of weight's keys.
Returns the list of chains, each a list of blocks.
"""
entry = blocks[0]
chain_of = {b: [b] for b in blocks}
order = sorted((e for e in weight if weight[e] > 0), key=lambda e: -weight[e]) # stable for ties
for a, b in order: # @line L2
ca, cb = chain_of[a], chain_of[b]
if a == b or b == entry or ca is cb: # @line L3
continue
if ca[-1] != a or cb[0] != b: # @line L4
continue
ca.extend(cb) # @line L5
for x in cb:
chain_of[x] = ca
seen, chains = set(), []
for b in blocks:
c = chain_of[b]
if id(c) not in seen:
seen.add(id(c))
chains.append(c)
return chains
def order_chains(chains, weight, entry):
"""Put the chains in a sequence: the chain of the entry first, then
repeatedly the chain with the largest total weight of edges from the
placed blocks into it (ties: the earlier chain in the list).
"""
rest = [c for c in chains if c[0] != entry]
placed = [c for c in chains if c[0] == entry] # @line L6
done = set(placed[0])
while rest: # @line L7
def pull(c):
members = set(c)
return sum(w for (a, b), w in weight.items() if a in done and b in members)
best = max(range(len(rest)), key=lambda i: (pull(rest[i]), -i)) # @line L8
c = rest.pop(best)
placed.append(c) # @line L9
done.update(c)
return placed
def layout(blocks, weight):
"""The block order: the chains of chain_blocks, put in a sequence."""
chains = chain_blocks(blocks, weight) # @line L1
order = []
for c in order_chains(chains, weight, blocks[0]):
order.extend(c)
return order # @line L10
def fallthrough_weight(order, weight):
"""The total weight of the edges a -> b where b directly follows a."""
return sum(weight.get((a, b), 0) for a, b in zip(order, order[1:]))
def best_layout(blocks, weight):
"""An order with the entry first and the largest fall-through weight,
by trying every order (for small graphs only)."""
entry, rest = blocks[0], blocks[1:]
best, best_w = None, -1
for p in permutations(rest):
order = [entry] + list(p)
w = fallthrough_weight(order, weight)
if w > best_w:
best, best_w = order, w
return best, best_w
def closest_is_best(procs, calls):
"""Pettis and Hansen's procedure ordering.
calls maps a pair (f, g) to the number of calls between f and g, in
either direction. Groups are merged along the heaviest edge between two
groups; of the four ways to join two groups (each one forwards or
reversed), the one that puts f and g closest wins. Returns the order of
all procedures.
"""
group = {p: [p] for p in procs}
pos = {p: i for i, p in enumerate(procs)}
w = {}
for (f, g), c in calls.items():
if f != g:
key = (f, g) if pos[f] < pos[g] else (g, f)
w[key] = w.get(key, 0) + c
# For each pair of groups: (total weight, f, g, c), where f -- g is the
# heaviest single edge between them, with weight c. It fixes the joining.
while True:
between = {}
for (f, g), c in w.items():
gf, gg = group[f], group[g]
if gf is gg:
continue
k = frozenset((id(gf), id(gg)))
tot, bf, bg, bc = between.get(k, (0, None, None, -1))
if c > bc:
bf, bg, bc = f, g, c
between[k] = (tot + c, bf, bg, bc)
if not between:
break
k = max(between, key=lambda k: (between[k][0], -pos[between[k][1]], -pos[between[k][2]]))
_, f, g, _ = between[k]
a, b = group[f], group[g]
best = None
for x in (a, a[::-1]):
for y in (b, b[::-1]):
joined = x + y
d = abs(joined.index(f) - joined.index(g))
if best is None or d < best[0]:
best = (d, joined)
joined = best[1]
for p in joined:
group[p] = joined
seen, order = set(), []
for p in procs:
if id(group[p]) not in seen:
seen.add(id(group[p]))
order.extend(group[p])
return order
def apply_layout(prog, order):
"""prog with its blocks in the given order. The entry must stay first,
because the toy IR starts at the first block."""
if order[0] != prog.entry or sorted(order) != sorted(prog.blocks):
raise ValueError("the order must be a permutation with the entry first")
return toyir.Program(list(prog.params), {b: prog.blocks[b] for b in order})
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_pettis_hansen_code_positioning.py 177 lines
# SPDX-License-Identifier: MIT
import random
import unittest
from itertools import permutations
import toyir
from pettis_hansen_code_positioning import (
apply_layout, best_layout, chain_blocks, closest_is_best,
fallthrough_weight, layout,
)
def random_graph(rng, n, p):
blocks = ["B%d" % i for i in range(n)]
weight = {}
for a in blocks:
for b in blocks:
if a != b and rng.random() < p:
weight[(a, b)] = rng.randint(1, 9)
return blocks, weight
def has_hamiltonian_path(nodes, arcs, start):
"""Brute force: a directed path from start through every node once."""
rest = [v for v in nodes if v != start]
for p in permutations(rest):
order = [start] + list(p)
if all((a, b) in arcs for a, b in zip(order, order[1:])):
return True
return False
class BlockTest(unittest.TestCase):
def test_layout_is_a_permutation_with_entry_first(self):
rng = random.Random(1)
for _ in range(500):
blocks, weight = random_graph(rng, rng.randint(1, 9), rng.random() * 0.6)
order = layout(blocks, weight)
self.assertEqual(order[0], blocks[0])
self.assertEqual(sorted(order), sorted(blocks))
for chain in chain_blocks(blocks, weight):
for a, b in zip(chain, chain[1:]):
self.assertIn((a, b), weight)
self.assertNotEqual(b, blocks[0])
def test_never_better_than_brute_force(self):
rng = random.Random(2)
trials = worse = 0
for _ in range(600):
blocks, weight = random_graph(rng, rng.randint(2, 7), rng.random() * 0.6)
got = fallthrough_weight(layout(blocks, weight), weight)
best, best_w = best_layout(blocks, weight)
self.assertEqual(best[0], blocks[0])
self.assertEqual(fallthrough_weight(best, weight), best_w)
self.assertLessEqual(got, best_w)
trials += 1
worse += got < best_w
# The greedy is often optimal, and sometimes not.
self.assertGreater(worse, 0)
self.assertGreater(trials - worse, worse)
def test_greedy_is_not_optimal(self):
blocks = ["E", "A", "B", "X", "D", "C"]
weight = {("E", "A"): 19, ("A", "B"): 10, ("A", "D"): 9,
("D", "C"): 9, ("C", "B"): 9, ("B", "X"): 19}
self.assertEqual(chain_blocks(blocks, weight), [["E", "A", "B", "X"], ["D", "C"]])
order = layout(blocks, weight)
self.assertEqual(order, ["E", "A", "B", "X", "D", "C"])
self.assertEqual(fallthrough_weight(order, weight), 57)
self.assertEqual(best_layout(blocks, weight), (["E", "A", "D", "C", "B", "X"], 65))
def test_loop_example(self):
blocks = ["B0", "B1", "B2", "B3", "B4"]
weight = {("B0", "B1"): 1, ("B1", "B2"): 100, ("B1", "B4"): 1,
("B2", "B3"): 10, ("B2", "B1"): 90, ("B3", "B1"): 10}
order = layout(blocks, weight)
self.assertEqual(order, ["B0", "B1", "B2", "B3", "B4"])
self.assertEqual(fallthrough_weight(order, weight), 111)
self.assertEqual(best_layout(blocks, weight)[1], 111)
def test_hamiltonian_path_reduction(self):
# With weight 1 on every arc, the best fall-through weight is n - 1
# exactly when a Hamiltonian path starts at the entry.
rng = random.Random(3)
yes = no = 0
for _ in range(300):
blocks, weight = random_graph(rng, rng.randint(2, 6), rng.random() * 0.7)
unit = {e: 1 for e in weight}
_, best_w = best_layout(blocks, unit)
ham = has_hamiltonian_path(blocks, set(unit), blocks[0])
self.assertEqual(best_w == len(blocks) - 1, ham)
yes += ham
no += not ham
self.assertGreater(yes, 20)
self.assertGreater(no, 20)
class ProcedureTest(unittest.TestCase):
def test_example(self):
procs = ["main", "parse", "lex", "eval", "print", "gc"]
calls = {("main", "parse"): 1, ("parse", "lex"): 500, ("main", "eval"): 1,
("eval", "gc"): 40, ("eval", "print"): 30, ("main", "print"): 2,
("parse", "gc"): 60}
self.assertEqual(closest_is_best(procs, calls),
["main", "print", "eval", "gc", "parse", "lex"])
def test_random_call_graphs(self):
rng = random.Random(4)
for _ in range(300):
n = rng.randint(1, 8)
procs = ["f%d" % i for i in range(n)]
calls = {}
for f in procs:
for g in procs:
if rng.random() < 0.3:
calls[(f, g)] = rng.randint(1, 50)
order = closest_is_best(procs, calls)
self.assertEqual(sorted(order), sorted(procs))
pair = {}
for (f, g), c in calls.items():
if f != g:
k = frozenset((f, g))
pair[k] = pair.get(k, 0) + c
if pair:
top = max(pair.values())
heavy = [k for k, c in pair.items() if c == top]
# The heaviest edge is merged first, from two single
# procedures, and they stay next to each other.
if len(heavy) == 1:
f, g = tuple(heavy[0])
self.assertEqual(abs(order.index(f) - order.index(g)), 1)
def block_trace(prog, args):
"""The blocks a run executes, by a tracing copy of the program."""
labels = list(prog.blocks)
k = len(labels) + 1
blocks = {"tr.entry": toyir.Block([("const", "tr", 0)], ("jump", prog.entry))}
for i, (lab, b) in enumerate(prog.blocks.items()):
code = [("op", "tr", "*", "tr", k), ("op", "tr", "+", "tr", i + 1)]
term = ("ret", "tr") if b.term[0] == "ret" else b.term
blocks[lab] = toyir.Block(code + list(b.instrs), term)
out = toyir.run(toyir.Program(list(prog.params), blocks), args, 100000)
if out[0] != "ret":
return None
h, seq = out[1], []
while h:
h, d = divmod(h, k)
seq.append(labels[d - 1])
return seq[::-1]
class ProgramTest(unittest.TestCase):
def test_layout_keeps_the_meaning(self):
rng = random.Random(5)
for _ in range(150):
prog = toyir.random_program(rng, 4, rng.randint(1, 9), rng.random() < 0.5)
weight = {e: 0 for e in toyir.edges(prog)}
inputs = [[rng.randint(-3, 6), rng.randint(-3, 6)] for _ in range(6)]
for args in inputs:
seq = block_trace(prog, args)
for a, b in zip(seq or [], (seq or [])[1:]):
weight[(a, b)] += 1
order = layout(list(prog.blocks), weight)
moved = apply_layout(prog, order)
self.assertEqual(list(moved.blocks), order)
for args in inputs:
self.assertEqual(toyir.run(moved, args, 5000), toyir.run(prog, args, 5000))
def test_entry_must_stay_first(self):
prog = toyir.parse("B0:\n jump B1\nB1:\n ret 0\n")
with self.assertRaises(ValueError):
apply_layout(prog, ["B1", "B0"])
if __name__ == "__main__":
unittest.main()
History
Pettis and Hansen presented profile guided code positioning at PLDI 1990. The paper introduced the three parts that later tools kept: closest-is-best procedure ordering, bottom-up block chaining and procedure splitting. Later work changed the cost model and the merge rules for large data-center binaries, for example the call-chain clustering of Ottoni and Maher in 2017 and the extended TSP layout of Newell and Pupyrev in 2020.
References
- Karl Pettis and Robert C. Hansen, Profile guided code positioning, Proceedings of the ACM SIGPLAN 1990 Conference on Programming Language Design and Implementation (PLDI), 16-27, procedure positioning by the closest-is-best merging of the call graph, basic block positioning by bottom-up chain merging along the heaviest edges, and procedure splitting into hot and cold parts
- Ján Plesník, The NP-completeness of the Hamiltonian cycle problem in planar digraphs with degree bound two, Information Processing Letters 8(4), 1979, 199-201, the main theorem, used here for the hardness of layout with two-way branches
- Guilherme Ottoni and Bertrand Maher, Optimizing function placement for large-scale data-center applications, Proceedings of the 2017 IEEE/ACM International Symposium on Code Generation and Optimization (CGO), 233-244, the comparison with Pettis-Hansen procedure ordering and the call-chain clustering heuristic for large binaries
- Andy Newell and Sergey Pupyrev, Improved basic block reordering, IEEE Transactions on Computers 69(12), 2020, 1784-1794, the extended TSP model of block layout, which also rewards short forward and backward jumps, and its heuristics
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YB331X Edit this page History Report an error Markdown