LLVM: Creating a CallInst with a null pointer operand - c++

I'm trying to use the LLVM C++ bindings to write a pass which generates the following IR
%1 = call i64 #time(i64* null) #3
#time here is the C standard library time() function.
Here's the code I've written
void Pass::Insert(BasicBlock *bb, Type *timety, Module *m) {
Type *timetype[1];
timetype[0] = timety;
ArrayRef<Type *> timeTypeAref(timetype, 1);
Value *args[1];
args[0] = ConstantInt::get(timety, 0, false);
ArrayRef<Value *> argsRef(args, 1);
FunctionType *signature = FunctionType::get(timety, false);
Function *timeFunc =
Function::Create(signature, Function::ExternalLinkage, "time", m);
IRBuilder<> Builder(&*(bb->getFirstInsertionPt()));
AllocaInst *a1 = Builder.CreateAlloca(timety, nullptr, Twine("a1"));
CallInst *c1 = Builder.CreateCall(timeFunc, args, Twine("time"));
}
This compiles, but results in the following error when run
Incorrect number of arguments passed to called function!
%time = call i64 #time(i64 0)
As I understand this, I need to pass an int64 pointer which deferences to nullptr, but I'm unable to figure out how to do that.

LLVM provides a ConstantPointerNull class which does exactly what I want - it returns a null pointer of the required type.
All that needs to be changed is the line beginning with args[0] = ... to
args[0] = ConstantPointerNull::get(PointerType::get(timety, 0));.

Related

How can I pass array to LLVM IR Function arguments and get value by index

I want to pass an array to LLVM IR Function, and get value by index. The code as follows, but it dont't work.
Function *FooF =
Function::Create(FunctionType::get(Type::getInt32Ty(Context), {ArrayType::getInt32PtrTy(Context), Type::getInt32Ty(Context)}, false),
Function::ExternalLinkage, "foo", M);
// Add a basic block to the FooF function.
BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FooF);
IRBuilder<> builder(BB);
// Get pointer to array
Value *arg1 = FooF->arg_begin();
// Get index
Value *index = arg1+1;
// Get first_element
Value *first_element = builder.CreateExtractElement(arg1, index);
builder.CreateRet(first_element);
// Now we create the JIT.
ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
using FunctionPtr = int(*)(int32_t *, int);
FunctionPtr func = reinterpret_cast<FunctionPtr>(EE->getFunctionAddress("foo")) ;
int32_t array[3] = {1,2,3};
int first = func(array, 0);
}

LLVM how to map custom function call to printf

I just started with LLVM. I am using C++ to create a compiler for Pascal-like language. Given that print functions are system calls, how do I map from my language writeln(5) to the system function printf ("%d",5)? I thought that code below should do it.
NamedValues.clear();
vector<Type *> Doubles(1, Type::getInt32Ty(TheContext));
FunctionType * FT = FunctionType::get(Type::getInt32Ty(TheContext), Doubles, false);
Function * function = Function::Create(FT, Function::ExternalLinkage, "writeln", TheModule.get());
// create function body
BasicBlock * BB = BasicBlock::Create(TheContext, "entry", function);
Builder.SetInsertPoint(BB);
// get param
Function::arg_iterator AI = function->arg_begin();
Value * val = AI;
AI->setName("val");
// get format string
string format = "%d";
Constant * ConstStr = ConstantDataArray::getString(TheContext, format.c_str());
ConstStr = new GlobalVariable(*TheModule, ConstStr->getType(), true, GlobalValue::InternalLinkage, ConstStr, format);
Constant * Idxs[] = {ConstantInt::get(Type::getInt32Ty(TheContext), 0), 0};
Idxs[1] = Idxs[0];
// make params
vector<Type *> params;
params.push_back(PointerType::getUnqual(Type::getInt8Ty(TheContext)));
// get printf function
FunctionCallee PrintF = TheModule->getOrInsertFunction("printf", FunctionType::get(Type::getVoidTy(TheContext), params, true));
// call
/*
* CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = None,
const Twine &Name = "", MDNode *FPMathTag = nullptr)
*/
Builder.CreateCall(PrintF.getFunctionType(), ConstantExpr::getGetElementPtr(ConstStr->getType(), ConstStr, Idxs), val);
Builder.CreateRet(Builder.getInt32(0));
main_loop();
Error I got:
Assertion failed: (Ty == cast<PointerType>(C->getType()->getScalarType())->getElementType()), function getGetElementPtr, file /Users/ustynov/Documents/Study/HOMEWORKS/semestralwork/llvm/lib/IR/Constants.cpp, line 2012.

Why does LLVMRunFunction with interpreter return same value for different functions?

