Chapter 9.1: Macros

Microprocessors
What a macro isMACRO / ENDMExpansionParameter pitfallsMacros vs proceduresCode sizeLOCALPUTCPOWERemu8086.inc
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Macro definition

Write parameterized macros with MACRO / ENDM.

Expansion

Trace how the assembler expands a macro call as text.

Macro or procedure?

Compare the two in size, speed and usage, and choose the right one.

LOCAL

Avoid the Duplicate declaration error in macros that contain labels.

Practice

Step through the PUTC (print a character) and POWER (exponentiation) macros.

Pitfalls

Spot parameter side effects, clobbered registers and edge cases.

What a Macro Is

Macros

  • Macros resemble procedures: they give a name to a repeated piece of code.
  • But they are not called at run time; they are placeholders replaced by real instructions at assembly time.
  • Macros that are never used are ignored: they add no bytes to the machine code.
  • Unlike procedures, macros must be defined above the code that uses them; the assembler cannot expand a call to a macro it does not yet know.
Source codePUTC 'A'Assemblerexpands macropush axmov al, 'A'mov ah, 0Ehint 10h / pop axmachine code(no call)

What a Macro Is

Defining a Macro

name    MACRO  [parametreler,...]
        <instructions>
        ENDM
nameThe macro's name, used like an instruction.
parametersComma-separated formal names (optional). The values in the call replace them as text.
ENDMEnds the macro body. Unlike a procedure, the name is not repeated.
MyMacroMyMacrop1,4,p2,5,p3DXdefinition: formal namescall: replacement textMOV CX, p3 →MOV CX, DX
Parameters may be registers, memory or immediates: the assembler only substitutes text; whether the resulting instruction is valid is checked after expansion.

What a Macro Is

Macro Expansion Step by Step

MyMacro  MACRO  p1, p2, p3
         MOV AX, p1
         MOV BX, p2
         MOV CX, p3
ENDM

First the definition: the assembler learns MyMacro and its parameters p1, p2, p3; no code is generated yet.

MyMacro 1, 2, 3
MOV AX, p1
MOV BX, p2
MOV CX, p3

MyMacro 1, 2, 3: p1 = 1, p2 = 2, p3 = 3.

MyMacro 1, 2, 3
MOV AX, 1
MOV BX, p2
MOV CX, p3

Line 1: MOV AX, p1 → MOV AX, 1.

MyMacro 1, 2, 3
MOV AX, 1
MOV BX, 2
MOV CX, p3

Line 2: MOV BX, p2 → MOV BX, 2.

MyMacro 1, 2, 3
MOV AX, 1
MOV BX, 2
MOV CX, 3

Line 3: MOV CX, p3 → MOV CX, 3.

MyMacro 4, 5, DX
MOV AX, p1
MOV BX, p2
MOV CX, p3

MyMacro 4, 5, DX: p1 = 4, p2 = 5, p3 = DX.

MyMacro 4, 5, DX
MOV AX, 4
MOV BX, p2
MOV CX, p3

Line 1: MOV AX, p1 → MOV AX, 4.

MyMacro 4, 5, DX
MOV AX, 4
MOV BX, 5
MOV CX, p3

Line 2: MOV BX, p2 → MOV BX, 5.

MyMacro 4, 5, DX
MOV AX, 4
MOV BX, 5
MOV CX, DX

Line 3: MOV CX, p3 → MOV CX, DX.

MOV AX, 00001h
MOV BX, 00002h
MOV CX, 00003h
MOV AX, 00004h
MOV BX, 00005h
MOV CX, DX
RET

Result (as emu8086 shows it): the two calls expanded into 6 instructions. Constants are shown in hex.

What a Macro Is · Step through the code

Running the Expanded Code

After loading, CX = 0012h: the program is 5 × 3 + 2 + 1 = 18 bytes. SP = FFFEh.

AX = 0001h.

BX = 0002h.

CX = 0003h. The first call is done; there is no CALL/RET.

AX = 0004h.

BX = 0005h.

CX ← DX = 0000h (DX starts at zero).

RET: the program ends.

ORG 100h
MOV AX, 00001h   ; MyMacro 1, 2, 3
MOV BX, 00002h
MOV CX, 00003h
MOV AX, 00004h   ; MyMacro 4, 5, DX
MOV BX, 00005h
MOV CX, DX
RET

SP never changed: a macro does not use the stack (unless its body has PUSH/POP). In a procedure, CALL/RET would change SP.

What a Macro Is · Step through the code

Pitfall: Parameters Are Text

The call MyMacro BX, AX, 0 is meant to do AX ← BX, BX ← AX (a swap).

AX = 1111h.

BX = 2222h.

Line 1 of the macro: MOV AX, p1 → MOV AX, BX → AX = 2222h.

Line 2: MOV BX, AX. The programmer expected the “old AX” (1111h), but AX changed on the line before → BX = 2222h.

CX = 0.

Result: AX = BX = 2222h. 1111h is lost.

ORG 100h
MOV  AX, 1111h
MOV  BX, 2222h
MOV  AX, BX  ; MyMacro BX,AX,0
MOV  BX, AX  ; p2 = AX (bad!)
MOV  CX, 0
RET

A macro parameter is not a variable but replacement text: its value is read on the line where it is used. Do not pass as parameters registers that the body changes.

What a Macro Is

Parameter Kinds: Same Macro, Different Expansions

ADD3 MACRO x, y, z
  MOV AX, x
  ADD AX, y
  MOV z, AX
ENDM
CallExpansionStatus
ADD3 a, b, cMOV AX, a · ADD AX, b · MOV c, AXvalid
ADD3 BX, 5, CXMOV AX, BX · ADD AX, 5 · MOV CX, AXvalid
ADD3 a, b, 7MOV 7, AXdest can't be immediate
ADD3 k, b, c (k DB)MOV AX, ksize mismatch
ADD3 a, bMOV , AXmissing operand
  • A parameter may be a register, a variable, an immediate or an expression; the expanded instruction, not the macro, decides what is valid.
  • The error is reported on the line that uses the macro, but its cause is a line in the body: picture the expansion to understand the message.
  • A missing parameter is replaced by empty text. In MASM, z:REQ makes a parameter required and y:=<1> gives it a default value.

