2

We know that the IR file can be obtained from foo.cpp through the clang driver:

clang++ -emit-llvm -S foo.cpp -o foo.ll

Now I want to do this by using the libTooling's API without clang driver.

But I don't know how these APIs are used, I would like to know if there are some examples of using them, for example:

How to generate AST from cpp file?

How to convert AST to IR in memory form?

How to convert AST to IR in human readable text form?

All of this jobs' source code is very complex, but if libTooling provides some APIs, it may be simple, so what I want to know is whether these APIs exist and how to use them. Are there any examples that can be referenced?

273K
  • 29,503
  • 10
  • 41
  • 64

1 Answers1

2
  1. The libTooling tutorial documentation shows a code snippet that parses .cpp into AST: https://clang.llvm.org/docs/LibTooling.html . Remember that the hard part of doing this on real files is having all the include search paths and defines and everything set up correctly.

  2. You can use the clang::EmitLLVMOnlyAction to create LLVM IR in memory, use takeModule() to retrieve the LLVM module that clang produces. See https://github.com/llvm/llvm-project/blob/main/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp for an example of running an action over some AST (they use clang::EmitObjAction instead, but other than that it's the same).

  3. LLVM IR is a 1:1:1 representation between in-memory : bitcode : text. A llvm::Module has a print method, you can print to a llvm::raw_ostream backed by a string or backed by a file descriptor.

Nick Lewycky
  • 1,182
  • 6
  • 14
  • 1
    Thanks for your patience. But I still want to ask you a question: Is there any way to parse a cpp source file to IR(memory form)? There i find an example with very old version: https://fdiv.net/2012/08/15/compiling-code-clang-api .So is there some likely way to get IR(memory form) like this? @Nick Lewycky – StudyingCui Jul 18 '22 at 09:18
  • There is! I completely missed it, `clang::CodeGenAction` has a method `takeModule()` which returns the Module. `clang::EmitLLVMOnlyAction` derives from CodeGenAction. I've edited the answer. – Nick Lewycky Jul 18 '22 at 15:41
  • Thank you so much for your patience in answering!! @Nick Lewycky – StudyingCui Jul 19 '22 at 01:09