简体   繁体   中英

Inserting a block between two blocks in LLVM

I want to insert a block in between two basic blocks in LLVM. So for example, if a basic block A was jumping to basic block B, I want to insert a basic block C in between them such that A jumps to C and C jumps to B. How can I do that? I do have the basic idea that I need to change the terminating instruction of Basic Block A, such that the target B is replaced by C, but how do I go on adding the new basic block C in between?

Yes, you need to change (or replace) the terminating instruction of basic block A - for example, if it's a branch, you can use BranchInst::setSuccessor() . You then create basic block C and make sure that its terminating instruction jumps to B, which will make it in-between.

All you need to do is to change the terminators' targets - you don't need to rearrange the block order in the memory or anything like that.

However, you must be aware that there are two special instructions you need to worry about - phi nodes and landing pads.

  • Phi nodes only refer to the block's immediate predecessor. That means that if you insert C between A and B, you must fix all the phi nodes in B by either removing them or making them refer to C instead of A.

  • If B is a landingpad block (contains a landingpad instruction), it is only legal to jump into it directly from the unwind target of an invoke instruction. If the jump from A to B is through the unwind target, you can't add a basic block in-between unless you make C itself into a landingpad and remove the landingpad from B.

There is a function called llvm::splitEdge . It does exactly what the question asked for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM