AMD 250 Computer Hardware User Manual


 
48 C and C++ Source-Level Optimizations Chapter 2
25112 Rev. 3.06 September 2005
Software Optimization Guide for AMD64 Processors
2.24 Sign of Integer Operands
Optimization
Where there is a choice of using either a signed or an unsigned type, take into consideration that some
operations are faster with unsigned types while others are faster for signed types.
Application
This optimization applies to:
32-bit software
Rationale
In many cases, the type of data to be stored in an integer variable determines whether a signed or an
unsigned integer type is appropriate. For example, to record the weight of a person in pounds, no
negative numbers are required, so an unsigned type is appropriate. However, recording temperatures
in degrees Celsius may require both positive and negative numbers, so a signed type is needed.
Integer-to-floating-point conversion using integers larger than 16 bits is faster with signed types, as
the AMD64 architecture provides instructions for converting signed integers to floating-point but has
no instructions for converting unsigned integers. In a typical case, a 32-bit integer is converted by a
compiler to assembly as follows:
Examples
Listing 18. (Avoid)
double x; ====> mov [temp+4], 0
unsigned int i; mov eax, i
mov [temp], eax
x = i; fild QWORD PTR [temp]
fstp QWORD PTR [x]
The preceding code is slow not only because of the number of instructions, but also because a size
mismatch prevents store-to-load forwarding to the FILD instruction. Instead, use the following code:
Listing 19. (Preferred)
double x; ====> fild DWORD PTR [i]
int i; fstp QWORD PTR [x]
x = i;
Computing quotients and remainders in integer division by constants is faster when performed on
unsigned types. The following typical case is the compiler output for a 32-bit integer divided by 4: