Sub topic 10
Basic Blocks and Control Flow Graphs
Prerequisites and purpose
Assume you know three-address code, conditional and unconditional jumps, and basic directed graphs. This chapter shows how a compiler divides intermediate code into basic blocks and connects those blocks into a control flow graph (CFG).
A basic block is a maximal sequence of consecutive instructions with:
- One entry point, the first instruction.
- One exit point, the last instruction.
- No jump into the middle of the sequence.
- No jump out of the sequence except from its final instruction.
These properties let local optimizations examine a block without considering every possible path through the program.
Finding leaders
A leader is the first instruction of a basic block. Mark an instruction as a leader when it is:
- The first instruction in the procedure.
- The target of a conditional or unconditional jump.
- The instruction immediately following a jump.
Consider this complete C function:
int classify(int x) {
int result;
if (x > 0) {
result = 1;
} else {
result = -1;
}
return result;
}One possible three-address translation is:
| Instruction | Code |
|---|---|
| 1 | `if x <= 0 goto L1` |
| 2 | `result = 1` |
| 3 | `goto L2` |
| 4 | `L1: result = -1` |
| 5 | `L2: return result` |
Instruction 1 is a leader because it starts the procedure. Instruction 2 is a leader because it follows a conditional jump. Instruction 4 is a leader because it is a jump target. Instruction 5 is a leader because it follows an unconditional jump.
Therefore, the basic blocks are:
- B1: instructions 1
- B2: instruction 2 through instruction 3
- B3: instruction 4
- B4: instruction 5
The label itself does not create a block by itself. It identifies an instruction that is already a leader.
Building the control flow graph
A CFG has one node for each basic block. Add an edge when execution can move from one block to another.
For the example:
- B1 goes to B2 when
x > 0. - B1 goes to B3 when
x <= 0. - B2 goes to B4 through
goto L2. - B3 goes to B4 after its assignment.
The CFG makes control-flow questions explicit. For example, B4 has two predecessors, so any analysis that combines information at B4 must account for both incoming paths.
Common errors
- Treating every label as a separate block, even when it is not a leader.
- Forgetting the instruction after a jump.
- Adding an edge from a block to an instruction inside another block.
- Omitting the fall-through edge of a conditional branch.
- Including unreachable code without identifying that it has no incoming CFG path.
Exercise
For the sequence 1: a = 0, 2: if p goto 5, 3: b = 1, 4: goto 6, 5: b = 2, 6: return b, which instructions begin basic blocks?
Show answer
Instructions 1, 3, 5, and 6. Instruction 1 starts the procedure, instruction 3 follows a conditional jump, instruction 5 is a jump target, and instruction 6 follows an unconditional jump.