AMD x86 Signed Division by Multiplication of Constant, Simpler Code for, Restricted Dividend

Models: x86

1 256
Download 256 pages 58.62 Kb
Page 95
Image 95

22007E/0 — November 1999

AMD Athlon™ Processor x86 Code Optimization

Example 1:

 

;In:

 

EDX = dividend

 

;Out:

 

EDX = quotient

 

XOR EDX,

EDX;0

 

CMP EAX,

d ;CF = (dividend < divisor) ? 1 : 0

 

SBB EDX,

-1 ;quotient = 0+1-CF = (dividend < divisor) ? 0 : 1

 

In cases where the dividend does not need to be preserved, the

 

division can be accomplished without the use of an additional

 

register, thus reducing register pressure. This is shown in

 

example 2 below:

 

Example 2:

 

;In:

EDX = dividend

 

;Out: EAX = quotient

 

CMP EDX,

d ;CF = (dividend < divisor) ? 1 : 0

 

MOV EAX,

0 ;0

 

SBB EAX,

-1 ;quotient = 0+1-CF = (dividend < divisor) ? 0 : 1

Simpler Code for

Integer division by a constant can be made faster if the range of

Restricted Dividend

the dividend is limited, which removes a shift associated with

 

most divisors. For example, for a divide by 10 operation, use the

 

following code if the dividend is less than 40000005h:

 

MOV

EAX, dividend

 

MOV

EDX, 01999999Ah

 

MUL

EDX

 

 

MOV

quotient, EDX

Signed Division by Multiplication of Constant

Algorithm: Divisors These algorithms work if the divisor is positive. If the divisor is

2 <= d < 231negative, use abs(d) instead of d, and append a ‘NEG EDX’ to the code. The code makes use of the fact that n/–d = –(n/d).

;IN: d = divisor, 2 <= d < 2^31

;OUT: a = algorithm

;m = multiplier

;s = shift count

;algorithm

0

 

MOV

EAX,

m

 

MOV

EDX,

dividend

 

MOV

ECX,

EDX

 

IMUL

EDX

 

 

SHR

ECX,

31

 

SAR

EDX,

s

 

ADD

EDX,

ECX

;quotient in EDX

Replace Divides with Multiplies

79

Page 95
Image 95
AMD x86 manual Signed Division by Multiplication of Constant, Simpler Code for, Restricted Dividend