Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Predecessors for BasicBlock in LLVM

What is the easiest way to get the predecessors of a BasicBlock in the LLVM framework?

I have taken a look at DepthFirstIterator and idf_iterator<BasicBlock*>, but I actually need to do a breadth-first search on the control flow graph.

I feel like this should be easy, but it's not obvious from the documentation or the examples I have been exploring online.

like image 479
adu Avatar asked Feb 11 '14 17:02

adu


2 Answers

It isn't clear from the documentation, but the basic block class has support for a pred iterator, which gives the predecessors to the basic block. In C++11 style, one could loop through the predecessors of a block as follows:

BasicBlock* B = ...
for (auto it = pred_begin(B), et = pred_end(B); it != et; ++it)
{
  BasicBlock* predecessor = *it;
  ...
}
like image 173
Brian Avatar answered Nov 01 '22 19:11

Brian


A simpler way to iterate through the predecessors or successors is shown by using a for-each loop in the Programmer's Manual:

Iterating over the predecessors and successors of a block is quite easy with the routines defined in llvm/IR/CFG.h. Just use code like this to iterate over all predecessors of BB:

#include "llvm/IR/CFG.h"
BasicBlock *BB = ...; 
for (BasicBlock *Pred : predecessors(BB)) {
  // ...
}

Similarly, to iterate over successors use successors.

This is a lot cleaner than using explicit iteration with pred_begin and pred_end.

like image 38
River Avatar answered Nov 01 '22 20:11

River