Note that there are some explanatory texts on larger screens.

plurals
  1. POavr-gcc destructive optimizations
    primarykey
    data
    text
    <p>I'm programming an Atmel ATtiny13a microcontroller using avr-gcc 4.8.2.</p> <p>This is my c code:</p> <pre><code>#include &lt;avr/io.h&gt; #include &lt;util/delay.h&gt; int main(void) { DDRB = 1; // PB0 is output for (uint8_t i = 0; i &lt; 10; i++) { PORTB = 1; _delay_ms(500); PORTB = 0; _delay_ms(500); } while(1); } void test(void) { DDRB = 1; // PB0 is output for (uint8_t i = 0; i &lt; 10; i++) { PORTB = 1; _delay_ms(100); PORTB = 0; _delay_ms(100); } } </code></pre> <p>The test function (fast blinking of an LED) is never called from the main function, so the controller should only enter the main function (slow blinking).</p> <p>When I compile the code with <code>-O1</code>, everything works fine:</p> <pre><code>avr-gcc -std=gnu99 -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -mmcu=attiny13 -DF_CPU=1200000 -Wall -Wstrict-prototypes -Os -c test.c -o test.o avr-gcc test.o -o test.elf avr-objcopy -O ihex -R .eeprom -R .fuse -R .lock -R .signature test.elf test.hex </code></pre> <p>But if I use <code>-Os</code> (optimization for size) or <code>-O2</code>, the microcontroller runs the <code>test</code> function instead of the <code>main</code> function: The LED blinks quickly and never stops.</p> <p>Is the <code>-Os</code> flag simply too dangerous to use, should it be avoided? Or is there something I can change in my code to avoid this kind of bug? The ATtiny13a only has 1K of flash, so size reduction is something important.</p> <hr> <p><em>Edit:</em> As suggested in the comments, here's the assembler diff with <code>-O1</code> and <code>-O2</code>: <a href="http://www.diffchecker.com/3l9cdln6" rel="nofollow">http://www.diffchecker.com/3l9cdln6</a></p> <p>In there you can see that <code>-O2</code> changes the first section from <code>.text</code> to <code>.text.startup</code>.</p> <pre><code>--- test.o1.txt 2013-12-03 19:10:43.874598682 +0100 +++ test.o2.txt 2013-12-03 19:10:50.574674155 +0100 @@ -3,7 +3,7 @@ __SREG__ = 0x3f __tmp_reg__ = 0 __zero_reg__ = 1 - .text + .section .text.startup,"ax",@progbits .global main .type main, @function main: </code></pre> <p>That's probably the main issue here. After some further testing I found that the culprit is the <code>-freorder-functions</code> optimization. Is there a way to prevent this behavior?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload