Microprocessors · Lecture Notes
Chapter 11: Instruction Encoding and String Instructions
Every line written in assembly language ends up as a few bytes. The processor sees only these bytes: it reads them from memory, puts them in the prefetch queue, decodes them, and executes them. This note first divides the 8086 instruction set into functional classes. It then shows, bit by bit, how an instruction is turned into machine code: prefix, opcode, the D and W bits, the ModR/M byte, displacement, and immediate value. The reverse of the same rules, recovering an instruction from bytes in memory, is worked step by step as well, and an example shows how decoding that starts at a wrong address turns the same bytes into completely different instructions. Next come the data-transfer instructions XLAT, LEA, LDS, and LES. The second half of the note is devoted to the string instructions: how MOVS, CMPS, SCAS, LODS, and STOS work together with SI, DI, CX, and the direction flag. The REP, REPE, and REPNE prefixes, overlapping blocks, and timings follow. The last sections cover the encoding of JMP, the processor-control instructions, and reference tables showing which instruction changes which flag. Every piece of code is traced together with the registers, flags, and memory.
Learning outcomes
- Recognizing instruction classes
- Divide the roughly one hundred instructions of the 8086 into the classes data transfer, arithmetic, logic and shift, string, control transfer, and processor control; explain the typical use of each class.
- Encoding instructions
- Find the opcode, the D and W bits, the ModR/M byte, the displacement, and the immediate value of an assembly instruction and write out its machine code byte by byte; recognize the short special forms and the prefixes.
- Decoding machine code
- Split a byte sequence in memory into instructions from the correct starting address; show why decoding that starts at a wrong address produces different instructions.
- Using address-loading instructions
- Translate through a table with XLAT; get an address with LEA and the contents with MOV; load a far pointer from memory into the segment and offset registers with LDS and LES.
- Tracing string instructions
- Use MOVS, CMPS, SCAS, LODS, and STOS with the REP, REPE, and REPNE prefixes; show how SI, DI, CX, ZF, and DF change at every step; choose the correct direction for overlapping blocks.
- Reading the reference tables
- Compute the encoding and the relative displacement of the JMP forms; explain how the processor-control instructions relate to processor pins; read from the flag-effects table which flags an instruction changes.
11.1Overview of the instruction set
11.1.1What is an instruction set?
The list of all the instructions a processor can execute is called its instruction set. The instruction set is the contract between the processor and the person who programs it. The programmer knows which instructions exist, which operands each accepts, and what each does to the registers, memory, and flags. There is no need to know how the circuits inside the processor are built. Two different processors that execute the same instruction set run the same program; that is why the 8086, the 8088, and the later x86 processors can run programs written for the 8086.
Depending on how they are counted, the 8086 instruction set has about a hundred instructions. The programmer writes them with mnemonics such as MOV, ADD, and JMP. A mnemonic is a name that is easy for a person to remember; the processor does not recognize it. The assembler converts every line to the numeric form the processor understands, the machine code. The same mnemonic can turn into many different machine codes depending on its operands. For example MOV uses separate codes for register to register, memory to register, immediate to memory, and moves to a segment register. So while the 8086 has about a hundred mnemonics, the number of distinct opcodes runs to a few hundred.
The instructions of the 8086 are of variable length. The shortest instruction is a single byte (NOP = 90h, INC AX = 40h). The longest reaches six bytes without prefixes (MOV WORD PTR [1234h], 5678h = C7 06 34 12 78 56). One or more prefix bytes can also be added in front. Variable length uses memory efficiently: frequently used instructions are kept short and rarely used ones long. The price is that the processor can tell where an instruction ends only by decoding its bytes in order.
11.1.2Six functional classes
The easiest way to memorize the instructions is to group them by what they do. Table 11.1 divides the 8086 instructions into six classes. The classes are not just a memory aid: instructions in the same class affect the flags in similar ways and are often encoded in similar ways. Data-transfer instructions do not touch the flags; arithmetic and logic instructions write the flags that describe the result; control-transfer instructions read the flags but do not change them.
| Class | What it does | Instructions |
|---|---|---|
| 1. Data transfer | copying data between registers, memory, the stack, and I/O | MOV PUSH POP XCHG IN OUT XLAT LEA LDS LES LAHF SAHF PUSHF POPF |
| 2. Arithmetic | the four operations, BCD adjustment, sign extension | ADD ADC INC AAA DAA SUB SBB DEC NEG CMP AAS DAS MUL IMUL AAM DIV IDIV AAD CBW CWD |
| 3. Logic, shift, rotate | bit-level operations | NOT AND OR XOR TEST SHL SAL SHR SAR ROL ROR RCL RCR |
| 4. String processing | scanning and copying memory blocks with SI and DI | MOVSB/W CMPSB/W SCASB/W LODSB/W STOSB/W; prefixes REP REPE REPZ REPNE REPNZ |
| 5. Control transfer | branches, loops, procedures, and interrupts | JMP, Jcc (JE JNE JA JB JG JL …), LOOP LOOPE LOOPNE JCXZ CALL RET RETF INT INTO IRET |
| 6. Processor control | setting and clearing flags, managing the processor state | CLC STC CMC CLD STD CLI STI HLT WAIT ESC LOCK NOP |
This note covers in detail the address-loading instructions of the first class (XLAT, LEA, LDS, LES), all of the fourth class, the encoding of JMP from the fifth class, and all of the sixth class. The flag effects of the arithmetic and logic instructions are given together in the reference tables at the end of the note. The encoding rules, on the other hand, are common to all the classes.
11.1.3How do instruction bytes reach the processor?
To understand why the encoding rules are what they are, we need to look at the path an instruction follows inside the processor. The inside of the 8086 is divided into two units. The bus interface unit (BIU) manages the external buses. It reads instruction bytes from the address pointed to by CS:IP and puts them in the six-byte prefetch queue. As soon as two bytes are free in the queue it starts a new read. Because the data bus of the 8086 is 16 bits wide, a read that starts at an even address brings two bytes in a single bus cycle.
The execution unit (EU) takes bytes from the head of the queue one at a time. If the first byte is a prefix, it records it in a latch and moves on to the next byte. The first real opcode byte determines the type of the instruction and how many bytes follow. If the opcode needs a ModR/M byte, the EU takes a second byte from the queue. The MOD field of ModR/M says whether the displacement is 0, 1, or 2 bytes. The W bit in the opcode and the type of the instruction also determine the length of the immediate value. Once the EU has taken these bytes it knows where the instruction ends; the next byte is the first byte of a new instruction.
This sequential decoding explains two important properties of machine code. First, the length of an instruction follows from its first byte or two; that is why the important information (opcode, D, W, MOD) always comes first. Second, the processor does not distinguish code from data. Whatever byte CS:IP points to is taken as an opcode. If control jumps to a wrong address, the same bytes are executed as completely different instructions. This subject is worked out with an example in the section on decoding machine code.
Machine code is the byte sequence of an instruction as stored in memory and executed directly by the processor. The instruction format defines the fields of this sequence and their order. Encoding is producing machine code from an assembly instruction; decoding is recovering the assembly instruction from machine code.
11.2Instruction format
11.2.1Fields
The general instruction format of the 8086 is shown in Figure 11.1. An instruction consists of at most five fields, and these fields always appear in the same order:
- Prefixes (optional): a segment prefix (26h, 2Eh, 36h, 3Eh), a repeat prefix (F3h, F2h), or LOCK (F0h). It changes the behavior of the instruction.
- Opcode byte (always present): says what the instruction does. In most two-operand instructions 6 bits of this byte carry the operation and the last two bits carry the D and W bits.
- ModR/M byte (if one of the operands can be a register or memory): selects the two operands with the MOD, REG, and R/M fields.
- Displacement (0, 1, or 2 bytes): a constant added to the memory address; the low byte comes first.
- Immediate (0, 1, or 2 bytes): a constant operand given inside the instruction; the low byte comes first.
Displacement and immediate bytes are always written in little-endian order: the low byte of a 16-bit number goes to the lower address and the high byte to the next address. MOV AX, 1234h is therefore encoded as B8 34 12. In an assembly line numbers are written in the order people read them; in memory and in machine-code listings they appear reversed. This reversal comes from the layout of the 16-bit data bus of the 8086. A byte at an even address travels on the low half of the data bus (D0–D7) and a byte at an odd address on the high half (D8–D15). When the low byte of a word sits at an even address it connects directly to the low half of the register.
11.2.2The D and W bits
In most two-operand instructions one operand is a register and the other a register or memory. The 8086 describes the two operands with a single ModR/M byte: the REG field selects the register, and the R/M field selects a register or a memory address. Two questions remain: is the operation on a byte or a word, and is the result written to REG or to R/M? The last two bits of the opcode byte answer these two questions.
The W bit (word, bit 0 of the opcode) selects the operand size: W = 0 means a byte (8-bit) operation, W = 1 a word (16-bit) operation. The same three bits in the REG field point to one of AL…BH when W = 0 and to one of AX…DI when W = 1.
The D bit (direction, bit 1 of the opcode) selects the direction: if D = 1 the REG field is the destination and the R/M field is the source; if D = 0 the REG field is the source and the R/M field is the destination.
The D bit has an interesting consequence in two-register instructions. In MOV AX, BX both operands are registers; which goes into the REG field and which into the R/M field is free. If D = 1 is chosen, the destination AX goes into the REG field and the source BX into the R/M field: 100010 1 1 = 8Bh, ModR/M = 11 000 011 = C3h. If D = 0 is chosen, the source BX goes into the REG field and the destination AX into the R/M field: 100010 0 1 = 89h, ModR/M = 11 011 000 = D8h. Table 11.2 puts the two encodings side by side, together with ADD AX, BX in the same situation.
| Instruction | D | Opcode | ModR/M (MOD REG R/M) | Machine code |
|---|---|---|---|---|
MOV AX, BX | 1 | 100010 1 1 = 8Bh | 11 000 (AX) 011 (BX) = C3h | 8B C3 |
MOV AX, BX | 0 | 100010 0 1 = 89h | 11 011 (BX) 000 (AX) = D8h | 89 D8 |
ADD AX, BX | 1 | 000000 1 1 = 03h | 11 000 (AX) 011 (BX) = C3h | 03 C3 |
ADD AX, BX | 0 | 000000 0 1 = 01h | 11 011 (BX) 000 (AX) = D8h | 01 D8 |
Both encodings are valid and the processor executes both in the same way: the result is written to AX and BX is unchanged. Which form is produced depends on the assembler: MASM usually produces the D = 1 form (8B C3, 03 C3), NASM the D = 0 form (89 D8, 01 D8). Both do the same job and have the same length. For this reason the same instruction can appear with two different codes in course material: that 01 D8 is written for ADD AX, BX when the 8086 architecture is explained and 03 C3 in assembler output is not a contradiction. When one of the operands is memory there is no choice. In MOV [BX], AL memory can be expressed only in the R/M field, so AL goes into the REG field and D = 0 is forced (88 07). In MOV AL, [BX] D = 1 (8A 07).
Reading the D bit as "the first operand" or "the left operand". The meaning of the D bit is tied to the REG field: D = 1 says that the register in REG is the destination. In the instruction line the destination is always on the left; but in machine code whether the destination is REG or R/M depends on D.
11.2.3The REG field
The middle three bits of the ModR/M byte are the REG field. Three bits are enough to select eight registers. Which eight registers are meant depends on the W bit. Table 11.3 gives these codes. The same table also contains the two-bit codes of the segment registers. Segment registers appear in only two instruction families (MOV starting with 8Ch and 8Eh, and PUSH and POP) and are written in the REG field with a leading 0.
| Kod | W = 0 (byte) | W = 1 (word) | Segment register |
|---|---|---|---|
000 | AL | AX | ES (00) |
001 | CL | CX | CS (01) |
010 | DL | DX | SS (10) |
011 | BL | BX | DS (11) |
100 | AH | SP | – |
101 | CH | BP | – |
110 | DH | SI | – |
111 | BH | DI | – |
The order has a logic. The first four codes give AX, CX, DX, BX and their low halves. The last four codes select SP, BP, SI, DI in a word operation and the high halves of the first four registers (AH, CH, DH, BH) in a byte operation. So code 100 means AH when W = 0 and SP when W = 1. Overlooking the W bit in decoding leads to mistaking AH for SP. These codes are not used only inside ModR/M. In the single-byte short forms too, the last three bits of the opcode carry the same register code: INC 40h + r, PUSH 50h + r, MOV r8, imm8 B0h + r, MOV r16, imm16 B8h + r. PUSH BX is therefore 50h + 3 = 53h, and MOV SI, 1000h is B8h + 6 = BEh followed by 00 10.
11.2.4The MOD field
The two leftmost bits of the ModR/M byte are the MOD field. MOD says how the R/M field is to be interpreted and how many bytes of displacement the instruction contains. Table 11.4 gives the four cases.
| MOD | Meaning | Displacement |
|---|---|---|
00 | memory operand, no displacement; the only exception is R/M = 110: 16-bit direct address | 0 bytes (2 bytes if R/M = 110) |
01 | memory operand + 8-bit displacement; d8 is sign-extended to 16 bits | 1 byte |
10 | memory operand + 16-bit displacement | 2 bytes |
11 | register operand: the R/M field is a register code as well | none |
The sign extension in the MOD = 01 case has a practical benefit. If the displacement is between −128 and +127 the assembler uses a single byte. In MOV AX, [BX+DI−2], −2 = FEh fits in one byte and the instruction takes three bytes as 8B 41 FE. The processor extends FEh to FFFEh and adds it to BX + DI; in 16-bit addition, adding FFFEh gives the same result as subtracting 2. If the displacement is outside this range MOD = 10 is chosen and two bytes are needed: MOV CL, [BX+SI+1234h] = 8A 88 34 12.
11.2.5The R/M field and the effective address
If MOD is not 11, the R/M field selects an addressing form. The processor computes the effective address (EA) according to this form. The effective address is the offset of the operand within the segment. The physical address is found by adding EA to the segment register multiplied by 16. Table 11.5 gives the eight R/M codes with the three MOD values and the default segment.
| R/M | MOD = 00 | MOD = 01 | MOD = 10 | Default segment |
|---|---|---|---|---|
000 | [BX+SI] | [BX+SI+d8] | [BX+SI+d16] | DS |
001 | [BX+DI] | [BX+DI+d8] | [BX+DI+d16] | DS |
010 | [BP+SI] | [BP+SI+d8] | [BP+SI+d16] | SS |
011 | [BP+DI] | [BP+DI+d8] | [BP+DI+d16] | SS |
100 | [SI] | [SI+d8] | [SI+d16] | DS |
101 | [DI] | [DI+d8] | [DI+d16] | DS |
110 | [d16] direct | [BP+d8] | [BP+d16] | DS / SS |
111 | [BX] | [BX+d8] | [BX+d16] | DS |
Three rules follow from the table. First, only BX, BP, SI, and DI can be address registers; a base register (BX or BP) and an index register (SI or DI) can be used together. There is no R/M code for [AX], [CX], [SI+DI], or [BX+BP], and the assembler treats them as errors. Second, every form that contains BP uses the stack segment (SS). BP is designed for reaching parameters and local variables in a stack frame. Third, the combination MOD = 00 and R/M = 110 is reserved not for [BP] but for the 16-bit direct address. When you write just [BP], the assembler therefore uses MOD = 01 and d8 = 0: MOV AL, [BP] is three bytes (8A 46 00), whereas MOV AL, [BX] is two bytes (8A 07).
Computing the effective address takes time, and this time is added to the time of the instruction. On the 8086 the microcode of the execution unit computes the EA step by step with the ALU; the time therefore varies with the addressing form. Table 11.6 gives the EA times from the Intel 8086 manual. The total time of an instruction with a memory operand is written as "base time + EA". For example MOV reg, mem takes 8 + EA clock cycles; for MOV CL, [BX+SI+12h] this is 8 + 11 = 19 cycles. On a 5 MHz 8086 one clock cycle is 200 ns, so the instruction takes about 3.8 µs.
| Addressing form | Example | EA time |
|---|---|---|
| base or index only | [BX], [SI], [DI] | 5 |
| displacement only (direct) | [1234h], var1 | 6 |
| base + index | [BP+DI], [BX+SI] / [BP+SI], [BX+DI] | 7 / 8 |
| displacement + base or index | [BX+4], [BP+2], array[SI] | 9 |
| displacement + base + index | [BP+DI+d], [BX+SI+d] / [BP+SI+d], [BX+DI+d] | 11 / 12 |
One more number matters for every word read from or written to memory. If the word is at an even address, the BIU moves it in a single bus cycle (4 clock cycles). If it is at an odd address, two separate byte cycles are needed and 4 cycles are added to the time. The 8086 selects the low byte lane with A0 = 0 for an even address and the high byte lane with BHE̅ = 0 for an odd address. Because the two bytes of a word at an odd address fall in different lanes and at different word addresses, two cycles are unavoidable. This is why the EVEN directive of the assembler is used to align word arrays to even addresses.
11.2.6Short special forms
The general format can encode every instruction but does not always give the shortest code. The designers of the 8086 set aside separate opcodes that need no ModR/M byte for the most frequently used operations. These short forms save one or two bytes and are sometimes faster. Table 11.7 collects the most important ones.
| Form | Opcode | Example | Kod | General form |
|---|---|---|---|---|
| INC / DEC r16 | 40h+r / 48h+r | INC AX | 40 | FF C0 (2 bytes) |
| PUSH / POP r16 | 50h+r / 58h+r | PUSH BX | 53 | FF F3 (2 bytes) |
| XCHG AX, r16 | 90h+r | XCHG AX, BX | 93 | 87 C3 (2 bytes) |
| MOV r8, imm8 | B0h+r | MOV AL, 5 | B0 05 | C6 C0 05 (3 bytes) |
| MOV r16, imm16 | B8h+r | MOV AX, 1234h | B8 34 12 | C7 C0 34 12 (4 bytes) |
| MOV AL/AX ↔ memory | A0h–A3h | MOV AX, [2000h] | A1 00 20 | 8B 06 00 20 (4 bytes) |
| ADD AL/AX, imm | 04h / 05h | ADD AL, 7 | 04 07 | 80 C0 07 (3 bytes) |
| ADD r/m16, imm8 (sign-extended) | 83h /0 | ADD BX, 5 | 83 C3 05 | 81 C3 05 00 (4 bytes) |
The 83h form in the last row shows another idea. The opcodes 80h, 81h, and 83h perform eight different arithmetic and logic instructions (ADD, OR, ADC, SBB, AND, SUB, XOR, CMP) with an immediate value. The REG field of ModR/M says which operation is performed, because these instructions have no second register operand. In manuals this is written 83 /0: the "/0" says that 000 goes into the REG field, that is the operation is ADD. For ADD BX, 5 ModR/M = 11 000 011 = C3h and a single byte 05 follows. The processor sign-extends 05h to 0005h and adds it to BX. The same "operation selector" layout exists in the FEh and FFh families: FF /4 is indirect near JMP, FF /6 is PUSH memory, FE /0 is byte INC. This layout reappears when the encoding of JMP is explained.
Assuming that an instruction has only one machine code. MOV AL, [1000h] can be encoded both as A0 00 10 (3 bytes) and as 8A 06 00 10 (4 bytes); both are correct. The assembler picks the short form. When encoding by hand, checking first whether a short form exists avoids confusion on exams and when comparing with listing output.
11.3Encoding step by step
11.3.1The encoding method
Encoding an assembly instruction by hand repeats on paper the job the assembler does. The work always proceeds in the same order:
- Choose the format. Look at the types of the operands: register–register, register–memory, immediate–register, immediate–memory. If a short special form exists (AL/AX with memory, a register with an immediate value, INC r16 …), use it; otherwise go to the general format.
- Write the opcode. Write the 6-bit code of the instruction family (100010 for MOV, 000000 for ADD). Then add the D and W bits. D is chosen by whether the register in the REG field is the destination; W by the operand size.
- Build the ModR/M byte. Write the code of the register operand into the REG field. If the other operand is a register, MOD = 11 and its code goes into R/M. If it is memory, R/M is chosen according to the addressing form and MOD = 00, 01, or 10 according to the size of the displacement.
- Add the displacement and the immediate. The displacement comes first, then the immediate; both are written low byte first.
- Put the prefixes in front. If a segment other than the default is used, a segment prefix; if a string instruction is repeated, the REP prefix; if the bus is locked, LOCK is added at the very front.
11.3.2Example: MOV CL, [BX+SI+12h]
This instruction copies the byte at address DS:(BX + SI + 12h) into CL. One operand is a register (CL) and the other is memory. There is no short form, because the short memory form exists only for AL and AX and only for a direct address. The general format is used: MOV reg, r/m. Figure 11.2 shows the three stages of the encoding.
MOV CL, [BX+SI+12h]. At the top the first byte (opcode 100010, D = 1, W = 0 → 8Ah), in the middle the ModR/M byte (MOD = 01, REG = 001, R/M = 000 → 48h), at the bottom the 8-bit displacement (12h) and the result.- Opcode. The MOV family between a register and r/m is 100010.
- D and W. The destination CL is a register and goes into the REG field; since REG is the destination, D = 1. CL is a byte register; W = 0. The first byte is 1000 1010b = 8Ah.
- REG. The code of CL is 001 in the W = 0 column.
- R/M and MOD. The R/M code of the form [BX+SI+d] is 000. The displacement 12h fits in the range −128…+127; MOD = 01 (8-bit displacement). ModR/M = 01 001 000b = 48h.
- Displacement. 12h is added as a single byte.
The result is 8A 48 12 and the instruction is three bytes. Had the displacement been a word such as 1234h, MOD = 10 would be chosen, ModR/M would be 10 001 000b = 88h, and the instruction would take four bytes as 8A 88 34 12. The time of the instruction is 8 + EA; since the EA time of the form [BX+SI+d] is 11 cycles, the total is 19 clock cycles. Most of this time goes to the address calculation and to the BIU fetching the byte from memory.
Let us encode MOV [SI+20h], CX. The source CX goes into the REG field and the destination memory is in R/M: since REG is the source, D = 0, and since it is a word operation, W = 1. The first byte is 100010 0 1 = 89h. REG = 001 (CX), R/M = 100 ([SI+d]), and since 20h fits in one byte, MOD = 01. ModR/M = 01 001 100b = 4Ch. The result is 89 4C 20.
By the same method, ADD BX, [1234h]: the ADD family is 000000, BX is the destination and is in REG, so D = 1, W = 1 → 03h. REG = 011 (BX). For a direct address MOD = 00, R/M = 110 → ModR/M = 00 011 110b = 1Eh. The address 34 12 follows: 03 1E 34 12.
11.3.3Example instructions and their lengths
Table 11.8 gives ten instructions of different lengths together with their machine codes. The table shows when all the fields of the instruction format appear: opcode only (1 byte), opcode and immediate, opcode and ModR/M, prefix and ModR/M, and ModR/M with displacement and immediate together.
| Instruction | Machine code | Bytes | Explanation |
|---|---|---|---|
NOP | 90 | 1 | actually XCHG AX, AX (90h + 0) |
INC AX / PUSH BX | 40 / 53 | 1 | register code inside the opcode (40h + r, 50h + r) |
MOV AL, 5 | B0 05 | 2 | B0h + r, immediate byte |
INT 21h | CD 21 | 2 | interrupt number inside the instruction |
MOV AX, 1234h | B8 34 12 | 3 | low byte first (little-endian) |
MOV CL, [BX+SI+12h] | 8A 48 12 | 3 | ModR/M + d8 |
MOV ES:[BX], AL | 26 88 07 | 3 | 26h = ES prefix |
ADD [BX+DI+1000h], DX | 01 91 00 10 | 4 | MOD = 10, d16 |
MOV WORD PTR [1234h], 5678h | C7 06 34 12 78 56 | 6 | longest unprefixed form: d16 + imm16 |
REP MOVSB | F3 A4 | 2 | F3h = REP prefix |
It is useful to open up a few rows. In ADD [BX+DI+1000h], DX the source DX is in the REG field (D = 0, W = 1 → 01h). ModR/M = 10 010 001b = 91h: MOD = 10 (16-bit displacement), REG = 010 (DX), R/M = 001 ([BX+DI+d]). The displacement 1000h is added in little-endian order as 00 10. This instruction both reads and writes memory: the BIU first reads the word, the ALU does the addition, and the BIU writes the result back to the same address. On the 8086 the time of this form is 16 + EA, that is 16 + 12 = 28 clock cycles.
In MOV WORD PTR [1234h], 5678h all the fields are present together. C7h is the word form of the "move immediate to r/m" family. ModR/M = 00 000 110b = 06h: the REG field here is not a register but an operation selector, and it is 000 for MOV; MOD = 00, R/M = 110 means a direct address. Then comes the address (34 12) and finally the immediate value (78 56). This instruction is six bytes, the greatest length an unprefixed 8086 instruction can reach. The WORD PTR in the assembly line is necessary; without it the assembler cannot tell whether 5678h is to be written as a byte or a word. In this example the word can be guessed because 5678h does not fit in a byte, but in a line like MOV [1234h], 5 the size is really ambiguous and an error is given.
11.3.4The encoding forms of MOV
MOV is the most frequently used instruction of the 8086 and hides eight separate encoding forms behind a single mnemonic. Table 11.9 gives these forms, the fields that follow, an example of each, and the timings from the Intel 8086 manual.
| Form | Opcode (8 / 16 bit) | Followed by | Example | Kod | Time |
|---|---|---|---|---|---|
| register → r/m | 88 / 89 | ModR/M (+ disp) | MOV [BX], AL | 88 07 | 2 (register), 9 + EA |
| r/m → register | 8A / 8B | ModR/M (+ disp) | MOV CX, [SI] | 8B 0C | 2 (register), 8 + EA |
| immediate → r/m | C6 / C7 | ModR/M (REG = 000) + disp + imm | MOV BYTE PTR [BX], 5 | C6 07 05 | 10 + EA |
| immediate → register | B0+r / B8+r | imm8 / imm16 | MOV SI, 1000h | BE 00 10 | 4 |
| memory → AL / AX | A0 / A1 | 16-bit address | MOV AX, [2000h] | A1 00 20 | 10 |
| AL / AX → memory | A2 / A3 | 16-bit address | MOV [1000h], AL | A2 00 10 | 10 |
| segment register → r/m16 | 8C | ModR/M (REG = sreg) | MOV AX, ES | 8C C0 | 2, 9 + EA |
| r/m16 → segment register | 8E | ModR/M (REG = sreg) | MOV DS, AX | 8E D8 | 2, 8 + EA |
The first two rows of the table are the D = 0 and D = 1 cases of the same family: the only difference between 88h/89h and 8Ah/8Bh is bit 1. In MOV CX, [SI] CX is the destination and is in REG: 8Bh; ModR/M = 00 001 100b = 0Ch. In MOV [BX], AL AL is the source: 88h; ModR/M = 00 000 111b = 07h. In the third row the REG field selects no register but means "000 = MOV"; since the second operand is an immediate value, REG is free. The short form A0h–A3h for moves between AL/AX and a direct address skips the ModR/M byte and saves one byte. The short form takes 10 cycles; the general form takes 8 + 6 = 14 for a read and 9 + 6 = 15 for a write.
11.3.5MOV with segment registers
Segment registers are kept apart from the general-purpose registers and are moved with only two MOV forms. 8Ch copies from a segment register to r/m16, and 8Eh from r/m16 to a segment register. In both forms the first bit of the REG field is 0 and the last two bits are the code of the segment register: ES = 00, CS = 01, SS = 10, DS = 11. Figure 11.3 opens up the second byte of MOV DS, AX: MOD = 11 (register), REG = 011 (DS), R/M = 000 (AX), that is 1101 1000b = D8h. The instruction is 8E D8.
MOV DS, AX = 8E D8. The REG field of the ModR/M byte holds 0 + the segment register code (DS = 11), and the R/M field holds the source register (AX = 000).Some forms do not exist at all. There is no opcode that writes an immediate value into a segment register; MOV DS, 1234h is invalid and the value is first loaded into a general register such as AX. There is no memory-to-memory MOV either, because the ModR/M byte can describe only one memory operand. A job that needs two memory operands is the special task of the string instructions (MOVS, CMPS). MOV CS, AX may look encodable but is not used: an instruction that changes CS without IP would make the program fetch its next instruction from a completely different segment. CS changes only, together with IP, through far JMP, far CALL, RETF, INT, and IRET. The 8086 has one more feature: after a MOV or POP that writes SS, no interrupt is accepted until the next instruction ends. This prevents an interrupt from slipping in between MOV SS, AX and the MOV SP, … that follows it and using a wrong stack.
MOV ES, DX: the 8Eh family, REG = 0 + 00 (ES) = 000, MOD = 11, R/M = 010 (DX). ModR/M = 11 000 010b = C2h. The instruction is 8E C2. The opposite MOV AX, ES is encoded with 8Ch and ModR/M = 11 000 000b = C0h: 8C C0.
11.3.6Direct address: MOD = 00, R/M = 110
The only irregularity in the R/M table is the combination MOD = 00 and R/M = 110. Had the table been regular, this combination would have meant [BP]. The designers of the 8086 reserved it for the 16-bit direct address, because reaching variables by name is far more common than [BP]. MOV [1000h], BL is therefore encoded like this:
| Byte | Bits | Meaning |
|---|---|---|
88h | 100010 0 0 | MOV r/m ↔ reg; D = 0 (REG is the source), W = 0 (byte) |
1Eh | 00 011 110 | MOD = 00, REG = 011 (BL), R/M = 110 → direct address |
00 10 | 0001 0000 0000 0000 | 16-bit address 1000h (low byte first) |
The instruction is four bytes and the segment is DS. For BL there is no short form like A2h; the short form is only for AL and AX. Had AL been written to the same address, the assembler would have produced A2 00 10 (3 bytes). 88 06 00 10, written in the general form, does the same job: ModR/M 06h = 00 000 110b, REG = 000 (AL). Table 11.11 compares these forms with [BP].
| Instruction | Kod | Explanation |
|---|---|---|
MOV [1000h], AL | A2 00 10 | short form for AL, 3 bytes |
MOV [1000h], AL | 88 06 00 10 | general form, 4 bytes (same job): ModR/M 06h = 00 000 110 |
MOV [1000h], BL | 88 1E 00 10 | no short form for BL |
MOV [BP], BL | 88 5E 00 | 5Eh = 01 011 110: [BP+d8], d8 = 0; segment SS |
This rule concerns not only the assembler but also the decoder. A decoder that sees the byte 1Eh must notice that MOD = 00 and R/M = 110 and read two address bytes after it. A decoder that forgets the rule takes 88 1E for a two-byte MOV [BP], BL. The address bytes then become the start of a new instruction: 00 10 is read as ADD [BX+SI], DL (00h = ADD r/m8, r8; 10h = 00 010 000b). All the instruction boundaries after that shift. This is a small example of the general problem treated in the next section.
11.3.7Prefix bytes
A prefix is not an instruction by itself; it changes the behavior of the instruction that follows. The 8086 has three kinds of prefix and Table 11.12 lists all of them.
| Prefix | Byte | Effect |
|---|---|---|
| ES: / CS: / SS: / DS: | 26 / 2E / 36 / 3E | changes the default segment of the memory operand (001ss110 pattern) |
| REP / REPE / REPZ | F3 | repeats the string instruction while CX ≠ 0 (and ZF = 1 for CMPS/SCAS) |
| REPNE / REPNZ | F2 | repeats the string instruction while CX ≠ 0 and ZF = 0 |
| LOCK | F0 | keeps the LOCK̅ pin active for the duration of the instruction; closes the bus to other processors |
The bit pattern of the segment prefixes is interesting: 26h = 001 00 110, 2Eh = 001 01 110, 36h = 001 10 110, 3Eh = 001 11 110. The middle two bits are the same segment register code used in the MOV forms. MOV AL, ES:[BX] is therefore encoded as 26 8A 07: the prefix, then the code of MOV AL, [BX] itself. The assembler does not produce an unnecessary prefix. If MOV AL, DS:[BX] is written, no prefix is added because DS is already the default segment, and the code stays 8A 07. MOV AL, DS:[BP], however, needs the prefix, because the default for BP is SS.
A prefix adds 2 clock cycles to the time of the instruction and takes one byte. Another cost shows up with interrupts. If an interrupt arrives while a string instruction with a REP prefix is being executed, the 8086 can abandon the work and go to the interrupt. To restart the instruction on return it pushes the address of the prefix onto the stack. However the 8086 remembers only the last prefix: if REP and a segment prefix are used together (such as REP ES: MOVSB), the earlier prefix is lost on return. For this reason no segment prefix is added to a REP string instruction in 8086 programs; if necessary, interrupts are disabled with CLI.
Let us decode the bytes 2E FF 27. 2Eh is the CS prefix. FFh is a family whose operation is selected by the REG field of ModR/M. 27h = 00 100 111b: MOD = 00, REG = 100 (/4: indirect near JMP), R/M = 111 ([BX]). The instruction is JMP WORD PTR CS:[BX]: IP is replaced by the word at address CS:[BX]. This prefix is needed when the jump table is kept in the code segment.
11.4Decoding machine code
11.4.1The decoding method
Decoding (disassembly) is the reverse of encoding: recovering assembly instructions from bytes in memory. Debuggers, the memory window of emu8086, and listing output do this job. Decoding by hand is a way to understand how a program sits in memory and to answer the "which instructions are these bytes?" question that is often asked on exams. The method imitates what the EU of the processor does:
- Know the starting point. Decoding must start at the first byte of an instruction. The start of the program (0100h for .COM) or a jump target is a reliable starting point.
- Classify the first byte. If the byte is a prefix (26h, 2Eh, 36h, 3Eh, F0h, F2h, F3h), note it and move on to the next byte. Otherwise find the instruction family from the opcode table.
- Is it a short form? For codes such as 40h–5Fh, 90h–97h, and B0h–BFh the register is inside the opcode; there is no ModR/M. The length of the immediate value that follows is known from the rule of the family.
- Open up the ModR/M. If the family needs ModR/M, the next byte is split into the MOD, REG, and R/M fields. The length of the displacement follows from MOD and R/M (do not forget the special case MOD = 00 and R/M = 110).
- Take the remaining bytes. The displacement and the immediate are read little-endian. The instruction ends here; the next byte is the first byte of a new instruction.
11.4.2Example: a twelve-byte fragment
Let the following twelve bytes, starting at 0100h in memory, be part of a program: 8B 4E 04 03 C3 A3 00 02 F3 AB EB FE. Decoding starts at 0100h. Table 11.13 gives the result; the steps are explained below.
| Address | Bytes | Decoding | Instruction |
|---|---|---|---|
| 0100h | 8B 4E 04 | 8Bh = 100010 1 1; 4Eh = 01 001 110 → MOD = 01, REG = CX, R/M = [BP+d8]; d8 = 04h | MOV CX, [BP+04h] |
| 0103h | 03 C3 | 03h = 000000 1 1 (ADD, D = 1, W = 1); C3h = 11 000 011 → AX ← AX + BX | ADD AX, BX |
| 0105h | A3 00 02 | A3h = AX → memory short form; address 0200h | MOV [0200h], AX |
| 0108h | F3 AB | F3h = REP prefix; ABh = STOSW | REP STOSW |
| 010Ah | EB FE | EBh = short JMP; FEh = −2 → target 010Ch − 2 = 010Ah | JMP 010Ah (to itself) |
The first byte 8Bh belongs to the MOV r/m ↔ reg family and carries D = 1, W = 1: the REG field is the 16-bit destination register. The second byte 4Eh = 0100 1110b, split into its fields, is 01 | 001 | 110. Since MOD = 01, one byte of displacement will follow. REG = 001 with W = 1 is CX. R/M = 110 with MOD = 01 means [BP+d8]; with MOD = 00 it would have been a direct address. The third byte 04h is the displacement. The instruction is MOV CX, [BP+04h], with segment SS. This form is the typical pattern for reading a procedure parameter from the stack.
The fourth byte 03h is the D = 1, W = 1 form of the ADD family. In the fifth byte C3h = 11 000 011b, MOD = 11, so both operands are registers: REG = AX (destination), R/M = BX. The instruction is ADD AX, BX. It was shown above that the same instruction can also be encoded as 01 D8; here we meet the D = 1 form. The sixth byte A3h is a short form that uses no ModR/M: it writes AX to a direct address. The next two bytes give the address: 00 02 → 0200h. The ninth byte F3h is a prefix; the instruction is completed by the next byte. ABh = 1010 101 1b is the W = 1 form of the STOS family. The instruction is REP STOSW and takes only two bytes. The last two bytes are EB FE. EBh is the short JMP and FEh is −2 as signed. The target is found by adding −2 to 010Ch, the address of the next instruction: 010Ah, that is the instruction itself. These two bytes are the endless loop that stops a program where it is.
The result: twelve bytes are five instructions. The lengths of the instructions are 3, 2, 3, 2, and 2 bytes, and each length was derived by looking only at the first byte or two. That the byte count comes out exactly at the end of decoding (0100h + 12 = 010Ch) is a check that the boundaries were found correctly.
11.4.3Decoding from a wrong offset
The first step of the decoding method was to know the starting point. An example shows why this step cannot be skipped. Let the following eleven bytes be in memory starting at offset 0000h: B4 02 B2 41 CD 21 B8 00 4C CD 21. Decoded from offset 0, these bytes are a familiar program that writes 'A' to the screen and ends the program:
MOV AH, 02h ; B4 02
MOV DL, 41h ; B2 41 ('A')
INT 21h ; CD 21 write character
MOV AX, 4C00h ; B8 00 4C
INT 21h ; CD 21 end the programB4h = B0h + 4 is MOV AH, imm8 and takes one immediate byte: 02h. B2h = B0h + 2 is MOV DL, imm8: 41h = 'A'. CDh is the INT instruction and takes the interrupt number from the byte that follows. B8h is MOV AX, imm16 and takes two bytes: 00 4C → 4C00h. The final CD 21 calls the DOS program-termination service with AH = 4Ch. The decoding is exactly the code the programmer wrote.
Now suppose IP slips by one byte; for example, a faulty jump goes to 0001h. The processor takes 02h as an opcode. Figure 11.4 shows the two decodings one above the other and Table 11.14 gives a byte-by-byte explanation of the second.
| Offset | Bytes | Decoding | Instruction |
|---|---|---|---|
| 0001h | 02 B2 41 CD | 02h = ADD r8, r/m8 (D = 1, W = 0); B2h = 10 110 010 → MOD = 10 (d16), REG = DH, R/M = [BP+SI]; d16 = CD41h | ADD DH, [BP+SI+CD41h] |
| 0005h | 21 B8 00 4C | 21h = AND r/m16, r16 (D = 0, W = 1); B8h = 10 111 000 → MOD = 10, REG = DI, R/M = [BX+SI]; d16 = 4C00h | AND [BX+SI+4C00h], DI |
| 0009h | CD 21 | INT 21h | INT 21h |
Decoding from offset 1 gives three instructions. The first takes B2h as ModR/M and, because MOD = 10, reads two bytes of displacement. The character 'A' (41h) and the opcode of INT (CDh) are thereby lost inside a number, CD41h. This instruction adds the byte at address SS:(BP + SI + CD41h) to DH; it only reads. The second instruction is more dangerous: 21h is an AND with D = 0 and writes its result to the r/m operand in memory. The word at DS:(BX + SI + 4C00h) is ANDed with DI and corrupted. At the final CD 21 the two decodings fall on the same boundary again; the decoding has resynchronized by itself. But this time AX = 4C00h was never loaded. INT 21h is called with whatever happens to be in AH, with an unpredictable result.
The example teaches two things. First, the meaning of the bytes is determined not by the bytes but by where IP starts. The same eleven bytes are a harmless "write A and exit" program from one start and a memory-corrupting instruction sequence from one byte further. Second, in x86 code decoding usually returns to the correct boundary by itself after a few instructions. This makes a wrong decoding hard to notice: after a few meaningless instructions everything looks proper again.
Let us decode the bytes 8A 1E 34 12 from offset 0. 8Ah = 100010 1 0 (D = 1, W = 0), 1Eh = 00 011 110 (MOD = 00, REG = BL, R/M = 110 → direct address). The instruction is MOV BL, [1234h]. If we start at offset 1, 1Eh is the one-byte PUSH DS (the segment PUSH of the form 06h + 8 × 3), and then 34 12 becomes the two-byte XOR AL, 12h. The four bytes this time give two separate instructions, and an unexpected word is pushed onto the stack.
11.4.4Code and data: the processor's view
On the 8086 there is no hardware that separates code from data. The code segment and the data segment are just numbers in segment registers, and in .COM programs all four segment registers point to the same segment. The program puts its data right behind its code. If a JMP lands in the data area by mistake, or if the return address on the stack is corrupted and RET returns there, the processor starts executing data bytes as instructions. A variable such as num db 3Ch, read as an opcode, becomes 3Ch = CMP AL, imm8 and swallows the following byte as an immediate value.
Disassemblers run into the same problem. A disassembler can guess which of the bytes in memory are code and which are data only by following the flow of the program. A listing file does not have this problem, because the assembler knows from the source what every line is. The most reliable way to inspect the machine code of a program is therefore to look at the listing the assembler produces. The .lst file created after compilation in emu8086 gives the address and the bytes of every line side by side.
Forgetting the RET or INT 21h/4Ch at the end of the program. When the code ends the processor does not stop; IP keeps advancing and executes the variables right behind it as instructions. The program then behaves meaninglessly or hangs. Defining the variables before the code and jumping over them with a JMP, or making sure that every exit path explicitly ends the program, prevents this mistake.
11.5Data-transfer instructions
11.5.1Overview
Data-transfer instructions copy a value from one place to another: from register to register, from memory to a register, to the stack, or to an I/O port. What these instructions have in common is that no calculation result passes through the ALU. They therefore do not change the flags. The two exceptions are SAHF and POPF, which are designed to write the flags directly. Table 11.15 summarizes the instructions of this class.
| Instruction | Operation | Example | Kod |
|---|---|---|---|
MOV h, k | d ← s (copy) | MOV BX, [SI] | 8B 1C |
PUSH k / POP h | SP ← SP − 2, [SS:SP] ← k / h ← [SS:SP], SP ← SP + 2 | PUSH AX | 50 |
XCHG a, b | a ↔ b (one must be a register) | XCHG AL, [BX] | 86 07 |
IN / OUT | AL/AX ↔ I/O port | IN AL, 60h | E4 60 |
XLAT | AL ← [DS:BX + AL] | table translation | D7 |
LEA r, m | r ← address of m (EA) | LEA SI, [BX+DI+4] | 8D 71 04 |
LDS / LES r, m | r ← [m], DS/ES ← [m + 2] (far pointer) | LES DI, far_ptr | C4 3E … |
LAHF / SAHF | AH ← low byte of FLAGS / the reverse | 9F / 9E | |
PUSHF / POPF | push FLAGS onto the stack / pop it from the stack | 9C / 9D |
The encoding forms of MOV were covered in detail above. The register forms of PUSH and POP are single bytes (50h + r, 58h + r); those of the segment registers are single bytes too (PUSH ES = 06h, PUSH CS = 0Eh, PUSH SS = 16h, PUSH DS = 1Eh). XCHG swaps two operands and removes the need for a temporary register; swapping AX with a register is a single byte of the form 90h + r. IN and OUT are the only instructions that reach the I/O address space. If the port number is 0–255 it is given inside the instruction as a constant (E4h, E5h, E6h, E7h); larger port numbers are given in DX (ECh, EDh, EEh, EFh). While these instructions execute, the M/IO̅ pin of the 8086 is pulled to 0 and the address bus selects an I/O port instead of memory.
LAHF (load AH from flags) copies the low byte of the flag register into AH. This byte contains SF (bit 7), ZF (bit 6), AF (bit 4), PF (bit 2), and CF (bit 0). SAHF does the reverse and writes these five bits in AH into the flags. The two instructions were included to ease the flag handling of programs ported from the 8080 processor. OF, DF, IF, and TF can be reached only as a group with PUSHF/POPF.
11.5.2XLAT: table translation
Many programs translate one value to another through a table: a hexadecimal digit to an ASCII character, a key code to a letter, a number to the bit pattern of a seven-segment display. The general way to do this is to put the value in an index register and read from the table. The 8086 has set aside a special one-byte instruction for this frequent job.
XLAT (translate) uses the value in AL as an index into a translation table: AL ← [DS:BX + AL]. BX holds the start address of the table; AL is added as an unsigned number (0–255). The table can be at most 256 bytes. The instruction is a single byte (D7h), does not change the flags, and takes 11 clock cycles.
The effective address calculation of XLAT fits none of the ordinary addressing forms: the 8-bit AL is added to the 16-bit BX. XLAT therefore has no ModR/M byte, and its operands are implicit. Some assemblers also accept the notation XLAT hex_tab or XLATB; the operand is only for documentation and does not change the code. The one difference is that a segment prefix is added if the operand is in another segment (XLAT ES:hex_tab). Putting the address of the table into BX is the programmer's job.
11.5.3Code trace: printing a byte in hexadecimal with XLAT
The following program writes a byte in memory to the screen as two hexadecimal digits. The byte is 3Ch; "3C" should appear on the screen. A byte is split into two halves (nibbles); each half is a number between 0 and 15 and is translated by XLAT into one of the characters '0'…'F'.
org 100h
mov bx, offset hex_tab
mov al, num ; AL = 3Ch
mov cl, 4
shr al, cl ; high nibble
xlat ; AL = [BX+AL]
mov dl, al
mov ah, 2
int 21h ; print DL
mov al, num
and al, 0Fh ; low nibble
xlat
mov dl, al
int 21h
ret
num db 3Ch
hex_tab db '0123456789ABCDEF'The program starts at 0100h. The total length of the instructions is 28 bytes; num therefore sits at 011Ch and hex_tab at 011Dh. Table 11.16 gives the state after each instruction.
| Address | Kod | Instruction | AL | AH | BX | CL | DL | Output |
|---|---|---|---|---|---|---|---|---|
| 0100h | BB 1D 01 | MOV BX, OFFSET hex_tab | 00h | 00h | 011Dh | 00h | 00h | |
| 0103h | A0 1C 01 | MOV AL, num | 3Ch | 00h | 011Dh | 00h | 00h | |
| 0106h | B1 04 | MOV CL, 4 | 3Ch | 00h | 011Dh | 04h | 00h | |
| 0108h | D2 E8 | SHR AL, CL | 03h | 00h | 011Dh | 04h | 00h | |
| 010Ah | D7 | XLAT | 33h ('3') | 00h | 011Dh | 04h | 00h | |
| 010Bh | 8A D0 | MOV DL, AL | 33h | 00h | 011Dh | 04h | 33h | |
| 010Dh | B4 02 | MOV AH, 2 | 33h | 02h | 011Dh | 04h | 33h | |
| 010Fh | CD 21 | INT 21h | 33h | 02h | 011Dh | 04h | 33h | 3 |
| 0111h | A0 1C 01 | MOV AL, num | 3Ch | 02h | 011Dh | 04h | 33h | 3 |
| 0114h | 24 0F | AND AL, 0Fh | 0Ch | 02h | 011Dh | 04h | 33h | 3 |
| 0116h | D7 | XLAT | 43h ('C') | 02h | 011Dh | 04h | 33h | 3 |
| 0117h | 8A D0 | MOV DL, AL | 43h | 02h | 011Dh | 04h | 43h | 3 |
| 0119h | CD 21 | INT 21h | 43h | 02h | 011Dh | 04h | 43h | 3C |
| 011Bh | C3 | RET | 43h | 02h | 011Dh | 04h | 43h | 3C |
The first line loads the offset of the table into BX: 011Dh. MOV AL, num uses the short form for AL (A0h) and reads the direct address 011Ch. Because on the 8086 a shift count greater than 1 can be given only in CL, 4 is put in CL. SHR AL, CL shifts 0011 1100b right by four bits: 0000 0011b = 03h. The last bit shifted out is 1, so CF = 1; because the shift count is greater than 1, OF is undefined. These flags do not affect the flow of the program.
The first XLAT uses AL = 03h as the index. The address read is DS:(011Dh + 03h) = DS:0120h; there sits the fourth character of the table, '3' (33h). AL is now 33h. It is copied to DL, 02h is put in AH, and INT 21h is called. DOS service 02h writes the character in DL and puts the same value in AL; a "3" appears on the screen.
In the second half the byte is read again and AND AL, 0Fh clears the upper nibble: 3Ch AND 0Fh = 0Ch. AND sets CF and OF to 0. The second XLAT reads DS:(011Dh + 0Ch) = DS:0129h; there is 'C' (43h). Since AH is still 02h it is not reloaded; INT 21h is called with DL = 43h and "3C" appears on the screen. RET ends the program through the INT 20h in the PSP.
The gain of XLAT in this program is clear. The same translation could also have been done with preparation like MOV SI, AX and an instruction such as MOV AL, hex_tab[SI]. But extending AL into a 16-bit index register costs extra instructions. XLAT does the job in one byte and 11 cycles. Another benefit of the table method is that it needs no comparison and branching: instead of the logic "if the digit is less than 10 add '0', otherwise add 'A' − 10", a single table read is enough.
With DS = 1000h, BX = 0200h, and AL = 05h, which physical address does XLAT read? The effective address is BX + AL = 0200h + 05h = 0205h. The physical address is 1000h × 10h + 0205h = 10000h + 0205h = 10205h. The byte at that address is loaded into AL; BX is unchanged.
Thinking that AH must be cleared before XLAT, or the opposite, forgetting to clear the extra bits in AL. XLAT uses only AL; it does not look at AH. But all eight bits of AL take part in the index. Had AND AL, 0Fh been forgotten in the program above, the index would have been 3Ch = 60 and a byte far beyond the table would have been read.
11.5.4LEA: address or contents?
A memory operand has two sides: its address and the contents at that address. MOV reads the contents. Sometimes only the address is needed: putting the start of a string into SI, or handing the address of an array element to a procedure. The 8086 offers a separate instruction for this.
LEA (load effective address) computes the effective address of the memory operand and writes it to the destination register: r16 ← EA. It does not access memory and does not change the flags. Its code is 8Dh + ModR/M; its time is 2 + EA clock cycles.
For a variable whose address is known at assembly time, LEA SI, msg and MOV SI, OFFSET msg give the same result. emu8086 therefore compiles LEA with a direct address to the same three-byte code as MOV r16, imm16: LEA BX, vals = BB 14 01. Real MASM compiles the same line to a four-byte code beginning with 8D 1E; the extra byte also shifts the addresses of the variables that follow. The real strength of LEA shows in operands whose address is computed from registers at run time. LEA SI, [BX+DI+4] makes SI = BX + DI + 4 with the current values of BX and DI (8D 71 04). The OFFSET operator cannot do this, because it is a constant whose value is computed at assembly time.
That LEA neither accesses memory nor changes flags also makes it an addition tool. LEA AX, [BX+SI] performs AX = BX + SI in a single instruction; BX and SI are unchanged and the flags are preserved. The same job with ADD needs two instructions (MOV AX, BX / ADD AX, SI) and disturbs the flags. This feature is useful when an address has to be incremented between a CMP and a conditional jump.
mov bx, 0010h
mov di, 0004h
lea ax, [bx+di+2] ; AX = 0016h (address)
mov ax, [bx+di+2] ; AX = [0016h] (contents)These two lines use the same operand and compute the same effective address (0010h + 0004h + 2 = 0016h). LEA writes this number to AX and stops. MOV, however, makes the BIU read a word from DS:0016h and writes the value read to AX. Their machine codes differ only in the opcode: 8D 41 02 and 8B 41 02.
11.5.5LDS and LES: the far pointer
An offset alone is not enough to specify a place in memory; a segment is needed too. A four-byte value that holds both the segment and the offset is called a far pointer. A far pointer is stored in memory in a fixed order: the offset first (low word), then the segment (high word). Each word is itself little-endian. A far pointer to address B800:0000 sits in memory as the bytes 00 00 00 B8.
LDS r16, m32 loads a far pointer from memory: r16 ← [m], DS ← [m + 2]. LES r16, m32 does the same with ES. The opcodes are C5h (LDS) and C4h (LES), followed by ModR/M; the second operand must be memory. The flags do not change; the time is 16 + EA clock cycles.
LDS and LES read two words in a single instruction. Doing the same with MOV needs two instructions: one loads the offset into a general register, the other the segment into a segment register. Their use together with the string instructions is especially common: LDS SI prepares the full address of the source and LES DI the full address of the destination in one instruction. The typical pattern for writing to an area outside the program's own segment, such as screen memory, is LES DI, screen followed by STOSB or STOSW.
Let the bytes of the variable far_ptr dd in memory be 34 12 00 B8. After LES DI, far_ptr the first word (34 12 → 1234h) is loaded into DI and the second word (00 B8 → B800h) into ES: DI = 1234h, ES = B800h. ES:DI now points to the physical address B8000h + 1234h = B9234h. Had the bytes been 00 20 00 10, LDS SI, … would make SI = 2000h and DS = 1000h, and DS:SI would point to 12000h.
11.5.6Code trace: LEA, MOV, and LES
The following program shows together the difference between LEA and MOV and the loading of a far pointer with LES. At the end the program writes 'A' to the top-left corner of the screen.
org 100h
lea bx, vals ; BX ← address
mov di, 2
lea ax, [bx+di+2] ; AX ← EA
mov ax, [bx+di+2] ; AX ← [EA]
les di, screen ; far pointer
mov al, 'A'
stosb ; ES:[DI] ← AL
ret
vals dw 1111h, 2222h, 3333h
screen dw 0000h, 0B800hThe lengths of the instructions are 3 + 3 + 3 + 3 + 4 + 2 + 1 + 1 = 20 bytes. Since the program starts at 0100h, vals sits at 0114h and screen at 0114h + 6 = 011Ah. Table 11.17 gives the trace, and Figure 11.5 shows that LEA and MOV take different things from the same EA.
| Address | Kod | Instruction | AX | BX | DI | ES | Memory |
|---|---|---|---|---|---|---|---|
| 0100h | BB 14 01 | LEA BX, vals | 0000h | 0114h | 0000h | 0700h | |
| 0103h | BF 02 00 | MOV DI, 2 | 0000h | 0114h | 0002h | 0700h | |
| 0106h | 8D 41 02 | LEA AX, [BX+DI+2] | 0118h | 0114h | 0002h | 0700h | not read |
| 0109h | 8B 41 02 | MOV AX, [BX+DI+2] | 3333h | 0114h | 0002h | 0700h | DS:0118h is read |
| 010Ch | C4 3E 1A 01 | LES DI, screen | 3333h | 0114h | 0000h | B800h | DS:011Ah–011Dh are read |
| 0110h | B0 41 | MOV AL, 'A' | 3341h | 0114h | 0000h | B800h | |
| 0112h | AA | STOSB | 3341h | 0114h | 0001h | B800h | [B8000h] ← 41h |
| 0113h | C3 | RET | 3341h | 0114h | 0001h | B800h |
The first instruction is compiled in emu8086 as the three-byte MOV BX, 0114h; BX = 0114h and memory is not read. After MOV DI, 2 the two instructions use the same operand. EA = BX + DI + 2 = 0114h + 0002h + 0002h = 0118h. LEA writes this number to AX. MOV, however, reads the word at DS:0118h: 3333h, the third element of vals. The difference in machine code is only in the opcode (8Dh and 8Bh); the ModR/M (41h = 01 000 001: [BX+DI+d8], REG = AX) and the displacement (02h) are the same.
The ModR/M byte of LES DI, screen is 3Eh = 00 111 110b: REG = 111 (DI), MOD = 00 and R/M = 110 (direct address 011Ah). The processor reads four bytes from DS:011Ah: 00 00 00 B8. The first word 0000h goes to DI and the second, B800h, to ES. At this point the previous value of DI (2) is lost. MOV AL, 'A' changes only AL; AH keeps the 33h left over from the earlier MOV and AX = 3341h. STOSB writes AL to address ES:DI. The physical address is B800h × 10h + 0000h = B8000h; this is the character cell at the top-left corner of the screen in text mode. Since DF = 0, DI is incremented by one.
Continuing to access the program's own variables after changing DS with LDS. After LDS SI, ptr DS points to another segment; an instruction such as MOV AL, counter now reads from the wrong segment. The fix is to save DS with PUSH DS before the LDS and restore it with POP DS when the work is done, or to prefer LES, which uses ES:DI for the destination.
11.6Arithmetic, logic, and shift instructions: summary
The arithmetic and logic instructions are a topic in their own right; here only their place in the instruction set and the common layout of their encodings are summarized. Table 11.18 gives the groups.
| Group | Instructions | Explanation |
|---|---|---|
| Addition | ADD ADC INC | ADC also adds the carry (CF); INC does not change CF |
| Subtraction | SUB SBB DEC NEG CMP | SBB also subtracts the borrow (CF); NEG = 0 − d; CMP does not write the result |
| Multiplication | MUL IMUL | unsigned / signed; implicit AL or AX |
| Division | DIV IDIV | unsigned / signed; quotient and remainder |
| BCD adjust | DAA DAS AAA AAS AAM AAD | corrects the binary result to decimal |
| Sign extension | CBW CWD | AL → AX, AX → DX:AX |
| Logic | AND OR XOR NOT TEST | clear, set, and complement bits; TEST does not write the result |
| Shift / rotate | SHL SAL SHR SAR ROL ROR RCL RCR | shift count 1 or CL; the bit shifted out goes to CF |
The eight two-operand arithmetic-logic instructions (ADD, OR, ADC, SBB, AND, SUB, XOR, CMP) share the same encoding pattern. Bits 5–3 of the opcode select the operation: ADD = 000, OR = 001, ADC = 010, SBB = 011, AND = 100, SUB = 101, XOR = 110, CMP = 111. The register–r/m forms follow the pattern 00ooo0dw: 00–03h for ADD, 28–2Bh for SUB, 38–3Bh for CMP. The forms with an immediate value are 80h, 81h, and 83h, and the same three-bit operation number is written into the REG field of ModR/M this time. Thus SUB BX, 5 = 83 EB 05 (11 101 011: REG = 101 = SUB) and CMP BX, 5 = 83 FB 05. Once this layout has been seen, the twenty-four forms of the eight instructions collapse into a single table.
The processor does addition and subtraction with a single adder circuit and does not know whether the number is signed or unsigned. It therefore produces flags for both interpretations: CF shows unsigned overflow and OF shows signed overflow. The programmer decides which flag is meaningful. Which flag each of these instructions changes, and how, is collected in the reference table at the end of the note.
11.7String instructions
11.7.1Why do string instructions exist?
Doing the same job over and over on bytes or words that lie consecutively in memory is very common in programs. Examples: copying a text from one place to another, comparing two passwords, searching a text for a character, filling the screen with blanks. These jobs can also be done with MOV, CMP, and INC. But several instructions are needed for each element: read from the source, write to the destination, increment the two addresses, decrement the counter, go back to the top of the loop. Moreover, because MOV cannot copy from memory to memory, every element passes through a temporary register.
For jobs of this kind the 8086 offers five string instructions. The operands of these instructions are implicit and are not written in the instruction. The source is always DS:SI and the destination always ES:DI. After doing its job the instruction advances SI and DI to the next element by itself. Each instruction is therefore a single byte and takes care of all the address work of a loop within itself. Used together with a repeat prefix, a single two-byte instruction can process a block of thousands of bytes.
A string instruction is an instruction that processes one byte (B version) or one word (W version) at the source pointed to by DS:SI and/or at the destination pointed to by ES:DI. When it finishes, it increments or decrements the index registers it used by 1 or 2 according to the direction flag. The segment of the source can be changed with a segment prefix; the destination is always in ES.
11.7.2The five string instructions
Table 11.19 gives the five string instructions, what they do, the registers they update, their flag effects, their opcodes, and their times when executed alone.
| Instruction | Operation | Updated | Flags | Kod | Time |
|---|---|---|---|---|---|
MOVSB / MOVSW | [ES:DI] ← [DS:SI] | SI, DI | – | A4 / A5 | 18 |
CMPSB / CMPSW | [DS:SI] − [ES:DI] | SI, DI | like CMP | A6 / A7 | 22 |
SCASB / SCASW | AL/AX − [ES:DI] | DI | like CMP | AE / AF | 15 |
LODSB / LODSW | AL/AX ← [DS:SI] | SI | – | AC / AD | 12 |
STOSB / STOSW | [ES:DI] ← AL/AX | DI | – | AA / AB | 11 |
It helps to divide the instructions into two groups. MOVS, LODS, and STOS move data and do not touch the flags. CMPS and SCAS compare: they perform a subtraction without writing the result anywhere and set the flags as CMP does. All the opcodes follow the pattern 1010 xxxw; the last bit is W and distinguishes the byte and word versions. That the codes are only a single byte also explains why string instructions are so frequently used: the prefetch queue can take several string instructions in one read.
From the hardware point of view, string instructions make heavy use of the BIU. MOVSB needs one memory-read and one memory-write bus cycle; each cycle takes at least four clock cycles. CMPSB does two reads, SCASB and LODSB one read each, and STOSB one write. MOVSW moves two bytes in the same two cycles at even addresses; copying large blocks with the word version is therefore about twice as fast. If the source or destination is at an odd address, every word is split into two byte cycles and this gain shrinks.
A note on syntax: MASM and emu8086 also accept the form with operands. When MOVS dst, src is written, the assembler produces MOVSB or MOVSW by looking at the type of the variables. If a segment prefix is written on the source operand (MOVS dst, ES:src), that prefix is added to the code. The operands only determine the size and the prefix; loading the addresses into SI and DI is still the programmer's job.
11.7.3The direction flag and the step
Whether a string instruction increments or decrements SI and DI is determined by the direction flag (DF). DF is bit 10 of the flag register and is a control flag: arithmetic instructions do not change it. It is set with two instructions:
CLD(clear direction flag, FCh): DF = 0. String instructions increment SI and DI; the operation proceeds from a low address to a higher one.STD(set direction flag, FDh): DF = 1. String instructions decrement SI and DI; the operation proceeds from a high address to a lower one.
The step size depends on the version of the instruction: ±1 for the B version and ±2 for the W version. The update is always made after the operation. Therefore, after a string instruction finishes, SI and DI point not to the last element processed but to the next one. When a search instruction finds a match, the address of the match is DI − 1 (byte, DF = 0).
Assuming the value of DF. DOS usually leaves DF at 0 when it starts a program, but another procedure, a library, or an interrupt handler may have set DF to 1. Every piece of code that uses string instructions must set the direction explicitly with CLD or STD before starting. A procedure that uses STD must also restore DF with CLD before returning.
The source and destination of string instructions can be in different segments. In .COM programs CS, DS, ES, and SS point to the same segment, and DS:SI and ES:DI look at the same memory. In .EXE programs DOS sets ES not to the program's data segment but to the PSP. In these programs ES must be set explicitly, like DS:
mov ax, @data
mov ds, ax
mov es, ax ; for the string destination11.7.4Code trace: copying with MOVSB
The following program copies the four-byte text 'ABCD' to a four-byte area filled with dots. The copy is done with a LOOP loop and a single MOVSB in each round, so that every execution of the instruction can be traced separately.
org 100h
cld
lea si, src ; DS:SI source
lea di, dst ; ES:DI destination
mov cx, 4
copy_lp:
movsb ; [DI]←[SI], SI++, DI++
loop copy_lp ; = rep movsb
ret
src db 'ABCD'
dst db 4 dup('.')The code is 14 bytes long: CLD (1), two LEAs (3 + 3), MOV CX (3), MOVSB (1), LOOP (2), RET (1). src therefore starts at 010Eh and dst at 0112h. The code of LOOP is E2 FD: FDh = −3, 3 back from the address of the next instruction 010Dh, that is the address of MOVSB, 010Ah.
| Step | Instruction | SI | DI | CX | dst | Explanation |
|---|---|---|---|---|---|---|
| 1 | CLD | 0000h | 0000h | 0000h | .... | DF = 0: forward |
| 2 | LEA SI, src | 010Eh | 0000h | 0000h | .... | BE 0E 01 |
| 3 | LEA DI, dst | 010Eh | 0112h | 0000h | .... | BF 12 01 |
| 4 | MOV CX, 4 | 010Eh | 0112h | 0004h | .... | counter |
| 5 | MOVSB | 010Fh | 0113h | 0004h | A... | [0112h] ← [010Eh] = 41h |
| 6 | LOOP copy_lp | 010Fh | 0113h | 0003h | A... | CX ≠ 0 → jump |
| 7 | MOVSB | 0110h | 0114h | 0003h | AB.. | [0113h] ← 42h |
| 8 | LOOP copy_lp | 0110h | 0114h | 0002h | AB.. | jump |
| 9 | MOVSB | 0111h | 0115h | 0002h | ABC. | [0114h] ← 43h |
| 10 | LOOP copy_lp | 0111h | 0115h | 0001h | ABC. | jump |
| 11 | MOVSB | 0112h | 0116h | 0001h | ABCD | [0115h] ← 44h |
| 12 | LOOP copy_lp | 0112h | 0116h | 0000h | ABCD | CX = 0 → fall through |
| 13 | RET | 0112h | 0116h | 0000h | ABCD | the program ends |
Two things happen in every MOVSB step. The BIU first reads the byte at DS:SI and then writes it to ES:DI; the byte passes through no general register. Then SI and DI are incremented by one. After the last MOVSB SI = 0112h. This is the byte right behind the source and happens to be the start of dst. DI = 0116h points one past the destination. The flag register does not change from start to finish. LOOP does not touch the flags either; it decrements CX and jumps if it is not zero.
The same job is done with a single instruction using MOV CX, 4 and REP MOVSB, and the result registers are the same: SI = 0112h, DI = 0116h, CX = 0. The difference is the time. The LOOP version spends 18 cycles on MOVSB and 17 cycles on a taken LOOP for each byte; the last LOOP is not taken and takes 5 cycles. For four bytes that is 4 × 18 + 3 × 17 + 5 = 128 cycles. REP MOVSB takes 9 + 17 × 4 = 77 cycles. The difference approaches a factor of two as the block grows.
11.7.5Code trace: converting to upper case with LODSB and STOSB
When LODS and STOS are used together, a string is read, each element is processed in a register, and the result is written back. This pattern is the typical way to transform an array in place. The following program converts the text 'micro' to upper case. In ASCII the difference between a lowercase and an uppercase letter is only bit 5 ('m' = 6Dh = 0110 1101b, 'M' = 4Dh = 0100 1101b). AND AL, 0DFh clears this bit.
org 100h
cld ; DF = 0: forward
lea si, msg
mov di, si ; write in place
mov cx, 5
next_ch:
lodsb ; AL = [SI], SI++
and al, 0DFh ; upper case
stosb ; [DI] = AL, DI++
loop next_ch
ret
msg db 'micro'The code is 16 bytes and msg sits at 0110h. MOV DI, SI (8B FE) puts the destination at the same place as the source. In a .COM program ES = DS, so DS:SI and ES:DI point to the same byte. LODSB advances the read address by one, and STOSB, one step behind, overwrites the same byte. Table 11.21 gives the first round in detail and the later rounds in summary.
| Instruction | AL | SI | DI | CX | msg |
|---|---|---|---|---|---|
CLD, LEA SI, msg | 00h | 0110h | 0000h | 0000h | micro |
MOV DI, SI, MOV CX, 5 | 00h | 0110h | 0110h | 0005h | micro |
LODSB | 6Dh ('m') | 0111h | 0110h | 0005h | micro |
AND AL, 0DFh | 4Dh ('M') | 0111h | 0110h | 0005h | micro |
STOSB | 4Dh | 0111h | 0111h | 0005h | Micro |
LOOP next_ch | 4Dh | 0111h | 0111h | 0004h | Micro |
| end of round 2 | 49h ('I') | 0112h | 0112h | 0003h | MIcro |
| end of round 3 | 4Bh ('K') | 0113h | 0113h | 0002h | MICro |
| end of round 4 | 52h ('R') | 0114h | 0114h | 0001h | MICRo |
| end of round 5 | 4Fh ('O') | 0115h | 0115h | 0000h | MICRO |
In this program only AND changes the flags: it sets CF and OF to 0, sets SF and ZF according to the result, and sets PF according to the parity of the result. Because 4Dh = 0100 1101b has four 1s, PF = 1 in the first round; because 49h = 0100 1001b has three 1s, PF = 0 in the second. LODSB, STOSB, and LOOP leave these flags as they are. The program also works correctly on a text that starts with a capital: 'M' is already a letter whose bit 5 is 0 and AND does not change it. But care is needed with characters that are not letters. For example a digit ('1' = 31h) comes out of this operation as 11h; in a real program one first tests whether the character is in the range 'a'–'z'.
The time of each round is LODSB (12) + AND AL, imm8 (4) + STOSB (11) + LOOP (17) = 44 cycles. Since the last LOOP takes 5 cycles, the total is 5 × 27 + 4 × 17 + 5 = 208 clock cycles. REP cannot be put on this loop, because REP repeats only a single string instruction; since an AND operation is needed in between, the loop is built with LOOP.
11.7.6Summing a word array with LODSW
In the W versions the step is 2. The following program reads an array of four words with LODSW and adds them up in BX.
org 100h
cld
lea si, arr
mov cx, 4
xor bx, bx ; sum = 0
top:
lodsw ; AX = [SI], SI += 2
add bx, ax
loop top
ret
arr dw 100h, 200h, 300h, 400h| Tur | address read by LODSW | AX | SI | BX | CX (after LOOP) |
|---|---|---|---|---|---|
| 1 | 010Fh | 0100h | 0111h | 0100h | 0003h |
| 2 | 0111h | 0200h | 0113h | 0300h | 0002h |
| 3 | 0113h | 0300h | 0115h | 0600h | 0001h |
| 4 | 0115h | 0400h | 0117h | 0A00h | 0000h |
Since the code takes 15 bytes, the array starts at an odd address, 010Fh. Each LODSW increments SI by 2 and moves to the next word of the array. The result is BX = 0A00h (256 + 512 + 768 + 1024 = 2560 = 0A00h). Because the array is at an odd address, each LODSW needs two separate byte bus cycles. Had an EVEN directive been put in front of the array, the array would shift to 0110h and each word would be read in a single cycle.
11.7.7CMPS and SCAS: comparison
CMPS and SCAS perform a subtraction as CMP does, discard the result, and set the six status flags. The order of the operands matters for interpreting CF and SF in the result:
- CMPS: [DS:SI] − [ES:DI]. Source minus destination. Comparing 'R' (52h) with 'S' (53h) gives 52h − 53h = FFh: CF = 1, SF = 1, ZF = 0. CF = 1 shows, in the unsigned interpretation, that the source is less than the destination.
- SCAS: AL (or AX) − [ES:DI]. The searched value minus memory. With AL = 'S' and 'R' in memory, 53h − 52h = 01h: CF = 0, ZF = 0.
This order may look contrary to the general rule of Intel syntax that the destination is written on the left: in CMPS the left side is the source. After CMPS, unsigned jumps such as JA and JB are read as "the source is greater/less than the destination". SCAS advances only DI, because its source operand is a register. CMPS, like MOVS, addresses two memory strings at once and advances SI and DI together.
11.8Repeat prefixes
11.8.1REP, REPE, and REPNE
The real power of a string instruction shows when it is combined with a repeat prefix. The prefix repeats the string instruction that follows until the CX counter reaches zero or until a condition fails. Table 11.23 gives the three prefixes and their continuation conditions.
| Prefix | Byte | Continuation condition | Use |
|---|---|---|---|
REP | F3 | CX ≠ 0 | MOVS, STOS (meaningless with LODS) |
REPE / REPZ | F3 | CX ≠ 0 and ZF = 1 | CMPS, SCAS: "continue while equal" |
REPNE / REPNZ | F2 | CX ≠ 0 and ZF = 0 | CMPS, SCAS: "continue while not equal" |
REP and REPE are the same byte (F3h). The processor tells the difference not from the prefix but from the instruction that follows: since MOVS, LODS, and STOS produce no flags, the ZF condition is not tested for them; for CMPS and SCAS it is. Bit 0 of F2h is 0 and that of F3h is 1, and this bit says which value ZF must have for the repetition to continue. The execution of a prefixed string instruction follows this order:
- If CX = 0, stop. The instruction may not be executed at all.
- If an interrupt is pending, accept it (the return address is the address of the prefix).
- Execute the string instruction once; update SI and DI.
- CX ← CX − 1. This decrement does not change the flags.
- If it is REPE or REPNE and the instruction is CMPS or SCAS, test ZF; if the condition is not met, stop. If it is met, go back to step 1.
The importance of the first step is great. A REP MOVSB that starts with CX = 0 copies no bytes at all. LOOP behaves the opposite way: a LOOP loop entered with CX = 0 first brings CX down to FFFFh and runs 65,536 rounds. This difference lets REP be used safely on a block whose length is computed: if the length comes out 0, nothing happens.
A repeat prefix is a prefix that makes the string instruction that follows repeat CX times or until a ZF condition fails. CX decreases by one with every repetition. When the instruction finishes, CX shows the number of repetitions not performed, and SI and DI point one past the last element processed.
11.8.2Block copy and filling the screen
The two most common uses of REP are copying a block of memory and filling a block with a single value. The first piece below copies 100 bytes and the second fills the whole screen with blanks.
; copy a 100-byte block
cld
lea si, src
lea di, dst
mov cx, 100
rep movsb
; fill the screen with blanks
mov ax, 0B800h
mov es, ax
xor di, di
mov ax, 0720h ; ' ' + attribute
mov cx, 2000 ; 80×25
rep stoswIn the first piece REP MOVSB runs a hundred times. At the end CX = 0, SI and DI are 100 (64h) more than their starting values, and a copy of the source block is at the destination. When this piece is put into a program and run in emu8086, for example if the source starts at 010Dh and the destination at 0171h, SI = 0171h and DI = 01D5h are seen at the end. According to the 8086 manual the time is 9 + 17 × 100 = 1709 clock cycles. Had the same block been copied with the word version (MOV CX, 50 / REP MOVSW), the time would fall to 9 + 17 × 50 = 859 cycles; a MOVSW round takes the same as a MOVSB round but moves two bytes each time.
The second piece fills the screen memory in text mode. The color text screen starts at B800:0000. Each character cell is two bytes: at the even address the ASCII code of the character, at the odd address the attribute (color) byte. The low byte of AX = 0720h is AL = 20h (blank) and the high byte is AH = 07h (light gray on black). Because STOSW writes AX in little-endian order, 20h falls on the even address and 07h on the odd one; each STOSW therefore clears one cell completely. For 80 × 25 = 2000 cells, CX = 2000. When the instruction finishes DI = 2000 × 2 = 4000 = 0FA0h, CX = 0, and the last cell of the screen holds the values 20h, 07h at B8F9Eh–B8F9Fh. The time is 9 + 10 × 2000 = 20,009 cycles; at 5 MHz about 4 ms.
11.8.3Code trace: searching for a character with REPNE SCASB
REPNE SCASB searches a string for a character: the condition "continue while not equal" stops when the character is found or when CX runs out. The following program searches the text 'pushing' for the letter 'h' and puts the position it finds (counting from 0) in DI.
org 100h
cld
lea di, msg
mov cx, 7 ; length
mov al, 'h' ; target
repne scasb ; search
jne not_found
dec di ; match position
sub di, offset msg
not_found:
ret
msg db 'pushing'The code is 19 bytes and msg starts at 0113h. REPNE SCASB is two bytes (F2 AE). Table 11.24 shows the four repetitions of the instruction separately. In each repetition AL is compared with the byte at ES:DI, DI is incremented by one, and CX is decremented by one.
| Instruction | Comparison | DI | CX | ZF | CF | Explanation |
|---|---|---|---|---|---|---|
CLD | 0000h | 0000h | 0 | 0 | forward | |
LEA DI, msg | 0113h | 0000h | 0 | 0 | BF 13 01 | |
MOV CX, 7 | 0113h | 0007h | 0 | 0 | at most 7 comparisons | |
MOV AL, 'h' | 0113h | 0007h | 0 | 0 | AL = 68h | |
REPNE SCASB (1) | 68h − 'm' (6Dh) | 0114h | 0006h | 0 | 1 | not equal → continue |
REPNE SCASB (2) | 68h − 'e' (65h) | 0115h | 0005h | 0 | 0 | continue |
REPNE SCASB (3) | 68h − 'r' (72h) | 0116h | 0004h | 0 | 1 | continue |
REPNE SCASB (4) | 68h − 'h' (68h) | 0117h | 0003h | 1 | 0 | equal → stop |
JNE not_found | 0117h | 0003h | 1 | 0 | ZF = 1 → no jump | |
DEC DI | 0116h | 0003h | 0 | 0 | address of the match | |
SUB DI, OFFSET msg | 0003h | 0003h | 0 | 0 | 'h' at index 3 |
In the fourth repetition 'h' is found: 68h − 68h = 0 and ZF = 1. Because the REPNE condition (ZF = 0) fails, the instruction stops. DI points one past the match (0117h), because the update is made after the comparison. CX = 3 is the number of characters of the string left unscanned. Since there can be two reasons for the instruction to finish, a test is needed afterwards. If ZF = 1 the character has been found. If ZF = 0, CX has run down to zero and the whole string was scanned in vain; in that case JNE not_found jumps. Testing CX = 0 alone is not enough: if the searched character is exactly in the last position, both CX = 0 and ZF = 1.
DEC DI takes DI back to the match itself: 0116h. SUB DI, OFFSET msg subtracts the start address and gives 0116h − 0113h = 3: 'h' is at index 3, counting from 0. DEC and SUB change the flags according to their own results; since the result is not zero, ZF returns to 0. The time of the instruction is 9 + 15 × 4 = 69 clock cycles.
11.8.4Comparing two strings with REPE CMPSB
REPE CMPSB compares two strings "as long as they are equal" and stops at the first difference. The following program compares the first six characters of the strings 'ANKARA' and 'ANTALY' and leaves the index of the first difference in SI.
org 100h
cld
lea si, str1
lea di, str2
mov cx, 6
repe cmpsb
je same ; all equal
dec si
sub si, offset str1 ; index of first difference
same:
ret
str1 db 'ANKARA'
str2 db 'ANTALY'The code is 20 bytes; str1 starts at 0114h and str2 at 011Ah. The first repetition compares 'A' with 'A': difference 0, ZF = 1, SI = 0115h, DI = 011Bh, CX = 5. The second repetition compares 'N' with 'N': ZF = 1, CX = 4. In the third repetition 'K' (4Bh) − 'T' (54h) = F7h. ZF = 0 and REPE stops. At this moment SI = 0117h, DI = 011Dh, CX = 3. To interpret the result as unsigned, look at CF: CF = 1, that is 'K' < 'T'. This says that ANKARA comes before ANTALY in dictionary order. JE same does not jump; DEC SI and SUB SI, OFFSET str1 give 0116h − 0114h = 2: the first difference is at index 2.
Here too there are two reasons for the instruction to finish. Had the strings been completely equal, all six repetitions would end with ZF = 1 and CX would be 0; then JE same would jump. A password or command-name comparison is done with this pattern.
11.8.5Overlapping blocks and choosing the direction
If the source and destination overlap in memory, the direction of copying changes the result. Suppose we want to shift a text two bytes to the right: msg db '12345', 2 dup('.'). The destination is two bytes to the right of the source and the two blocks overlap in three bytes.
std ; backward
lea si, msg+4 ; last byte of the source
lea di, msg+6 ; last byte of the destination
mov cx, 5
rep movsbWith STD the copy proceeds from end to start: first '5' is written to position 6, then '4' to position 5, and '3' to position 4. Every source byte is read before anything is written over it. The result is '1212345': the text has shifted right by two and the old characters remain in the first two positions. Had the same job been done with CLD, giving SI = msg and DI = msg+2, the first step would write '1' to position 2, that is over the '3'. The third step would read this new '1' and carry it forward. The result would be '1212121' and the text would be corrupted. Table 11.25 compares the two results.
| Direction | Initial SI / DI | Final SI / DI | Result |
|---|---|---|---|
| STD (correct) | 0111h / 0113h | 010Ch / 010Eh | 1212345 |
| CLD (wrong) | 010Dh / 010Fh | 0112h / 0114h | 1212121 |
If the destination overlaps on the right of the source (at a higher address), the copy is done from end to start: STD, with SI and DI pointing to the last element of the blocks. If the destination overlaps on the left of the source, it is done from start to end: CLD, with SI and DI pointing to the first element of the blocks. If the blocks do not overlap, either direction is correct.
11.8.6Timing, interrupts, and hardware
A string instruction with REP is distinctly faster than a loop doing the same job. Table 11.26 gives a few comparisons according to the timings in the Intel 8086 manual. The source of the gain is that the loop control (decrementing CX, testing, jumping) is done inside the microcode and that the prefetch queue is not flushed on every round. When a LOOP or JMP is taken, the queue is flushed and the BIU has to start reading again from the new address; an instruction with REP never changes IP.
| Task | With a loop | With REP |
|---|---|---|
| copy 4 bytes | MOVSB + LOOP: 128 | REP MOVSB: 77 |
| copy 100 bytes | MOVSB + LOOP: 3488 | REP MOVSB: 1709; REP MOVSW (50 words): 859 |
| fill 2000 words | – | REP STOSW: 20.009 |
| search for the character at position 4 in 7 bytes | – | REPNE SCASB: 69 |
A long REP instruction can take thousands of cycles. The 8086 does not hold interrupts off during this time. At the start of each repetition it looks at whether an interrupt is pending. If there is one, it abandons the work done so far; SI, DI, and CX keep their current values. The return address pushed onto the stack is the address of the prefix. When the interrupt handler returns with IRET, the processor restarts the prefixed instruction and the work continues with the remaining CX value. This scheme keeps interrupt latency short but also brings the limitation described above: since the 8086 remembers only one prefix, REP and a segment prefix should not be used together.
Using REP with LODS or REPE with MOVS. REP LODSB is valid code but overwrites AL in every repetition; only the last byte remains in AL at the end. REPE MOVSB is the same as REP MOVSB, because MOVS produces no ZF. The pairing of prefix and instruction: REP for MOVS and STOS, REPE or REPNE for CMPS and SCAS.
11.9Control transfer: the encoding of JMP
11.9.1Kinds of JMP
The unconditional jump JMP loads a new value into IP (and also into CS in a far jump). The 8086 has five encoding forms of JMP. The forms are distinguished by how the target is given: as an offset inside the instruction, as an absolute address inside the instruction, or in a register or memory. Table 11.27 gives all five and their times.
| Type | Kod | Range | Example | Time |
|---|---|---|---|---|
| Short | EB d8 | −128 … +127 bytes | JMP SHORT again | 15 |
| Near | E9 d16 | same segment, ±32 K | JMP start | 15 |
| Far | EA IP CS | any segment | JMP FAR PTR target | 15 |
| Indirect near | FF /4 | IP ← register or memory | JMP BX, JMP table[BX] | 11 / 18 + EA |
| Indirect far | FF /5 | CS:IP ← memory (4 bytes) | JMP DWORD PTR [SI] | 24 + EA |
Short and near jumps are encoded relative: the instruction carries not the address of the target but the distance of the target from the next instruction. The processor adds this distance to IP. Since IP already points to the next instruction while the instruction is executing, the calculation is: target = address of the next instruction + displacement. In the short form the distance is a single byte and is sign-extended to 16 bits. A far jump, on the other hand, carries the absolute address of the target: first IP (2 bytes), then CS (2 bytes), both little-endian. A far JMP is therefore five bytes. JMP FAR PTR far_lbl is encoded as EA 56 02 00 07 if the target is 0700:0256h.
The indirect forms belong to the FFh family, and the REG field of ModR/M says which operation is performed: /4 is indirect near JMP, /5 indirect far JMP. JMP BX = FF E3 (11 100 011: MOD = 11, REG = 100, R/M = BX). JMP DWORD PTR [SI] = FF 2C (00 101 100: REG = 101, R/M = [SI]). In these two lines it is plain that the REG field shows not a register but the type of the operation.
11.9.2Computing the relative displacement
Figure 11.6 shows a short jump. The EB 10 at 0120h is two bytes; the next instruction is at 0122h. The target is 0122h + 10h = 0132h.
The reverse calculation is what the assembler does for every jump: displacement = target − address of the next instruction. If the result is negative it is written in two's complement. Three examples:
- Jump to itself. If a two-byte short JMP at 010Ah jumps to itself, the next instruction is at 010Ch. 010Ah − 010Ch = −2 = FEh. The code is EB FE; it is the endless loop that stops a program where it is.
- Backward jump. If the short JMP at 0150h jumps to 0130h, the next instruction is at 0152h. 0130h − 0152h = −22h. The two's complement of −22h is 100h − 22h = DEh. The code is EB DE.
- Near jump. If a JMP at 0122h goes to a label at 0251h, the distance does not fit the short range. The near form is three bytes and the next instruction is at 0125h. 0251h − 0125h = 012Ch. The code is E9 2C 01.
Relative encoding has an important consequence: when the code is moved to another address in memory, the bytes of short and near jumps do not change, because the jumping instruction and its target shift together. This is convenient for a system such as DOS that does not know in advance where the program will be loaded. A far jump, however, carries an absolute CS value, so in .EXE programs DOS has to fix it up during loading. On the 8086 the conditional jumps (Jcc) have only the short form. If the target is outside the −128…+127 range, the assembler inverts the condition and places a near JMP behind it.
Every jump pays one more cost besides its time. When a jump is taken, the bytes in the BIU's prefetch queue are no longer valid, because the next instruction is somewhere else. The queue is flushed and the BIU starts reading from the new CS:IP. Most of the 15-cycle time of JMP comes from this refill. That conditional jumps take only 4 cycles when not taken is also because the queue is preserved.
11.9.3Indirect jumps and the jump table
The indirect near JMP makes it possible to choose the target at run time. A menu or a state machine keeps the addresses of the possible targets in an array of words and jumps to one of them with an index. This structure is called a jump table; it is the machine-level counterpart of the switch statement of high-level languages.
mov bx, 2 ; choice (0, 1, 2)
shl bx, 1 ; word index: × 2
jmp table[bx] ; IP ← table[BX]
table dw s0, s1, s2
s0: mov dx, 0
ret
s1: mov dx, 1
ret
s2: mov dx, 2
retEvery element of the table is two bytes; the choice number is therefore multiplied by two with SHL. When the program starts at 0100h, JMP table[BX] is encoded as FF A7 09 01: ModR/M A7h = 10 100 111b (MOD = 10, REG = 100 = /4, R/M = [BX+d16]), then the address of the table, 0109h. With BX = 4 the processor reads the word at DS:010Dh; there is the address of s2, 0117h. IP ← 0117h and the program ends with DX = 2. It must be tested beforehand that the choice number does not exceed the table size; otherwise the code bytes behind the table are taken for addresses and the processor jumps to a random place.
11.10Processor-control instructions
11.10.1Flag instructions
Processor-control instructions do no calculation and move no data; they change the state of the processor. Some of them set or clear a single flag; all of these flag instructions are single bytes and take 2 clock cycles. Table 11.28 gives all the instructions with their codes and times.
| Instruction | Kod | Effect | Time |
|---|---|---|---|
CLC / STC | F8 / F9 | CF ← 0 / CF ← 1 | 2 |
CMC | F5 | CF ← ¬CF | 2 |
CLD / STD | FC / FD | DF ← 0 / 1 (string direction) | 2 |
CLI / STI | FA / FB | IF ← 0 / 1 (INTR interrupts) | 2 |
HLT | F4 | stop until an interrupt or RESET arrives | 2 |
WAIT | 9B | wait until the TEST̅ pin becomes active (8087 coordination) | 3 + 5n |
ESC | D8–DF | pass the instruction to the coprocessor (8087) | 2 / 8 + EA |
LOCK | F0 | prefix: for the duration of the next instruction the LOCK̅ pin is active, the bus is locked | 2 |
NOP | 90 | do nothing | 3 |
Each flag instruction touches a single flag; the others do not change. The reason such small instructions exist separately is that the program itself deliberately sets these three flags (CF, DF, IF). CF can be cleared before starting a multiword addition (CLC, then a chain of ADC). DF selects the direction before string instructions. IF determines whether interrupts are accepted. There are no separate set/clear instructions for OF, SF, ZF, AF, and PF; they are written with POPF (and, except for OF, with SAHF).
A common use of CLC and STC is returning success or failure information from a procedure. If the procedure finds an error it returns with STC, if not with CLC. The caller decides right afterwards with JC error or JNC ok. Most of the INT 21h services of DOS report errors this way too. The following procedure divides AX by BL, but if BL = 0 it returns with CF = 1 without causing a divide error:
divide:
cmp bl, 0
jne ok
stc ; error: divisor is zero
ret
ok:
div bl ; AL = quotient, AH = remainder
clc ; success
retWhen called with AX = 7 and BL = 0 the procedure returns with CF = 1 and AX unchanged. When called with AX = 7 and BL = 3, DIV produces AL = 2 (quotient) and AH = 1 (remainder); AX = 0102h and the return is with CF = 0. Because DIV leaves all the flags undefined, CLC is needed here: without it the value of CF would be unpredictable. Since RET does not change the flags, CF reaches the caller as it is.
11.10.2The interrupt flag: CLI and STI
IF determines whether the processor accepts the maskable interrupts coming from the INTR pin. When IF = 0 is made with CLI, INTR is ignored; the non-maskable interrupt from the NMI pin and interrupts called by software with INT n still work. The region between CLI and STI is a critical region in which an interrupt must not see a half-finished data structure. The typical example is moving the stack:
cli ; interrupts off
mov ss, ax
mov sp, 0FFFEh
sti ; interrupts onIf an interrupt arrives when SS has changed but SP still has its old value, the processor pushes FLAGS, CS, and IP to a wrong address and corrupts memory. The 8086 already holds off interrupts for the single instruction after one that writes SS. But this protection is only one instruction long; the CLI/STI pair shows the intent openly and is safe even when there are more instructions in between. STI has a similar property: interrupts are accepted after the instruction following STI finishes. So in the STI / IRET pair at the end of an interrupt handler, no new interrupt can slip in before IRET executes.
11.10.3HLT, WAIT, ESC, LOCK, and NOP
These instructions manage the processor's relation to the outside world and are directly tied to the pins of the 8086.
- HLT (halt) puts the processor into the halt state. No instruction is executed and no bus cycle is started; the processor waits without fetching the next instruction. There are three ways out of the state: an interrupt from the INTR pin (if IF = 1), an interrupt from the NMI pin, or RESET. When it leaves through an interrupt, the address of the instruction after HLT is pushed onto the stack; when the handler returns, the program continues after the HLT. That is why HLT is used to mean "wait for the next interrupt". An HLT after CLI makes the processor wakeable only by NMI or RESET.
- WAIT polls the TEST̅ input of the 8086. As long as the pin is 1 the processor keeps waiting and samples the pin again every five clock cycles. This pin is usually connected to the BUSY output of the 8087 floating-point coprocessor. WAIT keeps the 8086 from reading the result of the 8087 before it has finished a calculation.
- ESC (escape) instructions are those beginning with 11011xxx (D8h–DFh). The 8086 does not execute these instructions itself. If there is a memory operand, it computes the effective address and does a read from that address. The 8087, which watches the bus, captures both the instruction and the address and does the calculation itself. The three bits in the opcode and the REG field of ModR/M combine to give the six-bit instruction code of the 8087.
- LOCK is a prefix. As long as the instruction that follows it is executing, the LOCK̅ output of the 8086 (in maximum mode) is held at 0. The bus arbiter does not let another processor or a DMA controller take the bus during this time. An instruction made of a read and a write thus completes without another bus master slipping in between.
- NOP does nothing and takes 3 cycles. Its code is 90h, that is it is actually
XCHG AX, AX. It is used for short delays in timing loops, for filling gaps in code alignment, and in debugging for disabling an instruction without deleting it.
The best-known use of LOCK is building a semaphore to protect a resource shared by several processors. If the mutex byte in memory is 0 the resource is free. To take the resource a processor executes LOCK XCHG AL, mutex with AL = 1. The exchange is done in a single instruction and, because of LOCK, no other processor can slip in. If the old value that arrives in AL is 0, the resource has been taken; if it is 1, someone else has it and the loop tries again:
wait_lock:
mov al, 1
lock xchg al, mutex ; F0 86 06 …
test al, al
jnz wait_lock ; someone else has it
; critical section
mov mutex, 0 ; release the resourceHad the read and write been done with two separate instructions (MOV AL, mutex / MOV mutex, 1), two processors could read 0 at the same time and both think they had taken the resource. On a single-processor system CLI/STI gives the same protection; LOCK is for multiprocessor systems.
11.11Flag effects
11.11.1Computational instructions
The correct working of a program often depends on knowing which instruction changes which flag. Conditional jumps look at the result of the last instruction that changed the flags; any instruction in between can spoil this result. Table 11.29 gives the effect of the arithmetic, logic, and shift instructions on the six status flags.
| Instruction | OF | SF | ZF | AF | PF | CF |
|---|---|---|---|---|---|---|
ADD ADC SUB SBB CMP NEG | * | * | * | * | * | * |
CMPS SCAS | * | * | * | * | * | * |
INC DEC | * | * | * | * | * | – |
MUL IMUL | * | ? | ? | ? | ? | * |
DIV IDIV | ? | ? | ? | ? | ? | ? |
DAA DAS | ? | * | * | * | * | * |
AAA AAS | ? | ? | ? | * | ? | * |
AAM AAD | ? | * | * | ? | * | ? |
AND OR XOR TEST | 0 | * | * | ? | * | 0 |
SHL SAL SHR SAR | *¹ | * | * | ? | * | * |
ROL ROR RCL RCR | *¹ | – | – | – | – | * |
A few rows of the table need special attention. INC and DEC preserve CF; this property is designed so that incrementing a counter or an index in a multiword addition loop does not spoil the carry of ADC. MUL and IMUL set only CF and OF meaningfully: together they say whether the upper half of the result is needed. After DIV and IDIV no flag can be trusted. Logic instructions always set CF and OF to 0. TEST AX, AX is therefore a frequently used test: it does not change AX, sets ZF, SF, and PF according to AX, and clears CF. Rotate instructions change only CF and OF. In shifts and rotates, if the count is 0 (CL = 0) no flag changes.
An "undefined" (?) flag means that the processor writes some value to that flag but this value is not documented. In emu8086 or on a real processor a particular value is seen in this flag, but it may be different on another processor model. A correctly written program does not decide by looking at an undefined flag.
11.11.2Other instructions
Table 11.30 collects the effects of the remaining instructions on the flags. The main message of this table is that the great majority of instructions do not touch the flags at all.
| Instructions | Flags affected |
|---|---|
MOV XCHG LEA LDS LES XLAT PUSH POP IN OUT LAHF PUSHF CBW CWD NOT | none |
MOVS LODS STOS, REP | none |
JMP Jcc LOOP LOOPE LOOPNE JCXZ CALL RET | none (only read) |
SAHF | SF ZF AF PF CF ← AH |
POPF, IRET | all (from the stack) |
INT n, INTO | IF ← 0, TF ← 0 (old FLAGS on the stack) |
CLC STC CMC | CF |
CLD STD | DF |
CLI STI | IF |
Two rows may come as a surprise. NOT is a logic instruction but changes no flag; a program that wants to set the flags uses XOR AX, 0FFFFh instead. LOOP also decrements CX but, unlike DEC, does not touch the flags. LOOPE and LOOPNE read ZF and do not write it. INT n pushes the flags onto the stack before changing them; since IRET restores them, the flags of the program are back to their old state after returning from the interrupt handler.
11.11.3What can come between CMP and a conditional jump?
The place where the flag tables are most often used is between a comparison and the conditional jump that depends on it. If an instruction that changes flags comes in between, the jump looks at the result of that instruction, not of the comparison. In the following piece AL = 20 and BX = FFFFh:
cmp al, 10
add bx, 2 ; bug: corrupts the flags
jb small ; if AL < 10
mov dx, 1
ret
small:
mov dx, 2
retCMP computes 20 − 10 and produces CF = 0; AL is not less than 10 and JB must not jump. But the ADD BX, 2 in between computes FFFFh + 2 = 1 0001h: the result does not fit in 16 bits and CF = 1. JB looks at this CF, jumps, and the program ends in the wrong branch with DX = 2. If LEA BX, [BX+2] is written in place of ADD, BX is again 0001h but the flags do not change; JB sees the result of CMP, does not jump, and DX = 1, the correct result, comes out. The general rule: between CMP and Jcc only instructions that do not affect the flags, such as MOV, LEA, XCHG, PUSH, and POP, can come. If a counter has to be incremented, either move it before the CMP or do it with LEA.
11.12Common mistakes
This section lists in one place the mistakes met throughout the note. After each, it is given why it occurs and how to prevent it.
- Taking the D bit for "the left operand". D = 1 says that the register in the REG field is the destination. In two-register instructions both encodings are valid (8B C3 and 89 D8); in instructions with memory, which side the memory is on decides D.
- Skipping the W bit and reading the wrong register. REG = 100 is AH when W = 0 and SP when W = 1. In decoding, look at W first.
- Encoding [BP] with MOD = 00. MOD = 00 and R/M = 110 is the direct address. [BP] is encoded with MOD = 01 and d8 = 0 and is three bytes.
- Starting decoding at a wrong address. A one-byte shift changes all the boundaries; decoding starts from the start of a program or from a known jump target.
- Forgetting little-endian order. The displacement, the immediate, and each word of a far pointer are written low byte first. In a far pointer the offset comes first, then the segment.
- Confusing LEA with MOV.
LEA AX, [BX+DI+2]gives the address,MOV AX, [BX+DI+2]the contents. - Assuming DF. Before a string instruction the direction is set explicitly with CLD or STD.
- Not setting ES in an .EXE program. The string destination is always ES:DI, and DOS does not set ES to the data segment.
- Looking only at CX after REPNE/REPE. ZF tells why the instruction stopped; when the searched character is in the last position, CX = 0 and ZF = 1 occur together.
- The wrong direction with overlapping blocks. If the destination is to the right of the source, copy from end to start with STD.
- Putting a flag-corrupting instruction between CMP and Jcc. Instructions such as INC, ADD, SUB, and AND set the flags anew; only instructions that do not affect flags may come in between.
- Trusting an undefined flag. ZF after MUL, any flag after DIV, and OF after a shift by more than 1 are undefined.
11.13Exercises and solutions
The nine exercises in this section are the exercises at the end of the slides. The solution to each is given step by step with the method described in the note.
Exercise 1. Encode MOV DX, [BP+DI+8] (opcode 100010, D = 1, W = 1).
Solution. The first byte is 100010 1 1 = 8Bh. The destination DX gives REG = 010. The R/M code of the form [BP+DI+d] is 011. Since 8 fits in one byte, MOD = 01. ModR/M = 01 010 011b = 53h. The displacement is 08h. The code is 8B 53 08; because it contains BP, the default segment is SS.
Exercise 2. With DS = 1000h, BX = 0200h, AL = 05h, the byte at which physical address does XLAT load into AL?
Solution. EA = BX + AL = 0200h + 05h = 0205h. The physical address is 1000h × 10h + 0205h = 10205h.
Exercise 3. The bytes of the variable far_ptr dd in memory are 34 12 00 B8. What are ES and DI after LES DI, far_ptr?
Solution. In a far pointer the offset is stored first, then the segment. The first word 34 12 → 1234h, the second word 00 B8 → B800h. DI = 1234h, ES = B800h.
Exercise 4. How many bytes does REP MOVSB copy when CX = 0?
Solution. None. REP tests CX before every repetition; if CX = 0 the string instruction is not executed even once. SI, DI, and memory do not change.
Exercise 5. CLD, CX = 5, SI = 0100h, DI = 0200h; REPE CMPSB finds a difference at the 3rd byte. What are CX, SI, DI, and ZF afterwards?
Solution. Three comparisons are made: the first two are equal (ZF = 1), the third differs (ZF = 0) and REPE stops. In each comparison SI and DI increase by one and CX decreases by one: CX = 2, SI = 0103h, DI = 0203h, ZF = 0. The differing byte is at SI − 1 = 0102h.
Exercise 6. The JMP SHORT at address 0150h jumps to 0130h. What is the machine code?
Solution. The instruction is two bytes; the next instruction is at 0152h. The distance is 0130h − 0152h = −22h. In one byte −22h = 100h − 22h = DEh. The code is EB DE.
Exercise 7. Write code that counts the spaces in a string with REPNE SCASB.
Solution. REPNE SCASB stops when it finds a space; DI points behind the space found and CX shows the remaining length. If the counter is incremented and the instruction run again, the search continues where it left off. The loop ends when the search finishes without finding (ZF = 0) or when the string is exhausted (CX = 0).
org 100h
cld
xor bx, bx ; counter = 0
lea di, msg
mov cx, 19 ; length
mov al, ' '
search:
repne scasb
jne done ; no spaces left
inc bx ; one more space
jcxz done ; string finished
jmp search
done:
ret
msg db 'a short sample text'When run in emu8086 the program ends with BX = 3: 'a short sample text' is 19 characters and contains three spaces. The JCXZ test covers the case where the last character is a space. In that case REPNE SCASB finds the space in the last repetition; ZF = 1 and CX = 0. The counter is incremented and JCXZ leaves the loop. Without this test, the REPNE entered again with CX = 0 would not run at all and ZF would stay 1; JNE would not jump, the counter would increase without stopping, and the loop would never end. When the end of the text is changed to 'tex ' the program counts four spaces correctly.
Exercise 8. Which instruction are the bytes 8A 1E 34 12? What happens if the same bytes are decoded shifted by one byte (from offset 1)?
Solution. 8Ah = 100010 1 0: D = 1, W = 0. 1Eh = 00 011 110: MOD = 00, REG = 011 (BL), R/M = 110 → direct address. Then 34 12 → 1234h. The instruction is MOV BL, [1234h]. When decoded from offset 1, 1Eh is the one-byte PUSH DS, and then 34 12 is the two-byte XOR AL, 12h.
Exercise 9. Encode MOV ES, DX and MOV AL, [0020h].
Solution. MOV ES, DX: the 8Eh family; ModR/M = 11 000 010b = C2h (REG = 0 + 00 = ES, R/M = DX). The code is 8E C2. MOV AL, [0020h]: the short form between AL and a direct address is A0h, followed by the address in little-endian: A0 20 00.
11.14Summary
- Instruction set: the roughly one hundred instructions of the 8086 fall into six classes: data transfer, arithmetic, logic and shift, string, control transfer, and processor control. There is one mnemonic but many opcodes.
- Instruction format: prefixes + opcode (6 bits, D, W) + ModR/M (MOD, REG, R/M) + 0–2 bytes of displacement + 0–2 bytes of immediate. An unprefixed instruction is 1–6 bytes; numbers are written little-endian.
- D and W: W = 0 byte, W = 1 word; D = 1 REG is the destination, D = 0 REG is the source. Two-register instructions have two valid codes:
MOV AX, BX= 8B C3 or 89 D8;ADD AX, BX= 03 C3 or 01 D8. - ModR/M: MOD = 11 register, 00/01/10 memory (0/1/2 bytes of displacement). MOD = 00, R/M = 110 is the direct address; [BP] is therefore encoded with d8 = 0. The segment of forms containing BP is SS. The EA time is 5–12 cycles.
- Short forms: 40h+r, 50h+r, 90h+r, B0h+r, B8h+r, A0h–A3h, 04h/05h, 83h; one or two bytes shorter than the general form of the same job. In the 80h/81h/83h and FEh/FFh families the REG field selects the operation (/0 … /7).
- Decoding: from the starting point the first byte, ModR/M, displacement, and immediate are read in order. Decoding that starts at a wrong address turns the same bytes into other instructions; the processor does not distinguish code from data.
- Data transfer: does not change the flags (except SAHF and POPF). XLAT: AL ← [DS:BX + AL]. LEA gives the address, MOV the contents; in emu8086 LEA with a direct address is compiled as the three-byte MOV r16, imm16. LDS/LES load a far pointer (offset first, then segment).
- String instructions: MOVS, CMPS, SCAS, LODS, STOS; source DS:SI, destination ES:DI. DF = 0 (CLD) increments, DF = 1 (STD) decrements; the step is 1 for B and 2 for W. CMPS = [SI] − [DI], SCAS = AL/AX − [DI].
- Repeat prefixes: REP (F3h) while CX ≠ 0; REPE (F3h) and REPNE (F2h) with a ZF condition. If CX = 0 the instruction does not run at all. After it finishes, ZF says why the instruction stopped. With overlapping blocks, use STD if the destination is on the right.
- JMP: short (EB d8) and near (E9 d16) are relative; target = next instruction + distance. Far (EA IP CS) and indirect (FF /4, FF /5) use an absolute address. A jump flushes the prefetch queue.
- Processor control: CLC/STC/CMC, CLD/STD, CLI/STI are single-flag; HLT, WAIT, ESC, and LOCK work with the processor's pins (INTR/NMI/RESET, TEST̅, 8087, LOCK̅); NOP = XCHG AX, AX.
- Flag effects: moves, string moves, jumps, and NOT do not change flags; INC/DEC preserve CF; logic instructions make CF = OF = 0; the flags are undefined after DIV. No flag-affecting instruction should come between CMP and Jcc.
11.15Key terms
The terms introduced in this chapter:
- instruction set
- mnemonic
- machine code
- instruction format
- opcode
- ModR/M byte
- displacement
- immediate value
- effective address (EA)
- default segment
- prefix, segment override prefix
- little-endian
- prefetch queue
- data transfer instruction
- translation table (XLAT)
- far pointer
- string instruction
- direction flag (DF)
- repeat prefix (REP)
- short / near / far jump
- relative addressing
- processor control instruction
- clock cycle
- listing file
11.16Test Yourself
What is the machine code of
MOV [BX+SI+0Ah], DX?Answer
DX is the source and goes into the REG field: D = 0, W = 1 → 89h. REG = 010 (DX), R/M = 000 ([BX+SI+d]), and since 0Ah fits in one byte, MOD = 01. ModR/M = 01 010 000b = 50h. The code is 89 50 0A.
Which instruction are the bytes
C6 46 FE 07? In which segment is the memory operand?Answer
C6h is the MOV that moves an immediate byte to r/m8 (the REG field must be 000). 46h = 01 000 110b: MOD = 01 (d8), R/M = 110 → [BP+d8]. d8 = FEh = −2, and the immediate value is 07h. The instruction is
MOV BYTE PTR [BP−2], 7; because it contains BP, the segment is SS. This is the pattern for assigning a value to a local variable in a stack frame.Why is
MOV AL, [BX]two bytes whileMOV AL, [BP]is three bytes?Answer
The combination MOD = 00 and R/M = 110 is reserved for the direct address. [BP] is therefore encoded with MOD = 01 and d8 = 00: 8A 46 00. For [BX] there is no such conflict: 8A 07.
The near JMP (E9) at 0200h jumps to 0100h. What is the machine code?
Answer
The instruction is three bytes; the next instruction is at 0203h. 0100h − 0203h = −103h; in 16 bits 10000h − 103h = FEFDh. Written little-endian: E9 FD FE.
squares db 0, 1, 4, 9, 16, 25, 36, 49, 64, 81is defined. What is AL afterLEA BX, squares,MOV AL, 7,XLAT?Answer
XLAT does AL ← [DS:BX + 7]; element 7 of the table (counting from 0) is 49. AL = 49 = 31h. The table method gives the squares of small numbers without a multiplication, in 11 cycles.
The bytes of the variable
ptrin memory are 00 20 00 10. What are SI and DS afterLDS SI, ptr? Which physical address does DS:SI point to?Answer
The first word is the offset: SI = 2000h; the second word is the segment: DS = 1000h. The physical address is 10000h + 2000h = 12000h. From this moment on DS no longer points to the program's own data.
With CLD, SI = 0200h, DI = 0300h, CX = 3, how many bytes does
REP MOVSWcopy? What are SI, DI, and CX at the end?Answer
Three words, that is 6 bytes, are copied. In each repetition SI and DI increase by 2: SI = 0206h, DI = 0306h, CX = 0.
STD, DI = 0309h, CX = 10, AL = 'x'. Memory from 0300h to 0309h holds '0123x5x789'. What are DI, CX, and ZF after
REPNE SCASB?Answer
The scan proceeds from end to start: 0309h '9', 0308h '8', 0307h '7', 0306h 'x'. A match is found at the fourth comparison, ZF = 1, and the instruction stops. Since DI decreases after every comparison, DI = 0305h, CX = 6, ZF = 1. The address of the match is DI + 1 = 0306h; with STD the scan finds not the first 'x' but the last one.
Which of the following instructions can be placed between
CMP AX, BXandJE equal:INC CX,MOV CX, 0,XOR CX, CX,LEA CX, [BX+1],PUSH AX?Answer
MOV CX, 0,LEA CX, [BX+1], andPUSH AXdo not change the flags and can be placed there.INC CXsets ZF, SF, OF, AF, and PF anew;XOR CX, CXmakes ZF = 1 and makes JE always jump. This side effect of XOR, the short way to zero CX, leads to a bug here.What is the difference in behavior, when CX = 0, between
REP STOSBandMOV CX, 0/again: STOSB/LOOP again?Answer
REP tests CX first; with CX = 0, STOSB does not run at all and memory is unchanged. In the loop with LOOP, STOSB runs once, LOOP brings CX down to FFFFh, and the loop runs 65,536 times; a 64 KB area starting at ES:DI is filled with AL.
11.17Further reading
- Intel, The 8086 Family User's Manual (1979): the instruction set chapter gives the flag effect and clock-cycle time of each instruction, and the instruction encoding chapter gives the opcode tables and the ModR/M layout first hand.
- B. B. Brey, The Intel Microprocessors (8th edition), the chapters on data-transfer and string instructions: machine-language encoding, MOVS/STOS/LODS examples, and details that extend to later x86 processors.
- K. R. Irvine, Assembly Language for x86 Processors (7th edition): the chapter on string instructions and array processing; many examples of comparison with REPE CMPSB and table-driven search.
- emu8086 help documentation, "8086 instructions": a short description of each instruction, its valid operand forms, and the flag table; the explanations of the environment in which the examples in the slides were tried.
11.18References
- Intel, The 8086 Family User's Manual, 1979 — Chapter 2: the instruction set, Chapter 4: instruction encoding.
- B. B. Brey, The Intel Microprocessors, 8th edition, Pearson, 2009.
- K. R. Irvine, Assembly Language for x86 Processors, 7th edition, Pearson, 2014.
- Ş. Ç. Öztürk, O. Ergin, Intel 8086 ile Mikroişlemci Programlamaya Giriş, 2009.
- emu8086 help documentation: "8086 instructions" and "8086 assembler tutorial".
Related pages: Chapter 11 slides · © Sercan Külcü. All rights reserved.