blob: dc9df6aa3904224006bffcde05b63cb728d95506 [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 Lattner38acf9e2002-09-26 16:17:31 +000031
32namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000033 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
Chris Lattner38acf9e2002-09-26 16:17:31 +000034
35 struct Preheaders : public FunctionPass {
36 virtual bool runOnFunction(Function &F);
37
38 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39 // We need loop information to identify the loops...
40 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000041 AU.addRequired<DominatorSet>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000042
43 AU.addPreserved<LoopInfo>();
44 AU.addPreserved<DominatorSet>();
45 AU.addPreserved<ImmediateDominators>();
46 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000047 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000048 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
49 }
50 private:
51 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000052 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
53 const std::vector<BasicBlock*> &Preds);
54 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000055 void InsertPreheaderForLoop(Loop *L);
56 };
57
Chris Lattner0bd36162002-09-26 16:37:37 +000058 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
Chris Lattner38acf9e2002-09-26 16:17:31 +000059}
60
61// Publically exposed interface to pass...
62const PassInfo *LoopPreheadersID = X.getPassInfo();
63Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
64
65
66/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
67/// it in any convenient order) inserting preheaders...
68///
69bool Preheaders::runOnFunction(Function &F) {
70 bool Changed = false;
71 LoopInfo &LI = getAnalysis<LoopInfo>();
72
73 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
74 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
75
76 return Changed;
77}
78
79
80/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
81/// all loops have preheaders.
82///
83bool Preheaders::ProcessLoop(Loop *L) {
84 bool Changed = false;
85
86 // Does the loop already have a preheader? If so, don't modify the loop...
87 if (L->getLoopPreheader() == 0) {
88 InsertPreheaderForLoop(L);
89 NumInserted++;
90 Changed = true;
91 }
92
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000093 DominatorSet &DS = getAnalysis<DominatorSet>();
94 BasicBlock *Header = L->getHeader();
95 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
96 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
97 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
98 NumInserted++;
99 Changed = true;
100 }
101
Chris Lattner38acf9e2002-09-26 16:17:31 +0000102 const std::vector<Loop*> &SubLoops = L->getSubLoops();
103 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
104 Changed |= ProcessLoop(SubLoops[i]);
105 return Changed;
106}
107
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000108/// SplitBlockPredecessors - Split the specified block into two blocks. We want
109/// to move the predecessors specified in the Preds list to point to the new
110/// block, leaving the remaining predecessors pointing to BB. This method
111/// updates the SSA PHINode's, but no other analyses.
112///
113BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
114 const char *Suffix,
115 const std::vector<BasicBlock*> &Preds) {
116
117 // Create new basic block, insert right before the original block...
118 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
119
120 // The preheader first gets an unconditional branch to the loop header...
121 BranchInst *BI = new BranchInst(BB);
122 NewBB->getInstList().push_back(BI);
123
124 // For every PHI node in the block, insert a PHI node into NewBB where the
125 // incoming values from the out of loop edges are moved to NewBB. We have two
126 // possible cases here. If the loop is dead, we just insert dummy entries
127 // into the PHI nodes for the new edge. If the loop is not dead, we move the
128 // incoming edges in BB into new PHI nodes in NewBB.
129 //
130 if (!Preds.empty()) { // Is the loop not obviously dead?
131 for (BasicBlock::iterator I = BB->begin();
132 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
133
134 // Create the new PHI node, insert it into NewBB at the end of the block
135 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
136
137 // Move all of the edges from blocks outside the loop to the new PHI
138 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
139 Value *V = PN->removeIncomingValue(Preds[i]);
140 NewPHI->addIncoming(V, Preds[i]);
141 }
142
143 // Add an incoming value to the PHI node in the loop for the preheader
144 // edge
145 PN->addIncoming(NewPHI, NewBB);
146 }
147
148 // Now that the PHI nodes are updated, actually move the edges from
149 // Preds to point to NewBB instead of BB.
150 //
151 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
152 TerminatorInst *TI = Preds[i]->getTerminator();
153 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
154 if (TI->getSuccessor(s) == BB)
155 TI->setSuccessor(s, NewBB);
156 }
157
158 } else { // Otherwise the loop is dead...
159 for (BasicBlock::iterator I = BB->begin();
160 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
161 // Insert dummy values as the incoming value...
162 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
163 }
164 return NewBB;
165}
166
Chris Lattner38acf9e2002-09-26 16:17:31 +0000167
168/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
169/// preheader, this method is called to insert one. This method has two phases:
170/// preheader insertion and analysis updating.
171///
172void Preheaders::InsertPreheaderForLoop(Loop *L) {
173 BasicBlock *Header = L->getHeader();
174
175 // Compute the set of predecessors of the loop that are not in the loop.
176 std::vector<BasicBlock*> OutsideBlocks;
177 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
178 PI != PE; ++PI)
179 if (!L->contains(*PI)) // Coming in from outside the loop?
180 OutsideBlocks.push_back(*PI); // Keep track of it...
181
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000182 // Split out the loop pre-header
183 BasicBlock *NewBB =
184 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000185
Chris Lattner38acf9e2002-09-26 16:17:31 +0000186 //===--------------------------------------------------------------------===//
187 // Update analysis results now that we have preformed the transformation
188 //
189
190 // We know that we have loop information to update... update it now.
191 if (Loop *Parent = L->getParentLoop())
192 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
193
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000194 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
195 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000196 // The blocks that dominate NewBB are the blocks that dominate Header,
197 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000198 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000199 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner38acf9e2002-09-26 16:17:31 +0000200 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000201 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000202
203 // The newly created basic block dominates all nodes dominated by Header.
204 for (Function::iterator I = Header->getParent()->begin(),
205 E = Header->getParent()->end(); I != E; ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000206 if (DS.dominates(Header, I))
207 DS.addDominator(I, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000208 }
209
210 // Update immediate dominator information if we have it...
211 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
212 // Whatever i-dominated the header node now immediately dominates NewBB
213 ID->addNewBlock(NewBB, ID->get(Header));
214
215 // The preheader now is the immediate dominator for the header node...
216 ID->setImmediateDominator(Header, NewBB);
217 }
218
219 // Update DominatorTree information if it is active.
220 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
221 // The immediate dominator of the preheader is the immediate dominator of
222 // the old header.
223 //
224 DominatorTree::Node *HeaderNode = DT->getNode(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000225 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
226 HeaderNode->getIDom());
Chris Lattner38acf9e2002-09-26 16:17:31 +0000227
228 // Change the header node so that PNHode is the new immediate dominator
229 DT->changeImmediateDominator(HeaderNode, PHNode);
230 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000231
232 // Update dominance frontier information...
233 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
234 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
235 // everything that Header does, and it strictly dominates Header in
236 // addition.
237 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
238 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
239 NewDFSet.erase(Header);
240 DF->addBasicBlock(NewBB, NewDFSet);
241
242 // Now we must loop over all of the dominance frontiers in the function,
243 // replacing occurances of Header with NewBB in some cases. If a block
244 // dominates a (now) predecessor of NewBB, but did not strictly dominate
245 // Header, it will have Header in it's DF set, but should now have NewBB in
246 // its set.
247 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
248 // Get all of the dominators of the predecessor...
249 const DominatorSet::DomSetType &PredDoms =
250 DS.getDominators(OutsideBlocks[i]);
251 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
252 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
253 BasicBlock *PredDom = *PDI;
254 // If the loop header is in DF(PredDom), then PredDom didn't dominate
255 // the header but did dominate a predecessor outside of the loop. Now
256 // we change this entry to include the preheader in the DF instead of
257 // the header.
258 DominanceFrontier::iterator DFI = DF->find(PredDom);
259 assert(DFI != DF->end() && "No dominance frontier for node?");
260 if (DFI->second.count(Header)) {
261 DF->removeFromFrontier(DFI, Header);
262 DF->addToFrontier(DFI, NewBB);
263 }
264 }
265 }
266 }
267}
268
269void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
270 DominatorSet &DS = getAnalysis<DominatorSet>();
271 assert(!DS.dominates(L->getHeader(), Exit) &&
272 "Loop already dominates exit block??");
273
274 std::vector<BasicBlock*> LoopBlocks;
275 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
276 if (L->contains(*I))
277 LoopBlocks.push_back(*I);
278
279 BasicBlock *NewBB =
280 SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
281
Chris Lattner69269ac2003-02-27 21:50:19 +0000282 // Update Loop Information - we know that the new block will be in the parent
283 // loop of L.
284 if (Loop *Parent = L->getParentLoop())
285 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
286
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000287 // Update dominator information... The blocks that dominate NewBB are the
288 // intersection of the dominators of predecessors, plus the block itself.
289 // The newly created basic block does not dominate anything except itself.
290 //
291 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
292 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
293 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
294 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
295 DS.addBasicBlock(NewBB, NewBBDomSet);
296
297 // Update immediate dominator information if we have it...
298 BasicBlock *NewBBIDom = 0;
299 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
300 // This block does not strictly dominate anything, so it is not an immediate
301 // dominator. To find the immediate dominator of the new exit node, we
302 // trace up the immediate dominators of a predecessor until we find a basic
303 // block that dominates the exit block.
304 //
305 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
306 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
307 assert(Dom != 0 && "No shared dominator found???");
308 Dom = ID->get(Dom);
309 }
310
311 // Set the immediate dominator now...
312 ID->addNewBlock(NewBB, Dom);
313 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
314 }
315
316 // Update DominatorTree information if it is active.
317 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
318 // NewBB doesn't dominate anything, so just create a node and link it into
319 // its immediate dominator. If we don't have ImmediateDominator info
320 // around, calculate the idom as above.
321 DominatorTree::Node *NewBBIDomNode;
322 if (NewBBIDom) {
323 NewBBIDomNode = DT->getNode(NewBBIDom);
324 } else {
325 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
326 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
327 NewBBIDomNode = NewBBIDomNode->getIDom();
328 assert(NewBBIDomNode && "No shared dominator found??");
329 }
330 }
331
332 // Create the new dominator tree node...
333 DT->createNewNode(NewBB, NewBBIDomNode);
334 }
335
336 // Update dominance frontier information...
337 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
338 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
339 // does dominate itself (and there is an edge (NewBB -> Exit)).
340 DominanceFrontier::DomSetType NewDFSet;
341 NewDFSet.insert(Exit);
342 DF->addBasicBlock(NewBB, NewDFSet);
343
344 // Now we must loop over all of the dominance frontiers in the function,
345 // replacing occurances of Exit with NewBB in some cases. If a block
346 // dominates a (now) predecessor of NewBB, but did not strictly dominate
347 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
348 // set.
349 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
350 // Get all of the dominators of the predecessor...
351 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
352 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
353 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
354 BasicBlock *PredDom = *PDI;
355 // Make sure to only rewrite blocks that are part of the loop...
356 if (L->contains(PredDom)) {
357 // If the exit node is in DF(PredDom), then PredDom didn't dominate
358 // Exit but did dominate a predecessor inside of the loop. Now we
359 // change this entry to include NewBB in the DF instead of Exit.
360 DominanceFrontier::iterator DFI = DF->find(PredDom);
361 assert(DFI != DF->end() && "No dominance frontier for node?");
362 if (DFI->second.count(Exit)) {
363 DF->removeFromFrontier(DFI, Exit);
364 DF->addToFrontier(DFI, NewBB);
365 }
366 }
367 }
368 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000369 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000370}