How to make clang compile to llvm IR

bitcodecclangllvm

I want clang to compile my C/C++ code to LLVM bitcode rather than a binary executable. How can I achieve that?

And if I have the LLVM bitcode, how can I further compile it to a binary executable?

I want to add some of my own code to the LLVM bitcode before compiling to a binary executable.

Best Answer

Given some C/C++ file foo.c:

> clang -S -emit-llvm foo.c

Produces foo.ll which is an LLVM IR file.

The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

> clang -cc1 foo.c -emit-llvm

Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


To compile LLVM IR further to assembly, use the llc tool:

> llc foo.ll

Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.