I have the following C/C++ code, which uses __builtin_return_address
:
#include <stdio.h>
#ifdef __clang__
# define optnone __attribute__((optnone))
#else
# define optnone __attribute__((optimize("O0")))
#endif
void *f() {
return __builtin_extract_return_addr(__builtin_return_address(2));
}
optnone void nest1() {
printf("%p\n", f());
}
optnone void nest2() {
nest1();
}
optnone void nest3() {
nest2();
}
optnone void nest4() {
nest3();
}
optnone int main() {
nest4();
}
GCC generates the following assembly and works fine (does not crash):
f:
push rbp
mov rbp, rsp
mov rax, QWORD PTR [rbp+0]
pop rbp
mov rax, QWORD PTR [rax]
mov rax, QWORD PTR [rax+8]
ret
Clang compiles the following assembly, and crashes:
f: # @f
push rbp
mov rbp, rsp
mov rax, qword ptr [rbp]
mov rax, qword ptr [rax]
mov rax, qword ptr [rax + 8]
pop rbp
ret
What is the reason of the crash?