I build 2 functions using the LLVM C API. Each returns a different pointer to global string ("first" and "second"). However when I run each with LLVMRunFunction using the LLVM interpreter, they both return a pointer to the string "first".
The problem does not occur when I return integers or function pointers.
I tried looking at the produced llvm code and it is correct, each function returns a different pointer.
Here's a sample that will reproduce the problem (on LLVM 7.0.1)
#include <llvm-c/Core.h>
#include <llvm-c/ExecutionEngine.h>
#include <stdio.h>
int main() {
auto module = LLVMModuleCreateWithName("test");
LLVMExecutionEngineRef interpreter;
LLVMCreateInterpreterForModule(&interpreter, module, nullptr);
auto funType = LLVMFunctionType(LLVMPointerType(LLVMInt8Type(), 0), nullptr, 0, 0);
auto fun = LLVMAddFunction(module, "fun1", funType);
auto builder = LLVMCreateBuilder();
auto entry = LLVMAppendBasicBlock(fun, "entry");
LLVMPositionBuilderAtEnd(builder, entry);
LLVMBuildRet(builder, LLVMBuildGlobalStringPtr(builder, "first", ""));
auto generic = LLVMRunFunction(interpreter, fun, 0, nullptr);
printf("%s\n", (const char*)LLVMGenericValueToPointer(generic));
fun = LLVMAddFunction(module, "fun2", funType);
entry = LLVMAppendBasicBlock(fun, "entry");
LLVMPositionBuilderAtEnd(builder, entry);
LLVMBuildRet(builder, LLVMBuildGlobalStringPtr(builder, "second", ""));
generic = LLVMRunFunction(interpreter, fun, 0, nullptr);
printf("%s\n", (const char*)LLVMGenericValueToPointer(generic));
return 0;
}
I would expect the output
first
second
Instead it outputs
first
first
After having a closer look at the generated LLVM, I noticed that the global strings built with LLVMBuildGlobalStringPtr had the unnamed_addr modifier. When building the global string manually instead of using LLVMBuildGlobalStringPtr, the interpreter actually returns the correct string pointers and the output becomes as expected:
auto glbstr = LLVMAddGlobal(mBuilder.module_, llvmType, "glbstr");
LLVMSetInitializer(glbstr, LLVMConstString(toStringz(arg.value), cast(uint) arg.value.length, 0));
auto firstCharPtr = LLVMBuildGEP(builder, glbstr, [LLVMConstInt(LLVMInt8Type(), 0, 0), LLVMConstInt(LLVMInt8Type(), 0, 0)].ptr, 2, "");

LLVM StoreInst and AllocaInst

I am trying to write a simple interpreter.
I am trying to generate LLVM IR for assignment operation. The code for the generation part looks like this
llvm::Value* codeGenSymTab(llvm::LLVMContext& context) {
printf("\n CodeGen SymTab \n");
Value *num = ConstantInt::get(Type::getInt64Ty(context), aTable.value, true);
Value *alloc = new AllocaInst(IntegerType::get(context, 32), aTable.variableName,entry);
StoreInst *ptr = new StoreInst(num,alloc,false,entry);
}
Here goes the SymTab definition:
struct SymTab {
char* variableName;
int value;
llvm::Value* (*codeGen)(llvm::LLVMContext& context);
};
When I try to execute the output file,I get the following error:
Assertion failed: (getOperand(0)->getType() == cast<PointerType>(getOperand(1)->getType())->getElementType() && "Ptr must be a pointer to Val type!"), function AssertOK, file Instructions.cpp, line 1084.
Abort trap: 6
Can you help me resolve it ?
Thanks
You try to store a value of type i64 into an address of type i32*, and these don't match.
You can fix this by using the same type - or preferably, the actual same object:
IntegerType *int_type = Type::getInt64Ty(context);
Value *num = ConstantInt::get(int_type, aTable.value, true);
Value *alloc = new AllocaInst(int_type, aTable.variableName, entry);
StoreInst *ptr = new StoreInst(num,alloc,false,entry);

LLVM IR Function with an array parameter

I want to generate LLVM IR code from two basic c++ functions which are like below.
int newFun2(int x){
int z = x + x;
return z;
}
int newFun(int *y){
int first = y[3]; //How to define it using the LLVM API?
int num = newFun2(first);
return num;
}
My problem is to get an index of the array parameter using the LLVM API. Any ideas ?
Thank you so much
EDITTED
This is my code using the API:
llvm::LLVMContext &context = llvm::getGlobalContext();
llvm::Module *module = new llvm::Module("AST", context);
llvm::IRBuilder<> builder(context);
//newFun2
llvm::FunctionType *newFunc2Type = llvm::FunctionType::get(builder.getInt32Ty(), builder.getInt32Ty(), false);
llvm::Function *newFunc2 = llvm::Function::Create(newFunc2Type, llvm::Function::ExternalLinkage, "newFun2", module);
llvm::Function::arg_iterator argsFun2 = newFunc2->arg_begin();
llvm::Value* x = argsFun2++;
x->setName("x");
llvm::BasicBlock* block = llvm::BasicBlock::Create(context, "entry", newFunc2);
llvm::IRBuilder<> builder2(block);
llvm::Value* tmp = builder2.CreateBinOp(llvm::Instruction::Add,
x, x, "tmp");
builder2.CreateRet(tmp);
//newFun
llvm::FunctionType *newFuncType = llvm::FunctionType::get(builder.getInt32Ty(), builder.getInt32Ty()->getPointerTo(), false);
llvm::Function *newFunc = llvm::Function::Create(newFuncType, llvm::Function::ExternalLinkage, "newFun", module);
llvm::BasicBlock* block2 = llvm::BasicBlock::Create(context, "entry", newFunc);
llvm::IRBuilder<> builder3(block2);
module->dump();
And this is the LLVM IR that is generated :
; ModuleID = 'AST'
define i32 #newFun2(i32 %x) {
entry:
%tmp = add i32 %x, %x
ret i32 %tmp
}
define i32 #newFun(i32*) {
entry:
}
I am stuck on the body of newFun because of the array access.
I think that you first need to understand how the IR should look like. It can be done by peering into the language specification or by using Clang to compile the C code into IR and taking a look at the result.
In any case, the way to access an array element at a given index is either with extractvalue (which only accepts constant indices) or with a gep. Both of these have corresponding constructors / factory methods and IRBuilder methods to construct them, for example
builder.CreateExtractValue(y, 3);
Creating a gep is a little more complicated; I recommend taking a look at the gep guide.
However, a good way to see how to call the LLVM API to create the desired IR is to use llc (one of the LLVM command-line tools) to generate a source file with those calls itself from an IR file, see these two related questions:
Possible to auto-generate llvm c++ api code from LLVM-IR?
Generate LLVM C++ API code as backend