Microprocessors · Lecture Notes

Chapter 7: Flow Control

Left to itself, the processor executes instructions in the order they sit in memory. After each instruction the instruction pointer, IP, grows by the length of that instruction and points at the next one. Any program that makes a decision, repeats a task, or branches off on an error has to break this straight line. Flow control instructions do so by loading a new value into IP. This note first covers the unconditional jump (JMP) and how the jump displacement is written into machine code. It then turns to conditional jumps that test the flags, the CMP instruction, and the reason signed and unsigned numbers need separate families of jumps. Next it builds the assembly counterparts of the if/else and while constructs of high-level languages. Finally it studies the LOOP family, which uses CX as a counter, and JCXZ. Every example program is traced step by step at the level of registers, flags, and memory; the effect of a jump on the prefetch queue and on clock cycles is explained as well.

Learning outcomes

Jump mechanism
Direct program flow with JMP and labels; explain how IP changes and how the jump displacement (relative offset) is computed; distinguish short, near, far, and indirect jumps.
Conditional jumps
State which flag (ZF, CF, SF, OF, PF) each conditional jump tests, find its opposite and its synonyms, and compute its machine code.
Comparing correctly
After CMP, choose the JA/JB family for unsigned numbers and the JG/JL family for signed numbers; explain through overflow why the rule is SF = OF.
High-level constructs
Write if/else, while, and for constructs with patterns that jump on the opposite condition; fix an out-of-range conditional jump with the inverted condition plus JMP.
Loops
Write counted loops with LOOP, LOOPE/LOOPZ, LOOPNE/LOOPNZ, and JCXZ; explain the CX = 0 trap and why a nested loop must save its counter; trace the example programs step by step.

7.1Sequential execution and flow control

7.1.1IP and the prefetch queue

The instructions the 8086 executes are bytes laid out one after another in the code segment. The processor knows which of these bytes starts the next instruction from two registers: CS (the code segment) and IP (the instruction pointer). CS holds the start of the segment, and IP holds the offset of the next instruction within it. As with every other memory access, the physical address of the instruction is CS × 10h + IP. In a .COM program with CS = 0700h and the first instruction at 0100h, the processor fetches the first instruction from 07000h + 0100h = 07100h.

A program cannot write to IP with MOV; there is no MOV IP, AX. Only the processor itself changes IP. In the ordinary case the change is simple: once an instruction is decoded, IP grows by that instruction's byte count. If the three-byte MOV AX, 5 (B8 05 00) sits at 0100h, IP = 0103h when it finishes. The two-byte MOV AL, 25 (B0 19) advances IP by two. This pattern is called sequential execution.

Sequential execution has a hardware counterpart in the 8086. The processor consists of two units. The bus interface unit (BIU) manages the address and data buses and reads instruction bytes from memory. The execution unit (EU) decodes those bytes and carries out the operation. The BIU does not wait for the EU to finish: whenever the bus is idle, it reads ahead of CS:IP and stores the bytes in a six-byte prefetch queue. By the time the EU moves on to the next instruction, its bytes are usually already waiting in the queue. Reading from memory and executing instructions thus overlap, which makes this a simple pipeline.

The queue rests on one assumption: the next instruction follows immediately in memory. Flow control instructions break that assumption. When a jump executes, IP moves to a different address, and the bytes in the queue now belong to the wrong instructions. The EU flushes the queue and the BIU starts reading again from the new CS:IP. Much of the clock-cycle cost of a jump comes from this refill.

Definition 7.1

The instruction pointer (IP) is the 16-bit register that holds the offset, within the code segment, of the next instruction to execute. The physical address of the instruction is CS × 10h + IP. A flow control instruction is one that loads IP (and, for a far jump, CS as well) with a value other than the one given by the instruction length.

7.1.2Types of flow control instructions

The flow control instructions of the 8086 fall into three groups. The first is the unconditional jump: JMP label jumps in every case. The second is the conditional jumps (Jcc). These test one or more flags in the flags register: if the condition holds they jump, otherwise execution continues with the next instruction. Conditional jumps split into three subgroups: those that test a single flag (JZ, JC, JS, JO, JP and their opposites), those for signed numbers (the JG, JL family), and those for unsigned numbers (the JA, JB family). The third group is the loop instructions: LOOP, LOOPE/LOOPZ, LOOPNE/LOOPNZ, and JCXZ. They use CX as the counter.

Other instructions change the flow too. CALL and RET go to a subroutine and come back, keeping the return address on the stack. INT and IRET go to an interrupt service routine and return. The RET that ends every program in this note is also a flow control instruction. When a .COM program starts, the top of the stack holds 0000h, and RET loads this value into IP. At offset 0000h sits the PSP (program segment prefix) that DOS places at the start of the program. The first two bytes of the PSP are INT 20h, and that is how the program terminates. This is why the last row of the trace tables shows IP = 0000h and SP = 0000h.

In high-level languages, flow control appears as decision structures (if/else, switch) and loops (for, while, do-while). The compiler translates all of them into compare, conditional jump, and unconditional jump instructions. An assembly programmer does this translation by hand. Figure 7.1 compares how the same piece of program is traversed under sequential execution and under execution with jumps.

Sequential (IP += length)Jump (IP ← target)mov ax, 5mov ax, 5mov bx, 2mov bx, 2jmp calcjmp calcback: jmp stopback: jmp stopcalc: add ax, bxcalc: add ax, bxjmp backjmp backstop: retstop: ret
Figure 7.1: On the left, instructions execute in memory order and IP grows by the instruction length at every step. On the right, the jmp instructions load a new value into IP, and the flow leaps to the labels calc, back, and stop.

7.2The unconditional jump: JMP

7.2.1JMP and its forms

The JMP label instruction transfers control to another point in the program under all conditions. It can jump forward or backward. It changes no flag; the flags that held before the jump are still valid after it. This matters: the flags set by a CMP can still be read after an intervening JMP.

Definition 7.2

An unconditional jump makes execution continue at the specified target address regardless of the flags. On the 8086 it is performed by the JMP instruction. The target is given inside the instruction either as a displacement, as an absolute CS:IP pair, or indirectly through a register or memory word.

The 8086 recognizes four forms of the JMP instruction. Which one is used depends on how far away the target is and where it is written. Table 7.1 summarizes these forms.

Table 7.1: The forms of the JMP instruction, their machine codes, and their timings on the 8086.
FormCodeBytesRangeChangesClock cycles
short (JMP SHORT)EB rel82−128…+127IP15
near (JMP NEAR)E9 rel163anywhere in the segmentIP15
far (JMP FAR)EA ofs seg5anywhere in 1 MBCS and IP15
indirect, register (JMP BX)FF E32within the segmentIP11
indirect, memory (JMP [BX])FF 272–4within the segmentIP18 + EA

A short jump is two bytes: the opcode EBh and an 8-bit signed displacement (rel8). The displacement ranges from −128 to +127, counted from the address of the instruction immediately after the jump. Most loops and short if blocks fit in this range, so the short jump is the most common form.

A near jump is three bytes: E9h and a 16-bit displacement (rel16). Because 16-bit addition wraps around, rel16 reaches every offset (0000h–FFFFh) in the 64 KB of the code segment. Read as signed, the displacement means ±32 KB, but thanks to the wraparound the jump can also reach the other end of the segment. In short and near jumps only IP changes and CS stays the same, so both are intrasegment jumps.

A far jump is five bytes: EAh, followed by the 16-bit offset and the 16-bit segment value of the target. The byte order is little-endian, so the low byte of the offset comes first. For example, a far jump to 0800h:0000h is encoded as EA 00 00 00 08. The instruction loads 0000h into IP and 0800h into CS, and execution continues at physical address 08000h. This is the only way to move to another segment, and it is called an intersegment jump.

In an indirect jump the target is not written in the instruction. JMP BX loads the value of BX into IP. JMP [BX] reads the word at address DS:BX and loads it into IP. Indirect jumps suit cases where the target is computed at run time. A typical example is going to a different function according to the number chosen in a menu. The programmer builds a jump table: table dw task0, task1, task2. The selection number is multiplied by 2 and placed in SI, and JMP table[SI] goes to the right address. The machine code of this instruction consists of FF A4 and the 16-bit address of the table, four bytes in all.

The programmer often does not need to choose a form. If the assembler knows the target and the target is within short range, it picks the 2-byte short form itself. If the target lies further down in the code and is not yet defined, some assemblers first reserve 3 bytes. Multi-pass assemblers (emu8086 is one) shrink to the short form once the addresses are final. Writing JMP SHORT label forces the short form; if the target is out of range, the assembler reports an error. Writing JMP NEAR PTR label forces the 3-byte form even when the target is close.

Common mistake

The claim “JMP can go at most 127 bytes forward” is wrong. That limit applies only to the short form. A near JMP reaches anywhere in the code segment, and a far JMP reaches anywhere in the 1 MB address space. The 127-byte limit matters mainly for the 8086's conditional jumps, because they have no 16-bit form.

7.2.2Labels

An assembly programmer writes a jump target not as an address but as a label. A label is a name given to an address. To define one, write the name followed by a colon: loop_top:. A label can stand on a line of its own or in front of an instruction: back: jmp stop. In both forms the label receives the address of the first instruction that follows it.

A label takes no space in memory. While reading the source, the assembler keeps a location counter. It adds each instruction's byte count to the counter, and when it meets a label it records the counter's current value as the label's address. Later, when encoding a line such as jmp loop_top, it uses that address. In Figure 7.2 the label loop_top becomes the address of the DEC CX instruction that follows it, 0103h. In machine code there is no such thing as loop_top; only the displacement byte of the JNZ instruction holds a number leading to that address.

0100hMOV CX, 30103hloop_top: DEC CX0104hJNZ loop_topassembler: loop_top = 0103ha label occupies no bytes; it is an address
Figure 7.2: The label loop_top becomes the address (0103h) of the DEC CX instruction that follows it; JNZ loop_top jumps to that address. The label occupies no bytes in memory.

There are a few rules for label names. A name consists of characters such as letters, digits, and underscores, but it cannot start with a digit. It cannot contain spaces. Instruction names (mov, loop) and register names (ax, cx) cannot be labels, because the assembler first tries to recognize the word at the start of a line as an instruction or a register. A label is defined once in a program; a second definition would make it ambiguous which address is meant and causes an error.

Table 7.2: Examples of valid and invalid labels.
LabelStatusReason
loop_top:validmade of letters
next_char:validunderscores are allowed
k1:, calc:valida digit is not the first character
1start:invalidstarts with a digit
mov:invalidinstruction name
two words:invalidcontains a space

A label also has a type. Labels inside code are of type near: they carry only an offset, which is why they are used in intrasegment jumps. The names of data definitions (msg db 'Hello', 0) are addresses as well, but they are called variables and have data types (byte, word). The difference matters for JMP. Writing jmp calc makes the assembler produce a displacement leading to the address of calc. But when the name of a variable such as table dw 0103h is written, jmp table is encoded as an indirect jump (FF 26 and the address of the table). The processor reads the word inside the table and loads it into IP. Although the syntax looks alike, one jumps to a label and the other to the contents of a variable.

7.2.3Code trace: forward and backward with JMP

The program below shows that JMP can jump both forward and backward. It loads two numbers, jumps forward to the calc block that does the addition, returns from there backward to the line back, and finally jumps forward again to the line stop. In the source, the order of the lines differs from the order of execution.

org    100h
mov    ax, 5          ; ax = 5
mov    bx, 2          ; bx = 2
jmp    calc           ; go to 'calc'
back:  jmp stop       ; go to 'stop'
calc:
add    ax, bx         ; ax = ax + bx
jmp    back           ; back to 'back'
stop:
ret                   ; return to the OS

The org 100h directive is not an instruction. It tells the assembler to start the location counter at 0100h, because DOS loads a .COM program at offset 0100h of the segment. The first instruction, mov ax, 5, is therefore at 0100h. When the processor starts the program, IP = 0100h.

Table 7.3 gives each instruction of the program, its address, its machine code, and the state after the instruction completes. The IP in the last column is the address of the next instruction.

Table 7.3: Trace of the JMP example (CS = 0700h; values are the state after the instruction has executed).
StepAddressInstructionCodeAXBXIP (after)
0—start—0000h0000h0100h
10100hmov ax, 5B8 05 000005h0000h0103h
20103hmov bx, 2BB 02 000005h0002h0106h
30106hjmp calcEB 020005h0002h010Ah
4010Ahadd ax, bx01 D80007h0002h010Ch
5010Chjmp backEB FA0007h0002h0108h
60108hjmp stopEB 040007h0002h010Eh
7010EhretC30007h0002h0000h

