190 Integer Optimizations Chapter 8
25112 Rev. 3.06 September 2005
Software Optimization Guide for AMD64 Processors
int main(void)
{
fprintf(stderr, "\n");
fprintf(stderr, "Signed division by constant\n");
fprintf(stderr, "===========================\n\n");
fprintf(stderr, "enter divisor: ");
scanf("%ld", &d);
fprintf(stderr, "\n");
e = d;
d = labs(d);
if (d == 0) goto printed_code;
if (e == (-1)) {
printf("; dividend: register or memory location\n");
printf("\n");
printf("NEG dividend\n");
printf("\n");
printf("; quotient replaced dividend\n");
goto printed_code;
}
if (d == 2) {
printf("; dividend expected in EAX\n");
printf("\n");
printf("CMP EAX, 080000000h\n");
printf("SBB EAX, -1\n");
printf("SAR EAX, 1\n");
if (e < 0) printf("NEG EAX\n");
printf("\n");
printf("; quotient now in EAX\n");
goto printed_code;
}
if (!(d & (d - 1))) {
printf("; dividend expected in EAX\n");
printf("\n");
printf("CDQ\n");
printf("AND EDX, 0%08lXh\n", (d-1));
printf("ADD EAX, EDX\n");
if (log2(d)) printf("SAR EAX, %d\n", log2(d));
if (e < 0) printf("NEG EAX\n");
printf("\n");
printf("; quotient now in EAX\n");
goto printed_code;
}
/* Determine algorithm (a), multiplier (m), and shift factor (s) for 32-bit
signed integer division. Based on: Granlund, T.; Montgomery, P.L.: