[LLVMdev] Question adding dummy basic blocks

Chris Lattner sabre at nondot.org
Tue Dec 7 18:37:28 PST 2004

On Tue, 7 Dec 2004, Zhang Qiuyu wrote:
> Finally, We got some problems due to PHINODE. I knew the reason, but I failed to  fix it.


> The code is like the following
> if( TI->getNumSuccessors() ==1){
>   BasicBlock *TIBB=TI->getParent();
>   BasicBlock *DestBB=TI->getSuccessor(0);
>   BasicBlock *NewBB = new BasicBlock(TIBB->getName()+DestBB->getName()+"dummy_bb",&F);
>   new BranchInst(DestBB, NewBB);
>   BranchInst *NewBr = new BranchInst(DestBB, NewBB, V_dummy);
>   ReplaceInstWithInst(TI, NewBr);

If you're doing CFG manipulations, a good source of inspiration for your 
work might be the llvm/lib/Transforms/Utils/SimplifyCFG.cpp file.  It 
contains code to do many transformations like this.

I imagine that the problem with the code above is that you are adding new 
edges into 'NewBB', and if it has PHI nodes, the verifier will 
(rightfully) complain.  In particular, you're breaking the invariant that 
the # of incoming PHI node values equals the number of predecessors for 
that block.

In this case, you have to decide which values should be coming into the 
block.  Usually in cases like this, they are the same values that come in 
from some other path.  Given that you want control flow from your new 
block to emulate the control flow from some other predecessor of NewBB 
(I'll call it OtherBB), you'll want something like this:

PHINode *PN;
for (BasicBlock::iterator I = NewBB->begin();
      PN = dyn_cast<PHINode>(I); ++I)
   PN->addIncomingValue(PN->getIncomingValueForBlock(OtherBB), NewBB);



More information about the llvm-dev mailing list