What a Macro Is · Step through the code

Code Trace: Two Expansions of ADD3

org 100h
mov ax, a      ; ADD3 a, b, c
add ax, b
mov c, ax
mov ax, c      ; ADD3 c, 5, d
add ax, 5
mov d, ax
ret
a dw 1200h
b dw 0345h
c dw ?
d dw ?
1200ha · 01140345hb · 01160000hc · 01180000hd · 011AAX1200h

1st expansion ADD3 a, b, c: x was replaced by a → AX = 1200h.

1200ha · 01140345hb · 01160000hc · 01180000hd · 011AAX1545h

ADD AX, b: 1200h + 0345h = 1545h.

1200ha · 01140345hb · 01161545hc · 01180000hd · 011AAX1545h

MOV c, AX: c = 1545h. There is no memory-to-memory add, so the macro uses AX as a go-between.

1200ha · 01140345hb · 01161545hc · 01180000hd · 011AAX1545h

2nd expansion ADD3 c, 5, d: the same body, different text. x = c → AX = 1545h.

1200ha · 01140345hb · 01161545hc · 01180000hd · 011AAX154Ah

This time y = 5 is an immediate: ADD AX, 5 → AX = 154Ah.

1200ha · 01140345hb · 01161545hc · 0118154Ahd · 011AAX154Ah

MOV d, AX: d = 154Ah. The two expansions produced 6 instructions; the macro clobbered AX, and the caller must know it.

1200ha · 01140345hb · 01161545hc · 0118154Ahd · 011AAX154Ah

RET. Code (3 + 4 + 3) + (3 + 3 + 3) = 19 bytes + RET = 20 bytes; ADD AX, 5 is 3 bytes in the short AX form. Every use of ADD3 writes the body again.

Macro: ADD3 MACRO x, y, z / MOV AX, x / ADD AX, y / MOV z, AX / ENDM. The code is the expanded form of the two calls.

What a Macro Is

Parameter Expressions and Operator Precedence

AREA MACRO wd, ht
  MOV AX, wd*ht
ENDM

DIFF MACRO p, q
  MOV CX, p-q
ENDM
  • A parameter is text, not a value: operator precedence is applied again on the line where the expression is substituted.
  • AREA 2+3, 4: the multiplication is done first, so AX = 14; 20 was expected.
  • Fix: put the parameters in parentheses in the body: (wd)*(ht), (p)-(q).
CallExpansionResult
AREA 2+3, 4MOV AX, 2+3*4AX = 000Eh (14)
fixed AREA 2+3, 4MOV AX, (2+3)*(4)AX = 0014h (20)
DIFF 10, 4+1MOV CX, 10-4+1CX = 0007h
AREA BX, 2MOV AX, BX*2error: * with constants only

The expression is evaluated at assembly time; an expression with a register cannot be multiplied at run time. Multiplying a register needs MUL or SHL.

What a Macro Is

Interactive Macro Expander

Call
Code generated by the assembler

Size comparison: as a procedure, the body + RET would be written once, and each use would be just a 3-byte CALL.

Macros vs Procedures

Procedure Features

  • A procedure is called with the CALL instruction.
  • A procedure exists as a single copy at a specific address in memory.
  • When it is called, the CPU transfers control there; RET returns control to the main program.
  • The stack holds the return address.
  • Calling the same procedure 100 times barely grows the file: a near CALL takes only 3 bytes.
  • Parameters are passed on the stack or in registers.
  • A procedure ends with its name and the ENDP directive.
PRINT_A PROC
      PUSH AX
      MOV  AL, 'A'
      MOV  AH, 0Eh
      INT  10h
      POP  AX
      RET
PRINT_A ENDP

      CALL PRINT_A  ; 3 bytes
      CALL PRINT_A  ; 3 bytes
main programCALL PRINT_ACALL PRINT_APRINT_A (one copy)PUSH AX … POP AXRET3 bytes, return address pushedRET: return to the address on the stack

Macros vs Procedures

Macro Features

  • A macro is used just by writing its name (no CALL).
  • Macros are expanded in place in the program code.
  • Use the same macro 100 times and the assembler expands it 100 times; the executable keeps growing.
  • Parameters are written after the macro name.
  • The ENDM directive alone ends a macro.
  • If a macro definition contains labels and the macro is used more than once, you can get a Duplicate declaration error; use the LOCAL directive for variable, label and procedure names.
PUTC MACRO char
     PUSH AX
     MOV  AL, char
     MOV  AH, 0Eh
     INT  10h
     POP  AX
ENDM

     PUTC 'A'  ; 8 bytes
     PUTC 'B'  ; 8 bytes
PUTC 'A'PUTC 'B'50B041B40ECD10588 bytes50B042B40ECD10588 bytespush ax · mov al, char · mov ah, 0Eh · int 10h · pop ax (highlighted: parameter)

Macros vs Procedures

Macro or Procedure?

CriterionMacroProcedure
When is it processed?Assembly time (text substitution)Run time (CALL/RET)
UsagePUTC 'A'CALL PRINT_A
Code sizeGrows by the body at every useBody once + 3 bytes per call
SpeedFaster (no CALL/RET, no stack access)CALL + RET cost on every call
ParametersValues after the name, as textRegisters or the stack
StackNot used (unless the body uses it)Used for the return address
Where definedBefore useAnywhere
EndENDMname ENDP
LabelsLOCAL neededNo problem (one copy)

Rule: short, frequently used, speed-critical code → macro; long code used in many places → procedure. The two can be combined: a macro can put its parameters in registers and call a procedure.

Macros vs Procedures

Code Size: 1, 10 and 100 Uses

Code size (bytes) · PUTC body 8 bytes; procedure = the same 8 bytes + RET (1 byte)1 usemacro: 1 × 8 = 8procedure: 9 + 1 × 3 = 12

