[Clang] How to emit final (after optimizations) IR for the given code?

Hi!
I’m playing with Clang and LLVM and I would like to see IR after the optimizations.
-emit-llvm emits non-optimized IR that is really hard to read
-mllvm -print-after-all emits IR after each optimization which is really verbose
I want to see optimized (e.g. -O2) IR, is there a way to do so?

Thanks in advance!

P. S. Couldn’t google the solution

Clang with -emit-llvm should emit the optimized IR if it’s combined with -O2 (or anything but the default -O0). E.g.

tim@Tims-iMac-Pro:~ $ cat tmp.c
int foo(int a, int b) {
  return a + b;
}
tim@Tims-iMac-Pro:~ $ clang tmp.c -emit-llvm -S -o- -Os
[...]
define i32 @foo(i32 %0, i32 %1) local_unnamed_addr #0 {
  %3 = add nsw i32 %1, %0
  ret i32 %3
}

That’s definitely optimized, the unoptimized one would have all kinds of extra allocas, loads & stores etc (try adding -Xclang -disable-llvm-passes to see, or compiling -O0).

So what other options are you passing to Clang? And could you show us a very simple transcript example like mine?

2 Likes

Yes, you’re absolutely right
I was confused with an error that something like this: cannot use -emit-llvm while linking
That’s why I switched to frontend driver -cc1 which probably just ignores any optimization levels flags - that’s why the IR wasn’t optimized every time
Thank you for the quick reply!