How do I link when building with llvm libraries?

2019-05-30 16:33发布

问题:

I am trying to parse a LLVM-IR file(.ll) and do a static analysis..

I found this sample code below, and I tried to build it, but I don't know which library to link.

#include <iostream>
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

int main(int argc, char** argv)
{
    if (argc < 2) {
        errs() << "Expected an argument - IR file name\n";
        exit(1);
    }

    LLVMContext &Context = getGlobalContext();
    SMDiagnostic Err;
    std::unique_ptr<Module> Mod = parseIRFile(argv[1], Err, Context);

    if (Mod) {
        std::cout << "Mod is not null" << std::endl;
    }
    else {
       std::cout << "Mod is null" << std::endl;
    }
    return 0;
}

I gave the below command to build, and it gives me some undefined reference error, which that I think is a linking error.

g++ -I~/llvm/build/include -I~/llvm/llvm/include  -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS -std=c++11 test.cpp

Which library file should I have to link with -L option in order to build this sample code? I want this to work as a standalone binary, not as a pass within the whole compile procedure.

回答1:

If you setup your project as a subproject of llvm, you may read this tutorial and examples.

But since you mentioned "standalone" I guess you tried to build your project out of llvm source project. llvm-config is your friend.

For example, you can find that inside tools/llvm-link's Makefile reads:

LINK_COMPONENTS := linker bitreader bitwriter asmparser irreader

or in CMakeLists.txt:

set(LLVM_LINK_COMPONENTS
  BitWriter
  Core
  IRReader
  Linker
  Support
  )

Then you can use llvm-config to see how to link these libs.

$ llvm-config --libs linker bitreader bitwriter asmparser irreader

or

$ llvm-config --libs BitWriter Core IRReader Linker Support

They will output the link options like:

-lLLVMLinker -lLLVMTransformUtils -lLLVMipa -lLLVMAnalysis -lLLVMTarget -lLLVMMC -lLLVMIRReader -lLLVMBitReader -lLLVMAsmParser -lLLVMBitWriter -lLLVMCore -lLLVMSupport

llvm-config --components can be used to see all the official components; if you are tired with specifying components, simply use llvm-config --libs and it will emit all linkable libraries.

Of course you should firstly make sure the library directory is in your link path, which is the result llvm-config --libdir.

You can use llvm-config --help for other useful options.