Home > database >  Why does the compiler copy RDI to another register, and then copy it back to RDI inside a loop?
Why does the compiler copy RDI to another register, and then copy it back to RDI inside a loop?

Time:02-12

I'm analysing a piece of inefficient code, but some of it is so confusing?

Original code:

#include <string.h>

void lowwer(char *str) {
  for (int i = 0; i < strlen(str);   i) {
    str[i] -= ('A' - 'a');
  }
}

Assembly code (generated by clang 13 with -Og option):

lowwer:
  pushq %r14 # use saved-registers
  pushq %rbx
  pushq %rax
  # guard do while
  cmpb  $0, (%rdi) # compare &str with null (check if strlen(str) == 0)
  je    .LBB0_3
  # loop initialization
  movq  %rdi, %r14 # %r14 = str
  xorl             
  • Related