c++ – Generating IR from clang using classes

Exception or error:

I am trying to generate LLVM IR using clang classes I am pretty new at this and so far I’ve used this code as a reference which is in turn copied from Method to create LLVM IR

The above link is pretty old and I did change my code here and there according to the new signatures

#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>

using namespace std;
using namespace clang;

clang::CodeGenAction * getAction(void)

    llvm::LLVMContext *llvmcx;
    static llvm::LLVMContext MyGlobalContext;
    llvmcx = &MyGlobalContext;
    // Path to the C file
    string inputPath = "test.c";

    // Arguments to pass to the clang frontend
    vector<const char *> args;

    // The compiler invocation needs a DiagnosticsEngine so it can report problems
    llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> opt(new clang::DiagnosticOptions());
    clang::DiagnosticConsumer *client(new DiagnosticConsumer());
    llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID(new clang::DiagnosticIDs());
    clang::DiagnosticsEngine Diags(DiagID, opt, client);

    // Create the compiler invocation
    shared_ptr<clang::CompilerInvocation> CI(new clang::CompilerInvocation());
    clang::CompilerInvocation::CreateFromArgs(*CI, &args[0], &args[0] + args.size(),Diags);

    // Create the compiler instance
    clang::CompilerInstance Clang;

    // Get ready to report problems
    if (!Clang.hasDiagnostics())
          return NULL;
    // Create an action and make the compiler instance carry it out
    clang::CodeGenAction *Act = new clang::EmitLLVMOnlyAction(llvmcx);
    if (!Clang.ExecuteAction(*Act))
        return NULL;

    return Act;

int main(void)
    clang::CodeGenAction* Act = getAction();

    Grab the module built by the EmitLLVMOnlyAction
    auto module = Act->takeModule();

    // Print all functions in the module
    for (llvm::Module::FunctionListType::iterator i = module->getFunctionList().begin(); i != module->getFunctionList().end(); ++i)
        printf("%s\n", i->getName().str().c_str());

    return 0;

But getAction() returns NULL. Any idea as to where I am going wrong?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *