0

In The following code in LLVM

   unsigned ii=0;
BasicBlock* Bb = &*i;
TerminatorInst *TI = i->getTerminator();
    for( std::set<BasicBlock*>::iterator rit=Result.begin(); rit!=Result.end();++rit,++ii)
      {
    TI->setSuccessor(ii,(*rit));
    errs() << "\n\tBasic block (name=" <<(*rit)->getName() << ")";

      }

The code gives me the following error when it is implemented in Module Pass

    Basic block (name=if.then)opt: /home/rasha/llvm2/llvm/include/llvm/IR
/Instructions.h:2406: void llvm::BranchInst::setSuccessor(unsigned int, llvm::BasicBlock
 *): Assertion `idx < getNumSuccessors() && "Successor # out of range for Branch!"' failed.

0  opt             0x00000000018895be llvm::sys::PrintStackTrace(_IO_FILE*) + 46

Is there a criteria I should use to set the idx of each basic block to be a successor In addition it only doesn't issue this error once I remove the increment of ii , but with wrong result

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
R.Omar
  • 645
  • 1
  • 6
  • 18

1 Answers1

2

You should first use TI->getNumSuccessors() to verify that this terminator supports the number of successors you want.

Also keep in mind that if you want to add a successor beyond the current number of successors in the terminator, you can't use setSuccessor - that can only change existing successors, not add new ones. To add new ones, you need to use either addCase if it's a switch or addDestination if it's an indirect branch. No other terminator kinds support unbounded number of branches.

As an aside, from the error message it seems you are trying to use setSuccessor on a BranchInst - which can have at most two successors. If you want to modify the CFG, I recommend first getting a feel on how your terminators should look like.

Oak
  • 26,231
  • 8
  • 93
  • 152
  • I could find that the basic block has one terminator by checking the number of new successors if they are 1 then I could use setSuccessor, but how to check the other cases?? – R.Omar Jul 15 '13 at 22:43
  • @R.Omar I didn't quite understand your comment... in particular, every basic block always has exactly one terminator. If you want to add more successors than the terminator can already support, you need to use a different kind of terminator - see my 3rd paragraph above. – Oak Jul 16 '13 at 06:31