Removing a redundant unconditional branch

Hi,

I want to remove a redundant unconditional branch from a Function. In the following example I want to remove br label %26 and merge them to a single basic block.

; <label>:9:                                      ; preds = %7
  %10 = fadd float %5, %8
  %11 = fmul float %5, %8
  %12 = fadd float %10, %11
  %13 = fdiv float %5, %8
  %14 = fadd float %13, %12
  br label %15

; <label>:15:                                     ; preds = %9
  br label %26

I tried to do this as follow but ended up getting runtime error. Can someone help?

Thanks

Charitha

for(auto it1 = F.begin(); it1 != F.end(); it1++){
BasicBlock& bb = *it1;
auto BI = dyn_cast<BranchInst>(bb.getTerminator());
if(BI && BI->isUnconditional() && bb.size() == 1){

for (BasicBlock *pred : predecessors(&bb)) {
auto predBI = dyn_cast<BranchInst>(pred->getTerminator());
if(predBI && predBI->isUnconditional()){
predBI->setSuccessor(0, bb.getSingleSuccessor());
BI->dropAllReferences();
BI->removeFromParent();
}
}
}

}

Perhaps, you’d need to also check that the block %15 has only one predecessor and has no other users?

Posting the error message might help.