1

I've been playing around with Godbolt a bit to see how the compiler optimizes instructions, and something I've noticed is how the optimization of simple C programs seems to return immediately without actually doing the computation. Say I have a very simple program in Godbolt (here):

int square(int num) {
    return num * num;
}

int main(int argc, const char* argv[]){
    return square(argc);
}

The MIPS instruction output is:

square:
        j       $31
        mul     $2,$4,$4

main:
        j       $31
        mul     $2,$4,$4

From my recollection of MIPS, isn't this just jumping to the $ra register immediately, effectively not doing anything at all? I thought that once we j $31 or jump to the return address (and not doing a jal), we're effectively returning from the function at that point. So how is this working if it's returning before doing the multiply?

rb612
  • 5,280
  • 3
  • 30
  • 68
  • 1
    There are some processors that will always execute the instruction after a branch instruction. MIPS may be one of those. – user3386109 Aug 09 '19 at 21:42
  • Here's a possible duplicate: https://stackoverflow.com/questions/4115847/strange-jump-in-mips-assembly – user3386109 Aug 09 '19 at 21:47
  • [MIPS jump instruction delay slot](https://stackoverflow.com/q/47423368/995714), [Weird MIPS assembler behavior with jump (and link) instruction](https://stackoverflow.com/q/3807480/995714), [Example with MIPS, Pipelining and Branch Delay Slot](https://stackoverflow.com/q/48650320/995714) – phuclv Aug 10 '19 at 01:17

1 Answers1

3

I'm totally not an assembler guy, but I did read about this a little while ago. The answer: branch delay slots. Read more here: https://devblogs.microsoft.com/oldnewthing/20180411-00/?p=98485

When you perform a branch instruction, the instruction after the branch instruction is executed, even if the branch is taken. The branch itself is delayed by one instruction.

Vilx-
  • 104,512
  • 87
  • 279
  • 422