Calling LLVM API from within an llvm::Module

Hi,

I'm looking into LLVM to build a self-hosting compiler. I'm trying to understand how to call LLVM from within a compiled LLVM Module (if that's possible).
As a first step I was just trying to compile some code that uses LLVM to LLVM bytecode, but can't get it to work.

$ cat test.cpp
#include <llvm/Module.h>
int main (int argc, char const *argv) {
   llvm::Module *mod = new llvm::Module("test");
   return 0;
}

# Compiling w/ no bytecode
$ llvm-gcc -c test.cpp `llvm-config --cppflags` -o test.o
$ llvm-gcc `llvm-config --ldflags --libs core` test.o # works fine

# Compiling to bytecode
$ llvm-gcc -emit-llvm -c test.cpp `llvm-config --cppflags` -o test.o
$ llvm-gcc `llvm-config --ldflags --libs core` test.o # craps w/ following: http://pastie.textmate.org/private/t33luliw4mdf7l2zkj8hg

Is that supposed to work?

I also tried creating a Function w/ ExternalLinkage calling LLVM C API function with no success:

   Function *f = Function::Create(type, Function::ExternalLinkage, StringValuePtr("LLVMModuleCreateWithName"), module);

Any pointer or explication would be greatly appreciated,

thanks a lot,
- ma

Marc-André Cournoyer wrote:

Hi,

I'm looking into LLVM to build a self-hosting compiler. I'm trying to understand how to call LLVM from within a compiled LLVM Module (if that's possible).
As a first step I was just trying to compile some code that uses LLVM to LLVM bytecode, but can't get it to work.

$ cat test.cpp
#include <llvm/Module.h>
int main (int argc, char const *argv) {
   llvm::Module *mod = new llvm::Module("test");
   return 0;
}

# Compiling w/ no bytecode
$ llvm-gcc -c test.cpp `llvm-config --cppflags` -o test.o
$ llvm-gcc `llvm-config --ldflags --libs core` test.o # works fine

# Compiling to bytecode
$ llvm-gcc -emit-llvm -c test.cpp `llvm-config --cppflags` -o test.o
$ llvm-gcc `llvm-config --ldflags --libs core` test.o # craps w/ following: http://pastie.textmate.org/private/t33luliw4mdf7l2zkj8hg

Is that supposed to work?

Try llvm-g++ instead of llvm-gcc. The difference is that g++ knows to link against libstdc++ while gcc won't. Your link error shows your linker being unable to find std::__throw_length_error, and that might be why.

There's no fundamental reason what you're doing won't work. Keep at it! I've often found that it helps to use llvm-config ... all instead of listing which libraries you actually need. (If you do that and it fixes things, please file a bug.)

Nick Lewycky