1 use: macro 8 bytes; procedure 8 bytes of body + 1 byte RET + 3 bytes CALL = 12 bytes. Here the macro is smaller.

Code size (bytes) · PUTC body 8 bytes; procedure = the same 8 bytes + RET (1 byte)1 usemacro: 1 × 8 = 8procedure: 9 + 1 × 3 = 1210 usesmacro: 10 × 8 = 80procedure: 9 + 10 × 3 = 39

10 uses: macro 80 bytes; procedure 9 + 30 = 39 bytes.

Code size (bytes) · PUTC body 8 bytes; procedure = the same 8 bytes + RET (1 byte)1 usemacro: 1 × 8 = 8procedure: 9 + 1 × 3 = 1210 usesmacro: 10 × 8 = 80procedure: 9 + 10 × 3 = 39100 usesmacro: 100 × 8 = 800procedure: 9 + 100 × 3 = 309

100 uses: macro 800 bytes; procedure 9 + 300 = 309 bytes. The gap grows with the number of uses.

For speed it is the other way round: each CALL + RET pair adds about 19 + 8 = 27 clocks and two stack accesses on the 8086. A macro has no such cost.

Macros vs Procedures

Decision Exercise: Macro or Procedure?

Five cases: in each, weigh code size (how many copies?) against speed (the CALL/RET cost).

1. Print one character, in 200 places → a short body (8 bytes) but 200 copies = 1600 bytes. A procedure: 9 + 600 = 609 bytes. If size matters, procedure; if speed matters, macro.

2. A one-line job swapping two registers → XCHG is already one instruction; a macro is enough for readability, a procedure is needless overhead (macro).

3. A 300-byte sorting algorithm, in 3 places → macro 900 bytes, procedure 300 + 9 bytes: clearly a procedure.

4. A 2-instruction job done on every pass of a tight loop → the CALL/RET cost exceeds the job itself: macro.

5. Put the parameters in registers and call shared code → both together: macro SHOW_NUM x → MOV AX, x + CALL print_num (emu8086.inc works this way too).

Macros vs Procedures · Step through the code

Macro Sets the Parameter, Procedure Does the Work

org 100h
mov  al, 4       ; PUT_DIGIT 4
call print_digit
mov  al, 7       ; PUT_DIGIT 7
call print_digit
ret
print_digit:
add  al, '0'     ; digit → ASCII
mov  ah, 0Eh
int  10h
ret
AL04hAH00hSPFFFEhIP after: 0102hnow: macro copy 1screen▌stack (SS:offset)····FFF8····FFFA····FFFC0000hFFFESP

Macro PUT_DIGIT d expands at assembly time into mov al, d + call print_digit. The work is in the procedure, a single copy. First copy: AL = 04h.

AL04hAH00hSPFFFChIP after: 010Bhnow: macro copy 1screen▌stack (SS:offset)····FFF8····FFFA0105hFFFCreturnSP0000hFFFE

CALL pushes the return address (the instruction after the CALL, 0105h): SP = FFFCh. IP ← print_digit.

AL34hAH0EhSPFFFChIP after: 0111hnow: procedure (one copy)screen4▌stack (SS:offset)····FFF8····FFFA0105hFFFCreturnSP0000hFFFE

Procedure body: AL + 30h = 34h ('4'), AH = 0Eh, INT 10h prints 4.

AL34hAH0EhSPFFFEhIP after: 0105hnow: procedure (one copy)screen4▌stack (SS:offset)····FFF8····FFFA0105hFFFC0000hFFFESP

RET pops 0105h: SP = FFFEh; execution resumes after the macro's first copy.

AL07hAH0EhSPFFFEhIP after: 0107hnow: macro copy 2screen4▌stack (SS:offset)····FFF8····FFFA0105hFFFC0000hFFFESP

The macro's second copy: AL = 07h. Each copy is only 5 bytes (2-byte MOV + 3-byte CALL).

AL07hAH0EhSPFFFChIP after: 010Bhnow: macro copy 2screen4▌stack (SS:offset)····FFF8····FFFA010AhFFFCreturnSP0000hFFFE

CALL again: this time the return address is 010Ah. Same procedure, different return address.

AL37hAH0EhSPFFFChIP after: 0111hnow: procedure (one copy)screen47▌stack (SS:offset)····FFF8····FFFA010AhFFFCreturnSP0000hFFFE

The same single procedure copy runs: AL = 37h ('7'). The screen shows 47.

AL37hAH0EhSPFFFEhIP after: 010Ahnow: procedure (one copy)screen47▌stack (SS:offset)····FFF8····FFFA010AhFFFC0000hFFFESP

RET → 010Ah. The stack is empty again; the caller's SP was preserved.

AL37hAH0EhSP0000hIP after: 0000hnow: main programscreen47▌stack (SS:offset)····FFF8····FFFA010AhFFFCreturn0000hFFFE

The program ends. The macro loaded the parameter; the shared code is in the procedure, just like emu8086.inc's DEFINE_... + macro pairs.

Macro: PUT_DIGIT MACRO d / mov al, d / call print_digit / ENDM. 10 uses: 10 × 5 + 7 = 57 bytes; with the whole body in the macro, 10 × 8 = 80 bytes.

Macros vs Procedures · Step through the code

Code Trace: A RET Inside a Macro

org 100h
mov al, 'A'    ; EMIT 'A'
mov ah, 0Eh
int 10h
ret            ; the macro's RET
mov al, 'B'    ; EMIT 'B'
mov ah, 0Eh
int 10h
ret
ret
AX0041hIP0102hSPFFFEhscreen

1st expansion EMIT 'A': AL = 41h.

AX0E41hIP0106hSPFFFEhscreenA

AH = 0Eh, INT 10h: A is printed.

AX0E41hIP0000hSP0000hscreenA0000h from the stack

The RET in the macro body: a macro is not a procedure; nothing got here by CALL. RET pops the 0000h on top of the stack: IP = 0000h.

