0
votes

I want to implement bianry operation in my toy programming language with LLVM as its backend. In LLVM document, I found the Create API in both llvm::IRBuilderBase and llvm::BinaryOperator:

  1. llvm::IRBuilderBase::CreateAdd: https://llvm.org/doxygen/classllvm_1_1IRBuilderBase.html#a928603739e0e70713566011d44052a4f

  2. llvm::BinaryOperator::Create: https://llvm.org/doxygen/classllvm_1_1BinaryOperator.html#a02ce9966395063ac501ecbc1623deda4

I have 2 questions about the Create API:

  1. It seems that both of these 2 APIs can implement the bianry operations. But I don't know the difference between them.

  2. If I want to use llvm::IRBuilderBase::CreateAdd API, I need to construct a llvm::IRBuilder with a llvm::Context and llvm::Module first, just like:

llvm::Module module;
llvm::Context context(module);
llvm::IRBuilder<> irBuilder(&context);

then use irBuilder.CreateAdd to generate the binary operation, just like:

llvm::Value *v = irBuilder.CreateAdd(left, right);

If I want to use llvm::BinaryOperator::Create API, since it's a static method, I can call it directly, just like:

llvm::Value *v = llvm::BinaryOperator::Create(llvm::BinaryOps::Add, left, right);

But how does llvm::BinaryOperator know which llvm::Context or llvm::Module it belongs ?

1

1 Answers

1
votes

Both of them create a BinaryOperator object; IRBuilder calls BinaryOperator::Create(). IRBuilder is just a wrapper around a lot of different Something::Create()s, including BinaryOperator::Create(). I don't know why some people prefer to use the wrapper and others prefer not to. That's largely a matter of taste, I think.

Create can find the relevant Module and Context using the Instruction you gave it: insertBefore->getModule() and insertBefore->getModule()->getContext().