How to make clang compile to llvm IR

前端 未结 5 1681
感情败类
感情败类 2020-11-27 10:01

I want clang to compile my C/C++ code to LLVM bytecode rather than binary executable. How can I achieve that? And if I get the LLVM by

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 10:23

    If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.

    Instead, you want to compile with link-time-optimization

    clang -flto -c program1.c -o program1.o
    clang -flto -c program2.c -o program2.o
    

    and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm

    clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
    

    This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing

    clang program.bc -o program
    

    although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.

    Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option

    -B/home/jeremy/fakebin
    

    to any linking steps above.

提交回复
热议问题