AX0E41hIP0000hSP0000hscreenAlines 6–10 never ran: EMIT 'B' lost

The INT 20h at PSP:0000 ends the program. EMIT 'B' and the main program's own RET never ran; the screen shows only A.

Macro: EMIT MACRO c / MOV AL, c / MOV AH, 0Eh / INT 10h / RET / ENDM. RET makes sense only in a procedure entered with CALL.

Macros vs Procedures

Macro, EQU and Procedure

CriterionEQUMacroProcedure
What is substituted?a single value or expressionone or more linesnothing; reached with CALL
Parametersnoneyes (text)register, stack or memory
When?assemblyassemblyrun time
In memorytakes no spacethe body at every useone copy + 3 bytes per call
ExampleCOLS EQU 80PUTC 'A'CALL PRINT_NUM
In commonEQU and macros are text operations the assembler performs on the source; the CPU never sees either, it only executes the instructions they produce.
ChoosingEQU to name a single number, a macro for a short pattern of a few instructions, a procedure for long or widely used work.

Labels and LOCAL

Macros with Labels: The Problem

If a macro whose body contains a label is used twice, the expansion defines the same label twice:

DELAY MACRO
lp:  DEC CX
      JNZ lp
ENDM

MOV CX, 5
DELAY
MOV CX, 9
DELAY

What the assembler sees:

MOV CX, 5
lp:   DEC CX    ; copy 1
      JNZ lp
MOV CX, 9
lp:   DEC CX    ; copy 2 !
      JNZ lp
emu8086: a Duplicate declaration error. Which lp: to jump to is ambiguous.
copy 1lp:DEC CXJNZ lpcopy 2lp:DEC CXJNZ lp?same name twice → Duplicate declaration

Labels and LOCAL

Fix: The LOCAL Directive

MyMacro2 MACRO
    LOCAL label1, label2
    CMP  AX, 2
    JE   label1
    CMP  AX, 3
    JE   label2
label1:
    INC  AX
label2:
    ADD  AX, 2
ENDM
  • LOCAL must be the first line of the macro body (right after the MACRO line).
  • At each expansion the assembler replaces the listed names with unique names (??0000, ??0001, … in MASM).
  • It works for labels, variables and procedure names inside the macro.
Usagelabel1label2
1st MyMacro2??0000??0001
2nd MyMacro2??0002??0003

Labels and LOCAL · Step through the code

Running MyMacro2 (AX = 2)

LOCAL has turned the labels into unique names.

AX = 2.

CMP AX, 2: 2 − 2 = 0 → ZF = 1.

JE: ZF = 1, so it jumps to ??0000 (label1).

INC AX → AX = 3.

ADD AX, 2 → AX = 5.

The program ends.

ORG 100h
MOV  AX, 2       ; before MyMacro2
CMP  AX, 2       ; MyMacro2 starts
JE   ??0000
CMP  AX, 3
JE   ??0001
??0000:
INC  AX
??0001:
ADD  AX, 2       ; MyMacro2 ends
RET

With AX = 3 it would jump to label2 and AX = 5. With AX = 7 there is no jump and it falls into label1: INC + ADD → AX = 10.

Labels and LOCAL · Step through the code

LOCAL: Two Copies, Two Separate Labels

org 100h
mov cx, 3
??0000: dec cx   ; DELAY (copy 1)
jnz ??0000
mov cx, 2
??0001: dec cx   ; DELAY (copy 2)
jnz ??0001
ret
CX0003hZF0copy 1 · lp → ??0000label address 0103hcopy 2 · lp → ??0001label address 0109hIP after: 0103h

The macro has LOCAL lp. At each expansion the assembler renamed lp: ??0000 (0103h) in copy 1, ??0001 (0109h) in copy 2. CX = 3.

CX0002hZF0copy 1 · lp → ??0000label address 0103hJNZ: takencopy 2 · lp → ??0001label address 0109hIP after: 0103h

Pass 1: DEC CX → CX = 2, ZF = 0; JNZ goes back to ??0000 (0103h).

CX0001hZF0copy 1 · lp → ??0000label address 0103hJNZ: takencopy 2 · lp → ??0001label address 0109hIP after: 0103h

Pass 2: CX = 1, ZF = 0 → again 0103h.

CX0000hZF1copy 1 · lp → ??0000label address 0103hJNZ: not takencopy 2 · lp → ??0001label address 0109hIP after: 0106h

Pass 3: CX = 0 → ZF = 1; JNZ does not jump, copy 1 is done.

CX0002hZF1copy 1 · lp → ??0000label address 0103hcopy 2 · lp → ??0001label address 0109hIP after: 0109h

CX = 2: the counter for the macro's second use.

CX0001hZF0copy 1 · lp → ??0000label address 0103hcopy 2 · lp → ??0001label address 0109hJNZ: takenIP after: 0109h

Copy 2: DEC CX → CX = 1; JNZ goes back to ??0001 (0109h), not to copy 1's label.

CX0000hZF1copy 1 · lp → ??0000label address 0103hcopy 2 · lp → ??0001label address 0109hJNZ: not takenIP after: 010Ch

CX = 0, ZF = 1: the loop ends. No label name is defined twice, so there is no Duplicate declaration error.

CX0000hZF1copy 1 · lp → ??0000label address 0103hcopy 2 · lp → ??0001label address 0109hIP after: 0000h

RET: the program ends. 3 + 2 = 5 DECs ran in total.

Macro: DELAY MACRO / LOCAL lp / lp: DEC CX / JNZ lp / ENDM; main program mov cx, 3 / DELAY / mov cx, 2 / DELAY.

Labels and LOCAL · Step through the code

Code Trace: Two Expansions of MAX2 p, q, r

org 100h
mov ax, x      ; MAX2 x, y, m1
cmp ax, y
jge ??0000
mov ax, y
??0000: mov m1, ax
mov ax, y      ; MAX2 y, 4, m2
cmp ax, 4
jge ??0001
mov ax, 4
??0001: mov m2, ax
ret
x  dw 7
y  dw -3
m1 dw ?
m2 dw ?
7x-3y0m10m2AX0007hZF0SF0OF0

1st expansion MAX2 x, y, m1: AX = x = 7.

7x-3y0m10m2AX0007hZF0SF0OF0

CMP AX, y: 7 − (−3) = 10 → SF = 0, OF = 0.

7x-3y0m10m2AX0007hZF0SF0OF0SF = OF: taken

JGE compares signed: SF = OF → jumps to the ??0000 label. LOCAL turned this copy's ok label into ??0000.

7x-3y7m10m2AX0007hZF0SF0OF0

m1 = 7.

7x-3y7m10m2AXFFFDhZF0SF1OF0

2nd expansion MAX2 y, 4, m2: AX = y = −3 (FFFDh); CMP AX, 4: −3 − 4 = −7 → SF = 1, OF = 0.

7x-3y7m10m2AXFFFDhZF0SF1OF0SF ≠ OF

SF ≠ OF: JGE ??0001 does not jump. The second copy's label is ??0001; no clash with the first.

7x-3y7m10m2AX0004hZF0SF1OF0

The larger value is the second parameter: AX = 4.

7x-3y7m14m2AX0004hZF0SF1OF0

m2 = 4; RET. With JAE, −3 (FFFDh) would count as the unsigned 65533, and m2 would be −3.

Macro: MAX2 MACRO p, q, r / LOCAL ok / MOV AX, p / CMP AX, q / JGE ok / MOV AX, q / ok: MOV r, AX / ENDM. In the first call the parameters are variables; in the second, one is an immediate.

The PUTC Macro

PUTC: Printing a Character

; prints a char, moves the cursor
PUTC  MACRO  char
      push  ax
      mov   al, char
      mov   ah, 0eh
      int   10h
      pop   ax
ENDM

ORG  100h
START:
      PUTC  'A'
      PUTC  'B'
      RET
  • The macro prints the character in its char parameter and moves the cursor one place right.
  • INT 10h, AH = 0Eh: BIOS teletype output. The character in AL is written at the cursor; control characters such as 0Dh, 0Ah, 07h, 08h are interpreted.
  • push ax / pop ax: the macro uses AX, so it preserves the caller's AX. No “invisible” side effect remains.
  • This macro is identical to the PUTC macro in the emu8086.inc library.
The RET after PUTC 'B' ends the program; without it the CPU would go on executing the random bytes after the program.

The PUTC Macro · Step through the code

PUTC 'A' and PUTC 'B' at Run Time

····FFFA····FFFC0000hFFFESPSS:offset · low address at top

After loading, CX = 0011h: 2 copies × 8 bytes + RET = 17 bytes. The screen is empty.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

AX (0000h) is saved on the stack; SP = FFFCh.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

AL = 41h ('A').

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

AH = 0Eh → AX = 0E41h.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

INT 10h: A is printed and the cursor advances.

····FFFA0000hFFFC0000hFFFESPSS:offset · low address at top

AX gets its old value (0000h) back; SP = FFFEh.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

Second copy: AX is saved again.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

AL = 42h ('B').

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

AX = 0E42h.

····FFFA0000hFFFCSP0000hFFFESS:offset · low address at top

INT 10h: the screen shows AB.

····FFFA0000hFFFC0000hFFFESPSS:offset · low address at top

AX = 0000h; the macro did not clobber the caller's AX.

····FFFA0000hFFFC0000hFFFESS:offset · low address at top

RET: the program ends.

ORG  100h
push ax          ; PUTC 'A'
mov  al, 'A'
mov  ah, 0eh
int  10h
pop  ax
push ax          ; PUTC 'B'
mov  al, 'B'
mov  ah, 0eh
int  10h
pop  ax
RET

Output in the emu8086 screen window (80×25): AB. Each PUTC copy is 8 bytes: 50 B0 41 B4 0E CD 10 58.

The PUTC Macro

Register-Saving Macros

SAVE MACRO
  PUSH AX
  PUSH BX
  PUSH CX
  PUSH DX
ENDM

RESTORE MACRO
  POP DX
  POP CX
  POP BX
  POP AX
ENDM
  • PUTC's push ax / pop ax pattern grows to four registers in larger macros; the pattern itself can be a macro.
  • RESTORE pops the registers in the reverse of the order SAVE pushed them: the stack is last in, first out. In the same order, AX and DX, BX and CX would swap.
  • Each SAVE + RESTORE pair adds 8 bytes and 8 stack accesses: 4 × 11 (PUSH) + 4 × 8 (POP) = 76 clocks on the 8086.
  • Use the two macros together in one body; a conditional exit in between leaves the stack unbalanced.
On the 80186 and later, single-instruction PUSHA / POPA save all general-purpose registers; the 8086 lacks them, so a macro does the job.

The POWER Macro

Exponentiation: The POWER Macro

POWER macro b, e, r
    mov ax, 1        ; result so far = 1
    mov cx, e        ; exponent → CX
    mov bx, b        ; base → BX
powerloop:
    mul bx           ; DX:AX = AX * BX
    loop powerloop   ; repeat e times
    mov r, ax        ; store result
endm
ORG 100h
start:
    POWER base, exponent, result
    ret
base     dw 2     ; base
exponent dw 3     ; exponent
result   dw ?     ; result
  • Result r = be: start AX at 1 and multiply by the base e times.
  • MUL BX: DX:AX ← AX × BX (unsigned). DX changes too!
  • LOOP: decrements CX and jumps to the label if CX ≠ 0.

The POWER Macro · Step through the code

POWER 2, 3 Step by Step

The data comes right after the code: base = 0113h, exponent = 0115h, result = 0117h (code is 19 bytes).

AX = 1 (result so far).

CX ← [0115h] = 3 (exponent).

BX ← [0113h] = 2 (base).

Pass 1: DX:AX = 1 × 2 = 0002h.

LOOP: CX = 2 ≠ 0 → powerloop.

Pass 2: AX = 2 × 2 = 0004h.

LOOP: CX = 1 → powerloop.

Pass 3: AX = 4 × 2 = 0008h.

LOOP: CX = 0 → exit the loop.

result ← AX: [0117h] = 0008h = 23.

RET: the program ends.

ORG 100h
mov ax, 1        ; POWER expansion
mov cx, exponent
mov bx, base
powerloop:
mul bx
loop powerloop
mov result, ax
ret
base     dw 2    ; 0113h
exponent dw 3    ; 0115h
result   dw ?    ; 0117h

After MUL, DX = 0, so CF = OF = 0. Had the result exceeded 16 bits (e.g. 216), DX ≠ 0 and CF = 1; since the macro stores only AX, the result would be wrong.

The POWER Macro

Pitfalls of the POWER Macro

1. Exponent = 0With CX = 0, LOOP decrements CX first: FFFFh → the loop runs 65,536 times; b0 should be 1. Fix: JCXZ.
2. Labelpowerloop is not LOCAL: a Duplicate declaration on the second use.
3. Clobbered registersAX, BX, CX and (because of MUL) DX change.
4. OverflowIf the result exceeds 65,535, the high part stays in DX and is not stored.

Fixed version:

POWER MACRO b, e, r
      LOCAL p_loop, p_end
      PUSH BX
      PUSH CX
      PUSH DX
      MOV  AX, 1
      MOV  CX, e
      MOV  BX, b
      JCXZ p_end   ; e = 0 → 1
p_loop: MUL BX
      LOOP p_loop
p_end: MOV r, AX
      POP  DX
      POP  CX
      POP  BX
ENDM

The POWER Macro · Step through the code

Fixed POWER 7, 2 Step by Step

org 100h
push bx          ; POWER expansion
push cx
push dx
mov  ax, 1
mov  cx, expn
mov  bx, base
jcxz ??0001      ; expn = 0 → 1
??0000: mul bx
loop ??0000
??0001: mov res, ax
pop  dx
pop  cx
pop  bx
ret
base dw 7
expn    dw 2
res dw ?
AX0000hBX0AAAhCX0BBBhDX0CCChres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

The caller's registers are BX = 0AAAh, CX = 0BBBh, DX = 0CCCh. The fixed macro first saves all three on the stack: SP = FFF8h.

AX0001hBX0007hCX0002hDX0CCChres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

AX = 1, CX ← expn = 2, BX ← base = 7. The registers now belong to the macro.

AX0001hBX0007hCX0002hDX0CCChres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

JCXZ: CX = 2 ≠ 0, no jump. Had expn been 0, it would go straight to ??0001 and the result would be 1 (no 65,536-pass LOOP trap).

AX0007hBX0007hCX0002hDX0000hres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

1st MUL: DX:AX = 1 × 7 = 0007h. MUL writes DX too (DX = 0).

AX0007hBX0007hCX0001hDX0000hres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

LOOP: CX = 1 ≠ 0 → ??0000.

AX0031hBX0007hCX0001hDX0000hres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

2nd MUL: DX:AX = 7 × 7 = 0031h = 49.

AX0031hBX0007hCX0000hDX0000hres????stack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

LOOP: CX = 0 → exit the loop.

AX0031hBX0007hCX0000hDX0000hres0031hstack0CCChFFF8DXSP0BBBhFFFACX0AAAhFFFCBX0000hFFFE

res ← AX: [011Fh] = 0031h = 7². LOCAL renamed the labels ??0000 / ??0001.

AX0031hBX0AAAhCX0BBBhDX0CCChres0031hstack0CCChFFF80BBBhFFFA0AAAhFFFC0000hFFFESP

Three POPs, in reverse order of the PUSHes: DX = 0CCCh, CX = 0BBBh, BX = 0AAAh are back; SP = FFFEh. The macro changed only AX.

AX0031hBX0AAAhCX0BBBhDX0CCChres0031hstack0CCChFFF8DX0BBBhFFFACX0AAAhFFFCBX0000hFFFE

RET: the program ends.

The code is the expansion POWER base, expn, res of the fixed macro; LOCAL names are shown as the assembler generates them.

The POWER Macro

Nested Macros

PRINT2 MACRO c1, c2
       PUTC c1
       PUTC c2
ENDM

PRINT2 'O', 'K'
; level 1: PRINT2 expands
PUTC 'O'
PUTC 'K'

The outer macro expands first: both lines in its body are themselves macro calls.

PRINT2 MACRO c1, c2
       PUTC c1
       PUTC c2
ENDM

PRINT2 'O', 'K'
PRINT2 'O', 'K'PUTC 'O'5 instructions · 8 bytesPUTC 'K'5 instructions · 8 bytes
; level 2: the PUTCs expand
push ax
mov  al, 'O'
mov  ah, 0eh
int  10h
pop  ax
push ax
mov  al, 'K'
mov  ah, 0eh
int  10h
pop  ax

The assembler expands the inner macros too: a one-line call produces 10 instructions (16 bytes). The screen shows: OK.

PUTC must be defined before PRINT2. If a macro calls itself (recursion), the expansion never ends without conditional assembly.

Macro Libraries

Macro Libraries: emu8086.inc

  • Frequently used macros are collected in a separate file and added to a program with INCLUDE.
  • Unused macros generate no code, so including a large library does not grow the file.
  • Macros can call other macros (nested expansion).
  • Besides macros, the library offers procedures through the DEFINE_... macros (e.g. DEFINE_SCAN_NUM): the two are used together.
MacroFunction
PUTC chPrints one character
PRINT 'text'Prints text
PRINTN 'text'Text + new line
GOTOXY x, yMoves the cursor
CURSOROFFHides the cursor
include 'emu8086.inc'
ORG 100h
    GOTOXY 10, 5
    PRINT 'Hello'
    PUTC  '!'
    RET

Macro Libraries · Step through the code

emu8086.inc: Expanding PRINT 'OK'

