• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

A basic block captures straight-line code, but programs have branches, loops, and conditional execution. The compiler needs a global view of how control flows between blocks to perform inter-block optimizations, data-flow analysis, and loop detection. Without a control-flow graph, each block is an island — no analysis can cross block boundaries.

Core Idea

A control-flow graph (CFG) is a directed graph where nodes are basic blocks and edges represent potential control flow paths. There is a directed edge from block A to block B if control can pass from the last instruction of A to the first instruction of B (via jump, fall-through, or call). The CFG has a unique entry node (start of the program) and typically one or more exit nodes (program termination points).

How It Works

The CFG is constructed after basic block identification. For each block, the compiler examines its last instruction: if it ends with a conditional jump if X goto L, edges go to the block starting with label L and to the next block (fall-through). If it ends with an unconditional jump goto L, a single edge goes to L’s block. If it ends with a return, it’s an exit node. The resulting graph is the framework for all global compiler analysis and optimization.

Visual Explanation

cfg_example Entry Entry B1 B1: x = 1 y = 2 Entry->B1 B2 B2: if cond goto B4 B1->B2 B3 B3: x = x + 1 B2->B3 true B4 B4: y = x * 2 B2->B4 false B3->B2 loop B5 B5: return y B4->B5 Exit Exit B5->Exit

Semantic Network

semantic_cfg THIS Control Flow Graph PRE1 Basic Blocks THIS--PRE1 built from — blocks are nodes PRE2 Three-Address Code THIS--PRE2 built from OUT1 Data Flow Analysis THIS--OUT1 builds into — DFA iterates over CFG OUT2 Loop Detection THIS--OUT2 builds into — loops from CFG cycles REL1 Code Optimization THIS--REL1 related — optimizations use CFG

Key Properties

  • Directed graph: Nodes = basic blocks, Edges = control flow
  • Unique entry: Single entry node (start of the program)
  • Edges represent jumps: Conditional, unconditional, and fall-through
  • Cycle = loop: Back edges in the CFG identify loops (using dominator analysis)
  • Framework for analysis: All global data-flow analysis works by iterating over the CFG

Connections

Edge Cases & Gotchas

  • Irreducible CFG: When gotos create multiple-entry loops, the CFG is irreducible — some analyses cannot handle this
  • Dead code: Blocks unreachable from the entry are dead code and can be removed
  • Critical edges: Edges from blocks with multiple successors to blocks with multiple predecessors — they complicate code motion optimizations
  • CFG explosion: For large programs, the CFG can have thousands of nodes — iterative analysis must be efficient