Tricks in preserving registers

When you are developing mixed assembler/API code, and you do not know what registers are used in the API functions, you can draw upon two pairs of assembler instructions that preserve all of the usual registers and the CPU flags as well: PUSHAD, POPAD, PUSHFD, and POPFD.

PUSHAD/POPAD

The first pair of mnemonics, PUSHAD and POPAD, save and restore the registers in a block.  These mnemonics allow you to do things like display the value of a register in the middle of assembler code with a MessageBox API call.

' ...Assembler code

! PUSHAD

var& = 0

! MOV var&, EAX

MessageBox hWnd&,BYCOPY STR$(var&),"Test Value",%MB_OK

! POPAD

' ...More assembler code

It should be noted that the use of PUSHAD and POPAD in release code is less-than-optimal code design.  That is, it does more work than is usually needed, but in the development stage, these two instructions can be very convenient.

PUSHFD/POPFD

If the code being tested has certain instructions, such as conditional jumps that depend on flag states within the processor, the other pair of block instructions to utilize is likely to be PUSHFD and POPFD.  These preserve the state of the processor flags while code that may modify the flags is executed.

PROGRAMMING TIP:  If the STD instruction is used to set the CPU direction flag, a CLD instruction must be executed before releasing control to a Windows API function or a BASIC statement.

 

See Also

ASM statement

The stack