org 100h
push ax          ; PRINT 'OK'
push si
jmp  ??0003      ; skip the data
??0001 db 'OK', 0
??0003: lea si, ??0001
??0000: mov al, cs:[si]
cmp  al, 0
jz   ??0002
inc  si
mov  ah, 0Eh
int  10h
jmp  ??0000
??0002: pop si
pop  ax
ret
string in the code segment'O'0104h'K'0105h00h0106hAL00hSI0000hscreen▌stack0000hFFFASP0000hFFFC0000hFFFE

PRINT 'OK' is expanded. The macro will use AX and SI, so it saves both on the stack first.

string in the code segment'O'0104h'K'0105h00h0106hAL00hSI0000hscreen▌stack0000hFFFASP0000hFFFC0000hFFFE

The string is embedded between instructions inside the macro (0104h: 'O', 'K', 0). The JMP jumps over these bytes so the CPU does not take them for instructions.

string in the code segment'O'0104h'K'0105h00h0106hSIAL00hSI0104hscreen▌stack0000hFFFASP0000hFFFC0000hFFFE

SI ← the string address 0104h. LOCAL names (??0000…) are new for each PRINT.

string in the code segment'O'0104h'K'0105h00h0106hSIAL4FhSI0104hscreen▌stack0000hFFFASP0000hFFFC0000hFFFE

AL ← CS:[SI] = 4Fh ('O'). The string is in the code segment, so the CS: prefix is used. Not 0 → continue.

string in the code segment'O'0104h'K'0105h00h0106hSIAL4FhSI0105hscreenO▌stack0000hFFFASP0000hFFFC0000hFFFE

SI advances by one, INT 10h/0Eh prints O, JMP goes back to the top of the loop.

string in the code segment'O'0104h'K'0105h00h0106hSIAL4BhSI0105hscreenO▌stack0000hFFFASP0000hFFFC0000hFFFE

AL = 4Bh ('K'); not the terminator.

string in the code segment'O'0104h'K'0105h00h0106hSIAL4BhSI0106hscreenOK▌stack0000hFFFASP0000hFFFC0000hFFFE

The screen shows OK.

string in the code segment'O'0104h'K'0105h00h0106hSIAL00hSI0106hscreenOK▌stack0000hFFFASP0000hFFFC0000hFFFE

AL = 00h: CMP → ZF = 1, JZ jumps to the exit.

string in the code segment'O'0104h'K'0105h00h0106hAL00hSI0000hscreenOK▌stack0000hFFFA0000hFFFC0000hFFFESP

SI and AX are popped back: the macro did not clobber the caller's registers.

string in the code segment'O'0104h'K'0105h00h0106hAL00hSI0000hscreenOK▌stack0000hFFFA0000hFFFC0000hFFFE

RET: the program ends. The one-line PRINT 'OK' produced 26 bytes of code + data.

Expansion of the PRINT macro from emu8086.inc (LOCAL names as the assembler generates them). PRINTN does the same and appends CR LF.

Advanced Macro Features

Macro Operators: &, <>, !, %, ;;

OperatorRoleExample and expansion
&joins a parameter to adjacent textCLEAR MACRO r · XOR r&X, r&X → CLEAR B: XOR BX, BX
< >makes text containing commas or spaces a single parameterEMIT <'A', 'B'> → one parameter: 'A', 'B'
!makes the next character an ordinary character<5 !> 3> → text: 5 > 3
%evaluates an expression and substitutes the result as textSHOW %(4*8) → parameter 32
;;macro comment; not copied into the expansion;; visible only in the definition
  • These operators are defined in MASM and TASM; they are used to split and join text when writing a macro definition.
  • Without &, rX counts as a single name and is not substituted.
  • A comment written with a single ; is repeated in every expansion; ;; keeps the listing short.

Advanced Macro Features

Repeat Blocks: REPT, IRP, IRPC

REPT n
REPT 3
  SHL AX, 1
ENDM
expansion: SHL AX, 1 three times (AX × 8)
IRP p, <list>
IRP r, <AX,BX,CX>
  PUSH r
ENDM
expansion: PUSH AX · PUSH BX · PUSH CX
IRPC p, text
IRPC c, OK
  PUTC '&c'
ENDM
expansion: PUTC 'O' · PUTC 'K'
  • Repeat blocks are nameless macros expanded right where they are defined; they end with ENDM.
  • REPT writes the body n times, IRP once for each item in the list, IRPC once for each character of the text. In MASM 6, IRP and IRPC can also be written as FOR and FORC.
  • No loop counter is needed, but the code grows: REPT 100 copies the body 100 times. A counted LOOP works with a single copy.
  • The most common use is generating tables at assembly time: number tables, masks, squares or sine values.

Advanced Macro Features · Step through the code

Code Trace: A Table of Squares Generated by REPT

org 100h
lea  bx, sq
mov  al, 5
xlat           ; AL = sq[5]
mov  dl, al
mov  al, 7
xlat           ; AL = sq[7]
add  al, dl
ret
sq db 0, 1, 4, 9, 16, 25, 36, 49
0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL00hDL00h

REPT generated the table at assembly time; memory holds just 8 bytes. LEA BX, sq: BX = 010Eh.

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL05hDL00h

AL = 5: the number to square, which is also the table index.

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL19hDL00h[BX + AL]

XLAT: AL ← [BX + AL] = sq+5 = 25 (19h). No multiplication, just a table read.

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL19hDL19h

DL = 19h: the first result is saved.

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL31hDL19h

AL = 7, XLAT → sq+7 = 49 (31h).

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL4AhDL19h25 + 49

ADD AL, DL: 49 + 25 = 74 (4Ah) = 5² + 7².

0sq+01sq+14sq+29sq+316sq+425sq+536sq+649sq+7BX010EhAL4AhDL19h

RET. XLAT takes 11 clocks; an 8-bit MUL on the 8086 takes 70–77.

Source of the table: n = 0 / sq LABEL BYTE / REPT 8 / DB n*n / n = n + 1 / ENDM. The code ran in the expanded form of this block. An EQU constant cannot change; a symbol defined with = takes a new value on each pass.

Advanced Macro Features

