Search code examples
buildclangllvmcross-compilingklee

How to use llvm target initialize function


My Host System

: Default target: x86_64-unknown-linux-gnu

: Host CPU: skylake

LLVM/Clang built with LLVM_TARGETS_TO_BUILD=all option.

How to Use another target's Initialize Function in My code?

I modifying klee (symbolic execution tool) to run cross-platform Target's IR.

#include "llvm/Support/TargetSelect.h"

int main () {
    ...
    // llvm::InitializeAllTargets(); -> Error    
    llvm::InitializeNativeTargets(); -> Success
    ...
}

In this case, error

${LLVM}/build/include/llvm/Config/Targets.def:28: undefined reference to `LLVMInitializeARMTargetInfo'
${LLVM}/build/include/llvm/Config/Targets.def:29: undefined reference to `LLVMInitializeBPFTargetInfo'
...

Solution

  • The LLVMInitializexxxTargetInfo() functions are used by InitializeAllTargets(), and the error message implys that you didn't link the required LLVM libraries.

    InitializeNativeTargets() succeeded, because you maybe did't include your native arch in -DLLVM_TARGETS_TO_BUILD.

    You can add the following lines in your CMakeLists.txt to link LLVM Targets libraries:

    set(LLVM_LINK_COMPONENTS 
      ${LLVM_TARGETS_TO_BUILD}
      )
    
    
    # Build your .cpp with llvm macro to use LLVM_LINK_COMPONENTS
    add_llvm_xxx_macro(YourOutputFile
      ...
      )