ARM Compiler does strange things in Release mode...

Comments

1 comment

  • Avatar
    Paul Curtis

    The solution is quite simple: use volatile correctly on variables that are likely, or will, change behind the compiler's back without it knowing about them!

    Let's take a very simple function:

    static int x;
    
    void foo(void)
    {
      while (x == 1)
        {
          ++x;
        }
    }
    

    There's a loop in there, correct? No, you're wrong, there isn't, and the compiler knows it because it can reason about the code it sees. If it could not reason about the code that it sees, it would not be able to optimize it. Customers want their code optimized, but they tell the compiler all sorts of lies about the way their code runs. Here's the output:

    foo:
    	ldr	r3, .L8
    	ldr	r3, [r3]
    	cmp	r3, #1
     	bne	.L5
     	movs	r2, #2
     	ldr	r3, .L8
    	str	r2, [r3]
    .L5:
    	bx	lr
    .L9:
    

    No loop. The compiler knows that if it enters and sees that x is 1, then on exit x will be 2. If it enters and sees that x is not one, x is unchanged. And that is what the compiler coded into the function.

    Let's change this a bit more. Rather than a static x, let's do something that is unexpected. Let's move the declaration of x into the function and see if we get a loop.

    void foo(void)
    {
      int x;
      while (x == 1)
        {
          ++x;
        }
    }
    

    Now, what do you suppose the compiler produces? Well, ithis:

    foo:
    	bx	lr
    

    No loop! Nothing! What's that? Well, it's because x doesn't have a defined value on entry, so it could be one, or it could be 925. So, the compiler says "well, I can do anything here, so le me do what generates the fastest/smallest/best code" and it throws everything away. There are many, many more examples of this. The compiler will reason about your code, and can do so very well, and in the end it generates what it feels you've asked for. If you have not applied volatile correctly.

    0
    Comment actions Permalink

Please sign in to leave a comment.