CIE AS & A Level Computer Science, section 4.2 (Assembly language)
What an assembler does
An assembler is a program that translates assembly language into machine code.
Why two passes?
A program can contain forward references: a jump to a label that appears later in the program. The assembler does not yet know that label's address when it reaches the jump, so it makes two passes through the program.
Pass 1
- Read each line and count the address of each instruction (starting from the load address).
- Build a symbol table: a list of every label and variable name with its address.
- Do not generate the machine code yet.
Pass 2
- Read each line again.
- Replace each mnemonic with its machine code opcode.
- Replace each symbolic address (label) with the actual address from the symbol table.
- Output the machine code (and detect errors such as an unknown label).
Worked example
Source program starting at address 100:
100 LDM #0
101 STO TOTAL
102 LOOP: LDD TOTAL
103 INC ACC
104 STO TOTAL
105 CMP #3
106 JPN LOOP
107 END
108 TOTAL: 0
Pass 1 builds the symbol table:
| Symbol | Address |
|---|---|
| LOOP | 102 |
| TOTAL | 108 |
Pass 2 replaces TOTAL with 108 and LOOP with 102, and each mnemonic with its binary opcode.
Benefits
Two passes allow forward references to be resolved. The assembler can also report errors (such as an undefined label) in the first pass.
Common mistake: saying the first pass "converts the code to machine code". The first pass builds the symbol table; the second pass produces the machine code. Also, the symbol table holds names and addresses, not opcodes.
Exam tip: give the purpose of each pass in order. If you are asked to complete a symbol table, number the instructions carefully from the starting address.
Check yourself
What is stored in the symbol table?
Each label or variable name together with its address.
Why does an assembler need two passes?
To resolve forward references: a label may be used before the assembler has found its address.
What happens in the second pass?
Mnemonics are replaced by opcodes and symbolic addresses are replaced by real addresses from the symbol table.