Search code examples
gccoptimizationdelay

Why adding delay when gcc -o2 optimization is used?


I read an example code of STM32 with LCD and found below code, and its purpose is to write the LCD controller register index as output data of LCD controller.

void LCD_WR_REG(uint16_t regval)
{ 
    regval = regval;       // Necessary delay when using -o2 optimization
    LCD->LCD_REG = regval;
}

I searched for a while for -o2, but didn't get much useful info about the what the comment here means, or why a self assignment is necessary here.


Solution

  • The comment is simply wrong. This operation will be optimized out. I believe that this comment was written where the original author of the code is struggling to make it work and something else was in this line.

    LCD_WR_REG:
            ldr     r3, .L3
            strh    r0, [r3]        @ movhi
            bx      lr
    .L3:
            .word   1207993344
    

    It could have some effect if regval was declared as volatile

    void LCD_WR_REG1(volatile uint16_t regval)
    { 
        regval = regval;       // Necessary delay when using -o2 optimization
        LCD->LCD_REG = regval;
    }
    
    LCD_WR_REG1:
            sub     sp, sp, #8
            strh    r0, [sp, #6]    @ movhi
            ldrh    r3, [sp, #6]
            strh    r3, [sp, #6]    @ movhi
            ldr     r2, .L7
            ldrh    r3, [sp, #6]
            strh    r3, [r2]        @ movhi
            add     sp, sp, #8
            bx      lr
    .L7:
            .word   1207993344
    

    https://godbolt.org/z/Th7naabf7