int f(int x) { int a[] = {0, 1}; return a[x]; } On AMD64, with -O3, this is generated : f(int): mov rax, QWORD PTR .LC0[rip] movsx rdi, edi mov QWORD PTR [rsp-8], rax mov eax, DWORD PTR [rsp-8+rdi*4] ret .LC0: .long 0 .long 1 LLVM generates this : f(int): # @f(int) movsxd rax, edi mov eax, dword ptr [4*rax + .L__const.f(int).a] ret .L__const.f(int).a: .long 0 # 0x0 .long 1 # 0x1 It seems to me like not copying the entire array on the stack makes for faster code.
It could be optimized to return x even ... Note we're forcing the array to the stack because of the variable array access. We could optimize this on the GIMPLE level from MEM <unsigned long> [(int *)&a] = 3547642986509; _5 = a[x_4(D)]; to 3547642986509ul >> (x_4(D)*32) for example when using more "interesting" constants like int f(int x) { int a[] = {13, 826}; return a[x]; }