blob: d5988b16526780eecdd770fbb5a5399168401825 [file] [log] [blame]
Chris Lattner38acf9e2002-09-26 16:17:31 +00001//===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
2//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +00003// 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.
5//
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.
9//
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.
14//
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.
Chris Lattner38acf9e2002-09-26 16:17:31 +000018//
19//===----------------------------------------------------------------------===//
20
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"
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000029#include "Support/SetOperations.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000030#include "Support/Statistic.h"
Chris Lattner74cd04e2003-02-28 03:07:54 +000031#include "Support/DepthFirstIterator.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000032
33namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000034 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
Chris Lattner38acf9e2002-09-26 16:17:31 +000035
36 struct Preheaders : public FunctionPass {
37 virtual bool runOnFunction(Function &F);
38
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 // We need loop information to identify the loops...
41 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000042 AU.addRequired<DominatorSet>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000043
44 AU.addPreserved<LoopInfo>();
45 AU.addPreserved<DominatorSet>();
46 AU.addPreserved<ImmediateDominators>();
47 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000048 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000049 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
50 }
51 private:
52 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000053 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
54 const std::vector<BasicBlock*> &Preds);
55 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000056 void InsertPreheaderForLoop(Loop *L);
57 };
58
Chris Lattner0bd36162002-09-26 16:37:37 +000059 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
Chris Lattner38acf9e2002-09-26 16:17:31 +000060}
61
62// Publically exposed interface to pass...
63const PassInfo *LoopPreheadersID = X.getPassInfo();
64Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
65
66
67/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
68/// it in any convenient order) inserting preheaders...
69///
70bool Preheaders::runOnFunction(Function &F) {
71 bool Changed = false;
72 LoopInfo &LI = getAnalysis<LoopInfo>();
73
74 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
75 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
76
77 return Changed;
78}
79
80
81/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
82/// all loops have preheaders.
83///
84bool Preheaders::ProcessLoop(Loop *L) {
85 bool Changed = false;
86
87 // Does the loop already have a preheader? If so, don't modify the loop...
88 if (L->getLoopPreheader() == 0) {
89 InsertPreheaderForLoop(L);
90 NumInserted++;
91 Changed = true;
92 }
93
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000094 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]);
Chris Lattner7e7ad492003-02-27 22:31:07 +000099 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
100 "RewriteLoopExitBlock failed?");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000101 NumInserted++;
102 Changed = true;
103 }
104
Chris Lattner38acf9e2002-09-26 16:17:31 +0000105 const std::vector<Loop*> &SubLoops = L->getSubLoops();
106 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
107 Changed |= ProcessLoop(SubLoops[i]);
108 return Changed;
109}
110
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000111/// 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.
115///
116BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
117 const char *Suffix,
118 const std::vector<BasicBlock*> &Preds) {
119
120 // Create new basic block, insert right before the original block...
121 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
122
123 // The preheader first gets an unconditional branch to the loop header...
124 BranchInst *BI = new BranchInst(BB);
125 NewBB->getInstList().push_back(BI);
126
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.
132 //
133 if (!Preds.empty()) { // Is the loop not obviously dead?
134 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000135 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000136
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);
139
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]);
144 }
145
146 // Add an incoming value to the PHI node in the loop for the preheader
147 // edge
148 PN->addIncoming(NewPHI, NewBB);
149 }
150
151 // Now that the PHI nodes are updated, actually move the edges from
152 // Preds to point to NewBB instead of BB.
153 //
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);
159 }
160
161 } else { // Otherwise the loop is dead...
162 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000163 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000164 // Insert dummy values as the incoming value...
165 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
166 }
167 return NewBB;
168}
169
Chris Lattner38acf9e2002-09-26 16:17:31 +0000170
171/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
172/// preheader, this method is called to insert one. This method has two phases:
173/// preheader insertion and analysis updating.
174///
175void Preheaders::InsertPreheaderForLoop(Loop *L) {
176 BasicBlock *Header = L->getHeader();
177
178 // Compute the set of predecessors of the loop that are not in the loop.
179 std::vector<BasicBlock*> OutsideBlocks;
180 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
181 PI != PE; ++PI)
182 if (!L->contains(*PI)) // Coming in from outside the loop?
183 OutsideBlocks.push_back(*PI); // Keep track of it...
184
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000185 // Split out the loop pre-header
186 BasicBlock *NewBB =
187 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000188
Chris Lattner38acf9e2002-09-26 16:17:31 +0000189 //===--------------------------------------------------------------------===//
190 // Update analysis results now that we have preformed the transformation
191 //
192
193 // We know that we have loop information to update... update it now.
194 if (Loop *Parent = L->getParentLoop())
195 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000196
197 // If the header for the loop used to be an exit node for another loop, then
198 // we need to update this to know that the loop-preheader is now the exit
199 // node. Note that the only loop that could have our header as an exit node
200 // is a sibling loop, ie, one with the same parent loop.
201 const std::vector<Loop*> *ParentSubLoops;
202 if (Loop *Parent = L->getParentLoop())
203 ParentSubLoops = &Parent->getSubLoops();
204 else // Must check top-level loops...
205 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
206
207 // Loop over all sibling loops, performing the substitution...
208 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
209 if ((*ParentSubLoops)[i]->hasExitBlock(Header))
210 (*ParentSubLoops)[i]->changeExitBlock(Header, NewBB);
211
Chris Lattner38acf9e2002-09-26 16:17:31 +0000212
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000213 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
214 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000215 // The blocks that dominate NewBB are the blocks that dominate Header,
216 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000217 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000218 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner38acf9e2002-09-26 16:17:31 +0000219 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000220 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000221
222 // The newly created basic block dominates all nodes dominated by Header.
223 for (Function::iterator I = Header->getParent()->begin(),
224 E = Header->getParent()->end(); I != E; ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000225 if (DS.dominates(Header, I))
226 DS.addDominator(I, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000227 }
228
229 // Update immediate dominator information if we have it...
230 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
231 // Whatever i-dominated the header node now immediately dominates NewBB
232 ID->addNewBlock(NewBB, ID->get(Header));
233
234 // The preheader now is the immediate dominator for the header node...
235 ID->setImmediateDominator(Header, NewBB);
236 }
237
238 // Update DominatorTree information if it is active.
239 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
240 // The immediate dominator of the preheader is the immediate dominator of
241 // the old header.
242 //
243 DominatorTree::Node *HeaderNode = DT->getNode(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000244 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
245 HeaderNode->getIDom());
Chris Lattner38acf9e2002-09-26 16:17:31 +0000246
247 // Change the header node so that PNHode is the new immediate dominator
248 DT->changeImmediateDominator(HeaderNode, PHNode);
249 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000250
251 // Update dominance frontier information...
252 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
253 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
254 // everything that Header does, and it strictly dominates Header in
255 // addition.
256 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
257 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
258 NewDFSet.erase(Header);
259 DF->addBasicBlock(NewBB, NewDFSet);
260
261 // Now we must loop over all of the dominance frontiers in the function,
262 // replacing occurances of Header with NewBB in some cases. If a block
263 // dominates a (now) predecessor of NewBB, but did not strictly dominate
264 // Header, it will have Header in it's DF set, but should now have NewBB in
265 // its set.
266 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
267 // Get all of the dominators of the predecessor...
268 const DominatorSet::DomSetType &PredDoms =
269 DS.getDominators(OutsideBlocks[i]);
270 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
271 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
272 BasicBlock *PredDom = *PDI;
273 // If the loop header is in DF(PredDom), then PredDom didn't dominate
274 // the header but did dominate a predecessor outside of the loop. Now
275 // we change this entry to include the preheader in the DF instead of
276 // the header.
277 DominanceFrontier::iterator DFI = DF->find(PredDom);
278 assert(DFI != DF->end() && "No dominance frontier for node?");
279 if (DFI->second.count(Header)) {
280 DF->removeFromFrontier(DFI, Header);
281 DF->addToFrontier(DFI, NewBB);
282 }
283 }
284 }
285 }
286}
287
288void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
289 DominatorSet &DS = getAnalysis<DominatorSet>();
290 assert(!DS.dominates(L->getHeader(), Exit) &&
291 "Loop already dominates exit block??");
Chris Lattner7e7ad492003-02-27 22:31:07 +0000292 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
293 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000294
295 std::vector<BasicBlock*> LoopBlocks;
296 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
297 if (L->contains(*I))
298 LoopBlocks.push_back(*I);
299
Chris Lattner7e7ad492003-02-27 22:31:07 +0000300 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
301 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
302
Chris Lattner69269ac2003-02-27 21:50:19 +0000303 // Update Loop Information - we know that the new block will be in the parent
304 // loop of L.
305 if (Loop *Parent = L->getParentLoop())
306 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000307
308 // Replace any instances of Exit with NewBB in this and any nested loops...
309 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner63159382003-02-28 16:54:17 +0000310 if (I->hasExitBlock(Exit))
311 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner69269ac2003-02-27 21:50:19 +0000312
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000313 // Update dominator information... The blocks that dominate NewBB are the
314 // intersection of the dominators of predecessors, plus the block itself.
315 // The newly created basic block does not dominate anything except itself.
316 //
317 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
318 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
319 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
320 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
321 DS.addBasicBlock(NewBB, NewBBDomSet);
322
323 // Update immediate dominator information if we have it...
324 BasicBlock *NewBBIDom = 0;
325 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
326 // This block does not strictly dominate anything, so it is not an immediate
327 // dominator. To find the immediate dominator of the new exit node, we
328 // trace up the immediate dominators of a predecessor until we find a basic
329 // block that dominates the exit block.
330 //
331 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
332 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
333 assert(Dom != 0 && "No shared dominator found???");
334 Dom = ID->get(Dom);
335 }
336
337 // Set the immediate dominator now...
338 ID->addNewBlock(NewBB, Dom);
339 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
340 }
341
342 // Update DominatorTree information if it is active.
343 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
344 // NewBB doesn't dominate anything, so just create a node and link it into
345 // its immediate dominator. If we don't have ImmediateDominator info
346 // around, calculate the idom as above.
347 DominatorTree::Node *NewBBIDomNode;
348 if (NewBBIDom) {
349 NewBBIDomNode = DT->getNode(NewBBIDom);
350 } else {
351 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
352 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
353 NewBBIDomNode = NewBBIDomNode->getIDom();
354 assert(NewBBIDomNode && "No shared dominator found??");
355 }
356 }
357
358 // Create the new dominator tree node...
359 DT->createNewNode(NewBB, NewBBIDomNode);
360 }
361
362 // Update dominance frontier information...
363 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
364 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
365 // does dominate itself (and there is an edge (NewBB -> Exit)).
366 DominanceFrontier::DomSetType NewDFSet;
367 NewDFSet.insert(Exit);
368 DF->addBasicBlock(NewBB, NewDFSet);
369
370 // Now we must loop over all of the dominance frontiers in the function,
371 // replacing occurances of Exit with NewBB in some cases. If a block
372 // dominates a (now) predecessor of NewBB, but did not strictly dominate
373 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
374 // set.
375 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
376 // Get all of the dominators of the predecessor...
377 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
378 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
379 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
380 BasicBlock *PredDom = *PDI;
381 // Make sure to only rewrite blocks that are part of the loop...
382 if (L->contains(PredDom)) {
383 // If the exit node is in DF(PredDom), then PredDom didn't dominate
384 // Exit but did dominate a predecessor inside of the loop. Now we
385 // change this entry to include NewBB in the DF instead of Exit.
386 DominanceFrontier::iterator DFI = DF->find(PredDom);
387 assert(DFI != DF->end() && "No dominance frontier for node?");
388 if (DFI->second.count(Exit)) {
389 DF->removeFromFrontier(DFI, Exit);
390 DF->addToFrontier(DFI, NewBB);
391 }
392 }
393 }
394 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000395 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000396}