AMD 250 Computer Hardware User Manual


 
170 Integer Optimizations Chapter 8
25112 Rev. 3.06 September 2005
Software Optimization Guide for AMD64 Processors
8.5 Efficient 64-Bit Integer Arithmetic in 32-Bit Mode
Optimization
The following section contains a collection of code snippets and subroutines showing the efficient
implementation of 64-bit arithmetic in 32-bit mode. Note that these are 32-bit recommendations, in
64-bit mode it is important to use 64-bit integer instructions for best performance.
Addition, subtraction, negation, and shifting are best handled by inline code. Multiplication, division,
and the computation of remainders are less common operations and are usually implemented as
subroutines. If these subroutines are used often, the programmer should consider inlining them.
Except for division and remainder calculations, the following code works for both signed and
unsigned integers. The division and remainder code shown works for unsigned integers, but can easily
be extended to handle signed integers.
64-Bit Addition
; Add ECX:EBX to EDX:EAX, and place sum in EDX:EAX.
add eax, ebx
adc edx, ecx
64-Bit Subtraction
; Subtract ECX:EBX from EDX:EAX and place difference in EDX:EAX.
sub eax, ebx
sbb edx, ecx
64-Bit Negation
; Negate EDX:EAX.
not edx
neg eax
sbb edx, -1 ; Fix: Increment high word if low word was 0.
64-Bit Left Shift
; Shift EDX:EAX left, shift count in ECX (count
; applied modulo 64).
shld edx, eax, cl ; First apply shift count.
shl eax, cl ; mod 32 to EDX:EAX
test ecx, 32 ; Need to shift by another 32?
jz lshift_done ; No, done.
mov edx, eax ; Left shift EDX:EAX
xor eax, eax ; by 32 bits
lshift_done: