Extract operations as function

Hi,
I am planning to extract every operation as function.

eg. z=x+y; ==> z=func(x,y,op);

I wish to write a custom definition of op. Which I would like to define in func.

It would be really helpful if someone could suggest passes already available in llvm to look for or point some references how should one proceed on it.

Is codeExtractor.cpp useful for this. I was also thinking of going like loop-extract way. any other suggestion would be extremely helpful

Hi Manish,

I am planning to extract every operation as function.

eg. z=x+y; ==> z=func(x,y,op);

I wish to write a custom definition of op. Which I would like to define in func.

It would be really helpful if someone could suggest passes already available in
llvm to look for or point some references how should one proceed on it.

I think you should write your own pass that
(1) adds a declaration of "func" to the module
(2) iterates over all functions, and all instructions in the function. When it
sees a binary operator ("isa<BinaryOperator>(Instruction)") it needs to first
insert a call just in front of the instruction (see an IRBuilder to do this;
use "SetInsertPoint(Instruction)" to tell it where to add the call; use
CreateCall3 to create the call). Then use replaceAllUsesWith to replace every
use of the binary operator with the call you just created. Finally, delete the
original instruction (eraseFromParent).

Ciao, Duncan.

Great!! Thanks Duncan.
By step 1 that you mentioned it seems I can write my function func(x,y,op) in mypass.cpp itself. Please elaborate how can add it to the module?

Hi Manish,

Great!! Thanks Duncan.
By step 1 that you mentioned it seems I can write my function func(x,y,op) in
mypass.cpp itself. Please elaborate how can add it to the module?

the minimum is to add a prototype for "func" to the module. For that you can
use getOrInsertFunction. If you want to insert the code defining "func" too,
then insert the prototype, add a basic block to it, use an IRBuilder to add
instructions to the basic block.

Ciao, Duncan.

Thanks again Duncan.
As you said just prototype is enough. So in mypass.c I write my pass and declare func(x,y,op) and in mypass.h I write my definition for func(x,y,op). Kindly let me know my understanding is correct? So next when ever i replace instruction with op uses with this func automatically correct code in intermediate llvm IR representation would be inserted.

Writing function definition for func(x,y,op) using IR builder will be painful I guess.

Regards,
Manish