Search code examples
c++clangllvmllvm-irinstrumentation

How to linking a external function from a .h file (header file) for LLVM getOrInsertFunction in a LLVM pass


let consider a header file named foo.h

#ifndef __FOO_H__
#define __FOO_H__
#include<stdio.h>
void display(){
    printf("Hello");
}
#endif

and a simple program named simple.c

#include<stdio.h>
void main(){
    //instrument display() at these point to print "Hello".
    printf(" World\n");
}

so how to coded in instrumentation.cpp to link that foo.h file and get that display() function for doing getOrInsertFunction("display", false);.


Solution

  • What does the input to your instrumentation pass look like? You will need to be comfortable thinking in terms of LLVM IR.

    Take that simple.c and turn it into LLVM IR and look at it. What do you want the result to look like after your instrumentation? Does this instrumentation add a declaration of "display" and a call to it? That would imply that "display()" function is in a separate library which gets linked in. Or do you want to compile display() down to LLVM IR and have your instrumentation pass add the whole thing to the module being instrumented? Are you OK with placing a call to display() or do you want to then inline that call?

    clang -S -emit-llvm file.c will produce LLVM IR as text.

    Given an llvm::IRBuilder Builder, Builder.CreateCall can be used to add a function call.

    Once you have two modules in memory, you can add another module into the current module with llvm::linkModules, or you may want to use CloneModuleInto.