开发者

How to prevent GCC from optimizing out a busy wait loop?

I want to write a C code firmware for Atmel AVR microcontrollers. I will compile it using GCC. Also, I want to enable compiler optimizations (-Os or -O2), as I see no reason to not enable them, and they will probably generate a better assembly way faster than writing assembly manually.

But I want a small piece of code not optimized. I want to delay the execution of a function by some time, and thus I wanted to write a do-nothing loop just to waste some time. No need to be precise, just wait some time.

/* How to NOT optimize this, while optimizing other code? */
unsigned char i, j;
j = 0;
while(--j) {
    i = 0;
    while(--i);
}

Since memory access in AVR is a lot slower, I want i and j to be kept in CPU registers.


Update: I just found util/delay.h and util/delay_basic.h开发者_JS百科 from AVR Libc. Although most times it might be a better idea to use those functions, this question remains valid and interesting.


Related questions:

  • How to prevent gcc optimizing some statements in C?
  • Is there a way to tell GCC not to optimise a particular piece of code?
  • How not to optimize away - mechanics of a folly function


I developed this answer after following a link from dmckee's answer, but it takes a different approach than his/her answer.

Function Attributes documentation from GCC mentions:

noinline This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm ("");

This gave me an interesting idea... Instead of adding a nop instruction at the inner loop, I tried adding an empty assembly code in there, like this:

unsigned char i, j;
j = 0;
while(--j) {
    i = 0;
    while(--i)
        asm("");
}

And it worked! That loop has not been optimized-out, and no extra nop instructions were inserted.

What's more, if you use volatile, gcc will store those variables in RAM and add a bunch of ldd and std to copy them to temporary registers. This approach, on the other hand, doesn't use volatile and generates no such overhead.


Update: If you are compiling code using -ansi or -std, you must replace the asm keyword with __asm__, as described in GCC documentation.

In addition, you can also use __asm__ __volatile__("") if your assembly statement must execute where we put it, (i.e. must not be moved out of a loop as an optimization).


Declare i and j variables as volatile. This will prevent compiler to optimize code involving these variables.

unsigned volatile char i, j;


Empty __asm__ statements are not enough: better use data dependencies

Like this:

main.c

int main(void) {
    unsigned i;
    for (i = 0; i < 10; i++) {
        __asm__ volatile("" : "+g" (i) : :);

    }
}

Compile and disassemble:

gcc -O3 -ggdb3 -o main.out main.c
gdb -batch -ex 'disas main' main.out

Output:

   0x0000000000001040 <+0>:     xor    %eax,%eax
   0x0000000000001042 <+2>:     nopw   0x0(%rax,%rax,1)
   0x0000000000001048 <+8>:     add    $0x1,%eax
   0x000000000000104b <+11>:    cmp    $0x9,%eax
   0x000000000000104e <+14>:    jbe    0x1048 <main+8>
   0x0000000000001050 <+16>:    xor    %eax,%eax
   0x0000000000001052 <+18>:    retq 

I believe that this is robust, because it places an explicit data dependency on the loop variable i as suggested at: Enforcing statement order in C++ and produces the desired loop:

This marks i as an input and output of inline assembly. Then, inline assembly is a black box for GCC, which cannot know how it modifies i, so I think that really can't be optimized away.

If I do the same with an empty __asm__ as in:

bad.c

int main(void) {
    unsigned i;
    for (i = 0; i < 10; i++) {
        __asm__ volatile("");
    }
}

it appears to completely remove the loop and outputs:

   0x0000000000001040 <+0>:     xor    %eax,%eax
   0x0000000000001042 <+2>:     retq

Also note that __asm__("") and __asm__ volatile("") should be the same since there are no output operands: The difference between asm, asm volatile and clobbering memory

What is happening becomes clearer if we replace it with:

__asm__ volatile("nop");

which produces:

   0x0000000000001040 <+0>:     nop
   0x0000000000001041 <+1>:     nop
   0x0000000000001042 <+2>:     nop
   0x0000000000001043 <+3>:     nop
   0x0000000000001044 <+4>:     nop
   0x0000000000001045 <+5>:     nop
   0x0000000000001046 <+6>:     nop
   0x0000000000001047 <+7>:     nop
   0x0000000000001048 <+8>:     nop
   0x0000000000001049 <+9>:     nop
   0x000000000000104a <+10>:    xor    %eax,%eax
   0x000000000000104c <+12>:    retq

So we see that GCC just loop unrolled the nop loop in this case because the loop was small enough.

