How to insert basic block in a loop

Dear All

I’m making a transformation pass that inserts a new basic block at the start of a loop. However when I try to change predecessor/successor relations, it does not consider the new block in the loop at all. So I got that just inserting a loop in a function before another loop is not enough. So how exactly to do this job?

Given lack of context in your question, it’s hard to figure out what you’re asking, but as a guess, I’d suggest you look at addBasicBlockToLoop on LoopBase in LoopInfo.h

Philip

Thanks a million. Now I managed to insert the block into the loop using the mentioned function. However I have another issue now. I’ve inserted a block (named foo) in the start of the loop. I want to make the predecessors of the the previous start block (for.cond) to jump to foo instead, and foo jumps to for.cond. Predecessors of for.cond are entry and for.inc. When I run my pass, only for.inc is changed, entry is not. Here is code:

pred_iterator PI = pred_begin(loopCond), PE = pred_end(loopCond);
while (PI != PE) {
if((*PI)!=foo){

BasicBlock::iterator it = (*PI)->end();
it–;
BranchInst *bi = dyn_cast(it);

bi->setSuccessor(0, foo);

}
PI++;
}

I guessed that the problem is that entry block is not part of the loop, and this is a loop pass. So, if this is this the problem, how can I overcome? And if not, what could be the problem?

You’ve identified the problem correctly. The notion your looking for is a loop preheader (For LoopSimplify form), or a non-loop contained predecessor of the loop header (for generalized loops). You need to explicitly locate and visit those blocks. See LoopInfo.h. I would strongly suggest you use some of the existing loop transforms (LICM, LoopUnswitch, etc…) as examples. They all have to do similar things.