Chapter 8 Integer Optimizations 191
Software Optimization Guide for AMD64 Processors
25112 Rev. 3.06 September 2005
"Division by Invariant Integers using Multiplication". SIGPLAN Notices,
Vol. 29, June 1994, page 61.
*/
l = log2(d);
j = (((U64)(0x80000000)) % ((U64)(d)));
k = (((U64)(1)) << (32 + l)) / ((U64)(0x80000000 - j));
m_low = (((U64)(1)) << (32 + l)) / d;
m_high = ((((U64)(1)) << (32 + l)) + k) / d;
while (((m_low >> 1) < (m_high >> 1)) && (l > 0)) {
m_low = m_low >> 1;
m_high = m_high >> 1;
l = l - 1;
}
m = ((U32)(m_high));
s = l;
a = (m_high >> 31) ? 1 : 0;
if (a) {
printf("; dividend: memory location or register other than EAX or EDX\n");
printf("\n");
printf("MOV EAX, 0%08LXh\n", m);
printf("IMUL dividend\n");
printf("MOV EAX, dividend\n");
printf("ADD EDX, EAX\n");
if (s) printf("SAR EDX, %d\n", s);
printf("SHR EAX, 31\n");
printf("ADD EDX, EAX\n");
if (e < 0) printf("NEG EDX\n");
printf("\n");
printf("; quotient now in EDX\n");
}
else {
printf("; dividend: memory location of register other than EAX or EDX\n");
printf("\n");
printf("MOV EAX, 0%08LXh\n", m);
printf("IMUL dividend\n");
printf("MOV EAX, dividend\n");
if (s) printf("SAR EDX, %d\n", s);
printf("SHR EAX, 31\n");
printf("ADD EDX, EAX\n");
if (e < 0) printf("NEG EDX\n");
printf("\n");
printf("; quotient now in EDX\n");
}
printed_code:
fprintf(stderr, "\n");
exit(0);
}