The first two steps are sequential execution: IP grows first by 3, then by 3 again. In the third step jmp calc executes. With sequential execution IP would be 0108h. The jump loads IP with the address of calc, 010Ah. The back: jmp stop instruction at 0108h, which lies in between, is not executed on this pass. In the fourth step add ax, bx makes AX 5 + 2 = 7. ADD affects the flags too. The result is not zero (ZF = 0), the sign bit is 0 (SF = 0), and there is no carry or overflow (CF = OF = 0). Because 07h = 0000 0111b contains three 1 bits, the parity is odd (PF = 0).

The fifth step is the backward jump. jmp back sits at 010Ch and pulls IP to 0108h, an address before itself. In the sixth step the jmp stop at 0108h is finally executed and IP becomes 010Eh. In the seventh step ret takes the value 0000h from the stack; IP = 0000h and SP = FFFEh + 2 = 0000h. The INT 20h in the PSP ends the program. The result is AX = 0007h. In terms of source lines, the execution order is 2 → 3 → 4 → 7 → 8 → 5 → 10. Since none of the three JMPs touches the flags, the flags set by ADD stay the same until the end of the program.

The code 01 D8 given for add ax, bx in the table is ADD's “register/memory ← register” form. The same instruction can also be encoded in the “register ← register/memory” form as 03 C3, and some assemblers produce that. Both encodings are two bytes and do the same job; addresses and jump displacements do not change.

7.2.4Computing the jump displacement

In the machine code of a short or near jump, the address of the target is not written. Instead, what is written is the signed displacement of the target relative to the address of the instruction after the jump. This approach is called relative addressing. The computation is:

displacement = target − (address of the jump instruction + length of the jump instruction)

The sum in parentheses is the value of IP at the moment the processor has read and finished the jump instruction. While executing the jump, the processor adds the displacement to this IP: IP ← IP + displacement. A negative displacement is stored in two's complement, and the addition is done by the same circuit.

Definition 7.3

The jump displacement is the signed difference between the jump target and the address of the instruction following the jump. It is 8 bits (rel8, −128…+127) in the short jump and in all conditional jumps of the 8086, and 16 bits (rel16) in the near jump. When executing, the processor computes IP ← IP + sign-extended displacement.

Figure 7.3 derives the code of the first jump in the JMP example, jmp calc. The instruction is at 0106h and is two bytes long. When the processor finishes it, IP = 0108h. The target calc = 010Ah. The displacement is 010Ah − 0108h = +2, and the machine code is EB 02. These two bytes mean skipping over the two-byte jmp stop instruction at 0108h.

addressmachine codeinstruction0100hB8 05 00mov ax, 50103hBB 02 00mov bx, 20106hEB 02jmp calc0108hEB 04back: jmp stop010Ah01 D8calc: add ax, bx010ChEB FAjmp back010EhC3stop: retjmp calc @ 0106h (2 bytes)next IP = 0108htarget calc = 010Ahrel8 = 010A − 0108 = +2code: EB 02
Figure 7.3: Forward jump: jmp calc at 0106h, next instruction at 0108h, target at 010Ah. Displacement 010Ah − 0108h = +2, code EB 02.

The computation for jmp stop at 0108h is the same. The next instruction is at 010Ah and the target stop = 010Eh. The displacement is 010Eh − 010Ah = +4 and the code is EB 04. During execution the processor computes IP ← 010Ah + 4 = 010Eh.

In a backward jump the displacement is negative. After the jmp back instruction at 010Ch, IP = 010Eh; the target back = 0108h. The displacement is 0108h − 010Eh = −6. The 8-bit two's complement of −6 is found like this: 6 = 0000 0110b; inverting the bits gives 1111 1001b; adding 1 gives 1111 1010b = FAh. The machine code is EB FA (Figure 7.4).

addressmachine codeinstruction0100hB8 05 00mov ax, 50103hBB 02 00mov bx, 20106hEB 02jmp calc0108hEB 04back: jmp stop010Ah01 D8calc: add ax, bx010ChEB FAjmp back010EhC3stop: retjmp back @ 010Chnext IP = 010Ehtarget back = 0108hrel8 = 0108 − 010E = −6−6 = FAh (two's complement)code: EB FA
Figure 7.4: Backward jump: jmp back at 010Ch, next IP 010Eh, target 0108h. Displacement −6, FAh in two's complement; code EB FA.

Before adding this eight-bit number to IP, the processor performs sign extension: since the most significant bit is 1, the upper eight bits are filled with 1s and FAh becomes FFFAh. The addition is 16-bit: 010Eh + FFFAh = 1 0108h. The seventeenth bit does not fit in the register and is discarded; IP = 0108h. A positive displacement goes through the same process, except that the upper bits fill with 0s: 02h → 0002h.

Example 7.1

A short JMP at address 0150h wants to jump to 0140h. What is its machine code?

The instruction is two bytes, so the next IP = 0152h. Displacement = 0140h − 0152h = −12h = −18. 18 = 0001 0010b; inverted 1110 1101b; adding 1 gives 1110 1110b = EEh. The code is EB EE. Check: 0152h + FFEEh = 1 0140h → IP = 0140h.

Had the jump to the same target been made from 0100h, the displacement would be 0140h − 0102h = +3Eh and the code EB 3E. From 0300h the displacement would be 0140h − 0302h = −1C2h = −450. This number is less than −128, so the short form cannot be used. The assembler chooses the near form: the instruction is 3 bytes, the next IP = 0303h, the displacement is 0140h − 0303h = −1C3h = FE3Dh, and the code is E9 3D FE.

Relative addressing has an important benefit. When the code is moved elsewhere in memory, the displacements do not change, because both the jump instruction and its target shift by the same amount. Such code is called position-independent code. Whatever segment DOS loads a .COM program into, the short and near jumps within the segment work correctly. A far jump, on the other hand, contains an absolute segment value, which must be fixed up if the program is moved.

7.2.5The hardware cost of a jump

Table 7.1 shows that JMP takes 15 clock cycles. That is a long time for a two-byte instruction; ADD AX, BX, which adds two registers, takes only 3. The reason is the prefetch queue. When a jump executes, the EU tells the BIU to flush the queue and start reading from the new address. The BIU puts the new CS:IP on the address bus and reads two bytes in one bus cycle (four clock cycles). The EU waits until the first byte of the new instruction arrives in the queue. A significant part of the 15 cycles is this wait.

For conditional jumps the cost is even more visible. If the condition holds and the jump is taken, the instruction takes 16 cycles. If the condition does not hold, it takes only 4, because IP points at the next instruction and the bytes in the queue remain valid. Between the two cases of the same instruction there is a fourfold difference. For this reason, in frequently executed loops, writing the jump so that it falls on the “mostly not taken” side gains speed even on the 8086.

Table 7.4: Clock cycle counts of flow control instructions on the 8086 (Intel 8086 manual).
InstructionIf takenIf not taken
JMP short / near / far15—
JMP register / memory11 / 18 + EA—
Jcc (all conditional jumps)164
LOOP175
LOOPE / LOOPZ186
LOOPNE / LOOPNZ195
JCXZ186

These numbers become concrete on a 5 MHz 8086. One clock cycle is 1 / 5 MHz = 200 ns. A 15-cycle JMP takes 3 µs. A conditional jump not taken takes 0.8 µs, and one taken takes 3.2 µs. The loop instruction alone of a thousand-iteration loop can therefore take milliseconds.

A jump has one more side effect. If the target address is odd, the BIU can fetch only one byte in the first bus cycle. The 8086 data bus is 16 bits wide and can read a word in a single bus cycle only from an even address. Aligning frequently used loop heads to an even address (the EVEN directive) therefore gives a small gain. The 8088, with its 8-bit data bus, has no such difference, but because every byte needs its own bus cycle, filling the queue takes even longer.

7.3Conditional jumps

7.3.1The idea of a conditional jump

An unconditional jump cannot decide anything on its own; it goes to the same place every time. To decide, a jump must depend on a condition. On the 8086 this condition is always read from the flags in the flags register. The general name of the conditional jump instructions is Jcc; in place of cc comes the abbreviation of the condition (Z, NZ, C, A, G …). The meaning of Jcc label is this: if the condition is true, IP ← label; otherwise IP keeps pointing at the next instruction.

Definition 7.4

A conditional jump is an instruction that, depending on the state of one or more flags in the flags register, either jumps to the target or moves on to the next instruction. A conditional jump only reads the flags; it changes none of them.

The flags are set by an instruction that comes before the conditional jump. This instruction is most often CMP, but arithmetic and logic instructions such as SUB, ADD, TEST, AND, INC, and DEC set the flags too. Instructions that do not touch the flags (MOV, JMP, LOOP, PUSH, POP) may come between the flag-setting instruction and the jump that reads the flags; the decision is still made from the result of the first instruction. If an instruction that changes the flags comes in between, the decision is made from that instruction instead. This is one of the main sources of errors in flow control.

The status flags used by jumps are the following:

  • ZF (zero flag): 1 if the result is zero.
  • CF (carry flag): 1 if addition produces a carry out of the most significant bit, or subtraction needs a borrow.
  • SF (sign flag): the most significant bit of the result; 1 if the result is negative in the signed interpretation.
  • OF (overflow flag): 1 if the result does not fit in the destination's bit width in the signed interpretation.
  • PF (parity flag): 1 if the low byte of the result has an even number of 1 bits.
  • AF (auxiliary carry flag): 1 if there is a carry or borrow at bit 3. No jump tests this flag; AF is used only by the BCD adjust instructions (DAA, DAS, AAA, AAS).

Figure 7.5 summarizes the flow of a conditional jump. After the instruction that sets the flags, the processor reaches a fork. If the condition holds it goes to the label, and if not it goes to the next instruction. Every if in a high-level language is an instance of this fork.

cmp / sub / …flagscondition met?yeslabel:nonext instruction
Figure 7.5: Flowchart of a conditional jump: after the instruction that sets the flags, if the condition is true the jump goes to the label; otherwise execution continues with the next instruction.

7.3.2Jumps that test a single flag

The simplest conditional jumps look at a single flag. For each flag there are two instructions: one jumps when the flag is 1, the other when it is 0. The letter N in an instruction name means “not”: JZ jumps if zero, JNZ if not zero. Table 7.5 gives these instructions, their conditions, and their opposites.

Table 7.5: Conditional jumps that test a single flag.
InstructionMeaningConditionOpposite
JZ, JEjump if zero / equalZF = 1JNZ, JNE
JC, JB, JNAEjump if carry / belowCF = 1JNC, JNB, JAE
JSjump if the result is negativeSF = 1JNS
JOjump if signed overflowOF = 1JNO
JPE, JPjump if parity is evenPF = 1JPO, JNP
JNZ, JNEjump if not zero / not equalZF = 0JZ, JE
JNC, JNB, JAEjump if no carry / not belowCF = 0JC, JB, JNAE
JNSjump if the result is not negativeSF = 0JS
JNOjump if no overflowOF = 0JO
JPO, JNPjump if parity is oddPF = 0JPE, JP

These instructions have different areas of use. JZ/JNZ are the most common: with them one tests whether a counter has reached zero, whether two values are equal, or whether the 0 byte at the end of a string has been reached. JC/JNC catch overflow in unsigned addition and a borrow in subtraction. Some DOS and BIOS services also report an error through CF, and JC error is written after the service call. JS/JNS look at the sign of a result. JO/JNO catch overflow in signed arithmetic. JP/JNP are rarely used; they are useful for jobs such as parity checking in serial communication.

Common mistake

The C in JC is the carry flag; overflow is OF. They are different concepts. CF reports a failure to fit in the unsigned interpretation, and OF a failure to fit in the signed interpretation. In the addition 7Fh + 01h = 80h, CF = 0 (127 + 1 = 128 fits in a byte), but OF = 1 (signed +127 + 1 = +128 does not fit in the range −128…127).

7.3.3Encoding and synonyms

On the 8086 all conditional jumps have a fixed length: 2 bytes. The first byte is the opcode and the second is the 8-bit signed displacement (rel8). A conditional jump can therefore go at most 128 bytes backward or 127 bytes forward relative to the instruction after it. Conditional jumps with a 16-bit displacement (the 0F 8x opcodes) arrived only with the 80386; the 8086 does not have them.

The same condition can have more than one name. For example, the condition CF = 1 can be read in three ways: “carry set” (JC), “below” (JB, unsigned less than), and “not above or equal” (JNAE). These names are called synonym instructions. The assembler translates all of them to the same machine code; the processor does not know which name was written. The programmer chooses the name that best fits the meaning of the condition in that program. Writing JE when testing the equality of two numbers and JZ when testing whether a counter has reached zero keeps the code readable.

70JO
71JNO
72JB / JC / JNAE
73JAE / JNB / JNC
74JE / JZ
75JNE / JNZ
76JBE / JNA
77JA / JNBE
78JS
79JNS
7AJP / JPE
7BJNP / JPO
7CJL / JNGE
7DJGE / JNL
7EJLE / JNG
7FJG / JNLE
E0LOOPNE / LOOPNZ
E1LOOPE / LOOPZ
E2LOOP
E3JCXZ

There is a pattern in the opcode sequence above. The conditional jumps all lie in the range 70h–7Fh and pair up two by two. In each pair the lowest bit of the opcode inverts the condition: 74h is JE while 75h is JNE, 72h is JB while 73h is JAE, 7Ch is JL while 7Dh is JGE. The upper bits select which flag or combination of flags is tested. The processor's condition circuit first computes this combination, then inverts the result if the lowest bit is 1. This pattern makes it easy to find the opposite of a condition: changing the last bit of the opcode is enough. The loop instructions also sit side by side, in the range E0h–E3h. The code of the short JMP is EBh.

7.3.4Code trace: JNC = JNB = JAE

A small program shows that synonym instructions really produce the same machine code. The program contains three synonymous jumps in a row; all three go to the same label a.

org 100h
jnc a          ; 0100h: 73 07
jnb a          ; 0102h: 73 05
jae a          ; 0104h: 73 03
mov ax, 4      ; 0106h: B8 04 00
a: mov ax, 5   ; 0109h: B8 05 00
ret            ; 010Ch: C3

The opcode of all three jumps is 73h; all three test the condition CF = 0. Only their second bytes differ, because each stands at a different address and so has a different distance to the target. jnc a is at 0100h: the next address is 0102h, displacement 0109h − 0102h = 7. jnb a is at 0102h: displacement 0109h − 0104h = 5. jae a is at 0104h: displacement 0109h − 0106h = 3.

Table 7.6: Trace of the synonymous jumps program (CF = 0 at the start).
StepAddressInstructionCFAXIP (after)Note
0—start00000h0100h.COM start
10100hjnc a00000h0109hCF = 0 → jumps: 0102h + 07h
20109hmov ax, 500005h010Chthe three instructions in between were not executed
3010Chret00005h0000hreturn to the PSP

When the program starts, all the status flags are 0, CF included. The first instruction, jnc a, therefore jumps and IP = 0109h. jnb, jae, and mov ax, 4 are never executed. AX = 0005h and the program ends. Had CF been 1 at the start (say, with an STC added at the top), none of the three jumps would be taken. The processor would pass through the three instructions in turn, and AX would become 4 and then 5. The final value is the same either way, but the number of instructions executed differs: 3 when CF = 0, 6 when CF = 1.

7.3.5Computing a jump code by hand

The jump code calculator in the slides finds the machine code of a jump instruction from its address and its target. The same computation can be done by hand in three steps. First determine the instruction length: JMP SHORT, all Jcc instructions, and the LOOP family are 2 bytes, and JMP NEAR is 3 bytes. Then compute the displacement: displacement = target − (address + length). Finally check whether the displacement fits the range and write it in two's complement.

Example 7.2

(a) A JNE at 0120h is to jump to 0100h. Next IP = 0122h; displacement = 0100h − 0122h = −22h. 22h = 0010 0010b; inverted 1101 1101b; plus 1: 1101 1110b = DEh. Code 75 DE. The processor computes 0122h + FFDEh = 1 0100h → IP = 0100h.

(b) A LOOP at 0105h is to return to 0100h. Displacement = 0100h − 0107h = −7 = F9h. Code E2 F9.

(c) A JE at 0100h is to jump to 0190h. Displacement = 0190h − 0102h = 8Eh = 142. This number is greater than +127; as an 8-bit signed number, 8Eh would be read as −114. The short form cannot be used, and the 8086 has no long form of the conditional jump. The solution is to invert the condition and use a near JMP.

(d) A JMP NEAR at 0100h is to jump to 0190h. The instruction is 3 bytes, the next IP = 0103h, and the displacement = 008Dh. Code E9 8D 00 (little-endian: low byte first).

If the result does not fit in the range −128…+127 in the short form, classic assemblers report a “relative jump out of range” error. This error says the displacement does not fit in one byte; the fix is to change the instruction or rearrange the code.

7.4Comparison: CMP

7.4.1The CMP instruction

A program often compares two values and decides according to the result: is the number greater than 100, is the character 'A', has the counter run out. The CMP destination, source instruction is used for this. CMP performs the subtraction that SUB does: destination − source. It does not store the result anywhere, however. It only sets the flags (CF, ZF, SF, OF, PF, AF) according to the result of the subtraction. Both operands are left unchanged.

Definition 7.5

Compare (CMP) is the instruction that performs the subtraction destination − source, discards the result, and only sets the flags. The flags are set by the same rules as in SUB. The conditional jump that follows CMP decides by looking at these flags.

CMP's operand rules are the same as SUB's. Register–register, register–memory, memory–register, and register-or-memory–constant combinations are valid. There cannot be two memory operands; CMP [SI], [DI] cannot be written. The two operands must be the same size. When memory is compared with a constant, the size must be specified: CMP BYTE PTR [SI], 3. If a variable name is used, the size follows from the variable's type: cmp arr[si], 3 is a byte comparison because arr is defined with DB.

CMP's execution time depends on the operands. Register–register takes 3 clock cycles and register–constant takes 4. With a memory operand the effective address is computed first and memory is read in one bus cycle: register–memory takes 9 + EA, memory–constant 10 + EA cycles. A comparison and the conditional jump behind it together make up the cost of one decision: CMP AL, BL + a JE not taken is 3 + 4 = 7 cycles, and with the JE taken it is 3 + 16 = 19 cycles.

Table 7.7: Two simple CMP examples.
InstructionSubtractionZFCFSFOFJE / JZ
CMP 05h, 02h5 − 2 = 3 → 03h0000not taken
CMP 07h, 07h7 − 7 = 0 → 00h1000taken

The notation in the table is conceptual; the 8086 has no instruction that compares two constants, so one operand must be a register or memory. In the first example the difference is not zero and ZF = 0. In the second example the difference is zero: ZF = 1, and JE or JZ is taken. That is all there is to an equality test: if two numbers are equal, their difference is zero.

7.4.2CMP flags step by step

Equality looks only at ZF. Decisions of “greater” and “less” depend on how the numbers are interpreted. The same eight bits carry a value in the range 0–255 as an unsigned number and −128…127 as a signed number. CMP does not make this distinction; it subtracts the bits and writes into the flags the information needed for both interpretations. The answer for the unsigned interpretation is in CF and ZF, and the answer for the signed interpretation is in SF, OF, and ZF. Table 7.8 shows how CMP AL, BL sets the flags for five different inputs.

Table 7.8: Flags set by CMP AL, BL for five inputs, and the resulting jump decisions.
ALBLAL − BLCFZFSFOFPFAFUnsignedSigned
05h (5)02h (2)03h0000105 > 2: JA5 > 2: JG
07h (7)07h (7)00h010010equal: JEequal: JE
05h (5)07h (7)FEh1010015 < 7: JB5 < 7: JL
7Fh (127)80h (128 / −128)FFh101110127 < 128: JB127 > −128: JG
FBh (251 / −5)03h (3)F8h001000251 > 3: JA−5 < 3: JL

In the first row the difference is positive and no flag is raised except PF; PF = 1 because 03h = 0000 0011b contains two 1 bits. In the second row the difference is zero and ZF = 1. In both the signed and the unsigned view the numbers are equal.

In the third row a larger number is subtracted from a smaller one. The operation 5 − 7 needs a borrow, so CF = 1. The result is FEh: 254 unsigned, −2 signed. Because the most significant bit of the result is 1, SF = 1. Since −2 fits in eight bits, there is no overflow: OF = 0. The low nibble also borrows in 5 − 7, so AF = 1. FEh = 1111 1110b contains seven 1 bits; PF = 0.

The fourth and fifth rows are the really interesting cases. In these two rows the signed and the unsigned interpretation give different answers (Figures 7.6 and 7.7).

AL0111 11117Fhunsigned 127 · signed 127BL1000 000080hunsigned 128 · signed -128AL−BL1111 1111FFhthe result is not stored, only the flagsCF=1ZF=0SF=1OF=1PF=1AF=0unsigned: AL < BLsigned: AL > BLCF=1, ZF=0 → JB takenSF=1, OF=1, ZF=0 → JG taken
Figure 7.6: CMP 7Fh, 80h: in the unsigned view 127 < 128 (CF = 1, JB is taken); in the signed view 127 − (−128) = 255 does not fit in eight bits, so OF = 1, and since SF = OF, JG is taken.

In the operation 7Fh − 80h, the unsigned interpretation is 127 − 128; a borrow is taken and CF = 1. The signed interpretation is 127 − (−128) = +255. This value does not fit in the range −128…127, so OF = 1. The eight-bit result is FFh, and since its most significant bit is 1, SF = 1. SF alone would say “the result is negative, so AL is smaller”; that is wrong. The correct decision is made by reading SF and OF together.

AL1111 1011FBhunsigned 251 · signed -5BL0000 001103hunsigned 3 · signed 3AL−BL1111 1000F8hthe result is not stored, only the flagsCF=0ZF=0SF=1OF=0PF=0AF=0unsigned: AL > BLsigned: AL < BLCF=0, ZF=0 → JA takenSF=1, OF=0, ZF=0 → JL taken
Figure 7.7: CMP FBh, 03h: FBh is 251 unsigned and −5 signed. In the unsigned view 251 > 3 (CF = 0, JA is taken); in the signed view −5 < 3 (SF ≠ OF, JL is taken). The same bits lead to different decisions.

In the operation FBh − 03h = F8h there is no borrow; CF = 0. In the unsigned interpretation 251 > 3. In the signed interpretation −5 − 3 = −8. −8 fits in eight bits (F8h) and there is no overflow: OF = 0. The result is negative: SF = 1. Since SF ≠ OF, AL is smaller in the signed interpretation. The same CMP gives two opposite decisions depending on the type of the data. The processor cannot know which decision is the right one; the programmer says so by choosing the appropriate jump instruction.

7.4.3Jumps for signed numbers

The jumps used for signed comparison are named after the English words for “greater” and “less”: Greater and Less. These names are used on the assumption that the numbers are signed, in two's complement representation. Table 7.9 gives this family with its conditions.

Table 7.9: Conditional jumps for signed numbers (after CMP A, B).
InstructionMeaningConditionOpposite
JE, JZA = BZF = 1JNE, JNZ
JNE, JNZA ≠ BZF = 0JE, JZ
JG, JNLEA > B (greater)ZF = 0 and SF = OFJNG, JLE
JL, JNGEA < B (less)SF ≠ OFJNL, JGE
JGE, JNLA ≥ BSF = OFJNGE, JL
JLE, JNGA ≤ BZF = 1 or SF ≠ OFJNLE, JG

The conditions look confusing at a glance, but they all derive from one principle: in the signed interpretation, “A < B” is given by SF ≠ OF, and the rest follows. A ≥ B is the negation of A < B: SF = OF. A > B means “A ≥ B and A ≠ B”: SF = OF and ZF = 0. A ≤ B is the negation of A > B: ZF = 1 or SF ≠ OF. The synonyms are built with the same logic. JG is also written JNLE, meaning “not less or equal”.

7.4.4Why SF = OF?

In the processor, CMP A, B is computed as A − B. If there is no overflow, the sign of the result is correct: if A < B the difference is negative and SF = 1. If there is overflow (OF = 1), the difference did not fit in eight or sixteen bits. The sign bit of a result that does not fit comes out inverted. The reason is that signed numbers are arranged on a circle (Figure 7.8): a value that goes past one end of the range enters from the other end. Adding 1 to 127 gives −128; subtracting 1 from −128 gives 127.

negative: 80h … FFhpositive: 00h … 7Fh−1280127127 + 1 → −128: at the end of the range the value wraps to the other end and the sign bit comes out inverted (OF = 1)
Figure 7.8: The signed byte range is −128 to 127. On overflow the value wraps to the other end of the range and the sign bit comes out inverted (OF = 1).

The true sign is therefore the exclusive OR of SF and OF: true sign = SF XOR OF. With no overflow (OF = 0) the true sign is SF itself. With overflow (OF = 1) the true sign is the inverse of SF. When SF ≠ OF the XOR gives 1: the true difference is negative and A < B. When SF = OF the XOR gives 0: the true difference is not negative and A ≥ B.

Theorem 7.1 (Signed comparison)

After CMP A, B, if A and B are interpreted as signed numbers in two's complement representation, then A < B ⇔ SF ≠ OF and A ≥ B ⇔ SF = OF.

Justification. The true difference d = A − B lies in the range −255…+255 for eight bits. If d is in the range −128…127, the result is shown correctly, OF = 0, and SF = (d < 0). If d > 127, the result appears as d − 256, which is negative: SF = 1, OF = 1; the true difference is positive. If d < −128, the result appears as d + 256, which is positive or zero: SF = 0, OF = 1; the true difference is negative. In all three cases (d < 0) = SF XOR OF.

Table 7.10: SF and OF together give the right decision (8 bits).
ABA − B (8 bits)True differenceSFOFDecision
57FEh (−2)−210SF ≠ OF → 5 < 7
127 (7Fh)−128 (80h)FFh (−1)+255, does not fit11SF = OF → 127 > −128
−128 (80h)17Fh (+127)−129, does not fit01SF ≠ OF → −128 < 1
−5 (FBh)3F8h (−8)−810SF ≠ OF → −5 < 3

The second and third rows of the table involve overflow. In both, SF alone would give the wrong answer: in the second row it would say “negative, A is smaller”, and in the third row “positive, A is greater”. Evaluated together with OF, the decision is correct. In hardware this is very cheap: the condition circuit of JL is a single XOR gate. For JLE, the output of this XOR is ORed with ZF.

Common mistake

Writing “jump if less” as JS after a signed comparison. JS looks only at SF and decides wrongly when there is overflow: after MOV AL, 80h / CMP AL, 1, SF = 0 and JS is not taken, although −128 < 1. The correct instruction is JL; since SF ≠ OF (0 ≠ 1), it is taken.

7.4.5Jumps for unsigned numbers

The jumps used for unsigned comparison are named after the English words “above” and “below”: Above and Below. In the unsigned interpretation the decision is much simpler, because there is no notion of overflow. In the subtraction A − B, if A < B a borrow is taken and CF = 1. So the “below” test is directly the carry flag: JB ≡ JC.

Table 7.11: Conditional jumps for unsigned numbers (after CMP A, B).
InstructionMeaningConditionOpposite
JE, JZA = BZF = 1JNE, JNZ
JNE, JNZA ≠ BZF = 0JE, JZ
JA, JNBEA > B (above)CF = 0 and ZF = 0JNA, JBE
JB, JNAE, JCA < B (below)CF = 1JNB, JAE, JNC
JAE, JNB, JNCA ≥ BCF = 0JNAE, JB, JC
JBE, JNAA ≤ BCF = 1 or ZF = 1JNBE, JA

The condition of JA means “no borrow and the difference is not zero”; A is neither less than B nor equal to it. JBE is its opposite. JAE looks only at CF = 0; since no borrow is taken on equality either, “greater or equal” is satisfied automatically.

7.4.6Above/Below or Greater/Less?

For each of the six comparison relations there are two instructions: one unsigned, one signed. For equality and inequality the two families use the same instruction, because equality means the bits are identical and does not depend on interpretation. Table 7.12 gives this mapping at a glance.

Table 7.12: Choosing a jump by relation and data type.
ComparisonUnsigned (A/B)Signed (G/L)
A = BJE / JZJE / JZ
A ≠ BJNE / JNZJNE / JNZ
A > BJA / JNBEJG / JNLE
A ≥ BJAE / JNBJGE / JNL
A < BJB / JNAEJL / JNGE
A ≤ BJBE / JNAJLE / JNG

The type of the data decides the choice. Addresses, counters, array indices, lengths, and ASCII codes are unsigned; use the A/B family with them. Values that can be negative, such as a temperature, the difference between two measurements, or a change of position, are signed; use the G/L family with them. An easy mnemonic: Above / Below is unsigned, Greater / Less is signed. As long as the values stay in the range 0–127, the two families give the same result; the difference shows up only for values whose most significant bit is 1. That is why a wrong choice of family often goes unnoticed with small test data.

7.4.7Code trace: same bits, JA and JG

The program below shows JA and JG making different decisions after the same CMP. Its second half also checks that JG works correctly in a comparison with overflow. The registers CL, CH, and DL serve as flags: if a jump is not taken, the corresponding register becomes 1.

MOV  AL, 0FBh    ; 251 or -5
MOV  BL, 03h
CMP  AL, BL      ; FBh - 03h
JA   a1          ; unsigned: 251 > 3 ?
MOV  CL, 1       ; if JA failed
a1:  JG  g1      ; signed: -5 > 3 ?
MOV  CH, 1       ; JG not taken
g1:  MOV AL, 7Fh ; 127
CMP  AL, 80h     ; 127 - (-128)
JG   g2          ; SF = OF ?
MOV  DL, 1       ; if JG failed
g2:  RET

Note the spelling 0FBh in the source. A hexadecimal number that begins with a letter gets a 0 in front. If FBh were written, the assembler would take it for a name and report an error.

Table 7.13: Trace of the JA and JG program (CX and DX are 0000h at the start).
StepAddressInstructionCodeALCF ZF SF OFResult
10100hMOV AL, 0FBhB0 FBFBh0 0 0 0—
20102hMOV BL, 03hB3 03FBh0 0 0 0BL = 03h
30104hCMP AL, BL3A C3FBh0 0 1 0F8h, not stored
40106hJA a177 02FBh0 0 1 0taken → 010Ah
5010AhJG g17F 02FBh0 0 1 0not taken → 010Ch
6010ChMOV CH, 1B5 01FBh0 0 1 0CX = 0100h
7010EhMOV AL, 7FhB0 7F7Fh0 0 1 0—
80110hCMP AL, 80h3C 807Fh1 0 1 1FFh, not stored
90112hJG g27F 027Fh1 0 1 1taken → 0116h
100116hRETC37Fh1 0 1 1IP = 0000h

In the third step CMP computes FBh − 03h = F8h. There is no borrow (CF = 0), the result is not zero (ZF = 0), the most significant bit is 1 (SF = 1), and there is no overflow (OF = 0). In the fourth step JA finds the condition CF = 0 and ZF = 0 satisfied and jumps; in the unsigned interpretation 251 > 3. The line MOV CL, 1 is skipped and CL stays 0. In the fifth step JG looks at the same flags. ZF = 0, but SF = 1 and OF = 0; since SF ≠ OF, it is not taken. In the signed interpretation −5 > 3 is false. In the sixth step CH becomes 1 and CX = 0100h. The same CMP has led to two different decisions.

In the second half of the program AL is set to 7Fh = 127 and compared with 80h. 7Fh − 80h = FFh. In the unsigned interpretation 127 < 128 and a borrow is taken: CF = 1. In the signed interpretation 127 − (−128) = 255 does not fit: OF = 1. The sign bit of the result is SF = 1. PF = 1, because FFh contains eight 1 bits. In the ninth step JG finds ZF = 0 and SF = OF (1 = 1) satisfied and jumps. 127 > −128 is true. SF alone would have said “less”. DL stays 0. When the program ends, CL = 0, CH = 1, DL = 0: in the signed interpretation −5 is not greater than 3, while 127 is greater than −128.

AL7FhBL03hCH01hDL00hCF1ZF0SF1OF1AL = 127signed 127JG → taken
Figure 7.9: The ninth step of the JA and JG trace: after CMP AL, 80h, CF = 1, SF = 1, OF = 1. Since ZF = 0 and SF = OF, JG is taken.

7.4.8Code trace: CMP + JE and CMP + JA

In real programs there are two separate blocks for the two outcomes of a comparison. The two short fragments below are the simplest form of this pattern. The fragments contain no RET, because they are meant to be placed inside a program. Instead of operations, the blocks contain only comments.

mov ax, 5
mov bx, 5
cmp ax, bx
je  equal_message
jmp not_equal_message
equal_message:          ; if equal
  jmp end_program
not_equal_message:      ; if not equal
end_program:

When the assembler places this fragment from 0100h, cmp ax, bx stands at 0106h (3B C3), je at 0108h (74 02), jmp not_equal_message at 010Ah (EB 02), and jmp end_program at 010Ch (EB 00). The trace is short:

  1. mov ax, 5 and mov bx, 5: AX = BX = 0005h.
  2. cmp ax, bx: 5 − 5 = 0 → ZF = 1, CF = 0, SF = 0, OF = 0. PF = 1 (00h has zero 1 bits, and zero is even). AX does not change.
  3. je equal_message: since ZF = 1 it jumps; IP = 010Ch.
  4. The operations in the equal_message block are performed, and then jmp end_program jumps over the other block.

The JMP in the last step is critical. In assembly, blocks are separated only by labels; nothing tells the processor that a block has ended. Without jmp end_program, once the processor finished the equal block it would fall through to the next line, the not-equal block, and both blocks would execute. In this example both blocks are empty, so jmp end_program goes to the address right after itself and its code is EB 00: the displacement is zero. When the blocks are filled, the displacement grows by the length of the block. If the numbers were not equal, je would not be taken, and jmp not_equal_message would carry the flow to the not-equal block.

The second fragment builds the same pattern with the unsigned question “is it greater?”:

mov ax, 5
mov bx, 7
cmp ax, bx
ja  jump_above
jmp not_jump_above
jump_above:             ; if ax is greater
  jmp end_program
not_jump_above:         ; if ax is less/equal
end_program:

Here cmp ax, bx computes 5 − 7 = FFFEh, which is −2 in the signed interpretation. Since a borrow is taken, CF = 1; since the result is not zero, ZF = 0; since the most significant bit is 1, SF = 1. There is no overflow: OF = 0. In the low nibble 5 − 7 takes a borrow, so AF = 1. ja needs CF = 0 and ZF = 0; since CF = 1 it is not taken. jmp not_jump_above carries the flow to the “less or equal” block. Had jg been written instead of ja in the same code, the result would not change either: SF = 1, OF = 0, and since SF ≠ OF, JG would not be taken. Because both values are positive and small, the two families give the same answer.

7.4.9Code trace: compare and print

The program below compares two numbers. If they are equal it prints y on the screen, otherwise n. It prints the character with the DOS INT 21h service: when AH = 02h, DOS displays the character in DL. The structure of the program matters: the two branches only put a different value into DL and then merge at the common prt label. The printing code is not written twice.

org    100h
mov    al, 25         ; al = 25
mov    bl, 10         ; bl = 10
cmp    al, bl         ; compare al - bl
je     equal          ; jump if al = bl (zf = 1)
mov    dl, 'n'        ; al <> bl: print 'n'
jmp    prt            ; go to the print line
equal:
mov    dl, 'y'        ; al = bl: print 'y'
prt:
mov    ah, 2          ; DOS: print char in DL
int    21h
ret                   ; return to DOS
Table 7.14: Trace of the compare-and-print program.
StepAddressInstructionCodeAXDLZF CFScreen
10100hmov al, 25B0 190019h00h0 0
20102hmov bl, 10B3 0A0019h00h0 0
30104hcmp al, bl3A C30019h00h0 0
40106hje equal74 040019h00h0 0
50108hmov dl, 'n'B2 6E0019h6Eh0 0
6010Ahjmp prtEB 020019h6Eh0 0
7010Ehmov ah, 2B4 020219h6Eh0 0
80110hint 21hCD 21026Eh6Eh0 0n
90112hretC3026Eh6Eh0 0n

AL = 25 = 19h and BL = 10 = 0Ah are loaded. cmp al, bl computes 25 − 10 = 15 = 0Fh; ZF = 0. AF = 1 because the low nibble takes a borrow in 9 − A, and PF = 1 because 0Fh contains four 1 bits. je equal is not taken. mov dl, 'n' puts the ASCII code of the character 'n', 6Eh, into DL. jmp prt skips the 'y' line; its displacement is 2, because the skipped mov dl, 'y' is two bytes. The two branches merge at the prt label.

mov ah, 2 makes AH 02h; AX = 0219h. int 21h prints n on the screen. When returning from this service DOS also puts the character it printed into AL: AL = 6Eh, AX = 026Eh. The ret at the end of the program is required. Without it the processor would take the bytes after int 21h for instructions and keep executing them; those bytes are whatever happens to be in memory.

In this program mov dl, 'y' is never executed, but it still occupies memory. If the numbers were equal (for example with mov bl, 25), je equal would be taken, DL would be 79h ('y'), and jmp prt would never be executed. In comparison blocks, one branch is always the one that falls through, and the other is the one reached by the jump.

7.5Counterparts of high-level constructs

7.5.1The if/else pattern

The if (condition) A else B construct of a high-level language is built in assembly with two jumps. The first idea that comes to mind is to jump on the condition itself: if the condition is true, go to block A. But this reverses the order of the code; block B, which runs when the condition fails, has to be written right below the jump instruction. The tidier way is to jump on the opposite of the condition. If the condition fails, the jump skips over block A to block B. If the condition holds, no jump is made and the processor falls through into block A. This way the assembly code keeps the A–B order of the high-level code.

if (ax == bx) {
    ; block A
} else {
    ; block B
}
    cmp  ax, bx
    jne  not_eq       ; the OPPOSITE test
    ; block A
    jmp  after
not_eq:
    ; block B
after:

The pattern has two parts. The first is the jump on the opposite of the condition: JNE for ==, JGE or JAE for <, JLE or JBE for >. The second is the jmp after at the end of block A. If this jump is forgotten, the processor enters block B as well when block A ends. In an if construct with no else part the second jump is unnecessary; the opposite condition jumps straight to the end of the block.

Table 7.15: If conditions and the opposite jumps used to skip a block.
High-level conditionJump on unsigned dataJump on signed data
a == bJNEJNE
a != bJEJE
a < bJAEJGE
a <= bJAJG
a > bJBEJLE
a >= bJBJL

Compound conditions are built the same way. In an AND condition such as if (a >= -10 && a <= 10), each subcondition is tested with its own CMP and opposite jump. When one of the subconditions fails, execution jumps straight out of the block. In an OR condition, when one of the subconditions holds, execution jumps straight into the block. This is the machine-level counterpart of “short-circuit” evaluation in high-level languages: the rest of a condition whose outcome is already settled is never tested.

7.5.2The while, do-while, and for patterns

A loop is a jump made backward. In the while (condition) body construct the condition is tested before the body; if the condition is false from the start, the body never runs. In the assembly counterpart a label is placed at the top of the loop, the condition is tested with the opposite jump, and the end of the body jumps back to the top:

while (cx > 0) {     ; unsigned
    ; body
}
top:  cmp  cx, 0
      jbe  done       ; cx <= 0 → exit
      ; body
      jmp  top
done:

In the do { body } while (condition) construct the condition is tested after the body; the body runs at least once. Its counterpart is shorter, because a single conditional jump does both the test and the return:

top:  ; body
      cmp  cx, 0
      ja   top        ; if true, back to the top

This second form executes one fewer jump per iteration. The while form contains a conditional jump (not taken, 4 cycles) and a JMP (15 cycles) in every iteration. The do-while form contains only a conditional jump (taken, 16 cycles). That is why compilers usually turn a while loop into the form “test once first, then loop as a do-while”.

A counted loop such as for (i = n; i > 0; i--) is most naturally written on the 8086 with CX and the LOOP instruction. LOOP does the decrementing of CX, the comparison with zero, and the jump back in a single instruction. If the counter counts upward (for (i = 0; i < n; i++)), the counter is kept in another register. It is incremented with INC on each iteration and tested with CMP followed by JB or JNE.

7.5.3Code trace: if/else and while

The program below uses the two patterns one after the other. First the construct if (AX == BX) DX = 1; else DX = 2; executes. Then, with CX = 2, the loop while (CX > 0) { DX += CX; CX--; } runs.

MOV  AX, 12
MOV  BX, 30
CMP  AX, BX
JNE  not_eq      ; OPPOSITE test
MOV  DX, 1       ; block A: AX = BX
JMP  after
not_eq: MOV DX, 2 ; block B: AX ≠ BX
after: MOV CX, 2  ; while (CX > 0)
top: CMP CX, 0
JBE  done         ; CX ≤ 0 → exit
ADD  DX, CX      ; body
DEC  CX
JMP  top
done: RET
Table 7.16: Trace of the if/else and while program (AX = 000Ch and BX = 001Eh throughout).
StepAddressInstructionCodeCXDXZF CFDecision
1–20100hMOV AX, 12 / MOV BX, 30B8 0C 00 / BB 1E 000000h0000h0 0—
30106hCMP AX, BX3B C30000h0000h0 112 − 30: not equal, borrow
40108hJNE not_eq75 050000h0000h0 1taken → 010Fh
5010FhMOV DX, 2BA 02 000000h0002h0 1block B
60112hMOV CX, 2B9 02 000002h0002h0 1—
7–80115hCMP CX, 0 / JBE done83 F9 00 / 76 050002h0002h0 02 > 0: not taken
9–10011AhADD DX, CX / DEC CX03 D1 / 490001h0004h0 0body, iteration 1
11–13011DhJMP top / CMP / JBEEB F60001h0004h0 01 > 0: not taken
14–15011AhADD DX, CX / DEC CX—0000h0005h1 0body, iteration 2
16–18011DhJMP top / CMP / JBE—0000h0005h1 00 = 0: taken → 011Fh
19011FhRETC30000h0005h1 0IP = 0000h

In the third step CMP AX, BX computes 12 − 30 = −18; the 16-bit result is FFEEh. The result is not zero (ZF = 0), a borrow was taken (CF = 1), and the sign bit is 1 (SF = 1). In the fourth step JNE not_eq finds the opposite condition satisfied and jumps over block A. MOV DX, 1 and JMP after are not executed. In the fifth step block B makes DX = 2. Block B is the last block and falls straight into the after label; no JMP is needed on this path.

In the sixth step CX = 2 and the loop begins. CMP CX, 0 computes 2 − 0 = 2: CF = 0, ZF = 0. JBE done needs CF = 1 or ZF = 1; it is not taken and the body is entered. The body makes DX = 2 + 2 = 4 and CX = 1. JMP top returns to the top and the condition is tested again: 1 > 0, not taken. In the second iteration DX = 4 + 1 = 5 and CX = 0. In this iteration ZF = 1 because DEC CX made the result zero, but the decision is still made at the top. CMP CX, 0 computes 0 − 0 = 0: ZF = 1, CF = 0. JBE done is taken. The result is DX = 5: the 2 from block B, plus 2, plus 1.

The code of CMP CX, 0 is 83 F9 00. The opcode 83h compares a 16-bit operand with a sign-extended 8-bit constant, so the constant takes 1 byte instead of 2. The JMP top at the end of the loop is at 011Dh and is two bytes: displacement 0115h − 011Fh = −0Ah = F6h, code EB F6.

This loop is a while loop; the condition is tested before the body. Had it started with CX = 0, the body would never have run. The LOOP instruction, in contrast, tests the condition after the body; this is the important difference between the two constructs.

The first rows of Table 7.16 show CX = 0000h. The trace in the slides is made under the same assumption. In reality, when emu8086 loads a .COM program it puts the program's byte count into CX. This program is 32 bytes (0100h–011Fh), so in emu8086 the program starts with CX = 0020h. The result is not affected, because CX is written by MOV CX, 2 before it is first read. The general rule is: never rely on initial register values; load every register with a value before using it.

7.5.4Conditional jumps out of range

On the 8086, conditional jumps exist only in the short form: −128…+127 bytes relative to the next instruction. When one has to skip over a long if block or return to the top of a long loop, this range may not be enough (Figure 7.10).

Jcc range: −128 … +127next IPfar_away+200 bytesnear JMP: anywhere in the segment (±32 KB)
Figure 7.10: A conditional jump reaches between −128 and +127 bytes around the next IP. A target 200 bytes away lies outside this window; a near JMP, however, goes anywhere within the segment.

The solution is to invert the condition, hop over the next instruction with a short jump, and reach the far target with a near JMP:

; wrong: target too far
cmp al, 0
je  far_away        ; out of range!
; ... 200 bytes of code ...
far_away:
; right: opposite test + near JMP
cmp al, 0
jne cont            ; opposite test, short
jmp far_away        ; near JMP (E9)
cont:
; ... 200 bytes of code ...
far_away:

In the second version jne cont jumps forward only 3 bytes and fits the short range with ease. If AL = 0, JNE is not taken and the processor falls into the near JMP, which reaches anywhere in the segment. If AL ≠ 0, JNE passes over the JMP to the cont label. The behavior is the same as in the first version; only the instruction pair is 5 bytes instead of 2.

This transformation can be applied to any conditional jump, because every condition has an opposite, found by flipping the last bit of the opcode. Classic assemblers (MASM in 8086 mode, for instance) report a “relative jump out of range” error when they see an out-of-range Jcc and leave the transformation to the programmer. The emu8086 assembler, on the other hand, performs the same transformation itself and notes it with a warning. For example, a je far_away at 0102h with the target at 01CFh is encoded as 75 03 E9 C8 00: JNE +3 (hopping over the three bytes of the JMP) and JMP 01CFh (0107h + 00C8h = 01CFh). Whichever assembler is used, what happens at machine level is the same. The program is also 3 bytes longer than it looks in the source.

Common mistake

Trying to fix the range error by writing the synonym JZ in place of JE, or by writing JE SHORT. A synonym translates to the same machine code and has the same range. SHORT does not widen the range; it only forces the short form. A loop instruction such as LOOPE is no solution either: it too is 2 bytes with rel8, and it changes CX besides.

7.6Loop instructions

7.6.1The LOOP family

Counted loops are written so often that the 8086 offers separate instructions for them. All of these instructions use the CX register as the counter. That is why CX is called the count register. Table 7.17 summarizes the family.

Table 7.17: Loop instructions (all 2 bytes: opcode + rel8).
InstructionCodeOperation and jump condition
LOOPE2Decrement CX by 1; jump to the label if CX ≠ 0.
LOOPEE1Decrement CX by 1; jump if CX ≠ 0 and equal (ZF = 1).
LOOPZE1Same as LOOPE: jump if CX ≠ 0 and ZF = 1.
LOOPNEE0Decrement CX by 1; jump if CX ≠ 0 and not equal (ZF = 0).
LOOPNZE0Same as LOOPNE: jump if CX ≠ 0 and ZF = 0.
JCXZE3Jump to the label if CX = 0 (CX is not decremented).

The family has three common properties. First, the counter is always CX; no other register can be chosen. Second, the LOOP family does not change the flags when it decrements CX. Even when CX falls to zero, ZF is not raised. This is an important difference from the DEC CX instruction, which does the same job. Third, all of them are 2 bytes and use rel8; the loop body can reach back at most 128 bytes. If the body is longer, the loop is written with DEC CX, JZ, and a near JMP.

CX ← CX − 1CX ≠ 0 (+ ZF condition)?yesjump to the labelnonext instructionflags unchanged
Figure 7.11: The LOOP family first decrements CX by one. If CX is not zero (and, for LOOPE/LOOPNE, the ZF condition also holds), it jumps to the label; otherwise it moves on to the next instruction. The flags do not change.

7.6.2How LOOP works

In LOOP label the order of operations matters: CX is decremented first, and then tested for zero. LOOP therefore builds a do-while loop. The body executes at least once before reaching LOOP. In a loop that starts with CX = n, the body runs exactly n times: the jump back is taken with CX at n − 1, n − 2, …, 1, and the loop is left at 0.

      mov  cx, n
label:
      ; loop body
      loop label

In effect LOOP resembles the pair DEC CX and JNZ label, but it preserves the flags. LOOPE and LOOPNE keep the loop going only while one more condition is met. LOOPE (LOOPZ) jumps while CX ≠ 0 and ZF = 1; it continues as long as equal items are found and stops at the first difference. LOOPNE (LOOPNZ) jumps while CX ≠ 0 and ZF = 0; it continues as long as items are unequal and stops when the wanted value is found. These two instructions are designed for search loops of the form “at most n times, but earlier if the condition changes”. ZF is set by a CMP in the loop body.

mov cx, nlabel:loop bodyCX ← CX − 1CX ≠ 0 ?yesno → next instructionLOOPE: and ZF=1LOOPNE: and ZF=0
Figure 7.12: LOOP flowchart: the body executes, CX is decremented by one, and if CX is not zero control returns to the body; if it is zero, execution continues with the next instruction. For LOOPE and LOOPNE the ZF condition is also required to go back.

This order has a trap. If the loop is entered with CX = 0, the body runs once, and then LOOP decrements CX. 0 − 1 = FFFFh. Since CX is not zero, the jump back is taken. The loop continues until CX falls to zero again, and the body runs 65,536 times in all. If the iteration count is computed at run time and can be zero, this case must be prevented specifically. The remedy is called JCXZ.

Definition 7.6

A loop is the repetition of a group of instructions until a condition is met. In a counted loop the number of iterations is kept in a counter register; the LOOP family of the 8086 uses CX as the counter, decrements CX on every iteration, and leaves the loop when CX reaches zero.

7.6.3Code trace: LOOP

The simplest LOOP example is a loop with an empty body. The program shows only the effect of LOOP on CX.

org 100h
mov cx, 5      ; CX = repeat count
again:
; loop body
loop again     ; if CX ≠ 0 go to again
jmp quit       ; loop done: go to quit
quit:
ret

mov cx, 5 is three bytes at 0100h (B9 05 00). The again label points to 0103h. Since the body is empty, loop again is also at 0103h; its code is E2 FE. The displacement FEh = −2: the LOOP instruction jumps to itself. jmp quit is at 0105h and its code is EB 00, because quit is the next line anyway.

Table 7.18: Trace of the LOOP example.
IterationInstructionCX (after)DecisionIP (after)
—mov cx, 50005h—0103h
1loop again0004h≠ 0, taken0103h
2loop again0003h≠ 0, taken0103h
3loop again0002h≠ 0, taken0103h
4loop again0001h≠ 0, taken0103h
5loop again0000h= 0, exits0105h
—jmp quit0000h—0107h
—ret0000h—0000h

The body (empty here) runs five times and LOOP is executed five times. The first four LOOPs jump and the fifth does not. The duration of the loop can be computed from Table 7.4: 4 × 17 + 5 = 73 clock cycles. When the program ends, CX = 0000h. The jmp quit after the loop is unnecessary but harmless; a jump with displacement 0 spends 15 cycles and flushes the queue.

7.6.4Code trace: nested loops

Since the counter of the LOOP family is a single register, two nested LOOPs share the same CX. The moment the inner loop loads its own count into CX, the outer loop's counter is lost. The solution is to push the outer counter onto the stack before the inner loop and pop it back after the inner loop. The program below uses this method. The outer loop runs 5 times; in each outer iteration the screen gets a 1, and then the inner loop prints five 2 characters. BX holds the total number of steps.

org 100h
mov bx, 0      ; total steps
mov cx, 5      ; outer counter
k1:
 add bx, 1
 mov al, '1'
 mov ah, 0eh
 int 10h       ; print '1'
 push cx       ; save outer
 mov cx, 5     ; inner counter
k2:
  add bx, 1
  mov al, '2'
  mov ah, 0eh
  int 10h      ; print '2'
  loop k2      ; inner loop
 pop cx        ; restore outer
loop k1        ; outer loop
ret

The characters are printed with the BIOS INT 10h service. When AH = 0Eh, BIOS writes the character in AL at the cursor position and advances the cursor; this service is called teletype output. The service uses BH as the page number. Since BX does not exceed 256 in this program, BH is always 0 and the output goes to page 0.

Table 7.19: Trace of the nested loops (selected steps).
StepInstructionBXCXSPStackScreen
startmov bx, 0 / mov cx, 50000h0005hFFFEh[FFFEh] = 0000h
outer 1add bx, 1 … int 10h0001h0005hFFFEh[FFFEh] = 0000h1
outer 1push cx0001h0005hFFFCh[FFFCh] = 0005h1
inner 1mov cx, 5 … int 10h0002h0005hFFFCh[FFFCh] = 0005h12
inner 1loop k20002h0004hFFFCh[FFFCh] = 0005h12
inner 5loop k2 (exits)0006h0000hFFFCh[FFFCh] = 0005h122222
outer 1pop cx0006h0005hFFFEh[FFFEh] = 0000h122222
outer 1loop k10006h0004hFFFEh[FFFEh] = 0000h122222
end of outer 2loop k1000Ch0003hFFFEh[FFFEh] = 0000h122222 ×2
end of outer 3loop k10012h0002hFFFEh[FFFEh] = 0000h122222 ×3
end of outer 4loop k10018h0001hFFFEh[FFFEh] = 0000h122222 ×4
end of outer 5loop k1 (exits)001Eh0000hFFFEh[FFFEh] = 0000h122222 ×5
endret001Eh0000h0000hempty122222 ×5

When the program starts, SP = FFFEh and the top of the stack holds the return address 0000h that DOS put there. In the first outer iteration BX = 1 and 1 is printed on the screen. AL = '1' = 31h and AH = 0Eh. push cx pushes the value of the outer counter, 5, onto the stack. SP decreases by two to FFFCh; [FFFCh] = 0005h. In little-endian order, FFFCh holds the byte 05h and FFFDh holds 00h.

The inner loop sets CX to 5 again. The value of the outer counter now lives only on the stack. The inner loop runs five times, incrementing BX and printing a 2 on each pass. The LOOP of the fifth inner iteration brings CX to zero and leaves the loop. At this point BX = 6 and CX = 0. pop cx restores the 0005h on the stack into CX, and SP = FFFEh. loop k1 makes CX 4 and returns to the top of the outer loop.

Each outer iteration adds 1 + 5 = 6 to BX. After five iterations BX = 30 = 001Eh. The screen shows 122222 five times, 30 characters in all. The last LOOP brings CX to zero and the loop is left. Because the numbers of push and pop are equal, the stack is back in its initial state. ret takes the 0000h on top of the stack into IP, SP = 0000h, and the program ends.

The inner loop's loop k2 is at 011Ch and its code is E2 F5: next address 011Eh, target k2 = 0113h, displacement −0Bh = F5h. The outer loop's loop k1 is at 011Fh and its code is E2 E5: next address 0121h, target k1 = 0106h, displacement −1Bh = E5h. The body of the outer loop is 27 bytes, still far from the rel8 limit (128).

Common mistake

Forgetting the push cx / pop cx pair in a nested loop. When the inner loop ends, CX = 0. The outer loop's LOOP decrements this zero to FFFFh, and the outer loop runs tens of thousands of times instead of 5. Writing only one of the pair is even worse. The stack balance is broken, and the ret at the end of the program takes a wrong value for the return address.

7.6.5Code trace: searching with LOOPNE

LOOPNE is made to order for searching a value in an array. The loop ends in one of two cases: when the value is found (ZF = 1), or when all elements have been examined (CX = 0). The program below searches for the value 3 in a five-element array.

org 100h
mov cx, 5          ; element count
mov si, -1         ; first inc makes it 0
scan:
inc si             ; next element
cmp arr[si], 3     ; is it 3?
loopne scan        ; go on if CX≠0, ZF=0
jne notfound       ; ZF=0 → not found
mov al, 1          ; found, position in SI
ret
notfound:
mov al, 0          ; not found
ret
arr db 7, 1, 3, 9, 4

Initializing SI to −1 (FFFFh) is a subtlety. The first instruction of the loop is inc si, which makes SI 0. SI thus points at the index of the element being examined on every pass, and when the loop is left it carries the position of the element found. The instruction cmp arr[si], 3 is 5 bytes (80 BC 16 01 03): opcode, ModR/M, the 16-bit address of the array (0116h), and the constant. Because the array is defined with DB, the comparison is byte-sized.

Table 7.20: Trace of the search with LOOPNE (arr = 7, 1, 3, 9, 4; searching for 3).
IterationSIarr[SI]ZF CF SF after CMPCX after LOOPNEDecision
10000h70 0 00004hCX ≠ 0, ZF = 0 → continue
20001h10 1 10003hCX ≠ 0, ZF = 0 → continue
30002h31 0 00002hZF = 1 → exit
7[0]1[1]3[2]9[3]4[4]SI
Figure 7.13: In the third iteration SI = 2 and arr[2] = 3: the comparison sets ZF = 1, and LOOPNE leaves the loop.

In the first iteration inc si takes SI from FFFFh to 0000h. This increment gives a zero result and so sets ZF = 1, but the CMP that follows immediately sets the flags again. 7 − 3 = 4 is not zero: ZF = 0. LOOPNE makes CX 4; since CX ≠ 0 and ZF = 0, it continues the search. In the second iteration arr[1] = 1. For 1 − 3 = −2 (FEh) a borrow is taken; CF = 1 and SF = 1. ZF is 0 again and the loop continues.

In the third iteration arr[2] = 3, and 3 − 3 = 0 sets ZF = 1. LOOPNE decrements CX again, to 2. CX is not zero, but since ZF = 1 the jump is not taken and the loop is left. Because LOOPNE does not change the flags, ZF = 1 is preserved. The jne notfound after the loop looks at exactly this flag. Since ZF = 1 it is not taken, and mov al, 1 records the “found” result. SI = 2 is the position of the element found. The loop has ended after three iterations instead of five.

It matters why ZF is tested after the loop. The loop can end for two reasons, and looking at CX does not tell them apart: if the value is found at the last element, CX falls to zero too. The result of the last comparison, on the other hand, sits in ZF, and LOOPNE does not disturb it. If the array did not contain 3, after five iterations CX = 0 and ZF = 0; jne notfound would be taken and AL would be 0. This structure is a direct benefit of the LOOP family preserving the flags.

7.6.6JCXZ; LOOP mu, DEC–JNZ mi?

The JCXZ label instruction jumps if CX = 0; it neither decrements CX nor looks at the flags. Its main use is as protection against a zero-iteration loop. If the iteration count is computed at run time, a JCXZ is placed in front of the loop:

      mov  cx, n      ; n known at run time
      jcxz skip       ; skip if CX = 0
again:
      ; body
      loop again
skip:

Without JCXZ, with CX = 0 the LOOP first makes CX FFFFh and the body runs 65,536 times. With JCXZ, the loop is jumped over in this case. The instruction tests whether CX is zero without another instruction having to look at CX; a CMP CX, 0 that compares CX with zero would disturb the flags, while JCXZ does not.

A counted loop can also be written with the DEC and JNZ pair instead of LOOP. The differences between the two forms are collected in Table 7.21.

Table 7.21: Comparison of LOOP and DEC CX + JNZ.
FeatureLOOPDEC CX + JNZ
Size2 bytes1 + 2 = 3 bytes
FlagsunchangedZF, SF, OF, PF, AF change (CF is preserved)
CounterCX onlyany register
Extra conditionLOOPE / LOOPNEa different Jcc can be chosen
Timing on the 8086 (taken / not taken)17 / 5 cycles2 + 16 = 18 / 2 + 4 = 6 cycles

On the 8086, LOOP is both shorter and slightly faster. In a ten-iteration loop, LOOP spends 9 × 17 + 5 = 158 cycles with nine jumps and one exit. The DEC–JNZ pair spends 10 × 2 + 9 × 16 + 4 = 168 cycles. On the other hand DEC–JNZ is more flexible: a register other than CX can serve as the counter. This matters in loops that use CX for something else (for example as a shift count or the counter of a string instruction). On later x86 processors the LOOP instruction became slow and compilers stopped using it; for the 8086, however, the situation is the opposite.

The flag difference matters too. DEC sets the status flags other than CF according to the result. Information kept in CF throughout the loop (for example the carry of a multiword addition) is not affected by DEC. But information kept in ZF or SF is destroyed. LOOP touches no flag. In loops where the carry is carried from iteration to iteration, such as multiword addition, both forms preserve CF, so either can be used.

7.6.7Code trace: JCXZ guard and DEC–JNZ

The program below contains two loops. The first loop is run with n = 0, and JCXZ guards it. The second loop runs with n = 3 in the DEC–JNZ form and uses BX as the counter. Before the second loop CF is set to 1; we observe that CF is preserved throughout the loop.

MOV  CX, 0       ; n = 0
MOV  AX, 0
JCXZ skip         ; CX = 0 → skip
again: INC AX
LOOP again
skip: MOV BX, 3   ; n = 3, counter BX
STC              ; CF = 1
again2: INC AX
DEC  BX          ; CF is kept
JNZ  again2
RET
Table 7.22: Trace of the JCXZ and DEC–JNZ program.
StepInstructionAXBXCXZFCFDecision
1–2MOV CX, 0 / MOV AX, 00000h0000h0000h00—
3JCXZ skip (E3 03)0000h0000h0000h00CX = 0 → taken, 010Bh
4MOV BX, 30000h0003h0000h00—
5STC0000h0003h0000h01—
6–8INC AX / DEC BX / JNZ0001h0002h0000h01taken (iteration 1)
9–11INC AX / DEC BX / JNZ0002h0001h0000h01taken (iteration 2)
12–14INC AX / DEC BX / JNZ0003h0000h0000h11not taken (iteration 3)
15RET0003h0000h0000h11IP = 0000h

In the third step JCXZ sees that CX = 0 and jumps over the loop. INC AX and LOOP again are never executed; AX stays 0. Without the guard the body would run 65,536 times and AX would end up 0000h again (65,536 = 1 0000h does not fit in 16 bits). The result would look the same, but the processor would have gone around 65,536 times for nothing. Had the body modified a memory array instead of AX, the result would be a disaster.

In the second loop the counter is BX; LOOP could not do this. STC sets CF to 1. In each iteration INC AX and DEC BX set the flags, but neither touches CF. In the first iteration BX = 2 and ZF = 0, and JNZ jumps back. In the second iteration BX = 1. In the third iteration DEC BX makes BX 0 and ZF = 1. JNZ is not taken and the loop ends. In the end AX = 3 and CF = 1 is preserved. When INC AX makes AX 3 in the third iteration, PF = 1 (0000 0011b contains two 1 bits); this is set again by DEC. LOOP does not change flags either, but it works only with CX.

7.7Example programs

7.7.1Sum of array elements

Summing the elements of an array is the most typical use of a counted loop. The program below adds up a five-byte array and writes the result to the variable m. CX holds the element count, BX the index, and AL the sum.

org 100h
mov cx, 5             ; element count
mov al, 0             ; sum (AL) = 0
mov bx, 0             ; BX = index
next:
add al, vector[bx]    ; add element
inc bx                ; next element
loop next             ; until CX = 0
mov m, al             ; store in m
ret
vector db 5, 4, 5, 2, 1
m db 0

The data is defined after ret. Because the program ends with ret, the processor never reaches the data bytes and never mistakes them for instructions. When the assembler lays out the code, vector sits at 0113h and m at 0118h. The instruction add al, vector[bx] is 4 bytes (02 87 13 01): the ModR/M byte 87h selects the “[BX] + 16-bit displacement” form, and the displacement is the address of vector. loop next is at 010Dh; its code is E2 F9 and the displacement is 0108h − 010Fh = −7.

Table 7.23: Trace of the array sum (each row is the end of one iteration).
IterationAddedAL (decimal)ALBXCXLOOP
start—000h0000h0005h—
1vector[0] = 5505h0001h0004htaken
2vector[1] = 4909h0002h0003htaken
3vector[2] = 5140Eh0003h0002htaken
4vector[3] = 21610h0004h0001htaken
5vector[4] = 11711h0005h0000hexits
5[0]4[1]5[2]2[3]1[4]BX
Figure 7.14: The last iteration of the array sum: with BX = 4, vector[4] = 1 is added and AL = 11h.

Three instructions execute in each iteration. add al, vector[bx] adds the element to AL; the effective address is 0113h + BX and the segment is DS. inc bx increments the index by one, because the elements are single bytes. For a word array the index would advance by two. loop next decrements CX and returns to the top if it is not zero. After the fifth iteration CX = 0 and the loop is left. mov m, al writes the result to address 0118h: m = 11h = 17 = 5 + 4 + 5 + 2 + 1.

The ADD in the loop body sets the flags again on every iteration, but LOOP never reads or changes them. For example, in the fourth iteration the addition 0Eh + 02h = 10h produces a carry out of the low nibble and AF = 1. No instruction uses this information. The case where the sum does not fit in a byte is reported by CF. In this array the sum is 17, and CF is never 1 in any iteration. Had the elements been larger, AL could have overflowed; this case is examined in one of the exercises.

7.7.2Printing Hello on the screen

The program below prints a string marked with a terminating 0 byte on the screen, character by character. The number of iterations is not known in advance; the loop ends when it meets the 0 byte. That is why CMP, JE, and JMP are used instead of LOOP. This structure is a while loop: the condition is tested at the start of every iteration.

org     100h
jmp     start
msg     db 'Hello', 0
start:
mov     si, 0          ; source index = 0
next_char:
mov     al, msg[si]    ; get the char
cmp     al, 0          ; compare with 0
je      stop           ; stop if 0
mov     ah, 0eh        ; teletype function
int     10h            ; print char in AL
inc     si             ; next character
jmp     next_char      ; loop back
stop:
ret

In this program the data sits among the code. msg, right behind the first instruction of the program, holds the bytes 48h 65h 6Ch 6Ch 6Fh 00h starting at 0102h. The first instruction, jmp start (EB 06), jumps over these six bytes to 0108h. Without the JMP the processor would decode the byte 48h at 0102h as an instruction. 48h is the code of DEC AX; the bytes that follow would also be decoded like other instructions, and what the program does would be unpredictable.

Table 7.24: Trace of the Hello program (each row is the end of one iteration).
IterationSI (at start)AL = msg[SI]ZFje stopScreen
10000h48h 'H'0not takenH
20001h65h 'e'0not takenHe
30002h6Ch 'l'0not takenHel
40003h6Ch 'l'0not takenHell
50004h6Fh 'o'0not takenHello
60005h00h1takenHello

In each iteration mov al, msg[si] (8A 84 02 01) takes the next character into AL. cmp al, 0 (3C 00) compares it with zero. If the character is not zero, ZF = 0 and je stop is not taken. With AH = 0Eh and INT 10h the character is printed on the screen. inc si increments the index and jmp next_char (EB F1) returns to the top. This JMP is at 0118h; the displacement is 010Bh − 011Ah = −0Fh = F1h.

In the sixth iteration msg[5] = 0 is read. Since 0 − 0 = 0, ZF = 1 and je stop is taken. The screen shows Hello and SI = 5. ret ends the program. At the end of the program AX = 0E00h: AH keeps the 0Eh of the last iteration, and AL is the 00h read last.

'H'48h'e'65h'l'6Ch'l'6Ch'o'6Fh000hSI
Figure 7.15: The Hello string in memory: six bytes, the last one 00h. With SI = 5, the 0 byte that is read ends the loop.

A string marked at the end with zero is called a null-terminated string. In this scheme the length is not stored separately; the string continues up to the 0 byte. The C language uses the same scheme. The DOS INT 21h/09h service, on the other hand, uses a different marker: the end of the string is the '$' character. What the two schemes have in common is that the loop ends by a condition, not by a counter.

Each iteration of the program executes seven instructions, two of which are flow control instructions. A je not taken spends 4 clock cycles and a jmp taken spends 15. Had the loop been rewritten in do-while form (with the comparison and the conditional jump back at the end), each iteration would have one JMP fewer. For a short string the difference is negligible; for a very long text it makes up a significant part of the total time.

7.7.3Palindrome check: the idea

A palindrome is a sequence that reads the same from the front and from the back: 123321, kayak, ey edip adanada pide ye (if spaces are not counted). To tell whether a sequence is a palindrome, two pointers are used. DI points at the beginning of the sequence and SI at its end. At each step two characters are compared; then DI moves one forward and SI one back. If one of the pairs differs, the sequence is not a palindrome. If all the pairs match, it is a palindrome.

Comparisons up to half the length are enough. In a six-character sequence there are 3 pairs: (1st, 6th), (2nd, 5th), (3rd, 4th). More comparisons would just test the same pairs again in reverse order. With an odd length the middle character has no partner and is not compared; in 5 characters 2 pairs are tested. Halving is done with shr cx, 1: a one-bit right shift divides an unsigned number by 2 and discards the remainder.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6
Figure 7.16: The str array starts at 0102h in memory; DI moves from the front and SI from the back. After the string come the line end (0Dh, 0Ah) and '$'.

In the program the length of the string is a constant: str_size = $ - msg. Here $ is the assembler's location counter at that line, that is, the address right behind the string. The labels msg and str point to the same address; the difference is 6, the length of the string. The = directive defines a constant like EQU and takes no space in memory. If the string changes, the length updates by itself.

The program prints the string itself and the result with the DOS INT 21h/09h service. This service prints the string at DS:DX on the screen up to the '$' character; the '$' is not printed. The bytes 0Dh and 0Ah after the string are the carriage return and line feed characters. The result message is thereby printed one line below. The addresses in the figure assume org 100h and the two-byte short jmp start (at 0100h): str starts at 0102h.

7.7.4Palindrome: setup

org 100h
jmp start
msg:
str db '123321'
str_size = $ - msg     ; = 6
db 0Dh,0Ah,'$'
start:
mov ah, 9              ; print up to '$'
mov dx, offset str
int 21h
lea di, str            ; DI = address of str
mov si, di
add si, str_size       ; SI = last + 1
dec si                 ; SI = last char
mov cx, str_size
cmp cx, 1              ; one character?
je is_palindrome       ; one char is a palindrome
shr cx, 1              ; CX = length / 2

The jmp start (EB 09) at the beginning of the program skips nine bytes of data (six characters, 0Dh, 0Ah, '$') and goes to 010Bh. mov ah, 9 and mov dx, offset str prepare the DOS string output service: DX = 0102h. int 21h prints 123321 and the line end on the screen. DOS returns from this service with AL = 24h ('$'); AX = 0924h.

lea di, str loads into DI the address of str, 0102h. Here the effective address is a direct constant; emu8086 translates this instruction to the same 3-byte code as mov di, offset str (BF 02 01). mov si, di makes SI 0102h as well. add si, str_size adds 6: SI = 0108h. This is one past the last character of the string (the 0Dh byte). dec si brings SI to 0107h, the last character '1'. mov cx, str_size loads 6 into CX.

cmp cx, 1 and je is_palindrome are a shortcut for a one-character string. A one-character string is always a palindrome, but the real reason is a different one. With length 1, shr cx, 1 would make CX 0, and if the LOOP-based loop were entered with CX = 0, the comparison would run 65,536 times. Here CX = 6: 6 − 1 ≠ 0, ZF = 0, CF = 0; JE is not taken. shr cx, 1 shifts CX from 0110b to 0011b: CX = 3. The bit shifted out is 0, so CF = 0.

Table 7.25: Trace of the setup part of the palindrome program.
AddressInstructionCodeResult
0100hjmp startEB 09IP = 010Bh
010Bhmov ah, 9B4 09AH = 09h
010Dhmov dx, offset strBA 02 01DX = 0102h
0110hint 21hCD 21screen: 123321 ↵; AL = 24h
0112hlea di, strBF 02 01DI = 0102h
0115hmov si, di8B F7SI = 0102h
0117hadd si, str_size83 C6 06SI = 0108h
011Ahdec si4ESI = 0107h
011Bhmov cx, str_sizeB9 06 00CX = 0006h
011Ehcmp cx, 183 F9 01ZF = 0, CF = 0
0121hje is_palindrome74 0Enot taken
0123hshr cx, 1D1 E9CX = 0003h, CF = 0

7.7.5Palindrome: the comparison loop

next_char:
mov al, [di]          ; char at the start
mov bl, [si]          ; char at the end
cmp al, bl
jne not_palindrome    ; differ: not one
inc di                ; start: one forward
dec si                ; end: one back
loop next_char
is_palindrome:
mov ah, 9             ; print "palindrome!"
mov dx, offset msg1
int 21h
jmp stop
not_palindrome:
mov ah, 9             ; "not palindrome!"
mov dx, offset msg2
int 21h
stop:
ret
msg1 db "palindrome!$"
msg2 db "not palindrome!$"

The loop starts at 0125h with the label next_char. In each iteration mov al, [di] reads the character at the start and mov bl, [si] the character at the end. cmp al, bl compares the two. If they differ, jne not_palindrome leaves the loop at once. If they are equal, inc di and dec si bring the pointers closer together; loop next_char decrements CX and returns to the top.

Table 7.26: Trace of the palindrome comparison loop ('123321').
IterationDISIALBLZF after CMPDI, SI, ZF after INC/DECCX after LOOP
10102h0107h31h '1'31h '1'10103h, 0106h, 00002h
20103h0106h32h '2'32h '2'10104h, 0105h, 00001h
30104h0105h33h '3'33h '3'10105h, 0104h, 00000h

In every iteration CMP finds equality and sets ZF = 1; JNE is not taken. The inc di and dec si that follow set the flags too. Their results are not zero, so ZF becomes 0 again. This does not affect the correctness of the loop, because the decision was made at the JNE right behind CMP. The decision to loop belongs to LOOP, and LOOP looks only at CX. After the third iteration CX = 0 and the loop is left: all three pairs matched. At this point DI = 0105h and SI = 0104h; the pointers have crossed each other.

Leaving the loop, the processor falls through into the is_palindrome block. The DOS string output service is called with AH = 09h and DX = offset msg1. msg1 sits right after the code at 0142h, so DX = 0142h. palindrome! is printed on the screen and AL returns with 24h again. jmp stop (EB 07) jumps over the not_palindrome block, and ret ends the program.

The data comes right after the stop: label. Without ret, the processor would take the bytes of palindrome!$ for instructions and start executing them. The program is 94 bytes long (0100h–015Dh): msg1 takes 12 bytes and msg2 16.

'1'0102h'2'0103h'3'0104h'3'0105h'2'0106h'1'0107h0Dh0108h0Ah0109h'$'010AhDISIstr_size = 6
Figure 7.17: The comparison in the third iteration: DI = 0104h and SI = 0105h point at the two middle '3' characters.

7.7.6Palindrome: different inputs

Seeing how the program behaves on different inputs is the best way to find out whether the conditions it contains are necessary. Table 7.27 compares five inputs.

Table 7.27: Behavior of the palindrome program on different inputs.
strLengthCX (after shr)ComparisonsOutput
'123321'631=1, 2=2, 3=3palindrome!
'123421'631=1, 2=2, 3≠4 → jnenot palindrome!
'12321'521=1, 2=2 (the middle 3 is skipped)palindrome!
'7'1—cmp cx,1 → je is_palindromepalindrome!
'ab'21a≠b → jnenot palindrome!

In the second input, in the third iteration '3' is compared with '4'; ZF = 0 and jne not_palindrome leaves the loop. LOOP is never reached and CX stays at 1. In the third input the length is 5; shr divides 5 by 2 and discards the remainder 1 (CF = 1). Two pairs are compared, and the middle character is left alone. In the fourth input the cmp cx, 1 check proves useful: with length 1, shr cx, 1 would make CX 0 and the LOOP-based loop would run 65,536 times. Length 0 carries the same danger. For an empty string CX = 0, cmp cx, 1 finds no equality, and shr makes 0 into 0 again. This case can be prevented with a jcxz is_palindrome before the loop.

7.8Common mistakes

Most errors in flow control reduce to a few patterns. The list below collects these patterns and how to avoid them.

Common mistake

The wrong jump family. Using JA/JB on signed data or JG/JL on unsigned data. For AL = FBh and BL = 03h, JA is taken (251 > 3) and JG is not (−5 < 3). The error shows up only for values whose most significant bit is 1, and stays hidden with small test data. Remedy: decide the type of the data for each comparison and choose the family accordingly.

Common mistake

The forgotten JMP. In the if/else pattern, if the JMP after at the end of block A is not written, the processor enters block B as well when block A ends. Blocks are separated by labels; a label is not a wall, only an address.

Common mistake

A flag-changing instruction between CMP and the jump. In CMP AL, BL / INC SI / JE equal, the JE looks at the result of INC, not of CMP. If an instruction has to go in between, choose one that does not change flags (MOV, LEA, PUSH, POP), or move the CMP right in front of the jump.

Common mistake

LOOP with CX = 0. LOOP decrements first and tests afterward. A loop entered with CX = 0 runs 65,536 times. Remedy: if the iteration count is determined at run time, put a JCXZ in front of the loop.

Common mistake

Not saving CX in a nested loop. The inner loop's MOV CX, n wipes out the outer counter. Remedy: PUSH CX before the inner loop and POP CX after it; or use another counter register with DEC–JNZ in the outer loop.

Common mistake

Executing data as code. If the data lies in front of the code, the JMP start is forgotten; if it lies behind the code, the final RET is forgotten. In both cases the processor takes data bytes for instructions. The character 'H' (48h) executes as DEC AX; the bytes that follow turn into random instructions.

Common mistake

Fixing an out-of-range Jcc with a synonym. Writing JZ instead of JE or adding SHORT does not change the range. The right solution is a short jump on the opposite condition plus a near JMP.

Common mistake

Changing the counter inside the loop body. An instruction that changes CX in the body of a LOOP-based loop (for example DEC CX) corrupts the iteration count. In a loop that starts with CX = 3 and has DEC CX in its body, CX decreases by two per iteration. After LOOP, CX passes through odd values: 1, FFFFh, FFFDh, … Since CX never sees zero after LOOP, the loop never ends.

7.9Exercises and solutions

The exercises from the slides and their solutions follow. The solutions are given with their intermediate steps.

  1. A JNE instruction at address 0120h is to jump to address 0100h. What is its machine code?

    The opcode of JNE is 75h and the instruction is 2 bytes. Next IP = 0122h. Displacement = 0100h − 0122h = −22h. Two's complement of −22h: 22h = 0010 0010b, inverted 1101 1101b, plus 1: 1101 1110b = DEh. The code is 75 DE. Check: 0122h + FFDEh = 1 0100h → IP = 0100h.

  2. After mov al, 80h / cmp al, 1, are JA and JG taken?

    80h − 01h = 7Fh. There is no borrow (CF = 0) and the result is not zero (ZF = 0): JA is taken; in the unsigned interpretation 128 > 1. In the signed interpretation −128 − 1 = −129 does not fit in eight bits: OF = 1. The sign bit of the result is 0: SF = 0. Since SF ≠ OF, JG is not taken; −128 < 1. AF = 1 because 0 − 1 needs a borrow in the low nibble, and PF = 0 because 7Fh contains seven 1 bits.

  3. How many times does mov cx, 0 / d: loop d iterate? How is it prevented?

    LOOP first decrements CX: 0 − 1 = FFFFh ≠ 0, so it jumps back. It jumps at every value of CX from FFFFh down to 1 and exits at 0. LOOP is executed 65,536 times in total. To prevent this, the case CX = 0 is skipped with jcxz before the loop.

  4. Code that sets BX = 1 if the unsigned number in AX is greater than 100, otherwise BX = 0.

        mov  bx, 0
        cmp  ax, 100
        jbe  done       ; skip if AX <= 100 (unsigned)
        mov  bx, 1
    done:

    The opposite of the condition (≤) is taken from the unsigned family: JBE. Tried out, it gives BX = 0 for AX = 0, 99, and 100, and BX = 1 for AX = 101 and FFFFh (65,535). With JLE, FFFFh would count as signed −1 and BX would stay 0.

  5. In the array sum example, what would AL and CF be if the elements were 200 and 100? Propose a fix.

    200 + 100 = 300 = 12Ch. Only the low byte fits in AL: AL = 2Ch = 44. The ninth bit goes to CF: CF = 1 (carry). The result is wrong. The fix is to keep the sum in 16 bits. In the loop, adc ah, 0 is added after add al, vector[bx], and AX is cleared before the loop. ADC adds CF to AH along with 0; every carry moves into AH. With this fix AX = 012Ch = 300. Since LOOP does not change flags, it does not disturb the carry; but because ADD sets CF again on every iteration, ADC must stand right after ADD.

  6. What happens in the Hello example if the jmp start line is deleted?

    The program starts at 0100h, where the first byte of msg, 48h ('H'), now sits. The processor executes this byte as the instruction DEC AX. The bytes that follow, 65h, 6Ch, 6Ch, 6Fh, 00h, are also decoded and executed as instructions. The behavior of the program becomes unpredictable; Hello is not printed. The assembler does not catch this error, because the distinction between data and code exists only in the programmer's head.

7.10Summary

  • IP and the queue: the processor executes instructions in order from CS:IP; IP grows by the instruction length after each instruction. The BIU fetches the next bytes ahead of time into the six-byte prefetch queue. A jump flushes the queue; that is why a jump that is taken needs 15–19 clock cycles.
  • JMP is unconditional and does not change the flags. Its forms are short (EB rel8, −128…+127), near (E9 rel16, within the segment), far (EA ofs seg, CS:IP), and indirect (FF /4, register or memory).
  • Displacement = target − (instruction address + instruction length). A negative displacement is stored in two's complement; the processor sign-extends it and adds it to IP.
  • A label takes no space in memory; the assembler turns it into an offset. It cannot start with a digit, cannot contain spaces, and cannot be an instruction or register name.
  • Jcc looks at the flags and does not change them. On the 8086 all are 2 bytes (70h–7Fh + rel8); the last bit of the opcode inverts the condition. Synonyms assemble to the same code.
  • CMP is a SUB that does not store its result; the Jcc that follows makes the decision.
  • Unsigned comparison: JA, JAE, JB, JBE → CF and ZF. JB ≡ JC.
  • Signed comparison: JG, JGE, JL, JLE → ZF, SF, and OF. A < B ⇔ SF ≠ OF; because the sign bit comes out inverted on overflow, SF alone is not enough.
  • if/else: jump over block A on the opposite condition, and at the end of block A jump over block B with a JMP. while: the condition is tested at the top, and a JMP at the end of the body returns to the top.
  • Out-of-range Jcc: short jump on the opposite condition + near JMP. emu8086 makes this transformation itself.
  • The LOOP family: CX decrements, flags are preserved; LOOPE/LOOPNE also look at ZF; JCXZ jumps if CX = 0. All are 2 bytes with rel8.
  • Traps: LOOP with CX = 0 (65,536 iterations), not saving CX in a nested loop, a forgotten JMP, a flag-changing instruction between CMP and Jcc, executing data as code.

7.11Key terms

  • flow control
  • instruction pointer (IP)
  • prefetch queue
  • bus interface unit (BIU)
  • execution unit (EU)
  • jump
  • unconditional / conditional jump
  • short / near / far jump
  • jump displacement
  • relative addressing
  • label
  • offset
  • opcode
  • two's complement
  • sign extension
  • flag
  • zero flag (ZF)
  • carry flag (CF)
  • sign flag (SF)
  • overflow flag (OF)
  • parity flag (PF)
  • borrow
  • comparison (CMP)
  • signed / unsigned number
  • above / below (unsigned)
  • greater / less (signed)
  • loop
  • nested loop
  • count register
  • branch
  • stack
  • string
  • clock cycle
  • program segment prefix (PSP)

7.12Test Yourself

  1. A short JMP at address 0150h jumps to 0140h. What is its machine code? Which form would be used if the instruction were at 0300h?

    Answer

    Next IP = 0152h; displacement 0140h − 0152h = −12h → EEh. Code EB EE. From 0300h the displacement would be −1C2h (−450) and would not fit the short range. The near form is chosen: next IP 0303h, displacement FE3Dh, code E9 3D FE.

  2. With AX = 8000h and BX = 0001h, which flags does CMP AX, BX set? Are JB and JL taken?

    Answer

    8000h − 0001h = 7FFFh. CF = 0 (no borrow), ZF = 0, SF = 0 (the most significant bit of the result is 0), OF = 1 (signed −32,768 − 1 does not fit). JB is not taken: in the unsigned interpretation 32,768 > 1. JL is taken: SF ≠ OF, and in the signed interpretation −32,768 < 1.

  3. The opcode of JL is 7Ch. What is the opcode of its opposite? What code is needed to make a JL at 0108h jump back to 0100h?

    Answer

    The last bit changes: 7Dh, that is JGE (JNL). Backward jump: next IP = 010Ah, displacement 0100h − 010Ah = −0Ah = F6h; code 7C F6.

  4. A dec cx has been left in the body of the loop below by mistake. What is AX when the program ends if it starts with CX = 4? What happens if it starts with CX = 3?

        mov  cx, 4
        mov  ax, 0
    d:  inc  ax
        dec  cx
        loop d
    Answer

    CX = 4: in iteration 1, DEC gives 3 and LOOP 2 (taken); in iteration 2, DEC gives 1 and LOOP 0 (exits). AX = 2. CX = 3: in iteration 1, DEC gives 2 and LOOP 1 (taken); in iteration 2, DEC gives 0 and LOOP FFFFh (taken); after that CX always passes through odd values and is never 0 after LOOP. The loop is infinite.

  5. How can code that sets BL = 1 if the signed number in AL is negative and BL = 0 otherwise be written with CMP and a single conditional jump? Which jump should be chosen?

    Answer
        mov  bl, 0
        cmp  al, 0
        jge  done       ; skip if AL >= 0
        mov  bl, 1
    done:

    The opposite of the condition (AL ≥ 0) is taken from the signed family: JGE. For AL = 80h and FFh, BL = 1; for 00h, 05h, and 7Fh, BL = 0. Since a comparison with zero cannot overflow, JNS works correctly too.

  6. A ten-iteration loop is written with LOOP and with DEC CX + JNZ. How many clock cycles does the loop control alone take on the 8086?

    Answer

    LOOP: 9 jumps taken × 17 + 1 exit × 5 = 158 cycles. DEC CX + JNZ: 10 × 2 (DEC) + 9 × 16 + 1 × 4 = 168 cycles. On the 8086, LOOP is both 1 byte shorter and 10 cycles faster.

  7. The target of the je far_away instruction at 0102h is at 01CFh. How does emu8086 encode it? How many bytes in total?

    Answer

    The displacement 01CFh − 0104h = CBh = 203 > 127; the short form is not enough. The condition is inverted: 75 03 (JNE; if the condition holds it hops over the three bytes of the JMP) and E9 C8 00 (near JMP; next IP 0107h, 01CFh − 0107h = 00C8h). 5 bytes in total.

  8. If the array in the LOOPNE search example were 7, 1, 8, 9, 3, in how many iterations would the loop end? What are CX, ZF, and AL after the loop?

    Answer

    3 is the last element. In the fifth iteration CMP sets ZF = 1; LOOPNE takes CX from 1 to 0 and exits for both reasons. CX = 0 and ZF = 1. Since jne notfound looks at ZF, it is not taken and AL = 1, SI = 4. Had CX been checked, it would have been mistaken for “not found”.

7.13Further reading

  • B. B. Brey, The Intel Microprocessors (8th ed.), Chapter 6 (Program Control Instructions): the forms of JMP, conditional jumps, the LOOP family, and the assembly counterparts of high-level constructs; this is the closest source to this note.
  • Intel, The 8086 Family User's Manual (1979): the instruction encoding tables and clock cycle counts are first-hand here; the operation of the prefetch queue is also described.
  • K. R. Irvine, Assembly Language for x86 Processors (7th ed.), Chapter 6 (Conditional Processing): CMP, signed and unsigned jumps, compound conditions, and loop examples.
  • emu8086 documentation, 8086 assembler tutorial for beginners, Part 7 (Program Flow Control): the source of the examples in the slides; the out-of-range conditional jump trick is also explained here.

7.14References

  1. emu8086 documentation: 8086 Assembler Tutorial for Beginners (Part 7: Program Flow Control).
  2. Intel, The 8086 Family User's Manual, 1979: instruction set and encoding tables.
  3. Barry B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009: Chapter 6, “Program Control Instructions”.
  4. Kip R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014: conditional processing and loops.

Related pages: Chapter 7 slides · © Sercan Külcü. All rights reserved.