Microprocessors · Lecture Notes
Chapter 9.1: Macros
The same few instructions keep turning up side by side in assembly programs: print a character, save a few registers on the stack, add two numbers and store the sum. A procedure removes this repetition at run time, with CALL and RET. A macro does the same job at assembly time: wherever the assembler sees the macro's name, it writes the macro's body again. The processor never sees the macro; it executes only the instructions that result. These notes first show how a macro is defined and expanded and why its parameters behave like text. They then weigh the trade-off in size and speed between macros and procedures, and the problem that the LOCAL directive solves. The PUTC and POWER macros serve to treat register preservation and boundary cases. The last sections cover repeat blocks and conditional assembly, the more advanced text processing the assembler performs on the source. Every example is shown at the level of registers and memory, with a step-by-step trace of the expanded code.
Learning outcomes
- Macro definition
- Write a parameterized macro with MACRO and ENDM; explain why a macro must be defined before the line that uses it.
- Expansion
- Work out by hand which instructions a macro call expands to, by substituting the parameters as text.
- Macro or procedure?
- Compute code size byte by byte and the extra time in clock cycles, and choose a macro or a procedure for a given job with a justification.
- LOCAL
- Explain the cause of the Duplicate declaration error in macros that contain labels, and give each expansion a unique label with LOCAL.
- Side effects and boundary cases
- Protect the registers a macro clobbers with PUSH and POP; spot parameter pitfalls, operator-precedence errors and the CX = 0 trap of LOOP.
- Advanced macro features
- Generate code and tables at assembly time with REPT, IRP and IRPC; assemble conditionally with IF, IFB and IFIDN.
9.1.1The macro concept
9.1.1.1The text processing done by the assembler
An assembly program goes through two separate stages. First the assembler reads the source file and translates it into machine code. Then the processor fetches this machine code from memory and executes it. Everything written in the source has a meaning in the first stage, but not every line becomes machine code. Directives such as ORG 100h, DB and EQU give information to the assembler; some of them emit bytes and some emit none. A macro is also a tool of this first stage.
A macro gives a name to a piece of code that repeats. In this respect it resembles a procedure. The difference is where the name is processed. The name of a procedure becomes an address in the machine code; at run time the processor goes to that address with CALL and comes back with RET. The name of a macro never enters the machine code. The assembler deletes every line that uses the macro and writes the macro's body in its place. This operation is called macro expansion. After expansion the source no longer contains macros, only ordinary instructions.
A macro is a code template, written between the MACRO and ENDM directives, that has a name and optional parameters. The assembler replaces every line that uses the macro's name like an instruction with a copy of the body in which the parameters have been substituted. This replacement is called macro expansion; it takes place at assembly time, before the program runs.
Figure 9.1.1 summarizes the process. The single source line PUTC 'A' turns into five instructions after it passes through the assembler. The machine code contains no call, no return address and no jump. To the processor these five instructions are no different from five instructions written by hand.
PUTC 'A' the assembler writes the body; the machine code contains no call.Three important consequences follow from this view. First, a macro that is never used adds not a single byte to the machine code. The assembler reads the definition and records the name and body in a table, but it generates no code from the body. Code is produced only when the macro is used, and at the place where it is used. For this reason, including a library file with hundreds of macros does not enlarge the program.
Second, a macro must be defined before the line that uses it. The assembler reads the source file from top to bottom. If it reaches the line PUTC 'A' and does not yet know PUTC, it treats the line as an unknown instruction and reports an error. A procedure has no such ordering restriction. Because the assembler makes two passes, it finds the address of a procedure in the second pass even if the procedure is written at the end of the file. A macro, however, is not an address but a text, and the assembler cannot substitute a text it does not know.
Third, every use of a macro enlarges the program. If the same macro is used in ten places, the body is written ten times. The body of a procedure, by contrast, sits in memory once. This difference is the basis of the choice between a macro and a procedure.
9.1.1.2Defining a macro
The definition of a macro has three parts: a header line, a body and an end line. The general form is:
name MACRO [parameter1, parameter2, ...]
<instructions>
ENDMname is the name of the macro. When the macro is used, this name is written in the place of an instruction: PUTC is written where MOV would be. The name is followed by comma-separated parameter names. These are formal names; in the definition they are merely placeholders. The values given in the call replace these names as text. A macro may have no parameters at all: some macros just give a name to a pattern.
The body consists of the lines that are rewritten each time the macro is used. It may contain instructions, directives, calls to other macros, even data definitions. ENDM (end macro) ends the body. Unlike the name ENDP pattern of a procedure, the macro's name is not written before ENDM.
The parameter names mark the text to be substituted in the body. The assembler compares every word in the body with the parameter names. In place of a matching word it writes the corresponding text from the call. Figure 9.1.2 shows this mapping for the call MyMacro 4, 5, DX: the first parameter p1 maps to 4, the second p2 to 5, and the third p3 to DX. The line MOV CX, p3 in the body thus becomes MOV CX, DX.
MOV CX, p3 becomes MOV CX, DX.There is a critical point here. The assembler does not care whether a parameter is a register, a memory operand or a constant. It only replaces text. Whether the resulting line is a valid 8086 instruction is checked after expansion, like any ordinary line. A macro definition may therefore be free of errors and yet a particular call may produce one.
Writing the macro at the end of the program, next to the procedures. The placement that is right for a procedure causes an error for a macro: when the assembler reaches the call line it does not know the macro, so it treats the line as an unknown instruction. Macro definitions are written at the beginning of the file or in a library file added with INCLUDE.
9.1.1.3Expansion step by step
Expansion is best understood through a concrete example. The macro MyMacro, which has three parameters, loads a value into each of three registers:
MyMacro MACRO p1, p2, p3
MOV AX, p1
MOV BX, p2
MOV CX, p3
ENDM
ORG 100h
MyMacro 1, 2, 3
MyMacro 4, 5, DX
RETWhen the assembler reads the first four lines it generates no code. It records the name MyMacro, the three parameter names and the three body lines in a macro table. ORG 100h sets the location counter to 0100h. Then comes the line MyMacro 1, 2, 3. The assembler finds MyMacro in its table and pairs up the parameters: p1 = 1, p2 = 2, p3 = 3. Then it copies the body line by line:
- In the line
MOV AX, p1, the word p1 is replaced by 1:MOV AX, 1. - The line
MOV BX, p2becomesMOV BX, 2. - The line
MOV CX, p3becomesMOV CX, 3.
These three lines take the place of the call line and are translated into machine code like ordinary instructions. For the second call, MyMacro 4, 5, DX, the same process repeats with a new mapping: p1 = 4, p2 = 5, p3 = DX. The result is MOV AX, 4, MOV BX, 5 and MOV CX, DX. The DX in the last line is not a number but a register name. The assembler does not notice this; it simply substitutes the text "DX". The resulting MOV CX, DX is a valid register-to-register copy.
emu8086 shows the expanded code in the emulator window like this:
MOV AX, 00001h
MOV BX, 00002h
MOV CX, 00003h
MOV AX, 00004h
MOV BX, 00005h
MOV CX, DX
RETThe constants are written in hexadecimal with five digits; this is merely a display habit. What matters is that the two macro calls expand into six instructions and that the macro name never appears in the listing. Single-stepping in the emulator also advances over these six instructions. The programmer wrote two lines in the source; the processor executed six instructions.
The machine code of these instructions can also be computed. The MOV r16, imm16 instruction, which loads an immediate value into a 16-bit register, is 3 bytes: the opcode B8h + register number and two data bytes. MOV AX, 1 = B8 01 00, MOV BX, 2 = BB 02 00, MOV CX, 3 = B9 03 00. The register-to-register MOV CX, DX is 2 bytes (8B CA). RET is a single byte (C3). The total size of the program is 5 × 3 + 2 + 1 = 18 bytes, that is, 12h bytes.
9.1.1.4Code trace: running the expanded code
Running the expanded code is no different from running an ordinary program. Still, one detail matters for understanding the trace table. When emu8086 loads a .COM program into memory, it writes the program's size in bytes into register CX. This behavior comes from the DOS program loader. Since the size of this program is 18 bytes, CX = 0012h at load time. The other general-purpose registers are zero, and SP is FFFEh. The word 0000h sits at address FFFEh, which SP points to; the RET at the end of the program will pop this word.
Table 9.1.1 gives the trace of the expanded code. The first three steps are the instructions produced by the first call, the next three those of the second call. The small text under the instruction column shows which macro expansion the instruction comes from.
| Step | Address | Instruction | AX | BX | CX | DX | SP | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AX, 1MyMacro expansion | 0001h | 0000h | 0012h | 0000h | FFFEh | 1st expansion, p1 = 1: AX = 0001h |
| 2 | 0103h | MOV BX, 2MyMacro expansion | 0001h | 0002h | 0012h | 0000h | FFFEh | p2 = 2: BX = 0002h |
| 3 | 0106h | MOV CX, 3MyMacro expansion | 0001h | 0002h | 0003h | 0000h | FFFEh | p3 = 3: CX = 0003h; the load value 0012h is overwritten |
| 4 | 0109h | MOV AX, 4MyMacro expansion | 0004h | 0002h | 0003h | 0000h | FFFEh | 2nd expansion, p1 = 4 |
| 5 | 010Ch | MOV BX, 5MyMacro expansion | 0004h | 0005h | 0003h | 0000h | FFFEh | p2 = 5 |
| 6 | 010Fh | MOV CX, DXMyMacro expansion | 0004h | 0005h | 0000h | 0000h | FFFEh | p3 = DX: register-to-register copy, CX = DX = 0000h |
| 7 | 0111h | RETmain program | 0004h | 0005h | 0000h | 0000h | 0000h | 0000h at the top of the stack → IP; SP = 0000h |
| 8 | 0000h | INT 20h (PSP:0000h)PSP | 0004h | 0005h | 0000h | 0000h | 0000h | the INT 20h at PSP:0000h ends the program |
A few points in the table deserve attention. The load value of CX, 0012h, stays unchanged in the first two steps and is overwritten with 0003h in the third. The last instruction of the second call copies DX into CX; since DX is initially zero, CX becomes 0000h. SP does not change in any step. As long as the macro body contains no PUSH or POP, the macro does not touch the stack. If the same job were done with a procedure, every CALL would decrease SP by 2 and write the return address to the stack. The last RET does not belong to the macro; it is the main program's RET. It takes the word 0000h from the top of the stack into IP and goes to the INT 20h instruction in the program segment prefix (PSP).
The running time of this program can also be computed in clock cycles. On the 8086, MOV r16, imm16 takes 4 cycles and MOV r16, r16 takes 2. The six instructions take 5 × 4 + 2 = 22 cycles. In a version written with a procedure, the CALL and RET times would be added to this for every call.
9.1.2Parameters
9.1.2.1A parameter is text: the swap trap
In a high-level language, the value of a parameter passed to a function is computed at the moment of the call, and that value is what the function receives. Nothing of the kind happens in a macro. A macro parameter carries not a value but a text. The assembler writes this text at every place where the parameter occurs in the body. The value of the register or variable that the text refers to is read only at run time, when the line executes. This distinction looks small, but a large share of macro bugs come from it.
A macro parameter is a formal name written as a placeholder in the macro definition. Its counterpart in the call is not a value but a text. The assembler writes this text at every place in the body where the parameter occurs. If the text is a register or variable name, its value is read when the expanded line executes at run time.
Suppose a programmer wants to use MyMacro to swap AX and BX. Since the first line of the macro puts p1 into AX and the second puts p2 into BX, the call MyMacro BX, AX, 0 looks as if it does "AX ← BX, BX ← AX". After this call the programmer expects AX = 2222h and BX = 1111h. Writing out the expansion changes the picture:
ORG 100h
MOV AX, 1111h
MOV BX, 2222h
MOV AX, BX ; MyMacro BX, AX, 0
MOV BX, AX ; p2 = AX (broken!)
MOV CX, 0
RET| Step | Address | Instruction | AX | BX | CX | Explanation |
|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AX, 1111hmain program | 1111h | 0000h | 0000h | AX = 1111h |
| 2 | 0103h | MOV BX, 2222hmain program | 1111h | 2222h | 0000h | BX = 2222h |
| 3 | 0106h | MOV AX, BXMyMacro expansion | 2222h | 2222h | 0000h | p1 = BX: AX ← BX; 1111h is lost here |
| 4 | 0108h | MOV BX, AXMyMacro expansion | 2222h | 2222h | 0000h | p2 = AX: the current value of AX is read, BX = 2222h |
| 5 | 010Ah | MOV CX, 0MyMacro expansion | 2222h | 2222h | 0000h | p3 = 0 |
| 6 | 010Dh | RETmain program | 2222h | 2222h | 0000h | result: AX = BX = 2222h |
| 7 | 0000h | INT 20h (PSP:0000h)PSP | 2222h | 2222h | 0000h | the program ends |
In the third step AX is filled with the value of BX, that is, 2222h. The old value of AX, 1111h, no longer exists anywhere. The MOV BX, AX of the fourth step does not read the "old AX" the programmer had in mind but the current value of AX. As a result both registers hold 2222h. In a high-level language this error could not occur, because parameters are evaluated at the moment of the call. In a macro, p2 = AX does not mean "the value of AX at the time of the call"; it is just the text "AX".
The general rule behind this trap is: a register that the macro body modifies must not be passed as a parameter that the body reads after that modification. MyMacro first writes AX and then reads p2, so passing AX as p2 is wrong. For a real swap the 8086 has the single instruction XCHG AX, BX. A macro that swaps must either use XCHG or save one of the values on the stack first.
Treating a macro parameter like a by-value parameter of a high-level language. In a call such as ADD2 CX, AX, if the body first writes CX into AX and then does ADD AX, AX, the result is 2 × CX rather than the expected CX + AX. The registers that a macro uses for itself are documented, and they are not passed as parameters.
9.1.2.2Kinds of parameters and their validity
Because the assembler gives a parameter no type, the same macro can be called in very different ways. Which call is valid is decided not by the macro itself but by the instruction that results from the expansion. The ADD3 macro below shows this well:
ADD3 MACRO x, y, z
MOV AX, x
ADD AX, y
MOV z, AX
ENDMThe macro adds x and y and writes the result to z. One may ask why it does not simply write something like ADD z, x. The 8086 instruction set does not combine two memory operands in one instruction. In instructions such as ADD, MOV and CMP, at most one operand can be in memory. This restriction comes from the hardware: the ModR/M byte of an instruction can specify only one memory address. The macro therefore does the addition through AX. AX is an intermediate register here, and the macro clobbers it.
| Call | Expansion (problem line) | Status |
|---|---|---|
ADD3 a, b, c | MOV AX, a · ADD AX, b · MOV c, AX | valid; three variables |
ADD3 BX, 5, CX | MOV AX, BX · ADD AX, 5 · MOV CX, AX | valid; register, constant, register |
ADD3 a, b, 7 | MOV 7, AX | error: the destination cannot be a constant |
ADD3 k, b, c (k DB) | MOV AX, k | error: size mismatch (16 bits ← 8 bits) |
ADD3 a, b | MOV , AX | error: missing operand |
Table 9.1.3 compares five calls. In the first two calls the parameters are of different kinds, but the expansion produces valid instructions. In the third call z = 7, so the last line becomes MOV 7, AX. A constant cannot be written to; a constant is a number embedded in the instruction, not a memory cell or register that can be written. In the fourth call k is a byte variable. MOV AX, k tries to copy an 8-bit memory cell into a 16-bit register. The assembler catches this mismatch because it knows the variable's size from its definition. In the fifth call the third parameter is missing. The assembler replaces the missing parameter with empty text, and the last line turns into the meaningless MOV , AX.
All of these errors are reported at the line where the macro is used, although their cause is a line in the body. The way to understand the error message is to write out the expansion, in your head or on paper. If the same error message appears at several different lines of the program, the cause is usually in the body of the macro that all those lines use.
MASM offers two features for catching the missing-parameter problem at the definition level. If :REQ is written after a parameter name (for example z:REQ), that parameter becomes required, and a clear error message is produced when it is omitted. The form y:=<1> gives the parameter a default value; if y is left out of the call, 1 is used. These features are specific to MASM; in simpler assemblers a missing parameter always remains empty text.
9.1.2.3Code trace: two expansions of ADD3
In the following program the ADD3 macro is called in two different ways. In the first call all three parameters are variables. In the second call a constant is given in place of y, and the result of the first call is used as input:
org 100h
ADD3 a, b, c ; c = a + b
ADD3 c, 5, d ; d = c + 5
ret
a dw 1200h
b dw 0345h
c dw ?
d dw ?The expanded code is six instructions and a RET. The addresses of the variables depend on the size of the code, so the byte count must be worked out first. The instruction MOV AX, a is encoded in a short form specific to AX: the opcode A1 and a two-byte address, 3 bytes in all. ADD AX, b uses the general memory-operand form: 03 06 and a two-byte address, 4 bytes in all. MOV c, AX is again the short form (A3 + address), 3 bytes. The first expansion is 3 + 4 + 3 = 10 bytes.
In the second expansion the middle line is ADD AX, 5. The 8086 has a short form that adds an immediate value to AX: the opcode 05 and two data bytes, 3 bytes in all. The second expansion is therefore 3 + 3 + 3 = 9 bytes. The same macro has produced code of different lengths depending on the parameter. The code is 10 + 9 = 19 bytes, 20 bytes with the RET. Since the program starts at 0100h, a is at address 0100h + 14h = 0114h. b is at 0116h, c at 0118h and d at 011Ah.
| Step | Address | Instruction | AX | a | b | c | d | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AX, aADD3 expansion | 1200h | 1200h | 0345h | 0000h | 0000h | x = a: AX ← [0114h] |
| 2 | 0103h | ADD AX, bADD3 expansion | 1545h | 1200h | 0345h | 0000h | 0000h | y = b: 1200h + 0345h = 1545h |
| 3 | 0107h | MOV c, AXADD3 expansion | 1545h | 1200h | 0345h | 1545h | 0000h | z = c: [0118h] ← 1545h |
| 4 | 010Ah | MOV AX, cADD3 expansion | 1545h | 1200h | 0345h | 1545h | 0000h | 2nd expansion, x = c: AX ← [0118h] |
| 5 | 010Dh | ADD AX, 5ADD3 expansion | 154Ah | 1200h | 0345h | 1545h | 0000h | y = 5 is a constant: short AX form 05 05 00 |
| 6 | 0110h | MOV d, AXADD3 expansion | 154Ah | 1200h | 0345h | 1545h | 154Ah | z = d: [011Ah] ← 154Ah |
| 7 | 0113h | retmain program | 154Ah | 1200h | 0345h | 1545h | 154Ah | the program ends |
Table 9.1.4 gives the details of the trace. In the first step AX is loaded with the value of a, 1200h. In the second step 0345h is added: 1200h + 0345h = 1545h. In the third step this sum is written to c. The second expansion reads c, adds 5 and writes the result to d: 1545h + 5 = 154Ah. Although the two expansions come from the same body, in one y is a memory address and in the other a constant. The assembler infers this difference from the text alone and chooses the appropriate machine code.
The memory accesses can also be examined at the hardware level. While MOV AX, a executes, the BIU reads a word from DS:0114h, that is, from physical address 07114h. Since a is at an even address, the read finishes in a single bus cycle. Had the address been odd, the 8086 would have had to fetch the word with two separate byte reads. The macro does not change this detail. Every instruction in the expansion makes exactly the memory accesses that its hand-written equivalent would.
Another lesson from this example is that the macro clobbers AX. A calling program that expects an old value in AX after ADD3 is mistaken. Which registers a macro modifies must be stated explicitly in the macro's documentation. Register preservation is treated separately with the PUTC macro.
For s1 dw 1234h and s2 dw 0F00Fh, what are s3 and CF after the call ADD3 s1, s2, s3?
The expansion is MOV AX, s1, ADD AX, s2, MOV s3, AX. 1234h + F00Fh = 10243h, a 17-bit result. The low 16 bits, 0243h, fit in AX and the top bit goes to CF: CF = 1. Because MOV does not change flags, CF is still 1 after the macro. s3 = 0243h. Since the macro writes the carry nowhere, the correct result of the unsigned addition has been lost. The calling program can catch this situation with JC right after the macro.
9.1.2.4Expressions and operator precedence
Since a parameter is text, an expression can also be given in the call: for instance AREA 2+3, 4. The assembler does not evaluate this expression first; it substitutes it as it stands. Operator precedence is applied again on the line where the expression has been substituted. This leads to unexpected results:
AREA MACRO wd, ht
MOV AX, wd*ht
ENDM
DIFF MACRO p, q
MOV CX, p-q
ENDMIn the call AREA 2+3, 4, wd = "2+3" and ht = "4". The expansion is the line MOV AX, 2+3*4. The assembler evaluates this expression at assembly time, and since multiplication comes before addition it finds 2 + 12 = 14. The value (2 + 3) × 4 = 20 that the programmer expected does not appear. The DIFF macro has the same problem: the call DIFF 10, 4+1 becomes MOV CX, 10-4+1, and evaluated from left to right it gives CX = 7, not the expected 5.
| Call | Expansion | Machine code | Result |
|---|---|---|---|
ALAN 2+3, 4 | MOV AX, 2+3*4 | B8 0E 00 | AX = 000Eh (14) |
corrected AREA 2+3, 4 | MOV AX, (2+3)*(4) | B8 14 00 | AX = 0014h (20) |
FARK 10, 4+1 | MOV CX, 10-4+1 | B9 07 00 | CX = 0007h |
corrected DIFF 10, 4+1 | MOV CX, (10)-(4+1) | B9 05 00 | CX = 0005h |
ALAN BX, 2 | MOV AX, BX*2 | – | error: * works only on constants |
The solution is to put every parameter in parentheses in the body: MOV AX, (wd)*(ht) and MOV CX, (p)-(q). Then whatever text arrives is evaluated within itself first. Table 9.1.5 compares the two forms with their machine codes. Note that the machine code contains no multiply or add instruction. The expression was evaluated at assembly time, and the result is embedded in the MOV instruction as an immediate value. The processor merely loads the number 000Eh or 0014h into AX.
The last row shows the limit of this point. The call AREA BX, 2 produces the line MOV AX, BX*2. The value of BX is not known at assembly time; it is known only at run time. The assembler cannot multiply a register, so it reports an error. Multiplying a register's value takes an instruction that runs at run time: MUL, or SHL for powers of 2. This distinction between an expression evaluated at assembly time and an instruction executed at run time is the key to understanding macros.
Using parameters without parentheses in the body: write (wd)*(ht) instead of wd*ht. If the macro is tried only with parameters that consist of a single number, no error shows; at the first call with an expression the result is silently wrong. The assembler gives no warning, because 2+3*4 is a valid expression.
9.1.3Macros and procedures
A macro and a procedure are two different solutions to the same problem: gathering repeated code under a name. One does the job at assembly time, the other at run time. This difference shows up in code size, speed, stack usage and the behavior of labels. This section first defines the two methods separately and then compares them with byte and clock-cycle calculations.
9.1.3.1Properties of a procedure
A procedure is a block of code written between the PROC and ENDP directives, called with CALL and left with RET. Its body sits at one address in memory as a single copy. The PRINT_A procedure below writes 'A' to the screen:
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 bytesWhen a near CALL instruction executes, the processor does three things. First it decreases SP by 2. Then it writes the address of the instruction after the CALL, the return address, to SS:SP. Finally it loads IP with the address of the procedure. RET does the opposite: it takes the word at SS:SP into IP and increases SP by 2. Because the return address is kept on the stack, the same procedure can be called from different places in the program; each time it returns to the right place.
A near CALL instruction is 3 bytes: the opcode E8 and a two-byte relative displacement. The displacement is found by subtracting the address of the instruction after the CALL from the address of the procedure. Even if the same procedure is called a hundred times, the body is written once; each call adds only 3 bytes. Parameters are passed in registers, in memory or on the stack. Because the name of a procedure turns into an address in the machine code, a procedure can be defined anywhere in the file, even after the call.
9.1.3.2Properties of a macro
The PUTC macro that does the same job is written as follows:
PUTC MACRO char
PUSH AX
MOV AL, char
MOV AH, 0Eh
INT 10h
POP AX
ENDM
PUTC 'A' ; 8 bytes
PUTC 'B' ; 8 bytesA macro is used just by writing its name; there is no CALL. The parameter is written after the macro name. Because the assembler rewrites the body at every use, two uses of PUTC produce two separate 8-byte copies in the program (Figure 9.1.5). The bytes of the body are: PUSH AX 1 byte (50), MOV AL, 'A' 2 bytes (B0 41), MOV AH, 0Eh 2 bytes (B4 0E), INT 10h 2 bytes (CD 10), POP AX 1 byte (58). The total is 8 bytes. Note that the macro contains no RET; a macro is not a piece of code that is called but one that is written in place.
There is also an important difference with labels. The body of a procedure is a single copy, so the labels inside it are defined once. The body of a macro is rewritten at every use. If the body contains a label and the macro is used twice, the same label is defined twice and the assembler reports a Duplicate declaration error. The LOCAL directive, which solves this problem, is treated in its own section.
| Criterion | Macro | Procedure |
|---|---|---|
| When is it processed? | at assembly time (text substitution) | at run time (CALL/RET) |
| >Use | PUTC 'A' | CALL PRINT_A |
| Code size | grows by the body at every use | body once + 3 bytes per call |
| Speed | no CALL/RET and no stack access | CALL + RET time at every call |
| Parameters | text after the name | register, memory or stack |
| Stack | not used (unless the body uses it) | used for the return address |
| Where defined | before use | anywhere |
| End | ENDM | name ENDP |
| Labels | LOCAL needed | no problem (single copy) |
Table 9.1.6 puts the two methods side by side on nine criteria. The first row is the reason for all the others. Because a macro is processed at assembly time, it leaves no cost at run time, but it takes space at every use. Because a procedure is processed at run time, it saves space, but it spends time at every call.
9.1.3.3Size calculation and the break-even point
Two simple formulas suffice to compute code size as a function of the number of uses. Let a job whose body is n bytes be used in k places. In a macro the body is written k times: the size is k · n bytes. In a procedure the body is written once, a 1-byte RET is added at the end, and every use is a 3-byte CALL: the size is (n + 1) + 3k bytes.
macro = k · n procedure = (n + 1) + 3k
The body of PUTC is n = 8 bytes. For a single use the macro takes 8 bytes and the procedure 8 + 1 + 3 = 12 bytes; the macro is smaller. For ten uses the macro grows to 80 bytes and the procedure to 9 + 30 = 39 bytes. For a hundred uses the gap widens: the macro is 800 bytes, the procedure 9 + 300 = 309 bytes. Figure 9.1.6 shows these three cases with bars. The macro's bar grows in direct proportion to the number of uses; the procedure's bar adds only 3 bytes per use on top of a fixed 9-byte block.
The number of uses at which a macro starts to be larger than a procedure can be called the break-even point. For the procedure to be smaller we need k · n > (n + 1) + 3k. Collecting terms gives k · (n − 3) > n + 1. Two conclusions follow from this inequality.
- If n ≤ 3, the left side is zero or negative and the inequality holds for no k. If the body is as short as a CALL, the macro is always smaller. In that case a procedure does not reduce code size; it only adds RET and call time.
- If n > 3, the break-even point is k > (n + 1) / (n − 3). For n = 8, k > 9/5 = 1.8, so from two uses on the procedure is smaller: 15 bytes against 16. For n = 5, k > 3, that is, from four uses on. For n = 4, k > 5; at five uses both take 20 bytes, and at six uses the procedure pulls ahead with 23 bytes against 24.
The PUTC macro is used 50 times. What would the code sizes be if the same job were done with a procedure?
Macro: 50 × 8 = 400 bytes. Procedure: the body and RET once (8 + 1 = 9 bytes), the CALLs 50 × 3 = 150 bytes; 159 bytes in all. The procedure is 241 bytes smaller. A frequent arithmetic mistake is to count only the CALLs (150 bytes) for the procedure, or to count the macro copy as 9 bytes with a RET. A macro has no RET.
Why does this calculation matter? The code, data and stack of a .COM program must all fit in a single 64 KB segment. In an embedded system the program is written to a small ROM and every byte is a cost. Using a macro with a long body in hundreds of places quickly strains these limits.
9.1.3.4Speed: CALL, RET and the prefetch queue
On the speed side the table turns around. Every call of a procedure executes a CALL and a RET in addition to the job itself. According to Intel's 8086 data sheet, a near direct CALL takes 19 clock cycles and a near RET takes 8. Each call thus adds 27 cycles. On a 4.77 MHz 8086 one cycle is about 209.6 ns; 27 cycles come to about 5.66 µs. At 5 MHz one cycle is 200 ns and 27 cycles are 5.4 µs.
Behind this number lies what happens in the hardware. The CALL instruction writes the return address to the stack; this is a memory write bus cycle. A bus cycle lasts at least four clock cycles (T1–T4). RET reads a word from the stack, which is a read bus cycle. More importantly, both instructions change the flow of the program. In the 8086, while the execution unit (EU) executes one instruction, the bus interface unit (BIU) prefetches the following instruction bytes. These bytes wait in the six-byte prefetch queue. When the flow changes with a jump, the bytes in the queue become useless. The BIU flushes the queue and starts fetching again from the new address. The EU waits until the first instruction byte arrives. This is one reason why CALL and RET take so long.
In the expansion of a macro, by contrast, the flow is a straight line. The instructions sit one after another in memory, the BIU fetches them in order, and the queue is never flushed. No return address is written to or read from the stack. The body of PUTC takes about 78 cycles by itself: PUSH 11, two MOVs 4 each, INT 51, POP 8. To this are added the BIOS routine itself and its IRET. In the procedure version, 27 more cycles are added to the same job at every call.
| Instruction | Bytes | Clock cycles | Memory/stack access |
|---|---|---|---|
PUSH AX | 1 | 11 | 1 write (stack) |
MOV AL, 'A' | 2 | 4 | none |
MOV AH, 0Eh | 2 | 4 | none |
INT 10h | 2 | 51 | 3 writes (FLAGS, CS, IP) + vector read |
POP AX | 1 | 8 | 1 read (stack) |
| macro copy, total | 8 | 78 | |
CALL (near, direct) | 3 | 19 | 1 write (return address) |
RET (near) | 1 | 8 | 1 read (return address) |
| procedure call, total | 3 (+ 9 once) | 105 |
Table 9.1.7 compares the two versions in bytes and cycles. The extra time per call is small but it accumulates. A procedure called 10,000 times in a loop adds 10,000 × 27 = 270,000 cycles, about 56.6 ms at 4.77 MHz. For a short job this overhead can be even longer than the job itself. For example, if a two-instruction job taking 6–8 cycles in all is turned into a procedure, every call makes it four or five times as slow.
9.1.3.5Selection criteria
Weighing size and speed together gives the general rule. Short code that runs often and needs speed suits a macro; long code used in many places suits a procedure. Five typical cases make the rule concrete:
- Printing a single character, in 200 places. The body is short (8 bytes), but 200 copies come to 1600 bytes. The procedure takes 9 + 600 = 609 bytes. If size matters, choose the procedure; if speed matters, the macro. Since printing already involves a BIOS call, the extra 27 cycles are usually negligible; here the procedure is the wiser choice.
- A one-line job that swaps two registers.
XCHGis already a single instruction. A macro may improve readability; a procedure would add a burden of 27 cycles and 4 bytes to a one-instruction job. Choose the macro. - A 300-byte sorting algorithm, in 3 places. The macro takes 900 bytes, the procedure about 300 + 9 bytes. Next to the running time of a sort, 27 cycles are negligible. Clearly a procedure.
- A two-instruction job done on every iteration of a tight loop. The CALL/RET time exceeds the job itself. When the loop runs thousands of times, the difference becomes measurable. A macro.
- Putting parameters in registers and calling shared code. The two methods are used together: the macro places the parameters in registers and calls the procedure. Use is as convenient as a macro and the size as small as a procedure. The emu8086.inc library also uses this pattern.
9.1.3.6Code trace: the macro prepares, the procedure works
Let us trace the fifth case with a small program. The PUT_DIGIT macro puts a digit in AL and calls the print_digit procedure. The procedure converts the digit to its ASCII code and writes it to the screen:
PUT_DIGIT MACRO d
mov al, d
call print_digit
ENDM
org 100h
PUT_DIGIT 4
PUT_DIGIT 7
ret
print_digit:
add al, '0' ; digit → ASCII
mov ah, 0Eh
int 10h
retEach macro copy is only 5 bytes: a 2-byte MOV AL, imm8 and a 3-byte CALL. The first copy occupies 0100h–0104h and the second 0105h–0109h. The main program's RET is at 010Ah and the procedure starts at 010Bh. The body of the procedure is 2 + 2 + 2 + 1 = 7 bytes. If the macro were used in ten places the code would take 10 × 5 + 7 = 57 bytes. Had the whole body (MOV AL, ADD AL, MOV AH, INT) been in the macro, every copy would be 8 bytes and ten copies 80 bytes.
| Step | Address | Instruction | AL | AH | SP | [SS:SP] | Next IP | Screen | Explanation |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | mov al, 4PUT_DIGIT expansion | 04h | 00h | FFFEh | 0000h | 0102h | – | 1st expansion: AL ← 4 |
| 2 | 0102h | call print_digitPUT_DIGIT expansion | 04h | 00h | FFFCh | 0105h | 010Bh | – | return address 0105h to the stack; IP ← 010Bh |
| 3 | 010Bh | add al, '0'print_digit procedure | 34h | 00h | FFFCh | 0105h | 010Dh | – | 4 + 30h = 34h ('4') |
| 4 | 010Dh | mov ah, 0Ehprint_digit procedure | 34h | 0Eh | FFFCh | 0105h | 010Fh | – | AH = 0Eh: teletype output |
| 5 | 010Fh | int 10hprint_digit procedure | 34h | 0Eh | FFFCh | 0105h | 0111h | 4 | 4 to the screen |
| 6 | 0111h | retprint_digit procedure | 34h | 0Eh | FFFEh | 0000h | 0105h | 4 | 0105h from the stack to IP |
| 7 | 0105h | mov al, 7PUT_DIGIT expansion | 07h | 0Eh | FFFEh | 0000h | 0107h | 4 | 2nd expansion: AL ← 7 |
| 8 | 0107h | call print_digitPUT_DIGIT expansion | 07h | 0Eh | FFFCh | 010Ah | 010Bh | 4 | this time the return address is 010Ah |
| 9 | 010Bh | add al, '0'print_digit procedure | 37h | 0Eh | FFFCh | 010Ah | 010Dh | 4 | 37h ('7') |
| 10 | 010Dh | mov ah, 0Ehprint_digit procedure | 37h | 0Eh | FFFCh | 010Ah | 010Fh | 4 | |
| 11 | 010Fh | int 10hprint_digit procedure | 37h | 0Eh | FFFCh | 010Ah | 0111h | 47 | 47 on the screen |
| 12 | 0111h | retprint_digit procedure | 37h | 0Eh | FFFEh | 0000h | 010Ah | 47 | return to 010Ah |
| 13 | 010Ah | retmain program | 37h | 0Eh | 0000h | – | 0000h | 47 | the main program's RET |
Table 9.1.8 and Figure 9.1.7 should be read together. In the second step the CALL executes. The return address is 0105h, the address of the instruction after the CALL. This word is written to SS:FFFCh; since SS = 0700h, the physical address is 07000h + FFFCh = 16FFCh. SP becomes FFFCh and IP jumps to 010Bh. The procedure adds 30h to 4, obtaining the ASCII '4' (34h), and writes it with INT 10h. The RET in the sixth step takes 0105h from the top of the stack into IP and restores SP to FFFEh.
The second copy calls the same procedure, but this time the return address is 010Ah. The same single body has been called from two different places and has returned to the right place each time. 47 appears on the screen. The last RET belongs to the main program; it takes the 0000h at the top of the stack and ends the program. In this arrangement the macro acts as a thin wrapper that prepares the parameter; the work itself is in the procedure, in a single copy.
9.1.3.7Code trace: RET inside a macro
Writing RET at the end of a macro out of procedure habit is one of the most instructive mistakes with macros. The EMIT macro below writes a character and ends with RET:
EMIT MACRO c
MOV AL, c
MOV AH, 0Eh
INT 10h
RET ; wrong
ENDM
org 100h
EMIT 'A'
EMIT 'B'
retThe program assembles; to the assembler, RET is an ordinary instruction. The expanded code contains two copies of EMIT, each ending in a RET. The programmer expects AB on the screen.
| Step | Address | Instruction | AX | SP | Next IP | Screen | Explanation |
|---|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AL, 'A'EMIT expansion | 0041h | FFFEh | 0102h | – | 1st expansion: AL ← 'A' |
| 2 | 0102h | MOV AH, 0EhEMIT expansion | 0E41h | FFFEh | 0104h | – | AX = 0E41h |
| 3 | 0104h | INT 10hEMIT expansion | 0E41h | FFFEh | 0106h | A | A to the screen |
| 4 | 0106h | RETEMIT expansion | 0E41h | 0000h | 0000h | A | the macro's RET takes the 0000h at the top of the stack |
| 5 | 0000h | INT 20h (PSP:0000h)PSP | 0E41h | 0000h | – | A | the INT 20h in the PSP ends the program; nothing after 0107h ever runs |
Table 9.1.9 shows that what was expected does not happen. The first copy writes 'A'. The RET in the fourth step is the macro's RET. Since the macro was not entered with a CALL, there is no return address on the stack. RET nevertheless takes whatever it finds at the top of the stack into IP. In this .COM program the top holds the word 0000h that DOS placed there. IP becomes 0000h and the processor goes to the INT 20h instruction at the start of the PSP. The program ends. The copy of EMIT 'B' and the main program's RET never run; only A is on the screen.
This program ends luckily: the top of the stack happens to hold an address that terminates the program. Had the macro been used inside a procedure or after something was pushed on the stack, RET would have jumped to an arbitrary word on the stack and the program could have hung. RET makes sense only in a procedure entered with CALL.
Writing RET at the end of a macro body. A macro is not called with CALL; the RET in the body takes the return address of the code that uses the macro (or whatever is on the stack). A macro "ends" by itself on reaching ENDM: after the last instruction of the expansion, the instruction that follows the call line executes.
9.1.3.8EQU, macros and procedures
Another tool of the assembler that works on text is the EQU directive. When WIDTH EQU 80 is written, the assembler writes 80 wherever it sees the name WIDTH. This is like a one-line macro without parameters. The three tools are compared in Table 9.1.10.
| Criterion | EQU | Macro | Procedure |
|---|---|---|---|
| What is substituted? | a single value or expression | one or more lines | nothing; control goes there with CALL |
| Parameters | none | yes (text) | register, stack or memory |
| When? | assembly | assembly | run time |
| In memory | takes no space | the body at every use | single copy + 3 bytes per call |
| Example | WIDTH EQU 80 | PUTC 'A' | CALL PRINT_NUM |
What EQU and a macro have in common is that both are text operations the assembler performs on the source. The processor never sees either; it executes only the instructions they produce. An EQU constant by itself does not even produce a byte; only when it is used inside an instruction does it become that instruction's immediate value. The rule of choice is simple. Use EQU to name a single number, a macro for a short pattern of a few instructions, and a procedure for a long or widely shared job.
9.1.4Labels and LOCAL
9.1.4.1The same label twice
The body of every macro that contains a loop or a conditional jump contains a label. A label is a name that the assembler gives to an address. In a program each label may be defined only once; otherwise the same name would point to two different addresses and the target of a jump would become ambiguous. Because the body of a macro is rewritten at every use, this rule is easily broken in macros. A simple delay loop shows this:
DELAY MACRO
lp: DEC CX
JNZ lp
ENDM
MOV CX, 5
DELAY
MOV CX, 9
DELAYWith a single use of the macro there would be no problem. After two uses, the code the assembler sees is this:
MOV CX, 5
lp: DEC CX ; copy 1
JNZ lp
MOV CX, 9
lp: DEC CX ; copy 2 !
JNZ lplp in two expansions. JNZ lp cannot tell which of the two addresses to jump to; the assembler reports a Duplicate declaration error.When the assembler reaches the second lp: line, it already finds this name in the symbol table. emu8086 reports a Duplicate declaration error and the program does not assemble. The error message points to the second DELAY line; when the programmer looks at that line, all that is visible is the macro's name. To understand the cause of the error one again has to think of the expansion.
9.1.4.2The LOCAL directive
The solution is to give the label a different name in each expansion. The programmer cannot do this by hand, because the body is written in one place. The assembler takes over this job with the LOCAL directive.
The LOCAL directive is written on the first line of a macro body and makes the names that follow it local to the macro. At every expansion the assembler replaces these names with a unique name that has not been used so far. MASM and emu8086 generate these names as ??0000, ??0001, ??0002… with a counter that keeps increasing across all expansions in the program.
MyMacro2 MACRO
LOCAL label1, label2
CMP AX, 2
JE label1
CMP AX, 3
JE label2
label1:
INC AX
label2:
ADD AX, 2
ENDMMyMacro2 declares two local labels. At the first use label1 becomes ??0000 and label2 becomes ??0001. At the second use the counter continues where it left off: label1 becomes ??0002 and label2 ??0003. The counter belongs to the program, not to the macro; the local labels of another macro take numbers from the same sequence. Names starting with ?? are chosen deliberately: there is no chance of a clash with the programmer's own labels.
LOCAL must be the first line of the body; it must come right after the MACRO line. The assembler wants to know the local names before applying them to the rest of the body. LOCAL is used not only for labels but also for variable and procedure names defined inside the macro. If a macro defines a string inside itself (as in the PRINT macro), the name of the string must be local too.
The listing of a program with two uses shows the naming and the addresses together:
0100 3D 02 00 CMP AX, 2 ; 1st MyMacro2
0103 74 05 JE ??0000
0105 3D 03 00 CMP AX, 3
0108 74 01 JE ??0001
010A 40 ??0000: INC AX
010B 05 02 00 ??0001: ADD AX, 2
010E 3D 02 00 CMP AX, 2 ; 2nd MyMacro2
0111 74 05 JE ??0002
0113 3D 03 00 CMP AX, 3
0116 74 01 JE ??0003
0118 40 ??0002: INC AX
0119 05 02 00 ??0003: ADD AX, 2
011C C3 RETThe machine code of the conditional jumps is instructive too. JE ??0000 = 74 05: 74h is the opcode and 05h is the relative displacement. The jump target is found by adding 5 to the address of the instruction after the JE (0105h): 0105h + 5 = 010Ah. The JE ??0002 in the second copy is also 74 05: 0113h + 5 = 0118h. The machine code of the two copies is identical byte for byte, because the 8086's short jumps store the displacement, not the address. What differs is the names of the labels and the absolute addresses they point to.
9.1.4.3Code trace: MyMacro2
What MyMacro2 does depends on the value of AX. If AX = 2 it jumps to label1, INC and ADD run, and AX becomes 2 + 1 + 2 = 5. If AX = 3 it jumps to label2, only ADD runs, and again AX becomes 5. For any other value neither jump is taken and the flow falls through to label1; AX increases by 3. The trace of the program that starts with MOV AX, 2 is in Table 9.1.11.
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| Step | Address | Instruction | AX | ZF | SF | CF | Next IP | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AX, 2main program | 0002h | 0 | 0 | 0 | 0103h | AX = 2 |
| 2 | 0103h | CMP AX, 2MyMacro2 expansion | 0002h | 1 | 0 | 0 | 0106h | 2 − 2 = 0: ZF = 1 |
| 3 | 0106h | JE ??0000MyMacro2 expansion | 0002h | 1 | 0 | 0 | 010Dh | ZF = 1: jump to ??0000 (label1) |
| 4 | 010Dh | INC AXMyMacro2 expansion | 0003h | 0 | 0 | 0 | 010Eh | AX = 3 |
| 5 | 010Eh | ADD AX, 2MyMacro2 expansion | 0005h | 0 | 0 | 0 | 0111h | AX = 5 |
| 6 | 0111h | RETmain program | 0005h | 0 | 0 | 0 | 0000h | the program ends |
In the second step CMP AX, 2 subtracts 2 from AX but writes the result nowhere; it only sets the flags. Since 2 − 2 = 0, ZF = 1. The JE in the third step looks at ZF and jumps to ??0000, that is, to 010Dh. The Next IP column shows this jump: 010Dh instead of 0108h. CMP AX, 3 and the second JE are never executed. INC AX gives 3 and ADD AX, 2 gives 5. Had AX been 3 at the start of the program, the first JE would not jump, the second JE would jump to label2, and the result would again be 5. Had AX been 7, neither jump would be taken, INC and ADD would run and AX would be 10. A program that starts with AX = 0 would end with 3.
9.1.4.4Code trace: the two copies of DELAY
When LOCAL lp is added to the DELAY macro, the error disappears:
DELAY MACRO
LOCAL ilk
ilk: DEC CX
JNZ ilk
ENDM
org 100h
mov cx, 3
DELAY
mov cx, 2
DELAY
retIn the first copy the label lp gets the name ??0000 and is at 0103h. In the second copy it becomes ??0001 and is at 0109h. Each copy loops back to its own label.
| Step | Address | Instruction | CX | ZF | Next IP | Explanation |
|---|---|---|---|---|---|---|
| 1 | 0100h | mov cx, 3main program | 0003h | 0 | 0103h | counter of copy 1 |
| 2 | 0103h | ??0000: DEC CXDELAY expansion | 0002h | 0 | 0104h | 1st pass: CX = 2 |
| 3 | 0104h | JNZ ??0000DELAY expansion | 0002h | 0 | 0103h | ZF = 0: loop back to ??0000 (0103h) |
| 4 | 0103h | ??0000: DEC CXDELAY expansion | 0001h | 0 | 0104h | 2nd pass |
| 5 | 0104h | JNZ ??0000DELAY expansion | 0001h | 0 | 0103h | 0103h again |
| 6 | 0103h | ??0000: DEC CXDELAY expansion | 0000h | 1 | 0104h | 3rd pass: CX = 0, ZF = 1 |
| 7 | 0104h | JNZ ??0000DELAY expansion | 0000h | 1 | 0106h | no jump; copy 1 is done |
| 8 | 0106h | mov cx, 2main program | 0002h | 1 | 0109h | counter of copy 2 |
| 9 | 0109h | ??0001: DEC CXDELAY expansion | 0001h | 0 | 010Ah | 1st pass: CX = 1 |
| 10 | 010Ah | JNZ ??0001DELAY expansion | 0001h | 0 | 0109h | loop back to ??0001 (0109h), not to 0103h |
| 11 | 0109h | ??0001: DEC CXDELAY expansion | 0000h | 1 | 010Ah | CX = 0, ZF = 1 |
| 12 | 010Ah | JNZ ??0001DELAY expansion | 0000h | 1 | 010Ch | no jump |
| 13 | 010Ch | retmain program | 0000h | 1 | 0000h | the program ends; 5 DECs in all |
JNZ ??0001 loops back to 0109h, not to the label at 0103h of the first copy.In Table 9.1.12 the first copy loops three times. DEC CX decreases CX by one on every pass and sets ZF according to the result. As long as CX stays nonzero, ZF = 0 and JNZ jumps back to 0103h. On the third pass CX becomes 0, ZF becomes 1 and JNZ does not jump. The second copy runs two passes with CX = 2 and each time loops back to 0109h (Figure 9.1.9). Five DECs are executed in all. Recall also that DEC does not touch CF; it changes only ZF, SF, OF, AF and PF.
The delay time can be computed in clock cycles. DEC r16 takes 2 cycles. JNZ takes 16 cycles when it jumps and 4 when it does not; because the prefetch queue is flushed on a jump, the difference is large. With CX = 3 the first copy takes 2 × (2 + 16) + (2 + 4) = 42 cycles. Such a loop produces a crude delay that depends on the processor clock.
9.1.4.5Code trace: MAX2 and signed comparison
The last example combines LOCAL with a signed comparison. The MAX2 macro writes the larger of p and q to r:
MAX2 MACRO p, q, r
LOCAL ok
MOV AX, p
CMP AX, q
JGE ok
MOV AX, q
ok: MOV r, AX
ENDM
org 100h
MAX2 x, y, m1
MAX2 y, 4, m2
ret
x dw 7
y dw -3
m1 dw ?
m2 dw ?In the first call all three parameters are variables. In the second q is a constant, so CMP AX, 4 and MOV AX, 4 use the immediate form. y = −3 is stored as FFFDh in two's complement.
| Step | Address | Instruction | AX | SF | OF | CF | ZF | m1 | m2 | Explanation |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | MOV AX, xMAX2 expansion | 0007h | 0 | 0 | 0 | 0 | 0000h | 0000h | p = x: AX = 7 |
| 2 | 0103h | CMP AX, yMAX2 expansion | 0007h | 0 | 0 | 1 | 0 | 0000h | 0000h | 7 − (−3) = 10: SF = 0, OF = 0 |
| 3 | 0107h | JGE ??0000MAX2 expansion | 0007h | 0 | 0 | 1 | 0 | 0000h | 0000h | SF = OF: jump to ??0000 |
| 4 | 010Ch | ??0000: MOV m1, AXMAX2 expansion | 0007h | 0 | 0 | 1 | 0 | 0007h | 0000h | m1 = 7 |
| 5 | 010Fh | MOV AX, yMAX2 expansion | FFFDh | 0 | 0 | 1 | 0 | 0007h | 0000h | p = y: AX = FFFDh (−3) |
| 6 | 0112h | CMP AX, 4MAX2 expansion | FFFDh | 1 | 0 | 0 | 0 | 0007h | 0000h | −3 − 4 = −7: SF = 1, OF = 0 |
| 7 | 0115h | JGE ??0001MAX2 expansion | FFFDh | 1 | 0 | 0 | 0 | 0007h | 0000h | SF ≠ OF: no jump |
| 8 | 0117h | MOV AX, 4MAX2 expansion | 0004h | 1 | 0 | 0 | 0 | 0007h | 0000h | q = 4 is the larger one |
| 9 | 011Ah | ??0001: MOV m2, AXMAX2 expansion | 0004h | 1 | 0 | 0 | 0 | 0007h | 0004h | m2 = 4 |
| 10 | 011Dh | retmain program | 0004h | 1 | 0 | 0 | 0 | 0007h | 0004h | the program ends |
The CMP AX, y of the second step performs 7 − (−3). Under the signed interpretation the result is 10: positive (SF = 0) with no overflow (OF = 0). JGE (jump if greater or equal) looks at the result of the signed comparison with the condition SF = OF. Since the condition holds, control jumps to ??0000 and m1 = 7. Under the unsigned interpretation the same subtraction is 0007h − FFFDh; because a larger number is subtracted from a smaller one, a borrow occurs and CF = 1. Since JGE does not look at CF, this flag does not matter here.
In the second expansion AX = FFFDh (−3) and CMP AX, 4 gives −3 − 4 = −7: SF = 1, OF = 0. Since SF ≠ OF, JGE does not jump. The flow continues with MOV AX, 4 and m2 = 4. The label of the second copy is ??0001; it does not clash with the first one's.
The choice of conditional jump matters in this example. Had JAE, which compares as unsigned, been used instead of JGE, the second comparison would have treated FFFDh and 4 as unsigned numbers. FFFDh = 65,533 is greater than 4; there is no borrow (CF = 0) and JAE jumps. m2 would receive FFFDh, that is −3, instead of 4. Even though the macro stays the same, a single conditional jump instruction decides whether the result is right. With signed numbers use JG, JGE, JL, JLE; with unsigned numbers use JA, JAE, JB, JBE.
Forgetting LOCAL because a macro with a label worked correctly when tried once. The error appears only when the macro is used a second time, and then the error message points not to the body but to the line of use. Every macro that has a label gets a LOCAL, no matter how many times it will be used.
9.1.5PUTC and preserving registers
9.1.5.1The PUTC macro
PUTC is a short macro that writes a single character to the screen. It is identical to the PUTC macro of the emu8086.inc library:
; prints a character, advances 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'
RETThe real work of the macro is done by INT 10h. AH = 0Eh is the BIOS teletype output service. The character in AL is written where the cursor is and the cursor advances one position to the right. At the end of a line the cursor moves to the next line; at the end of the screen the screen scrolls by one line. Control characters such as 0Dh (carriage return), 0Ah (line feed), 07h (bell) and 08h (backspace) are not printed but interpreted.
Because the service uses AH and AL, the macro has to modify AX. The push ax at the start of the macro and the pop ax at the end hide this change from the caller. On leaving the macro, AX returns to the value it had before the macro was entered. The macro has no visible side effect. This principle holds for all library macros: a macro may use registers for its own work but restores them on exit.
Register preservation means that a macro or procedure saves the registers it modifies with PUSH at the start and restores them with POP in reverse order at the end. The values in the caller's registers are thus not corrupted by the use; only the registers explicitly designated for returning a result change.
The RET at the end of the program matters too. After the two PUTC copies the program's code ends in memory. Without the RET the processor would take the bytes after the last POP AX for instructions and keep executing. The processor does not distinguish code from data; it decodes every byte that IP points to as an opcode. Whatever is left in memory would run as random instructions and the system could hang. Macro expansion does not add this RET by itself.
9.1.5.2Code trace: PUTC 'A' and PUTC 'B'
The expanded code is two 8-byte copies and a RET, 17 bytes in all. Because emu8086 writes the program size into CX at load time, CX = 0011h at the start of the trace. This value does not change during the program, because PUTC does not touch CX. AX is initially 0000h. The machine code of each copy is the same except for the character byte: 50 B0 41 B4 0E CD 10 58 and 50 B0 42 B4 0E CD 10 58.
| Step | Address | Instruction | AX | CX | SP | [SS:SP] | Screen | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | push axPUTC expansion | 0000h | 0011h | FFFCh | 0000h | – | the caller's AX (0000h) to the stack; SP = FFFCh |
| 2 | 0101h | mov al, 'A'PUTC expansion | 0041h | 0011h | FFFCh | 0000h | – | AL ← 41h |
| 3 | 0103h | mov ah, 0ehPUTC expansion | 0E41h | 0011h | FFFCh | 0000h | – | AX = 0E41h |
| 4 | 0105h | int 10hPUTC expansion | 0E41h | 0011h | FFFCh | 0000h | A | A to the screen; cursor one position right |
| 5 | 0107h | pop axPUTC expansion | 0000h | 0011h | FFFEh | 0000h | A | AX has its old value back; SP = FFFEh |
| 6 | 0108h | push axPUTC expansion | 0000h | 0011h | FFFCh | 0000h | A | 2nd copy: AX is saved again |
| 7 | 0109h | mov al, 'B'PUTC expansion | 0042h | 0011h | FFFCh | 0000h | A | AL ← 42h |
| 8 | 010Bh | mov ah, 0ehPUTC expansion | 0E42h | 0011h | FFFCh | 0000h | A | AX = 0E42h |
| 9 | 010Dh | int 10hPUTC expansion | 0E42h | 0011h | FFFCh | 0000h | AB | AB on the screen |
| 10 | 010Fh | pop axPUTC expansion | 0000h | 0011h | FFFEh | 0000h | AB | AX = 0000h: the caller's AX was not corrupted |
| 11 | 0110h | RETmain program | 0000h | 0011h | 0000h | – | AB | the program ends |
push ax: the caller's AX (0000h) has been saved at address FFFCh and SP = FFFCh.In Table 9.1.14 the first step pushes AX on the stack. SP decreases by 2 to FFFCh and 0000h is written to the word at SS:FFFCh (Figure 9.1.10). The second and third steps load 'A' (41h) into AL and 0Eh into AH; AX becomes 0E41h. In the fourth step INT 10h writes A to the screen and advances the cursor. The INT instruction itself pushes FLAGS, CS and IP on the stack, goes to the BIOS routine and returns with IRET; this internal detail appears as a single step in the trace. The POP AX of the fifth step takes the 0000h from the stack into AX and restores SP to FFFEh. The second copy follows the same path with 'B', and AB appears on the screen. In the final state AX = 0000h: the macro has not corrupted the caller's AX.
In this trace the stack grows and shrinks by one word in each copy. As long as PUSH and POP are paired within the same macro, the stack is balanced: SP is the same on leaving the macro as on entering it. If this balance is broken, for example if a conditional jump in the body skips the POP, an extra word stays on the stack. The main program's RET takes this word for the return address and the program goes to a wrong place.
9.1.5.3Register-saving macros
The push ax / pop ax pattern of PUTC grows to four registers in larger macros. This pattern can itself be a macro:
SAVE MACRO
PUSH AX
PUSH BX
PUSH CX
PUSH DX
ENDM
RESTORE MACRO
POP DX
POP CX
POP BX
POP AX
ENDMRESTORE pops the registers in the reverse of the order in which SAVE pushed them. The stack works on the last-in, first-out (LIFO) principle: DX, the last one pushed, must be the first one popped. Suppose SAVE is used while AX = 1111h, BX = 2222h, CX = 3333h, DX = 4444h and the registers are then cleared. After RESTORE all four registers return to their old values. If the pops are written in the same order as the pushes (POP AX, POP BX, POP CX, POP DX), the result is AX = 4444h, BX = 3333h, CX = 2222h, DX = 1111h: AX and DX swap, and so do BX and CX. This error is not caught at assembly time, because every line is valid by itself.
Each SAVE and RESTORE pair adds 8 bytes; every PUSH and POP is a single byte. In time, on the 8086 PUSH r16 takes 11 cycles and POP r16 takes 8: 4 × 11 + 4 × 8 = 76 cycles. Within this time eight stack accesses, that is, eight bus cycles, are made. In a short macro this time can exceed that of the body itself; a macro should therefore save only the registers it really modifies.
The two macros must be used together in the same body. If there is a conditional exit in between (for instance a jump to the end of the body in an error case), this exit must also pass through RESTORE; otherwise the stack is left unbalanced. On the 80186 and later processors the single instructions PUSHA and POPA save and restore all the general-purpose registers. The 8086 does not have these instructions, which is why the same job is written as a macro.
9.1.5.4Nested macros
The body of a macro may contain a call to another macro. PRINT2 below uses PUTC twice to print two characters:
PRINT2 MACRO c1, c2
PUTC c1
PUTC c2
ENDM
PRINT2 'O', 'K'The assembler expands in two levels. It first expands the outer macro: the line PRINT2 'O', 'K' turns into the lines PUTC 'O' and PUTC 'K'. These two lines are macro calls as well, and the assembler expands them too. In the end the one-line call becomes ten instructions and 16 bytes (Figure 9.1.11). OK appears on the screen.
With nesting, the order of definition matters again. PUTC must be defined before the line where PRINT2 is used. A macro calling itself (recursion) is a boundary case. In a procedure, recursion is limited by the stack and stopped by a condition. In a macro the stopping condition must be an assembly-time one, not a run-time one; otherwise the expansion never ends. Conditional assembly directives make such a stop possible.
9.1.6The POWER macro
9.1.6.1Exponentiation: MUL and LOOP
The POWER macro computes the power of a base: r = be. The method is the simplest one. The running result is initialized to 1 and multiplied by the base e times:
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 ? ; resultThe macro uses two important instructions. MUL BX is unsigned multiplication: it multiplies AX by BX and writes the 32-bit result to the register pair DX:AX. The high 16 bits go to DX and the low 16 bits to AX. MUL therefore always modifies DX, even though DX is not named as an operand. If the high half of the result is nonzero, CF and OF become 1; if it is zero, both are 0. SF, ZF, AF and PF are undefined after MUL.
LOOP label decrements CX by 1 and jumps to the label if CX is nonzero. It does not change the flags. CX is the loop counter here; the macro loads it with the exponent. On the 8086, LOOP takes 17 cycles when it jumps and 5 when it does not. A 16-bit MUL takes between 118 and 133 cycles depending on the operand values; it is one of the slowest instructions in the instruction set.
The size of the expansion can also be computed. mov ax, 1 is 3 bytes, mov cx, exponent and mov bx, base are 4 bytes each with the general memory-operand form, mul bx is 2 bytes, loop is 2 bytes, and mov result, ax is 3 bytes with the short AX-specific form. The total is 18 bytes; with the RET, 19 bytes (13h). The variables start right after the code: base is at 0113h, exponent at 0115h and result at 0117h.
9.1.6.2Code trace: POWER 2, 3
The expanded code is:
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| Step | Address | Instruction | AX | BX | CX | DX | CF | result | Explanation |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | mov ax, 1POWER expansion | 0001h | 0000h | 0000h | 0000h | 0 | 0000h | result so far is 1 |
| 2 | 0103h | mov cx, exponentPOWER expansion | 0001h | 0000h | 0003h | 0000h | 0 | 0000h | CX ← [0115h] = 3 |
| 3 | 0107h | mov bx, basePOWER expansion | 0001h | 0002h | 0003h | 0000h | 0 | 0000h | BX ← [0113h] = 2 |
| 4 | 010Bh | mul bxPOWER expansion | 0002h | 0002h | 0003h | 0000h | 0 | 0000h | 1st pass: DX:AX = 1 × 2 |
| 5 | 010Dh | loop powerloopPOWER expansion | 0002h | 0002h | 0002h | 0000h | 0 | 0000h | CX = 2 ≠ 0: powerloop |
| 6 | 010Bh | mul bxPOWER expansion | 0004h | 0002h | 0002h | 0000h | 0 | 0000h | 2nd pass: 2 × 2 |
| 7 | 010Dh | loop powerloopPOWER expansion | 0004h | 0002h | 0001h | 0000h | 0 | 0000h | CX = 1 |
| 8 | 010Bh | mul bxPOWER expansion | 0008h | 0002h | 0001h | 0000h | 0 | 0000h | 3rd pass: 4 × 2 |
| 9 | 010Dh | loop powerloopPOWER expansion | 0008h | 0002h | 0000h | 0000h | 0 | 0000h | CX = 0: leave the loop |
| 10 | 010Fh | mov result, axPOWER expansion | 0008h | 0002h | 0000h | 0000h | 0 | 0008h | [0117h] ← 0008h |
| 11 | 0112h | retmain program | 0008h | 0002h | 0000h | 0000h | 0 | 0008h | the program ends |
Table 9.1.15 shows the three passes of the loop. In the first pass MUL computes 1 × 2 = 2: DX:AX = 0000:0002h. Since the high half is zero, CF = 0. LOOP decreases CX from 3 to 2 and returns to powerloop. In the second pass AX = 4, in the third AX = 8. The third LOOP makes CX 0 and does not jump. mov result, ax writes 0008h to the word at 0117h; 23 = 8.
The table shows that DX is 0000h after every MUL. This holds as long as the result fits in 16 bits. Had the result exceeded 16 bits, for example if 216 were computed, after the last MUL DX = 0001h, AX = 0000h and CF = OF = 1. Because the macro writes only AX to result, result would be 0; the high part of the correct result stays in DX and is lost.
9.1.6.3Four pitfalls
The POWER macro is small but hides four separate bugs. Each represents a kind of problem that is common when writing macros.
1. Exponent zero. In mathematics b0 = 1; the macro starting with AX = 1 looks as if it would give this result. But MUL runs at least once, because the loop condition is checked at the end. Worse, LOOP first decrements CX and then compares with zero. With CX = 0 the decrement makes CX FFFFh; this is not zero and the loop continues. The loop ends only when CX becomes 0 again, that is, after 65,536 passes. For base = 2, after 216 the low 16 bits of AX are zero and stay so; result = 0000h. For base = 1, result = 1. This is correct by accident; 65,536 needless MULs have still been executed. Since each MUL takes about 120 cycles, this wasted time exceeds one and a half seconds at 4.77 MHz.
2. The label. powerloop is not declared with LOCAL. When the macro is used a second time the label is defined twice and a Duplicate declaration error occurs.
3. Register corruption. The macro puts the result in AX; that is an expected change. But it loads BX with the base and CX with the counter, and because of MUL it also modifies DX. The caller's values in these three registers are lost.
4. Overflow. If the result exceeds 65,535, the high part stays in DX and is not written. The macro also does not report this to the caller through CF; the CF of the last MUL remains after the macro, but any later instruction can erase it.
The corrected version fixes the first three problems:
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
ENDMJCXZ (jump if CX is zero) checks the counter before LOOP. If CX = 0 it skips the whole loop and the 1 in AX is written directly to the result. LOCAL makes the two labels unique in every expansion. PUSH and POP preserve BX, CX and DX; the macro now modifies only AX. The overflow problem remains in this version too. To solve it, either the result must be written as 32 bits (DX:AX) or the overflow must be reported to the caller through CF.
Starting a LOOP-controlled loop when the counter may be zero. LOOP decrements first and checks afterwards; with CX = 0 it runs 65,536 times. Every loop whose counter comes from a variable or a parameter gets a JCXZ in front of it.
9.1.6.4Code trace: the corrected POWER
The expansion of the corrected macro, POWER base, expn, res, is traced for base = 7 and expn = 2. To see the effect of register preservation, let the caller's registers hold BX = 0AAAh, CX = 0BBBh, DX = 0CCCh:
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
expndw 2
res dw ?The expansion is 26 bytes (up to 011Ah); the RET is at 011Ah, base at 011Bh, expn at 011Dh and res at 011Fh. The LOCAL names are ??0000 for p_loop and ??0001 for p_end.
| Step | Address | Instruction | AX | BX | CX | DX | SP | res | Explanation |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | PUSH BXPOWER expansion | 0000h | 0AAAh | 0BBBh | 0CCCh | FFFCh | 0000h | BX saved |
| 2 | 0101h | PUSH CXPOWER expansion | 0000h | 0AAAh | 0BBBh | 0CCCh | FFFAh | 0000h | CX saved |
| 3 | 0102h | PUSH DXPOWER expansion | 0000h | 0AAAh | 0BBBh | 0CCCh | FFF8h | 0000h | DX saved; SP = FFF8h |
| 4 | 0103h | MOV AX, 1POWER expansion | 0001h | 0AAAh | 0BBBh | 0CCCh | FFF8h | 0000h | result so far is 1 |
| 5 | 0106h | MOV CX, expnPOWER expansion | 0001h | 0AAAh | 0002h | 0CCCh | FFF8h | 0000h | CX ← expn = 2 |
| 6 | 010Ah | MOV BX, basePOWER expansion | 0001h | 0007h | 0002h | 0CCCh | FFF8h | 0000h | BX ← base = 7 |
| 7 | 010Eh | JCXZ ??0001POWER expansion | 0001h | 0007h | 0002h | 0CCCh | FFF8h | 0000h | CX ≠ 0: no jump |
| 8 | 0110h | ??0000: MUL BXPOWER expansion | 0007h | 0007h | 0002h | 0000h | FFF8h | 0000h | 1 × 7; MUL also writes DX |
| 9 | 0112h | LOOP ??0000POWER expansion | 0007h | 0007h | 0001h | 0000h | FFF8h | 0000h | CX = 1 |
| 10 | 0110h | ??0000: MUL BXPOWER expansion | 0031h | 0007h | 0001h | 0000h | FFF8h | 0000h | 7 × 7 = 49 = 0031h |
| 11 | 0112h | LOOP ??0000POWER expansion | 0031h | 0007h | 0000h | 0000h | FFF8h | 0000h | CX = 0: the loop ends |
| 12 | 0114h | ??0001: MOV res, AXPOWER expansion | 0031h | 0007h | 0000h | 0000h | FFF8h | 0031h | [011Fh] ← 0031h |
| 13 | 0117h | POP DXPOWER expansion | 0031h | 0007h | 0000h | 0CCCh | FFFAh | 0031h | DX = 0CCCh |
| 14 | 0118h | POP CXPOWER expansion | 0031h | 0007h | 0BBBh | 0CCCh | FFFCh | 0031h | CX = 0BBBh |
| 15 | 0119h | POP BXPOWER expansion | 0031h | 0AAAh | 0BBBh | 0CCCh | FFFEh | 0031h | BX = 0AAAh; SP = FFFEh |
| 16 | 011Ah | retmain program | 0031h | 0AAAh | 0BBBh | 0CCCh | 0000h | 0031h | the program ends |
In Table 9.1.16 the first three steps save the caller's registers on the stack (Figure 9.1.12). The stack grows downward: 0AAAh is written to FFFCh, 0BBBh to FFFAh, 0CCCh to FFF8h. In the next three steps the registers pass into the macro's use: AX = 1, CX = 2, BX = 7. JCXZ does not jump, since CX ≠ 0. The first MUL gives 1 × 7 = 7 and makes DX 0000h. The second MUL gives 7 × 7 = 49 = 0031h. When LOOP brings CX down to 0 the loop ends and 0031h is written to res.
The last three steps unwind the stack in reverse order. POP DX restores 0CCCh, POP CX restores 0BBBh, POP BX restores 0AAAh; SP is FFFEh again. When the macro is left, the values of BX, CX and DX are the same as on entry. Only AX has changed, and AX carries the result anyway. Had it been run with expn = 0, JCXZ would have jumped straight to ??0001, res = 1, and not a single MUL would have run.
9.1.7Macro libraries
9.1.7.1INCLUDE and emu8086.inc
Frequently used macros are not rewritten in every program; they are collected in a separate file. Such a file is called a macro library. The INCLUDE directive inserts the text of the library file into the source at assembly time, at the place of the directive. To the assembler this is no different from typing the macros at the start of the program by hand. Because unused macros generate no code, including a large library does not enlarge the program; only the macros that are used are expanded.
include 'emu8086.inc'
ORG 100h
GOTOXY 10, 5
PRINT 'Hello'
PUTC '!'
RETThe emu8086.inc file that comes with emu8086 is a ready-made example of this arrangement. It contains macros that write characters and text to the screen (PUTC, PRINT, PRINTN), move the cursor (GOTOXY) and hide it (CURSOROFF). For longer jobs such as reading and printing numbers, the library also offers procedures. These procedures are added to the program once with special macros such as DEFINE_SCAN_NUM and called with CALL. The library thus follows the pattern in which macros and procedures work together: short jobs are macros, long jobs are single-copy procedures. The library's macros and procedures are treated in detail in the notes on the emu8086.inc library.
9.1.7.2Code trace: expansion of PRINT 'OK'
The PRINT macro of the library uses all the techniques so far together: register preservation, LOCAL labels and data defined inside the macro. The call PRINT 'OK' expands to the following code (the LOCAL names are as the assembler generates them):
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
retThe string 'OK' and the 0 byte after it are embedded in the code, at the place where the macro was expanded: 4Fh, 4Bh, 00h starting at 0104h. Because the processor does not distinguish code from data, it might take these three bytes for instructions. To prevent this, the macro first jumps over the string with JMP. The name of the string is LOCAL too (??0001); a second PRINT in the same program defines its own string under another name.
Because the string sits in the code segment, the instruction that reads it uses the CS: segment prefix: MOV AL, CS:[SI]. Without the prefix the read would use the default segment, DS. In a .COM program CS = DS, so the result would be the same, but the macro must also work in .EXE programs where DS points to another segment. In machine code the prefix is the byte 2Eh and it makes the instruction one byte longer.
In emu8086 the instruction LEA SI, ??0001 assembles to the same 3-byte code as MOV SI, OFFSET ??0001: BE 04 01. In real MASM, a LEA with a direct address takes 4 bytes (8D 36 + address) and the expansion would be one byte longer. The total size of the expansion is 26 bytes (0100h–0119h), 3 bytes of which are data. In general, for a text of n characters the PRINT expansion takes 24 + n bytes.
| Step | Address | Instruction | AL | SI | SP | ZF | Screen | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | 0100h | push axPRINT 'OK' expansion | 00h | 0000h | FFFCh | 0 | – | AX saved |
| 2 | 0101h | push siPRINT 'OK' expansion | 00h | 0000h | FFFAh | 0 | – | SI saved; SP = FFFAh |
| 3 | 0102h | jmp ??0003PRINT 'OK' expansion | 00h | 0000h | FFFAh | 0 | – | jump over the string's bytes |
| 4 | 0107h | ??0003: lea si, ??0001PRINT 'OK' expansion | 00h | 0104h | FFFAh | 0 | – | SI ← 0104h |
| 5 | 010Ah | ??0000: mov al, cs:[si]PRINT 'OK' expansion | 4Fh | 0104h | FFFAh | 0 | – | AL ← CS:[0104h] = 'O' |
| 6 | 010Dh | cmp al, 0PRINT 'OK' expansion | 4Fh | 0104h | FFFAh | 0 | – | 4Fh ≠ 0: ZF = 0 |
| 7 | 010Fh | jz ??0002PRINT 'OK' expansion | 4Fh | 0104h | FFFAh | 0 | – | no jump |
| 8 | 0111h | inc siPRINT 'OK' expansion | 4Fh | 0105h | FFFAh | 0 | – | SI = 0105h |
| 9 | 0112h | mov ah, 0EhPRINT 'OK' expansion | 4Fh | 0105h | FFFAh | 0 | – | |
| 10 | 0114h | int 10hPRINT 'OK' expansion | 4Fh | 0105h | FFFAh | 0 | O | O to the screen |
| 11 | 0116h | jmp ??0000PRINT 'OK' expansion | 4Fh | 0105h | FFFAh | 0 | O | back to the loop start |
| 12 | 010Ah | ??0000: mov al, cs:[si]PRINT 'OK' expansion | 4Bh | 0105h | FFFAh | 0 | O | AL = 'K' |
| 15 | 0111h | inc siPRINT 'OK' expansion | 4Bh | 0106h | FFFAh | 0 | O | SI = 0106h |
| 17 | 0114h | int 10hPRINT 'OK' expansion | 4Bh | 0106h | FFFAh | 0 | OK | OK on the screen |
| 19 | 010Ah | ??0000: mov al, cs:[si]PRINT 'OK' expansion | 00h | 0106h | FFFAh | 0 | OK | AL = 00h |
| 20 | 010Dh | cmp al, 0PRINT 'OK' expansion | 00h | 0106h | FFFAh | 1 | OK | terminator: ZF = 1 |
| 21 | 010Fh | jz ??0002PRINT 'OK' expansion | 00h | 0106h | FFFAh | 1 | OK | jump to the exit |
| 22 | 0118h | ??0002: pop siPRINT 'OK' expansion | 00h | 0000h | FFFCh | 1 | OK | SI = 0000h |
| 23 | 0119h | pop axPRINT 'OK' expansion | 00h | 0000h | FFFEh | 1 | OK | AX restored; SP = FFFEh |
| 24 | 011Ah | retmain program | 00h | 0000h | 0000h | 1 | OK | the program ends |
Table 9.1.17 shows the three passes of the loop; the repeated MOV AH and INT steps are abbreviated. In the first pass AL = 4Fh ('O') is read. CMP AL, 0 gives ZF = 0 and JZ does not jump. SI advances by one, INT 10h writes 'O' and JMP returns to the loop start. The second pass writes 'K'. In the third pass AL = 00h is read; CMP gives ZF = 1 and JZ jumps to the exit (??0002). The 0 byte at the end is the terminator that marks the end of the string. The two POPs return SI and AX to their old values; SP is FFFEh again. OK has been printed and the caller's registers are intact.
This expansion shows the power and the cost of the macro together. The single source line PRINT 'OK' has produced 26 bytes. If twenty different texts are printed with PRINT in a program, each carries its own loop. The same job takes far less space with an arrangement that keeps the strings in a separate place and calls a single print procedure. The library's procedures such as PRINT_STRING exist for exactly this purpose.
9.1.8Macro operators
Since macro expansion is a text operation, special marks are needed to split and join text. MASM and TASM define five macro operators for this purpose. These operators have meaning only inside macro definitions and calls.
| Operator | Role | Example and expansion |
|---|---|---|
& | joins a parameter to adjacent text | CLEAR MACRO r · XOR r&X, r&X → CLEAR B: XOR BX, BX |
< > | makes text containing commas or spaces a single parameter | EMIT <'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 text | SHOW %(4*8) → parameter 32 |
;; | macro comment; not copied into the expansion | ;; visible only in the definition |
The & (concatenation) operator is the most frequently used. The assembler looks for parameter names in the body as whole words. Had XOR rX, rX been written, "rX" would count as a single word and would not match the parameter r; the expansion would remain XOR rX, rX and give an unknown-name error. Writing r&X states that r is a parameter name and that the X that follows is to be glued to it. In the call CLEAR B, r = B and the expansion is XOR BX, BX. XORing a register with itself clears it and is a 2-byte, 3-cycle instruction; MOV BX, 0 takes 3 bytes and 4 cycles.
The angle brackets < > make it possible to pass text containing commas as a single parameter. Without the brackets, EMIT 'A', 'B' would count as two separate parameters. The ! operator removes the special meaning of the character after it; the first > in <5 !> 3> does not close the bracket but becomes part of the text. The % operator passes the parameter not as text but as a value: %(4*8) is first evaluated to 32, and the text "32" goes to the macro. This is an alternative to parentheses as protection against the operator-precedence trap.
The last operator concerns comments. A comment written with a single ; is part of the body and is written to the listing file again at every expansion. A comment written with a double ;; stays in the definition and is not copied into the expansion. For a macro used a hundred times, this saves the listing file hundreds of needless lines.
9.1.9Repeat blocks
9.1.9.1REPT, IRP and IRPC
Sometimes one wants a piece of code written several times in place, without having to define a macro. Repeat blocks do this job.
A repeat block is a macro that has no name and is expanded immediately where it is defined. REPT n writes the body n times, IRP p, <list> writes it once for each item of the list (with p replaced by that item), and IRPC p, text writes it once for each character of the text. The block ends with ENDM. In MASM 6, IRP and IRPC are also written as FOR and FORC.
REPT 3
SHL AX, 1
ENDM ; → SHL AX, 1 · SHL AX, 1 · SHL AX, 1
IRP r, <AX,BX,CX>
PUSH r
ENDM ; → PUSH AX · PUSH BX · PUSH CX
IRPC c, OK
PUTC '&c'
ENDM ; → PUTC 'O' · PUTC 'K'The REPT example shifts AX left by one bit three times, that is, multiplies it by 8: with AX = 5 the result is 40 (0028h). The IRP example pushes three registers on the stack; it is a short way of writing the SAVE macro. In the IRPC example c becomes the characters O and K in turn. For c to be recognized as a parameter inside the quotes, &c is written; the text inside quotes would otherwise stay as it is. Since both PUTCs in the expansion are macros, the expansion is nested, and OK is written on the screen.
A repeat block is not a loop. It needs no loop counter, but the code grows: REPT 100 copies the body a hundred times. The three SHLs of the REPT example take 6 bytes and run in 3 × 2 = 6 cycles. The same shift can be written in 4 bytes with MOV CL, 3 and SHL AX, CL. But on the 8086 a shift by CL adds 4 cycles per bit, and the job takes 4 + (8 + 4 × 3) = 24 cycles. For short repetitions REPT is both fast and of reasonable size; REPT 100, however, takes 200 bytes, and the same job is done with a counted LOOP in a single copy.
The most common use of repeat blocks is to generate tables at assembly time. This needs an assembler symbol whose value can be changed. A constant defined with EQU cannot be redefined. A symbol defined with =, however, can take a new value at every assignment. The block below generates the squares of the numbers from 0 to 7:
n = 0
squares LABEL BYTE
REPT 8
DB n*n
n = n + 1
ENDMsquares LABEL BYTE gives the current address a name of type byte but reserves no space. The body of REPT is expanded eight times. In each expansion DB n*n writes the square of the current n as one byte, and n = n + 1 increments the symbol. As a result the bytes 0, 1, 4, 9, 16, 25, 36, 49 sit one after another in memory. n is not a variable; it has no place in memory. It is a number that lives only at assembly time, in the assembler's table. The same method generates tables such as masks, powers of 2 or precomputed sine values.
9.1.9.2Code trace: a table of squares with REPT
The generated table can be used to find the square of a number without multiplying, with the XLAT instruction:
org 100h
lea bx, squares
mov al, 5
xlat ; AL = squares[5]
mov dl, al
mov al, 7
xlat ; AL = squares[7]
add al, dl
ret
squares db 0, 1, 4, 9, 16, 25, 36, 49 ; the bytes generated by the REPT blockXLAT (translate by table) uses AL as an index into the table that BX points to: AL ← DS:[BX + AL]. The address of the table must first be loaded into BX. The size of the code is 3 + 2 + 1 + 2 + 2 + 1 + 2 + 1 = 14 bytes; since LEA takes 3 bytes in emu8086, the table starts at 0100h + 0Eh = 010Eh.
| Step | Address | Instruction | BX | AL | DL | Explanation |
|---|---|---|---|---|---|---|
| 1 | 0100h | lea bx, squaresmain program | 010Eh | 00h | 00h | BX ← 010Eh (offset of squares) |
| 2 | 0103h | mov al, 5main program | 010Eh | 05h | 00h | the number to look up, and index 5 |
| 3 | 0105h | xlatmain program | 010Eh | 19h | 00h | AL ← [BX + AL] = [0113h] = 25 |
| 4 | 0106h | mov dl, almain program | 010Eh | 19h | 19h | first result in DL |
| 5 | 0108h | mov al, 7main program | 010Eh | 07h | 19h | index 7 |
| 6 | 010Ah | xlatmain program | 010Eh | 31h | 19h | AL ← [0115h] = 49 |
| 7 | 010Bh | add al, dlmain program | 010Eh | 4Ah | 19h | 25 + 49 = 74 = 4Ah |
| 8 | 010Dh | retmain program | 010Eh | 4Ah | 19h | the program ends |
In Table 9.1.19 the first XLAT reads the byte at address 010Eh + 5 = 0113h: 25 = 19h (Figure 9.1.14). This value is saved in DL. The second XLAT reads 49 = 31h from address 010Eh + 7 = 0115h. ADD AL, DL adds the two: 25 + 49 = 74 = 4Ah, that is, 5² + 7². No multiply instruction has run anywhere in the program.
The speed difference is clear. XLAT finishes in 11 cycles. An 8-bit MUL on the 8086 takes 70–77 cycles. The price of the table is memory: eight bytes. This is the classic trade-off between memory and time, and REPT keeps it as short as a single line in the source. Because the table is generated at assembly time, no time is spent computing it at run time either.
9.1.10Conditional assembly
9.1.10.1The IF family
Conditional assembly chooses whether a section of source code is included in the program at assembly time. It is the assembly counterpart of the #if and #ifdef preprocessor directives of C.
Conditional assembly is the selection, with directives such as IF, IFB, ELSE and ENDIF, of whether a source section is included in the code at assembly time. The condition is evaluated at assembly time; a branch that is not selected never enters the machine code.
| Directive | When is the branch taken? | Typical use |
|---|---|---|
IF expression | expression ≠ 0 | test builds, options |
IFE expression | expression = 0 | the opposite of IF |
IFB <p> | the parameter is blank | optional parameter |
IFNB <p> | the parameter is not blank | optional parameter |
IFIDN <a>,<b> | the two texts are identical | checking a register name |
IFDIF <a>,<b> | the two texts differ | checking a register name |
Every conditional block ends with ENDIF and may carry an optional ELSE branch. The condition does not look at a flag or register at run time. It looks at what the assembler knows at assembly time: the values of symbols and the text of macro parameters. Conditional assembly therefore produces no instruction, comparison or jump at run time.
The first area of use is producing different versions of a program from the same source:
DEBUG = 1
IF DEBUG
PUTC '*' ; test build only
ENDIFWith DEBUG = 1, PUTC is expanded and the program grows by 8 bytes; a star is printed on the screen first. When the symbol is set to 0, these lines are not assembled at all and leave no trace in the program. Debug output or checks are thus removed from the final version without being deleted from the source.
The second area of use is inside macros. IFB and IFNB (blank, not blank) make optional parameters possible. The SHIFTN macro below shifts a register left; if the shift count is not given, 1 is assumed:
SHIFTN MACRO r, n
IFB <n> ;; was n omitted?
SHL r, 1
ELSE
MOV CL, n
SHL r, CL
ENDIF
ENDMOn the 8086 the shift count is either 1 or given in CL. An immediate count such as SHL AX, 3 came with the 80186. The macro hides this rule from the user: if n is blank it produces a one-bit shift, otherwise a shift by CL. Writing the parameter inside angle brackets (<n>) lets even an empty text be compared as a text.
IFIDN and IFDIF set up a safety net against parameter pitfalls. SHIFTN clobbers CL; the call SHIFTN CX, 2 therefore gives a wrong result. MOV CL, 2 overwrites the low byte of CX, and the value being shifted is no longer the programmer's CX. A block starting with IFIDN <r>, <CX> can be added to the body to produce an error message in this case. The EXITM directive ends the expansion at that point; the remaining body lines are not written. Used together with conditional assembly, it also provides the stopping condition of a recursive macro.
9.1.10.2Code trace: SHIFTN
org 100h
mov ax, 5
mov bx, 3
SHIFTN AX ; → shl ax, 1
SHIFTN BX, 3 ; → mov cl, 3 · shl bx, cl
ret| Step | Address | Instruction | AX | BX | CL | CF | Explanation |
|---|---|---|---|---|---|---|---|
| 1 | 0100h | mov ax, 5main program | 0005h | 0000h | 00h | 0 | AX = 5 |
| 2 | 0103h | mov bx, 3main program | 0005h | 0003h | 00h | 0 | BX = 3 |
| 3 | 0106h | SHL AX, 1SHIFTN expansion | 000Ah | 0003h | 00h | 0 | n is blank, IFB branch: AX = 5 × 2 |
| 4 | 0108h | MOV CL, 3SHIFTN expansion | 000Ah | 0003h | 03h | 0 | n = 3, ELSE branch: the count goes to CL |
| 5 | 010Ah | SHL BX, CLSHIFTN expansion | 000Ah | 0018h | 03h | 0 | 3 × 2³ = 24 = 0018h |
| 6 | 010Ch | retmain program | 000Ah | 0018h | 03h | 0 | the program ends |
In the first call n is blank; the assembler selects the IFB branch and writes a single SHL AX, 1 (2 bytes, D1 E0). AX = 5 × 2 = 000Ah. In the second call n = 3; the ELSE branch is selected and two instructions are written: MOV CL, 3 (B1 03) and SHL BX, CL (D3 E3), 4 bytes in all. BX = 3 × 2³ = 24 = 0018h. The same macro has produced code of two different lengths. The first expansion does not touch CL; only the second expansion changes CL.
The trace contains no comparison or jump. The assembler decided which branch to write, and the processor merely executed the result. Had the same choice been made at run time, every call would have needed a CMP and a conditional jump; the code would have grown and the prefetch queue would have been flushed.
9.1.11Debugging and common mistakes
Macros shorten the code in the source but make debugging harder, because the code that runs is not written in the source. Four habits reduce this difficulty.
Look at the expansion. The instruction listing in emu8086's emulator window shows not the macro names but the expanded instructions; single-stepping also advances over these instructions. Because macro labels get names such as ??0000 through LOCAL, jump targets do not appear under their source names. These numbers show which copy is running.
The listing file. In MASM, .LISTMACROALL writes all lines of the expansion to the listing file. .LISTMACRO writes only the lines that generate code, and .NOLISTMACRO hides the expansion completely. Because the listing file gives the address and machine code of every line side by side, it is the most reliable source for byte counting and address checking.
Read the error line correctly. An error in the body is reported separately at every line where the macro is used. If the same error message is seen several times, the cause is usually in the body.
Expand by hand first. A new macro is developed by first writing its body as plain code and trying it out. Once the code works correctly with one parameter value, it is turned into a parameterized macro. Then it is tried separately with parameters of different kinds (register, variable, constant, expression).
| Mistake | Result | Fix |
|---|---|---|
| defining after use | the call is treated as an unknown instruction | put definitions at the top of the file or in an INCLUDE file |
| forgetting ENDM | the rest of the file counts as the body; the error shows up far below | check the ENDM of every MACRO |
| not making a label LOCAL | Duplicate declaration at the second use | LOCAL as the first line of the body |
| RET in the body | RET takes the caller's return address or an arbitrary word | do not write RET in a macro |
| passing a register the body clobbers as a parameter | in calls such as ADD3 AX, BX, CX the parameter changes before it is read | document the registers used; check with IFIDN |
| expression without parentheses | operator precedence changes | (wd)*(ht) |
| mistaking a macro for a loop | REPT 1000 produces 1000 copies | LOOP for repetition at run time |
| using a long body many times | code size grows with the number of uses | move the job into a procedure, make the macro a wrapper |
Table 9.1.22 collects the eight common mistakes. They all share the same root: a macro is a text pattern, not a unit that is called. The most reliable way to understand what a macro does is to expand it and read the resulting instructions like an ordinary program.
9.1.12Exercises and solutions
Exercise 1. What is the expanded form of the call MyMacro AX, BX, CX? Which lines are unnecessary?
Solution. p1 = AX, p2 = BX, p3 = CX. The expansion is the lines MOV AX, AX, MOV BX, BX, MOV CX, CX. All three are valid instructions and assemble to 2 bytes each (8B C0, 8B DB, 8B C9). But none of them changes a register; MOV does not affect the flags either. All three lines are unnecessary: 6 bytes and 6 cycles are wasted. A program that starts with AX = 1, BX = 2, CX = 3 carries the same values after the macro. The macro assembles without error but does nothing; the assembler gives no warning for such ineffective expansions.
Exercise 2. Write an ADD3 a, b, c macro that adds two word variables and writes the sum to a third.
Solution.
ADD3 MACRO a, b, c
MOV AX, a
ADD AX, b
MOV c, AX
ENDMBecause the 8086 has no memory-to-memory addition, AX is the intermediate register. The macro modifies AX; this must be stated in the macro's documentation. With s1 = 1234h and s2 = F00Fh, the call ADD3 s1, s2, s3 gives s3 = 0243h and CF = 1; the 17th bit of the unsigned sum is in the carry.
Exercise 3. What are the code sizes if the PUTC macro is used 50 times, and if a procedure doing the same job is called 50 times?
Solution. Macro: 50 × 8 = 400 bytes. Procedure: body 8 bytes + RET 1 byte = 9 bytes once, plus 50 × 3 = 150 bytes of CALLs; 159 bytes in all. In time, the procedure adds 50 × 27 = 1350 cycles.
Exercise 4. What error occurs when the first POWER macro, POWER base, exponent, result, is used twice, with a second call? How is it fixed?
Solution. The second expansion redefines the label powerloop:; the assembler reports a Duplicate declaration (powerloop) error and the program does not assemble. The fix is to add LOCAL powerloop as the first line of the macro. The label is then ??0000 in the first expansion and ??0001 in the second, and each LOOP returns to the label of its own copy.
Exercise 5. How many times does the first POWER macro execute MUL when exponent = 0?
Solution. 65,536 times. Since MUL is at the start of the loop, it runs once first. LOOP decrements CX from 0 to FFFFh and jumps. The loop continues until CX is 0 again: CX = 0 → FFFFh → … → 1 → 0. With base = 2, result = 0000h; with base = 1, result = 0001h. If the counter is checked beforehand with JCXZ, no MUL runs and result = 1.
Exercise 6. Which instructions must be added so that a macro corrupts no register except AX?
Solution. At the start of the body, one PUSH for every register the macro modifies (except AX); at the end, POPs for the same registers in reverse order. In the corrected POWER these are PUSH BX, PUSH CX, PUSH DX and POP DX, POP CX, POP BX. Instructions that modify registers implicitly deserve particular attention (MUL changes DX, LOOP changes CX, INT services change their return registers). If the flags must also be preserved, PUSHF and POPF are used.
9.1.13Summary
- A macro is a code template defined with
name MACRO p1, p2 … ENDM. The assembler writes the body in place of every line that uses the macro; this is called expansion. The processor never sees the macro. - A macro must be defined before the line that uses it. A macro that is never used generates no code.
- Parameters are text, not values. Their values are read when the expanded line executes. A register that the body modifies must not be passed as a parameter; expression parameters must be parenthesized in the body.
- Which call is valid is decided by the instruction produced in the expansion; the error is reported at the line of use, but its cause is in the body.
- Size: a macro takes k · n bytes, a procedure (n + 1) + 3k bytes. If the body is longer than 3 bytes, the procedure is smaller beyond the break-even point.
- Speed: every procedure call adds CALL + RET, 19 + 8 = 27 cycles, two stack accesses and two queue flushes. A macro has no such cost.
- RET is not written in a macro; RET takes the caller's return address or whatever is on the stack.
- Macros with labels are written with LOCAL; the assembler generates unique names such as ??0000, ??0001 … at every expansion.
- The registers a macro modifies are saved with PUSH and restored with POP in reverse order (PUTC, the corrected POWER).
- LOOP with CX = 0 runs 65,536 times; a JCXZ goes in front of loops whose counter is a variable. MUL also changes DX.
- INCLUDE inserts the library text into the source; emu8086.inc offers short jobs as macros and long jobs as procedures.
- The macro operators &, <>, !, % and ;; join, group and evaluate text.
- REPT, IRP and IRPC are unnamed repeat blocks expanded in place; with the
=symbol they generate tables at assembly time. - IF, IFE, IFB, IFNB, IFIDN and IFDIF evaluate the condition at assembly time; the branch not selected never enters the machine code.
9.1.14Key terms
- macro
- macro expansion
- LOCAL directive
- conditional assembly
- repeat block (REPT / IRP / IRPC)
- directive
- assembler
- procedure
- procedure call
- return address
- register preservation
- label
- library
- clock cycle
- prefetch queue
- bus cycle
- listing file
- emulator
9.1.15Test Yourself
The ADD3 macro (
MOV AX, x·ADD AX, y·MOV z, AX) is called asADD3 BX, AX, CXwith AX = 5 and BX = 7. What does CX become?Answer
The expansion is
MOV AX, BX·ADD AX, AX·MOV CX, AX. The first line makes AX 7; the text y = AX now refers to 7. ADD gives 7 + 7 = 14: CX = 000Eh, not the expected 12.What does the call
AREA 10-2, 3of the macroAREA MACRO wd, ht/MOV AX, wd*ht/ENDMload into AX? What does the parenthesized version load?Answer
The expansion is
MOV AX, 10-2*3; multiplication comes first: 10 − 6 = 4. The parenthesized(10-2)*(3)gives 24 (0018h). In both cases the multiplication is done at assembly time and the machine code contains only one MOV.From how many uses on does a job with a 4-byte body take less space as a procedure?
Answer
Macro 4k, procedure 5 + 3k bytes. 4k > 5 + 3k gives k > 5. At five uses both take 20 bytes; from six uses on the procedure is smaller (23 bytes against 24).
If a macro that contains a label but does not use LOCAL is used only once in a program, is there an assembly error?
Answer
No. With a single expansion the label is defined once and the program assembles. The error appears as Duplicate declaration the moment the macro is used a second time. This is why LOCAL is written even if the macro will be used only once.
MyMacro2 (jumps to label1 if AX = 2 and to label2 if AX = 3; label1: INC AX, label2: ADD AX, 2) is run with AX = 0. What does AX become?
Answer
Neither JE jumps and the flow falls into label1. INC AX gives 1 and ADD AX, 2 then gives 3.
The SHIFTN macro (when n is given:
MOV CL, n·SHL r, CL) is called asSHIFTN CX, 2with CX = 5. The programmer expects 5 × 4 = 20. What does CX become?Answer
MOV CL, 2overwrites the low byte of CX: CX = 0002h.SHL CX, CLshifts 2 left by 2 bits: CX = 0008h. A register that the body clobbers (CL, and therefore CX) has been passed as a parameter; IFIDN can catch this call.Which bytes does the block
n = 1·table LABEL BYTE·REPT 4·DB n·n = n * 2·ENDMwrite to memory? How many instructions does this block execute at run time?Answer
01h, 02h, 04h, 08h. The block produces only data; n is a symbol that lives at assembly time. No instruction is executed at run time.
A procedure is called 1000 times on a 5 MHz 8086. How much extra time do CALL and RET add?
Answer
1000 × (19 + 8) = 27,000 cycles. Since one cycle is 200 ns, 27,000 × 200 ns = 5.4 ms. With a macro this time would not exist, but the code would grow by 1000 copies.
How many bytes does the PRINT macro of emu8086.inc produce for
PRINT 'Hello'? Although the string is inside the code, why does the processor not execute it as instructions?Answer
26 bytes for 'OK'; every extra character adds one byte. For a 5-character text, 24 + 5 = 29 bytes. The macro puts a JMP in front of the string and the processor jumps over the string's bytes; the string is accessed only as data, with
MOV AL, CS:[SI].
9.1.16Further reading
- Microsoft, MASM Programmer's Guide: the reference description of macro definition, LOCAL, macro operators, repeat blocks and conditional assembly directives.
- K. R. Irvine, Assembly Language for x86 Processors, Chapter 10: treats macros, conditional assembly and repeat blocks with many examples.
- emu8086 help documents, 8086 Assembler Tutorial, Part 10 (Macros): writing macros in emu8086 and the emu8086.inc library.
- B. B. Brey, The Intel Microprocessors: treats the choice between a macro and a procedure together with 8086 instruction timings and the hardware structure.
9.1.17References
- emu8086 help documents: 8086 Assembler Tutorial, Part 10 (Macros) and
emu8086.inc. - Microsoft, MASM Programmer's Guide — the MACRO, ENDM and 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.
- Intel, 8086 16-Bit HMOS Microprocessor data sheet (instruction timings).
Related pages: Chapter 9.1 slides · © Sercan Külcü. All rights reserved.