clang does not pass pie-level and pic-level option values to the code generator with "-x ir" due to the following code in CompilerInvocation.cpp:
if (DashX == IK_AST || DashX == IK_LLVM_IR) { ....; } else { ParseLangArgs(*Res.getLangOpts(), Args, DashX, Res.getTargetOpts(), Diags); }
pie-level and pic-level are LangArgs and are not parsed with "-x ir". They define macros PIC and PIE_ when set, see lib/Frontend/InitPreprocessor.cpp
Not setting LangOpts.PIELevel means that Options.PositionIndependentExecutable is always false even when -fPIE is used. This patch fixes that.
I considered an alternative of making pie-level and pic-level CodeGen Options. However, since these options are used to set macros PIE, PIC, etc. this looked better as LangOpts. Please let me know what you think.
For a broader context, I am working on optimizing accesses to global variables with -fPIE on x86-64 and this patch is the first step to get there. In particular, I noticed the following code generated with clang:
hello.cpp:
int a = 0;
int main() {
return a;
}
$ clang -O2 -fPIE hello.cc -S
$ cat hello.s
main: # @main
movq a@GOTPCREL(%rip), %rax
movl (%rax), %eax
retq
Creating a GOT entry for global 'a' is unnecessary as 'a' is defined in hello.cpp which will be linked into a position independent executable (fPIE). Hence, the definition of 'a' cannot be overridden and we can remove a load. The efficient access is this:
main: # @main
movl a(%rip), %eax
retq
I plan to address this in a separate patch.
This code would probably be cleaner with a local variable LanguageOptions &LangOpts = *Res.getLangOpts()