title: How to implement function pointer by using LLVM C++ API?
body: <p>Let's say I want manually turn code below to IR code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main()
  {
    int (*p)(const char *__s);  // how to implement this?
    p = puts;                   // and this?
    p("Hello World!\n");
  }
  </code></pre>
  
  <p>I found that the IR representation of the function pointer is this:</p>
  
  <pre><code>%p = alloca i32 (i8*)*, align 8
  store i32 (i8*)* @puts, i32 (i8*)** %p, align 8 
  </code></pre>
  
  <p>but I don't know which api I should use to generate this.</p>
  
  <p>here's part of my implementation:</p>
  
  <pre><code>#include "llvm/Support/raw_ostream.h"
  
  int main() {
    llvm::LLVMContext context;
    llvm::IRBuilder&lt;&gt; builder(context);
    llvm::Module *module = new llvm::Module("top", context);
  
    llvm::FunctionType *functionType = llvm::FunctionType::get(builder.getInt32Ty(), false);
    llvm::Function *mainFunction = llvm::Function::Create(functionType, llvm::Function::ExternalLinkage, "main", module);
  
    llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunction);
    builder.SetInsertPoint(entry);
  
    llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world\n");
  
    std::vector&lt;llvm::Type *&gt; putArgs;
    putArgs.push_back(builder.getInt8Ty()-&gt;getPointerTo());
    llvm::ArrayRef&lt;llvm::Type *&gt; argsRef(putArgs);
    llvm::FunctionType *putsType = llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
    llvm::Constant *putFunction = module-&gt;getOrInsertFunction("puts", putsType);
  
    // code to implement function pointer
    // code to assign puts() to function pointer
  
    builder.CreateCall(putFunction, helloWorld);  // call the function pointer instead of the function it self
    builder.CreateRet(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
  
    module-&gt;print(llvm::errs(), nullptr);
  }
  </code></pre>
  
  <p>I found that <code>llvm::Function</code> is a subclass of <code>llvm::Value</code>, so I guess the <code>llvm::Constant *putFunction</code> itself is the function pointer I'm looking for, but how to make this value represented in IR code? More specific, how to use the builder to generate the IR code?</p>