<p>My C code snippet takes the address of an argument and stores it in a volatile memory location (preprocessed code):</p>

<pre><code>void foo(unsigned int x) {
    *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;x);
}

int main() {
    foo(1);
    while(1);
}
</code></pre>

<p>I used an SVN version of GCC for compiling this code. At the end of function <code>foo</code> I would expect to have the value <code>1</code> stored in the stack and, at <code>0x40000d4</code>, an address pointing to that value. When I compile without optimizations using the flag <code>-O0</code>, I get the expected ARM7TMDI assembly output (commented for your convenience):</p>

<pre><code>        .align  2
        .global foo
        .type   foo, %function
foo:
        @ Function supports interworking.
        @ args = 0, pretend = 0, frame = 8
        @ frame_needed = 0, uses_anonymous_args = 0
        @ link register save eliminated.
        sub     sp, sp, #8
        str     r0, [sp, #4]     @ 3. Store the argument on the stack
        mov     r3, #67108864
        add     r3, r3, #212
        add     r2, sp, #4       @ 4. Address of the stack variable
        str     r2, [r3, #0]     @ 5. Store the address at 0x40000d4
        add     sp, sp, #8
        bx      lr
        .size   foo, .-foo
        .align  2
        .global main
        .type   main, %function
main:
        @ Function supports interworking.
        @ args = 0, pretend = 0, frame = 0
        @ frame_needed = 0, uses_anonymous_args = 0
        stmfd   sp!, {r4, lr}
        mov     r0, #1           @ 1. Pass the argument in register 0
        bl      foo              @ 2. Call function foo
.L4:
        b       .L4
        .size   main, .-main
        .ident  "GCC: (GNU) 4.4.0 20080820 (experimental)"
</code></pre>

<p>It clearly stores the argument first on the stack and from there stores it at <code>0x40000d4</code>. When I compile with optimizations using <code>-O1</code>, I get something unexpected:</p>

<pre><code>        .align  2
        .global foo
        .type   foo, %function
foo:
        @ Function supports interworking.
        @ args = 0, pretend = 0, frame = 8
        @ frame_needed = 0, uses_anonymous_args = 0
        @ link register save eliminated.
        sub     sp, sp, #8
        mov     r2, #67108864
        add     r3, sp, #4        @ 3. Address of *something* on the stack
        str     r3, [r2, #212]    @ 4. Store the address at 0x40000d4
        add     sp, sp, #8
        bx      lr
        .size   foo, .-foo
        .align  2
        .global main
        .type   main, %function
main:
        @ Function supports interworking.
        @ args = 0, pretend = 0, frame = 0
        @ frame_needed = 0, uses_anonymous_args = 0
        stmfd   sp!, {r4, lr}
        mov     r0, #1           @ 1. Pass the argument in register 0
        bl      foo              @ 2. Call function foo
.L4:
        b       .L4
        .size   main, .-main
        .ident  "GCC: (GNU) 4.4.0 20080820 (experimental)"
</code></pre>

<p>This time the argument is never stored on the stack even though <em>something</em> from the stack is still stored at <code>0x40000d4</code>.</p>

<p>Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug&trade;?</p>

[{'answer_id': 28569, 'author': 'sparkes', 'author_id': 269, 'author_profile': 'https://Stackoverflow.com/users/269', 'pm_score': -1, 'selected': False, 'text': "<blockquote>\n  <p>Is this just expected/undefined\n  behaviour? Have I done something wrong\n  or have I in fact found a Compiler\n  Bug™?</p>\n</blockquote>\n\n<p>No bug just the defined behaviour that optimisation options can produce odd code which might not work :)</p>\n\n<p>EDIT:</p>\n\n<p>If you think you have found a bug in GCC the mailing lists will be glad you dropped by but generally they find some hole in your knowledge is to blame and mock mercilessly :(</p>\n\n<p>In this case I think it's probably the -O options attempting shortcuts that break your code that need working around.</p>\n"}, {'answer_id': 28651, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 1, 'selected': False, 'text': "<p>I'm darned if I can find a reference at the moment, but I'm 99% sure that you <em>are</em> always supposed to be able to take the address of an argument, and it's up to the compiler to finesse the details of calling conventions, register usage, etc.</p>\n\n<p>Indeed, I would have thought it to be such a common requirement that it's hard to see there can be general problem in this - I wonder if it's something about the volatile pointers which have upset the optimisation.</p>\n\n<p>Personally, I might do try this to see if it compiled better:</p>\n\n<pre><code>void foo(unsigned int x) \n{\n    volatile unsigned int* pArg = &amp;x;\n    *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n</code></pre>\n"}, {'answer_id': 28725, 'author': 'Tomi Kyöstilä', 'author_id': 616, 'author_profile': 'https://Stackoverflow.com/users/616', 'pm_score': 0, 'selected': False, 'text': "<p>sparkes wrote</p>\n\n<blockquote>\n  <p>If you think you have found a bug in\n  GCC the mailing lists will be glad you\n  dropped by but generally they find\n  some hole in your knowledge is to\n  blame and mock mercilessly :(</p>\n</blockquote>\n\n<p>I figured I'd try my luck here first before going to the GCC mailing list to show my incompetence :)</p>\n\n<hr>\n\n<p>Adam Davis wrote</p>\n\n<blockquote>\n  <p>Out of curiosity, what are you trying\n  to accomplish?</p>\n</blockquote>\n\n<p>I was trying out development for the Game Boy Advance. I was reading about its DMA system and I experimented with it by creating single-color tile bitmaps. The idea was to have the indexed color be passed as an argument to a function which would use DMA to fill a tile with that color. The source address for the DMA transfer is stored at <code>0x40000d4</code>.</p>\n\n<hr>\n\n<p>Will Dean wrote</p>\n\n<blockquote>\n  <p>Personally, I might do try this to see\n  if it compiled better:</p>\n\n<pre><code>void foo(unsigned int x) \n{\n    volatile unsigned int* pArg = &amp;x;\n    *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n</code></pre>\n</blockquote>\n\n<p>With <code>-O0</code> that works as well and with <code>-O1</code> that is optimized to the exact same <code>-O1</code> assembly I've posted in my question.</p>\n"}, {'answer_id': 54042, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 2, 'selected': False, 'text': "<p>So you're putting the address of a local stack variable into the DMA controller to be used, and then you're returning from the function where the stack variable is available?</p>\n\n<p>While this <em>might</em> work with your main() example (since you aren't writing on the stack again) it won't work in a 'real' program later - that value will be overwritten before or while DMA is accessing it when another function is called and the stack is used again.</p>\n\n<p>You need to have a structure, or a global variable you can use to store this value while the DMA accesses it - otherwise it's just going to get clobbered!</p>\n\n<p>-Adam</p>\n"}, {'answer_id': 54940, 'author': 'Alan H', 'author_id': 3807, 'author_profile': 'https://Stackoverflow.com/users/3807', 'pm_score': 0, 'selected': False, 'text': "<p>Not an answer, but just some more info for you.\nWe are running 3.4.5 20051201 (Red Hat 3.4.5-2) at my day job.</p>\n\n<p>We have also noticed some of our code (which I can't post here) stops working when\nwe add the -O1 flag.  Our solution was to remove the flag for now :(</p>\n"}, {'answer_id': 69454, 'author': 'Ben Combee', 'author_id': 1323, 'author_profile': 'https://Stackoverflow.com/users/1323', 'pm_score': 2, 'selected': False, 'text': '<p>I actually don\'t think the compiler is wrong, although this is an odd case.</p>\n\n<p>From a code analysis point-of-view, it sees you storing the address of a variable, but that address is never dereferenced and you don\'t jump outside of the function to external code that could use that address you stored.  When you exit the function, the address of the stack is now considered bogus, since its the address of a variable that no longer exists.</p>\n\n<p>The "volatile" keyword really doesn\'t do much in C, especially with regards to multiple threads or hardware.  It just tells the compiler that it has to do the access.  However, since there\'s no users of the value of x according to the data flow, there\'s no reason to store the "1" on the stack.</p>\n\n<p>It probably would work if you wrote</p>\n\n<pre><code>void foo(unsigned int x) {\n    volatile int y = x;\n    *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;y);\n}\n</code></pre>\n\n<p>although it still may be illegal code, since the address of y is considered invalid as soon as foo returns, but the nature of the DMA system would be to reference that location independently of the program flow.</p>\n'}, {'answer_id': 281072, 'author': 'flolo', 'author_id': 36472, 'author_profile': 'https://Stackoverflow.com/users/36472', 'pm_score': 0, 'selected': False, 'text': '<p>In general I would say, that it is a valid optimization. \nIf you want to look deeper into it, you could compile with -da\nThis generates a .c.Number.Passname, where you can have a look at the rtl (intermediate representation within the gcc). There you can see which pass makes which optimization (and maybe disable just the one, you dont want to have)</p>\n'}, {'answer_id': 293385, 'author': 'zaphod', 'author_id': 13871, 'author_profile': 'https://Stackoverflow.com/users/13871', 'pm_score': 3, 'selected': False, 'text': '<p>Once you return from <code>foo()</code>, <code>x</code> is gone, and any pointers to it are invalid.  Subsequently using such a pointer results in what the C standard likes to call "undefined behavior," which means the compiler is absolutely allowed to assume you won\'t dereference it, or (if you insist on doing it anyway) need not produce code that does anything remotely like what you might expect.  If you want the pointer to <code>x</code> to remain valid after <code>foo()</code> returns, you must not allocate <code>x</code> on foo\'s stack, period -- even if you <em>know</em> that in principle, nothing has any reason to clobber it -- because that just isn\'t allowed in C, no matter how often it happens to do what you expect.</p>\n\n<p>The simplest solution might be to make <code>x</code> a local variable in <code>main()</code> (or in whatever other function has a sufficiently long-lived scope) and to pass the address in to foo.  You could also make <code>x</code> a global variable, or allocate it on the heap using <code>malloc()</code>, or set aside memory for it in some more exotic way.  You can even try to figure out where the top of the stack is in some (hopefully) more portable way and explicitly store your data in some part of the stack, if you\'re sure you won\'t be needing for anything else and you\'re convinced that\'s what you really need to do.  But the method you\'ve been using to do that isn\'t sufficiently reliable, as you\'ve discovered.</p>\n'}, {'answer_id': 293387, 'author': 'Evan Teran', 'author_id': 13430, 'author_profile': 'https://Stackoverflow.com/users/13430', 'pm_score': 2, 'selected': False, 'text': '<p>One thing to note is that according to the standard, casts are r-values. GCC used to allow it, but in recent versions has become a bit of a standards stickler.</p>\n\n<p>I don\'t know if it will make a difference, but you should try this:</p>\n\n<pre><code>void foo(unsigned int x) {\n    volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n    *ptr = (unsigned int)(&amp;x);\n}\n\nint main() {\n    foo(1);\n    while(1);\n}\n</code></pre>\n\n<p>Also, I doubt you intended it, but you are storing the address of the function local x (which is a copy of the int you passed). You likely want to make foo take an "unsigned int *" and pass the address of what you really want to store.</p>\n\n<p>So I feel a more proper solution would be this:</p>\n\n<pre><code>void foo(unsigned int *x) {\n    volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n    *ptr = (unsigned int)(x);\n}\n\nint main() {\n    int x = 1;\n    foo(&amp;x);\n    while(1);\n}\n</code></pre>\n\n<p>EDIT: finally, if you code breaks with optimizations it is usually a sign that your code is doing something wrong.</p>\n'}, {'answer_id': 801152, 'author': 'old_timer', 'author_id': 16007, 'author_profile': 'https://Stackoverflow.com/users/16007', 'pm_score': 0, 'selected': False, 'text': '<p>I think Even T. has the answer.  You passed in a variable, you cannot take the address of that variable inside the function, you can take the address of a copy of that variable though, btw that variable is typically a register so it doesnt have an address.  Once you leave that function its all gone, the calling function loses it.  If you need the address in the function you have to pass by reference not pass by value, send the address.  It looks to me that the bug is in your code, not gcc.</p>\n\n<p>BTW, using *(volatile blah *)0xabcd or any other method to try to program registers is going to bite you eventually.  gcc and most other compilers have this uncanny way of knowing exactly the worst time to strike. </p>\n\n<p>Say the day you change from this</p>\n\n<pre><code>*(volatile unsigned int *)0x12345 = someuintvariable;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>*(volatile unsigned int *)0x12345 = 0x12;\n</code></pre>\n\n<p>A good compiler will realize that you are only storing 8 bits and there is no reason to waste a 32 bit store for that, depending on the architecture you specified, or the default architecture for that compiler that day, so it is within its rights to optimize that to an strb instead of an str.</p>\n\n<p>After having been burned by gcc and others with this dozens of times I have resorted to forcing the issue:</p>\n\n<pre><code>.globl PUT32\nPUT32:\n   str r1,[r0]\n   bx lr\n\n\n\n\n\n   PUT32(0x12345,0x12);\n</code></pre>\n\n<p>Costs a few extra clock cycles but my code continues to work yesterday, today, and will work tomorrow with any optimization flag.  Not having to re-visit old code and sleeping peacefully through the night is worth a few extra clock cycles here and there.</p>\n\n<p>Also if your code breaks when you compile for release instead of compile for debug, that also means it is most likely a bug in your code.</p>\n'}, {'answer_id': 5316968, 'author': 'David Cary', 'author_id': 238320, 'author_profile': 'https://Stackoverflow.com/users/238320', 'pm_score': 1, 'selected': False, 'text': '<p>Tomi Kyöstilä <a href="https://stackoverflow.com/questions/28542/is-gcc-broken-when-taking-the-address-of-an-argument-on-arm7tdmi/28725#28725">wrote</a></p>\n\n<blockquote>\n  <p>development for the Game Boy Advance.\n  I was reading about its DMA system and\n  I experimented with it by creating\n  single-color tile bitmaps. The idea\n  was to have the indexed color be\n  passed as an argument to a function\n  which would use DMA to fill a tile\n  with that color. The source address\n  for the DMA transfer is stored at\n  0x40000d4.</p>\n</blockquote>\n\n<p>That\'s a perfectly valid thing for you to do, and I can see how the (unexpected) code you got with the -O1 optimization wouldn\'t work.</p>\n\n<p>I see the (expected) code you got with the -O0 optimization does what you expect -- it puts value of the color you want on the stack, and a pointer to that color in the DMA transfer register.</p>\n\n<p>However, even the (expected) code you got with the -O0 optimization wouldn\'t work, either.\nBy the time the DMA hardware gets around to taking that pointer and using it to read the desired color, that value on the stack has (probably) long been overwritten by other subroutines or interrupt handlers or both.\nAnd so both the expected and the unexpected code result in the same thing -- the DMA is (probably) going to fetch the wrong color.</p>\n\n<p>I think you really intended to store the color value in some location where it stays safe until the DMA is finished reading it.\nSo a global variable, or a function-local static variable such as</p>\n\n<p>// Warning: <a href="http://c2.com/cgi/wiki?ThreeStarProgrammer" rel="nofollow noreferrer">Three Star Programmer</a> at work</p>\n\n<pre><code>// Warning: untested code.\nvoid foo(unsigned int x) {\n    static volatile unsigned int color = x; // "static" so it\'s not on the stack\n    volatile unsigned int** dma_register =\n        (volatile unsigned int**)(0x4000000 + 0xd4);\n    *dma_register = &amp;color;\n}\n\nint main() {\n    foo(1);\n    while(1);\n}\n</code></pre>\n\n<p>Does that work for you?</p>\n\n<p>You see I use "volatile" twice, because I want to force <em>two</em> values to be written in that particular order.</p>\n'}]
['https://Stackoverflow.com/questions/28542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/616/']