Search code examples
c++llvmclang

How to generate an executable from an llvm::Module?


I want to write a C++ function that takes an llvm::Module, which is already linked, and output it to an executable file. It should use the llvm/clang API rather than forking a process and invoking the command-line clang.

After looking through the llvm/clang source code, the closest thing I've found is to output a Module to a .o file. For example, the llc tool (tools/llc/llc.cpp) accomplishes this by calling TargetMachine::addPassesToEmitFile(...).

An alternative would be to write the Module to a .bc file, then create a CompilerInstance and call ExecuteCompilerInvocation (as in tools/clang/tools/driver/cc1_main.cpp). But then there's the overhead of file I/O.

So, am I asking for something possible, or must I fall back on the alternative?

Edit: (Of course this is possible. It happens somewhere in the clang source code, I just can't find it.)


Solution

  • Not possible! clang does not create the executable itself. It invokes ld.

    Found it in tools/clang/lib/Driver/Tools.cpp. In the ConstructJob functions for the various platforms (darwin::Link::ConstructJob, solaris::Link::ConstructJob, etc.), it does this:

    const char *Exec =
        Args.MakeArgString(getToolChain().GetProgramPath("ld"));
      C.addCommand(new Command(JA, *this, Exec, CmdArgs));
    

    (For visualstudio::Link::ConstructJob, it instead invokes link.exe.)

    Edit: In retrospect, it would have been faster to find this out by tracing clang's system calls with dtruss (Mac) or strace (Linux).

    Edit: I ended up using the Clang driver API for building and linking. I wrote up some example code.