How to replace a function using llvm?

Hi all,

I am a newbie and have a question.

Using llvm, I want to change the original function into a new function which have an additional pointer argument:

original function: int haha(int n) { … }
new function: int haha(int n, *ptr) { … }

Could you give me a suggestion?

Thank you in advance.
Shawn

Hi Shawn,

I am a newbie and have a question.

Using llvm, I want to change the original function into a new function which
have an additional pointer argument:

original function: int haha(int n) { .... }
new function: int haha(int n, *ptr) { ... }

Could you give me a suggestion?

I suggest you look at how lib/Transforms/IPO/ArgumentPromotion.cpp does this
kind of thing.

Best wishes, Duncan.

Hello Shawn,

I’ve just implemented something similar. It might be horribly wrong to do it this way, but at least it works for me :slight_smile:

Here’s what I do:

  • Rename your function “haha” → “haha_” to avoid name collisions in the next step;
  • Get its function type and modify to suite your needs: add new parameters, change types, whatever;
  • Create new function named “haha” with that signature;
  • Relink all basic blocks from original function to the new one. Now “haha_” is empty, but you can’t delete it yet;
  • Iterate over all modules/functions that reference your original function and replace call instructions to match new signature;
  • Delete “haha_” function.

I’m no LLVM expert by any means, so take this with a grain of salt…

  • Yury