In order to compile code for branch instructions, it is necessary to know
the address in memory (relative to the location counter) of the destination
of the branch. Branch instructions may be PC-relative or have absolute
addresses. For forward branches the
destination address will
not be known when the branch is encountered. There are two approaches
to this problem:
- Two passes. The first pass through the code generator computes
addresses but does not generate code. The second pass generates code and
uses the addresses determined in the first pass.
This approach takes longer.
- Backpatching. The generated code itself is
used to hold a linked list
of places where forward reference addresses are needed. When the address is
found, it is patched back into the generated code.