Conditional Assembly: IF, IFB, IFIDN

SHIFTN MACRO r, n
  IFB <n>          ;; n not given?
    SHL r, 1
  ELSE
    MOV CL, n
    SHL r, CL
  ENDIF
ENDM

DEBUG = 1
IF DEBUG
  PUTC '*'         ; debug build only
ENDIF
DirectiveCondition
IF exprexpr ≠ 0
IFE exprexpr = 0
IFB <p>parameter blank
IFNB <p>parameter not blank
IFIDN <a>,<b>two texts identical
IFDIF <a>,<b>two texts different
  • The condition is evaluated at assembly time: the branch not chosen never enters the machine code; there is no flag or jump at run time.
  • EXITM ends the expansion at that point; IFIDN <r>, <CX> can catch a clobbered register passed as a parameter.

Advanced Macro Features · Step through the code

Code Trace: SHIFTN AX and SHIFTN BX, 3

org 100h
mov ax, 5
mov bx, 3
shl ax, 1      ; SHIFTN AX
mov cl, 3      ; SHIFTN BX, 3
shl bx, cl
ret
AX0005hBX0003hCL00hAL = 00000101BL = 00000011CF = 0

AX = 5, BX = 3: the values to shift.

AX000AhBX0003hCL00hAL = 00001010BL = 00000011CF = 0IFB branch

SHIFTN AX: n is blank, the IFB branch is chosen → a single SHL AX, 1. AX = 000Ah (5 × 2).

AX000AhBX0003hCL03hAL = 00001010BL = 00000011CF = 0ELSE branch

SHIFTN BX, 3: n = 3, ELSE branch → MOV CL, 3. On the 8086 a shift count above 1 goes in CL.

AX000AhBX0018hCL03hAL = 00001010BL = 00011000CF = 0

SHL BX, CL: 3 × 2³ = 0018h (24). The same macro produced code of two different lengths: 2 bytes and 4 bytes.

AX000AhBX0018hCL03hAL = 00001010BL = 00011000CF = 0

RET. The SHIFTN AX expansion did not touch CL; only the second expansion changed it.

The code is the expanded form of two SHIFTN calls. The assembler chose which branch to emit; no comparison happened at run time.

Advanced Macro Features

Debugging and Listing Macros

Seeing the expansionThe instruction list in emu8086's emulator window shows the expanded instructions, not macro names; single-stepping moves through these instructions.
Listing fileIn MASM, .LISTMACROALL lists every line of the expansion, .LISTMACRO only the lines that generate code, and .NOLISTMACRO hides the expansion.
Error lineAn error in the body is reported separately at every line that uses the macro. If the same error shows up several times, the cause is usually in the body.
Expand by hand firstDevelop a new macro by writing and testing its body as plain code first; once it works, turn it into a parameterized macro.
Because LOCAL gives macro labels names like ??0000, jump targets in the emulator don't show the source names; these numbers tell you which copy is running.

Advanced Macro Features

Common Macro Mistakes

Defining after useThe assembler cannot expand a call to a macro it does not know; put definitions at the top of the file or in an INCLUDE file.
Forgetting ENDMThe rest of the file is taken as the macro body; the error shows up much further down.
Labels not made LOCALDuplicate declaration on the second use.
RET in the bodyA macro is not entered with CALL; RET takes the caller's return address.
Passing a clobbered registerIn a call such as ADD3 BX, AX, CX, the body may change a parameter before reading it.
Unparenthesized expressions(wd)*(ht) instead of wd*ht; otherwise precedence changes.
Mistaking a macro for a loopREPT 1000 produces 1000 copies; repeating at run time needs LOOP.
Using a long body many timesCode size grows with the number of uses; move long work into a procedure.

Lab · macro expansion step by step

Lab: Macros

Summary

Summary

TopicKey point
Definitionname MACRO p1, p2 … ENDM; defined before use.
ExpansionText substitution at assembly time; no CALL at run time.
ParametersSubstituted as text; their values are read on the line where they are used.
Size / speedMacro: grows by the body at every use, faster. Procedure: a 3-byte CALL, CALL/RET cost.
LOCALThe first line of the body, so labels are unique at each expansion.
Side effectsPreserve the registers a macro changes with PUSH/POP (as PUTC does).
Edge casesCheck CX = 0 before LOOP (JCXZ).

Summary

Exercises

  1. Write the expanded form of the call MyMacro AX, BX, CX. Which lines are redundant?
  2. Write an ADD3 a, b, c macro that adds two word variables and stores the sum in the third.
  3. What are the code sizes if the PUTC macro is used 50 times and an equivalent procedure is called 50 times?
  4. What error do you get when the POWER macro is used twice as POWER base, exponent, result? How do you fix it?
  5. With exponent = 0, how many times does the original POWER macro execute MUL?
  6. Which instructions must be added so that a macro clobbers no register other than AX?
Answers
  1. MOV AX, AX / MOV BX, BX / MOV CX, CX: all three have no effect (they assemble but change nothing).
  2. ADD3 MACRO a, b, c / MOV AX, a / ADD AX, b / MOV c, AX / ENDM (there is no memory-to-memory operation, so AX is the go-between).
  3. Macro: 50 × 8 = 400 bytes. Procedure: 9 + 50 × 3 = 159 bytes.
  4. Duplicate declaration (powerloop). Add LOCAL powerloop.
  5. 65,536 times (CX: 0 → FFFFh → … → 0).
  6. A PUSH at the start of the body for each register used, and POPs in reverse order at the end.

Summary

References

  • emu8086 help: 8086 Assembler Tutorial, Part 10 (Macros) and emu8086.inc.
  • Microsoft, MASM Programmer's Guide — the MACRO, ENDM, LOCAL directives.
  • K. R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014 — Chapter 10 (Macros).
  • B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009.

The End

Chapter 9.1: Macros
Previous: Chapter 8.2: Procedures · Next: Chapter 9.2: The emu8086.inc Library
1 / 1 Sercan KÜLCÜ. All rights reserved.