Search code examples
assemblygccinline-assemblyloop-unrollingno-op

GCC inline asm NOP loop not being unrolled at compile time


Venturing out of my usual VC++ realm into the world of GCC (via MINGW32). Trying to create a Windows PE that consists largely of NOPs, ala:

for(i = 0; i < 1000; i++)
{
    asm("nop");
}

But either I'm using the wrong syntax or the compiler is optimising through them because those NOPs don't survive the compilation process.

I'm using the -O0 flag, otherwise defaults. Any ideas on how I can coax the compiler into leaving the NOPs intact?


Solution

  • Are you expecting it to unroll the loop in to 1000 nops? I did a quick test with gcc and I don't see the (one) nop disappear:

            xorl    %eax, %eax
            .p2align 4,,7
    .L2:
    #APP
            nop
    #NO_APP
            addl    $1, %eax
            cmpl    $1000, %eax
            jne     .L2
    

    With gcc -S -O3 -funroll-all-loops I see it unroll the loop 8 times (thus 8 nop) but I think if you want 1000 it's going to be easiest to do:

    #define NOP10() asm("nop;nop;nop;nop;nop;nop;nop;nop;nop;nop")
    

    And then use NOP10(); ...