UNIHIVE

Study Hub UNIPORT CSC 382

CSC 382 · Computer Architecture 1

The assembler and its two passes

Why forward references need two passes, the location counter, the symbol table and the output of an assembler.

Our notes

2 min read

The problem

A label may be used before it is defined (a forward jump: JMP END when END is near the bottom). The assembler cannot finish that instruction until it knows END's address.

The two passes

Pass 1: build the symbol table.

  1. Set the location counter (LC) to the ORG value (or 0).
  2. For each line: if it has a label, enter label = LC in the symbol table (error if already defined); work out the length of the instruction or data; add it to LC.
  3. Process directives that affect LC (ORG, DATA, reserve).

Pass 2: generate code.

  1. Reset LC and read the source again.
  2. For each instruction: look up the opcode in the opcode table, look up symbols in the symbol table, build the machine word, write it to the object file and the listing.
  3. Report undefined symbols and other errors.

Worked example: pass 1

Each instruction and data word is 1 word; ORG 200.

LCSource
200START: LOAD X
201ADD Y
202JZ DONE
203STORE Z
204DONE: HALT
205X: DATA 4
206Y: DATA −4
207Z: DATA 0

Symbol table after pass 1: START = 200, DONE = 204, X = 205, Y = 206, Z = 207.
In pass 2, JZ DONE becomes the opcode for JZ with address 204. (Run: AC = 4 + (−4) = 0, so the jump to DONE is taken and Z is not stored.)

One-pass assemblers

Possible by leaving a hole for each forward reference and keeping a list of holes to patch when the label is defined (backpatching). Faster, but more complex and needs the whole program in memory.

Output of an assembler

  • Object code (machine instructions and data), usually relocatable: addresses relative to the start of the module.
  • Relocation information: which words hold addresses that must be adjusted when the program is loaded elsewhere.
  • External references (symbols used but defined in other modules) and entry points (symbols this module offers).
  • A listing with addresses, code and error messages.

Exams usually ask

  • Explain why a two-pass assembler is needed and what each pass does.
  • Build the symbol table for a given program.
  • Describe the tables an assembler uses and the object file it produces.

Common mistake

Putting the address of the instruction that uses a label into the symbol table. The table holds the address where the label is defined.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

No reading links here yet

Our team adds free books, videos and practice for each topic, and opens every link before it goes up.

All CSC 382 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.