So, if you rely on an empty __asm__, you would be relying on hard to predict GCC binary size/speed tradeoffs, which if applied optimally, should would always remove the loop for an empty __asm__ volatile(""); which has code size zero.

noinline busy loop function

If the loop size is not known at compile time, full unrolling is not possible, but GCC could still decide to unroll in chunks, which would make your delays inconsistent.

Putting that together with Denilson's answer, a busy loop function could be written as:

void __attribute__ ((noinline)) busy_loop(unsigned max) {
    for (unsigned i = 0; i < max; i++) {
        __asm__ volatile("" : "+g" (i) : :);
    }
}

int main(void) {
    busy_loop(10);
}

which disassembles at:

Dump of assembler code for function busy_loop:
   0x0000000000001140 <+0>:     test   %edi,%edi
   0x0000000000001142 <+2>:     je     0x1157 <busy_loop+23>
   0x0000000000001144 <+4>:     xor    %eax,%eax
   0x0000000000001146 <+6>:     nopw   %cs:0x0(%rax,%rax,1)
   0x0000000000001150 <+16>:    add    $0x1,%eax
   0x0000000000001153 <+19>:    cmp    %eax,%edi
   0x0000000000001155 <+21>:    ja     0x1150 <busy_loop+16>
   0x0000000000001157 <+23>:    retq   
End of assembler dump.
Dump of assembler code for function main:
   0x0000000000001040 <+0>:     mov    $0xa,%edi
   0x0000000000001045 <+5>:     callq  0x1140 <busy_loop>
   0x000000000000104a <+10>:    xor    %eax,%eax
   0x000000000000104c <+12>:    retq   
End of assembler dump.

Here the volatile is was needed to mark the assembly as potentially having side effects, since in this case we have an output variables.

A double loop version could be:

void __attribute__ ((noinline)) busy_loop(unsigned max, unsigned max2) {
    for (unsigned i = 0; i < max2; i++) {
        for (unsigned j = 0; j < max; j++) {
            __asm__ volatile ("" : "+g" (i), "+g" (j) : :);
        }
    }
}

int main(void) {
    busy_loop(10, 10);
}

GitHub upstream.

Related threads:

  • Endless loop in C/C++
  • Best way to implement busy loop?
  • Enforcing statement order in C++

Tested in Ubuntu 19.04, GCC 8.3.0.


I'm not sure why it hasn't been mentioned yet that this approach is completely misguided and easily broken by compiler upgrades, etc. It would make a lot more sense to determine the time value you want to wait until and spin polling the current time until the desired value is exceeded. On x86 you could use rdtsc for this purpose, but the more portable way would be to call clock_gettime (or the variant for your non-POSIX OS) to get the time. Current x86_64 Linux will even avoid the syscall for clock_gettime and use rdtsc internally. Or, if you can handle the cost of a syscall, just use clock_nanosleep to begin with...


I don't know off the top of my head if the avr version of the compiler supports the full set of #pragmas (the interesting ones in the link all date from gcc version 4.4), but that is where you would usually start.


For me, on GCC 4.7.0, empty asm was optimized away anyways with -O3 (didnt try with -O2). and using a i++ in register or volatile resulted in a big performance penalty (in my case).

What i did was linking with another empty function which the compiler couldnt see when compiling the "main program"

Basically this:

Created "helper.c" with this function declared (empty function)

void donotoptimize(){}

Then compiled gcc helper.c -c -o helper.o and then

while (...) { donotoptimize();}

and link it via gcc my_benchmark.cc helper.o.

This gave me best results (and from my belief, no overhead at all, but can't test because my program won't work without it :) )

I think it should work with icc too. Maybe not if you enable linking optimizations, but with gcc it does.


Putting volatile asm should help. You can read more on this here:-

http://www.nongnu.org/avr-libc/user-manual/optimization.html

If you are working on Windows, you can even try putting the code under pragmas, as explained in detail below:-

https://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data

Hope this helps.


put that loop in a separate .c file and do not optimize that one file. Even better write that routine in assembler and call it from C, either way the optimizer wont get involved.

I sometimes do the volatile thing but normally create an asm function that simply returns put a call to that function the optimizer will make the for/while loop tight but it wont optimize it out because it has to make all the calls to the dummy function. The nop answer from Denilson Sá does the same thing but even tighter...


You can also use the register keyword. Variables declared with register are stored in CPU registers.

In your case:

register unsigned char i, j;
j = 0;
while(--j) {
    i = 0;
    while(--i);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