assemblyx86x86-16zero-initialization

Zeroing %EAX Register on the 8086


The first instruction I issued without fail at the start of every program for a DEC PDP-8 Minicomputer was CLA CLL to clear the accumulator and link (overflow) bit.

That simple instruction doesn't seem to exist in 8086 range of processors and I have seen a lot of discussion on various technical websites on the quickest way to do it, like XORing it with itself.

Is this already handled somewhere by the processor logic? So it's guaranteed to be 0 before the program starts?


Solution

  • For a 8086, the fastest and shorter way to clear the AX register (not EAX) is by issuing some ALU instruction that performs the operation. That is:

    xor ax,ax  ; opcode: 29 C0
    

    Or

    sub ax,ax  ; opcode: 31 C0
    

    Shortest because the regular mov ax,0 needs 3 bytes: B8 00 00, one byte more. Fastest because xor and sub use 3 clock cycles. mov uses 4 cycles.

    On the other hand, xor and sub will alter the flags, while mov won't. Sometimes you won't mind changing the flags when a register is needed to be cleared, sometimes you won't want to change the flags. About code clearness, the xor/sub "trick" is widely known, and compilers do use it to fast register clear, so any assembler programmer will realize what you want to do.