Can a compiler optimize a conditional statement in a loop by moving it in a loop?

Here is the C code:

struct node{ void *value; struct node *next; }; void g(void *p){ /*...*/ } void f(struct node *head, const int ok){ struct node *p=head; while (p){ /* ... code 1 ... */ if (ok!=0){ g(p->value); } p=p->next; } } 

I used gcc to compile this code. If I compiled with -O , I would optimize the function f as follows:

 void f(struct node *head, const int ok){ struct node *p=head; if (ok!=0){ while (p){ /* ... code 1 ... */ g(p->value); p=p->next; } } else{ while (p){ /* ... code 1 ... */ p=p->next; } } } 
+7
source share
3 answers

This will greatly depend on how large /* code 1 */ . If he is very small, he can do it. But if it is something above a few lines, most likely this will not happen. Duplicating a lot of code for each if will have terrible performance consequences. In fact, this can happen with very aggressive optimizations and, of course, not only with -O . On the gcc man page (highlighted by me):

-O
-O1 ...

With -O, the compiler tries to reduce code size and runtime without performing any optimizations that require a lot of compilation time.

Thus, abbreviation code is also part of the optimization.

-O2 Optimize even more. GCC performs almost all supported optimizations that are not compromised in speed . Compared to -O, this option increases both compilation time and the performance of the generated code.

So, -O2 will not do what you want.

-O3 Optimize even more. -O3 includes all optimizations specified by -O2, and also includes -finline-functions , -funswitch-loops , -fpredictive-commoning , -fgcse-after-reload , -ftree-vectorize and -fipa-cp-clone .

Now we need to look at these options to see if any of them can do what you want:

-funswitch-loops
Move branches with closed loop conditions from the loop, with duplicates of the loop on both branches (modified according to the result of the condition).

Voila! With -O3 you get the optimization you need.

+15
source

Well, it depends on many things.

Since you are using gcc , you can always check if this was for a particular program by calling gcc -o -S fileName.c

+2
source

In such situations, I find this site http://gcc.godbolt.org/ very useful.

+2
source

All Articles