Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C/C++ compilers such as GCC generally optimize modulo by a constant power of 2?

Tags:

Let's say I have something like:

#define SIZE 32

/* ... */

unsigned x;

/* ... */

x %= SIZE;

Would the x % 32 generally be reduced to x & 31 by most C/C++ compilers such as GCC?

like image 976
Matt Avatar asked Mar 17 '14 03:03

Matt


People also ask

What optimization does GCC do?

The compiler optimizes to reduce the size of the binary instead of execution speed. If you do not specify an optimization option, gcc attempts to reduce the compilation time and to make debugging always yield the result expected from reading the source code.

What is compiler optimization in C?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Does GCC optimize assembly?

No. GCC passes your assembly source through the preprocessor and then to the assembler. At no time are any optimisations performed.

Do compilers Optimise code?

Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.


1 Answers

Yes, any respectable compiler should perform this optimization. Specifically, a % X operation, where X is a constant power of two will become the equivalent of an & (X-1) operation.

GCC will even do this with optimizations turned off:

Example (gcc -c -O0 version 3.4.4 on Cygwin):

unsigned int test(unsigned int a) {
   return a % 32;
}

Result (objdump -d):

00000000 <_test>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   8b 45 08                mov    0x8(%ebp),%eax
   6:   5d                      pop    %ebp
   7:   83 e0 1f                and    $0x1f,%eax          ;; Here
   a:   c3                      ret
like image 77
Jonathon Reinhart Avatar answered Oct 20 '22 16:10

Jonathon Reinhart