Backpatching
Backpatching is used during three-address code generation, especially in generating code for
control structures like conditional statements (if-else) and loops (while, for). It's used to patch
the target addresses of jumps (e.g., goto) once the target addresses are known.
Let's illustrate backpatching with a simple example of generating three-address code for an if-
else statement.
Consider the following pseudo-code:
if (condition) {
// true branch
} else {
// false branch
next_instruction:
Step 1: Generate Initial Code Skeleton
if condition goto true_branch
goto false_branch
true_branch:
// true branch code
goto next_instruction
false_branch:
// false branch code
goto next_instruction
next_instruction:
Here, true_branch and false_branch are placeholder labels for the target addresses of the
respective branches.
Step 2: Backpatching
Once we know the actual target addresses of the branches, we go back and patch them into
the generated code.
Let's assume:
The true branch code starts at address L1.
The false branch code starts at address L2.
if condition goto L1
goto L2
L1:
// true branch code
goto next_instruction
L2:
// false branch code
goto next_instruction
next_instruction: