Inserting a function with arguments to appendToGlobalCtors

I want to insert a function call that executes first. I figured the way to do this is to insert to the global constructors with appendToGlobalCtors() in this way:

LLVMContext &C = M.getContext();
Function* FInit = Function::Create(FunctionType::get(Type::getVoidTy(C), false), GlobalValue::ExternalLinkage, INITMEMORY, &M);
appendToGlobalCtors(M, FInit, 0);

This works well if the function has no arguments. But what if the function I need to insert has arguments that I would like to specify? How do I create the function to insert into the global constructors? The function I have returns void. I already know how to use the IRBuilder to create a function call. But the builder takes the arguments in the builder.CreateCall(Func, FuncArgs). In general, I need to execute a bunch of function calls first when I am able to obtain their parameters in the program.

Hope I was clear enough. Let me know if this needs more clarification. Thanks!

Best regards,

Mohannad Ismail

You probably need to create a function that takes no arguments - and have that function then create the arguments and call the functions-taking-arguments you want to run as global ctors. Add the outer no-argument-taking-function to the global ctors list.

Hi David,

Thank you for your fast reply.

That’s a good idea. But the arguments I need are obtained from the IR, or in more accurately, from the static analysis I do on the IR. I can’t get these arguments externally. Are you proposing I create the function within the pass? How do I do that?

Hi David,

Thank you for your fast reply.

That’s a good idea. But the arguments I need are obtained from the IR, or in more accurately, from the static analysis I do on the IR. I can’t get these arguments externally. Are you proposing I create the function within the pass? How do I do that?

If it’s necessary to create the pass you want to, yeah, you could introduce a function within the transformation pass. (I guess it’d have to be a module pass, if it adds a function - I’m not 100% sure on that). Same way you create an IR function at any point - I guess IRBuilder::createFunction or something like that.

Thank you for your reply.

I was able to create a function and append the call instructions to those functions-taking-arguments to it with IRBuilder. Then I added it to the global constructors and it worked! Thank you!