1 //===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
3 // Insert Loop pre-headers and exit blocks into the CFG for each function in the
4 // module. This pass updates loop information and dominator information.
6 // Loop pre-header insertion guarantees that there is a single, non-critical
7 // entry edge from outside of the loop to the loop header. This simplifies a
8 // number of analyses and transformations, such as LICM.
10 // Loop exit-block insertion guarantees that all exit blocks from the loop
11 // (blocks which are outside of the loop that have predecessors inside of the
12 // loop) are dominated by the loop header. This simplifies transformations such
13 // as store-sinking that is built into LICM.
15 // Note that the simplifycfg pass will clean up blocks which are split out but
16 // end up being unneccesary, so usage of this pass does not neccesarily
17 // pessimize generated code.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/Constant.h"
28 #include "llvm/Support/CFG.h"
29 #include "Support/SetOperations.h"
30 #include "Support/Statistic.h"
31 #include "Support/DepthFirstIterator.h"
34 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
36 struct Preheaders : public FunctionPass {
37 virtual bool runOnFunction(Function &F);
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 // We need loop information to identify the loops...
41 AU.addRequired<LoopInfo>();
42 AU.addRequired<DominatorSet>();
44 AU.addPreserved<LoopInfo>();
45 AU.addPreserved<DominatorSet>();
46 AU.addPreserved<ImmediateDominators>();
47 AU.addPreserved<DominatorTree>();
48 AU.addPreserved<DominanceFrontier>();
49 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
52 bool ProcessLoop(Loop *L);
53 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
54 const std::vector<BasicBlock*> &Preds);
55 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
56 void InsertPreheaderForLoop(Loop *L);
59 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
62 // Publically exposed interface to pass...
63 const PassInfo *LoopPreheadersID = X.getPassInfo();
64 Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
67 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
68 /// it in any convenient order) inserting preheaders...
70 bool Preheaders::runOnFunction(Function &F) {
72 LoopInfo &LI = getAnalysis<LoopInfo>();
74 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
75 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
81 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
82 /// all loops have preheaders.
84 bool Preheaders::ProcessLoop(Loop *L) {
87 // Does the loop already have a preheader? If so, don't modify the loop...
88 if (L->getLoopPreheader() == 0) {
89 InsertPreheaderForLoop(L);
94 DominatorSet &DS = getAnalysis<DominatorSet>();
95 BasicBlock *Header = L->getHeader();
96 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
97 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
98 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
99 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
100 "RewriteLoopExitBlock failed?");
105 const std::vector<Loop*> &SubLoops = L->getSubLoops();
106 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
107 Changed |= ProcessLoop(SubLoops[i]);
111 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
112 /// to move the predecessors specified in the Preds list to point to the new
113 /// block, leaving the remaining predecessors pointing to BB. This method
114 /// updates the SSA PHINode's, but no other analyses.
116 BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
118 const std::vector<BasicBlock*> &Preds) {
120 // Create new basic block, insert right before the original block...
121 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
123 // The preheader first gets an unconditional branch to the loop header...
124 BranchInst *BI = new BranchInst(BB);
125 NewBB->getInstList().push_back(BI);
127 // For every PHI node in the block, insert a PHI node into NewBB where the
128 // incoming values from the out of loop edges are moved to NewBB. We have two
129 // possible cases here. If the loop is dead, we just insert dummy entries
130 // into the PHI nodes for the new edge. If the loop is not dead, we move the
131 // incoming edges in BB into new PHI nodes in NewBB.
133 if (!Preds.empty()) { // Is the loop not obviously dead?
134 for (BasicBlock::iterator I = BB->begin();
135 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
137 // Create the new PHI node, insert it into NewBB at the end of the block
138 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
140 // Move all of the edges from blocks outside the loop to the new PHI
141 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
142 Value *V = PN->removeIncomingValue(Preds[i]);
143 NewPHI->addIncoming(V, Preds[i]);
146 // Add an incoming value to the PHI node in the loop for the preheader
148 PN->addIncoming(NewPHI, NewBB);
151 // Now that the PHI nodes are updated, actually move the edges from
152 // Preds to point to NewBB instead of BB.
154 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
155 TerminatorInst *TI = Preds[i]->getTerminator();
156 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
157 if (TI->getSuccessor(s) == BB)
158 TI->setSuccessor(s, NewBB);
161 } else { // Otherwise the loop is dead...
162 for (BasicBlock::iterator I = BB->begin();
163 PHINode *PN = dyn_cast<PHINode>(I); ++I)
164 // Insert dummy values as the incoming value...
165 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
170 // ChangeExitBlock - This recursive function is used to change any exit blocks
171 // that use OldExit to use NewExit instead. This is recursive because children
172 // may need to be processed as well.
174 static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
175 if (L->hasExitBlock(OldExit)) {
176 L->changeExitBlock(OldExit, NewExit);
177 const std::vector<Loop*> &SubLoops = L->getSubLoops();
178 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
179 ChangeExitBlock(SubLoops[i], OldExit, NewExit);
184 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
185 /// preheader, this method is called to insert one. This method has two phases:
186 /// preheader insertion and analysis updating.
188 void Preheaders::InsertPreheaderForLoop(Loop *L) {
189 BasicBlock *Header = L->getHeader();
191 // Compute the set of predecessors of the loop that are not in the loop.
192 std::vector<BasicBlock*> OutsideBlocks;
193 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
195 if (!L->contains(*PI)) // Coming in from outside the loop?
196 OutsideBlocks.push_back(*PI); // Keep track of it...
198 // Split out the loop pre-header
200 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
202 //===--------------------------------------------------------------------===//
203 // Update analysis results now that we have preformed the transformation
206 // We know that we have loop information to update... update it now.
207 if (Loop *Parent = L->getParentLoop())
208 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
210 // If the header for the loop used to be an exit node for another loop, then
211 // we need to update this to know that the loop-preheader is now the exit
212 // node. Note that the only loop that could have our header as an exit node
213 // is a sibling loop, ie, one with the same parent loop, or one if it's
216 const std::vector<Loop*> *ParentSubLoops;
217 if (Loop *Parent = L->getParentLoop())
218 ParentSubLoops = &Parent->getSubLoops();
219 else // Must check top-level loops...
220 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
222 // Loop over all sibling loops, performing the substitution (recursively to
223 // include child loops)...
224 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
225 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB);
227 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
229 // The blocks that dominate NewBB are the blocks that dominate Header,
230 // minus Header, plus NewBB.
231 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
232 DomSet.insert(NewBB); // We dominate ourself
233 DomSet.erase(Header); // Header does not dominate us...
234 DS.addBasicBlock(NewBB, DomSet);
236 // The newly created basic block dominates all nodes dominated by Header.
237 for (Function::iterator I = Header->getParent()->begin(),
238 E = Header->getParent()->end(); I != E; ++I)
239 if (DS.dominates(Header, I))
240 DS.addDominator(I, NewBB);
243 // Update immediate dominator information if we have it...
244 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
245 // Whatever i-dominated the header node now immediately dominates NewBB
246 ID->addNewBlock(NewBB, ID->get(Header));
248 // The preheader now is the immediate dominator for the header node...
249 ID->setImmediateDominator(Header, NewBB);
252 // Update DominatorTree information if it is active.
253 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
254 // The immediate dominator of the preheader is the immediate dominator of
257 DominatorTree::Node *HeaderNode = DT->getNode(Header);
258 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
259 HeaderNode->getIDom());
261 // Change the header node so that PNHode is the new immediate dominator
262 DT->changeImmediateDominator(HeaderNode, PHNode);
265 // Update dominance frontier information...
266 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
267 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
268 // everything that Header does, and it strictly dominates Header in
270 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
271 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
272 NewDFSet.erase(Header);
273 DF->addBasicBlock(NewBB, NewDFSet);
275 // Now we must loop over all of the dominance frontiers in the function,
276 // replacing occurances of Header with NewBB in some cases. If a block
277 // dominates a (now) predecessor of NewBB, but did not strictly dominate
278 // Header, it will have Header in it's DF set, but should now have NewBB in
280 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
281 // Get all of the dominators of the predecessor...
282 const DominatorSet::DomSetType &PredDoms =
283 DS.getDominators(OutsideBlocks[i]);
284 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
285 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
286 BasicBlock *PredDom = *PDI;
287 // If the loop header is in DF(PredDom), then PredDom didn't dominate
288 // the header but did dominate a predecessor outside of the loop. Now
289 // we change this entry to include the preheader in the DF instead of
291 DominanceFrontier::iterator DFI = DF->find(PredDom);
292 assert(DFI != DF->end() && "No dominance frontier for node?");
293 if (DFI->second.count(Header)) {
294 DF->removeFromFrontier(DFI, Header);
295 DF->addToFrontier(DFI, NewBB);
302 void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
303 DominatorSet &DS = getAnalysis<DominatorSet>();
304 assert(!DS.dominates(L->getHeader(), Exit) &&
305 "Loop already dominates exit block??");
306 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
307 != L->getExitBlocks().end() && "Not a current exit block!");
309 std::vector<BasicBlock*> LoopBlocks;
310 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
312 LoopBlocks.push_back(*I);
314 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
315 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
317 // Update Loop Information - we know that the new block will be in the parent
319 if (Loop *Parent = L->getParentLoop())
320 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
322 // Replace any instances of Exit with NewBB in this and any nested loops...
323 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
324 if (I->hasExitBlock(Exit))
325 I->changeExitBlock(Exit, NewBB); // Update exit block information
327 // Update dominator information... The blocks that dominate NewBB are the
328 // intersection of the dominators of predecessors, plus the block itself.
329 // The newly created basic block does not dominate anything except itself.
331 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
332 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
333 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
334 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
335 DS.addBasicBlock(NewBB, NewBBDomSet);
337 // Update immediate dominator information if we have it...
338 BasicBlock *NewBBIDom = 0;
339 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
340 // This block does not strictly dominate anything, so it is not an immediate
341 // dominator. To find the immediate dominator of the new exit node, we
342 // trace up the immediate dominators of a predecessor until we find a basic
343 // block that dominates the exit block.
345 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
346 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
347 assert(Dom != 0 && "No shared dominator found???");
351 // Set the immediate dominator now...
352 ID->addNewBlock(NewBB, Dom);
353 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
356 // Update DominatorTree information if it is active.
357 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
358 // NewBB doesn't dominate anything, so just create a node and link it into
359 // its immediate dominator. If we don't have ImmediateDominator info
360 // around, calculate the idom as above.
361 DominatorTree::Node *NewBBIDomNode;
363 NewBBIDomNode = DT->getNode(NewBBIDom);
365 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
366 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
367 NewBBIDomNode = NewBBIDomNode->getIDom();
368 assert(NewBBIDomNode && "No shared dominator found??");
372 // Create the new dominator tree node...
373 DT->createNewNode(NewBB, NewBBIDomNode);
376 // Update dominance frontier information...
377 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
378 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
379 // does dominate itself (and there is an edge (NewBB -> Exit)).
380 DominanceFrontier::DomSetType NewDFSet;
381 NewDFSet.insert(Exit);
382 DF->addBasicBlock(NewBB, NewDFSet);
384 // Now we must loop over all of the dominance frontiers in the function,
385 // replacing occurances of Exit with NewBB in some cases. If a block
386 // dominates a (now) predecessor of NewBB, but did not strictly dominate
387 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
389 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
390 // Get all of the dominators of the predecessor...
391 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
392 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
393 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
394 BasicBlock *PredDom = *PDI;
395 // Make sure to only rewrite blocks that are part of the loop...
396 if (L->contains(PredDom)) {
397 // If the exit node is in DF(PredDom), then PredDom didn't dominate
398 // Exit but did dominate a predecessor inside of the loop. Now we
399 // change this entry to include NewBB in the DF instead of Exit.
400 DominanceFrontier::iterator DFI = DF->find(PredDom);
401 assert(DFI != DF->end() && "No dominance frontier for node?");
402 if (DFI->second.count(Exit)) {
403 DF->removeFromFrontier(DFI, Exit);
404 DF->addToFrontier(DFI, NewBB);