Why do the compiler puts nops seemingly without any reason?

93 Views Asked by At

I was playing some code at Godbolt, trying to understand how the compiler outputs the assembly instructions. But while playing, i observed there are certain nops in the assembly instructions produced by the compiler.

Souce File:

char str[] = "Hello World";

void foo() { 
    for(char i = 0; i < (char)11; i++) {
        if(str[i] == 'o') {
            str[i] = 'a';
        }
    }
}

Output:

str:
        .string "Hello World"
foo:
        pushq   %rbp
        movq    %rsp, %rbp
        movb    $0, -1(%rbp)
        jmp     .L2
.L4:
        movsbl  -1(%rbp), %eax
        cltq
        movzbl  str(%rax), %eax
        cmpb    $111, %al
        jne     .L3
        movsbl  -1(%rbp), %eax
        cltq
        movb    $97, str(%rax)
.L3:
        movzbl  -1(%rbp), %eax
        addl    $1, %eax
        movb    %al, -1(%rbp)
.L2:
        cmpb    $10, -1(%rbp)
        jle     .L4
        nop
        nop
        popq    %rbp
        ret

As you can see at line 24 and 25, there are 2 nop instructions. I could not find any reason for these nops to be in there. I believe it has something to do with some timings, but it is not obvious to me... or maybe I am completely wrong. What am I missing?

Note: I am using x86-64 gcc 13.2

0

There are 0 best solutions below