inserting exit function into IR

Hi Everyone,
I am trying to insert an exit function into my IR.
However, I thought I can get access to exit by using
Module.getOrInsertFunction or Module.getFunction. However, I am
getting a null value returned. I have searched through the llvmdev archives
but not found any thing that addresses this question.

Any help will be greatly appreciated. Thanks.

George

Hi George,

Could you be a more specific about what you are trying to do, how you are trying to do it, and what is failing. A couple of relevant snippets of code would do wonders in helping you.

Thanks,

Joshua

Hi Joshua,
I have a function foo and I want to insert exit(0) at the end of foo. The problem is M.getFunction returns null, which is understandable. I am not sure what to do. Below is the code snippet.

void foo(int argc, char* argv[]) {
printf(“hello world\n”);
exit(0); //***I want to insert this exit
}

My llvm code snippet is

vector<const Type *> params = vector<const Type *>();

params.push_back(Type::getInt32Ty(M.getContext()));

FunctionType *fType = FunctionType::get(Type::getVoidTy(M.getContext()), params, false);

Constant *temp = M.getFunction(“exit”, fType);

if(!temp){

errs() << “exit function not in symbol table\n”;

exit(1);

}

Function *f = cast(temp);

CallInst *ci = CallInst::Create(…)

Hi George,

Unless you already inserted the function into the module previously, it looks like your problem is here:

Constant *temp = M.getFunction(“exit”, fType);

needs to be:

Constant* temp = M.getOrInsertFunction(“exit”, fType);

In LLVM, declarations are just functions without bodies. A declaration (without a body) or definition (with a body) needs to be added for every function referenced in the module, including “standard” functions like exit.

Let me know if this helps.

-Joshua

Hi Joshua,
I have a function foo and I want to insert exit(0) at the end of foo.
The problem is M.getFunction returns null, which is understandable. I am not
sure what to do. Below is the code snippet.
void foo(int argc, char* argv[]) {
printf("hello world\n");
exit(0); //***I want to insert this exit
}
My llvm code snippet is

vector<const Type *> params = vector<const Type *>();

The initialization is unnecessary (but harmless).

params.push_back(Type::getInt32Ty(M.getContext()));

FunctionType *fType = FunctionType::get(Type::getVoidTy(M.getContext()),
params, false);

Constant *temp = M.getFunction("exit", fType);

M.getOrInsertFunction("exit", fType);

I did M.getOrInsertFunction and called the exit function with .

IRBuilder<> builder = IRBuilder<>(…);

Value *one = ConstantInt::get(Type::getInt32Ty(M.getContext()),1);

builder.CreateCall(exitF,one,“tmp4”);

"Instruction has a name, but provides a void value!
%tmp4 = call void @exit(i32 1)
Broken module found, compilation aborted! "

So... don't give the call a name? (just remove the "tmp4" parameter)

Thank you very much guys, I really appreciate your help.

George

Oh, BTW it worked!!