Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 1 | //===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===// |
| 2 | // |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 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. |
| 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 Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 18 | // |
| 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 Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 29 | #include "Support/SetOperations.h" |
Chris Lattner | a92f696 | 2002-10-01 22:38:41 +0000 | [diff] [blame] | 30 | #include "Support/Statistic.h" |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 31 | |
| 32 | namespace { |
Chris Lattner | a92f696 | 2002-10-01 22:38:41 +0000 | [diff] [blame] | 33 | Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted"); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 34 | |
| 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 Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 41 | AU.addRequired<DominatorSet>(); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 42 | |
| 43 | AU.addPreserved<LoopInfo>(); |
| 44 | AU.addPreserved<DominatorSet>(); |
| 45 | AU.addPreserved<ImmediateDominators>(); |
| 46 | AU.addPreserved<DominatorTree>(); |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 47 | AU.addPreserved<DominanceFrontier>(); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 48 | AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added.... |
| 49 | } |
| 50 | private: |
| 51 | bool ProcessLoop(Loop *L); |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 52 | BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix, |
| 53 | const std::vector<BasicBlock*> &Preds); |
| 54 | void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 55 | void InsertPreheaderForLoop(Loop *L); |
| 56 | }; |
| 57 | |
Chris Lattner | 0bd3616 | 2002-09-26 16:37:37 +0000 | [diff] [blame] | 58 | RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion"); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 59 | } |
| 60 | |
| 61 | // Publically exposed interface to pass... |
| 62 | const PassInfo *LoopPreheadersID = X.getPassInfo(); |
| 63 | Pass *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 | /// |
| 69 | bool 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 | /// |
| 83 | bool 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 Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 93 | 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 Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 102 | 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 Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 108 | /// 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 | /// |
| 113 | BasicBlock *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 Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 167 | |
| 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 | /// |
| 172 | void 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 | |
| 182 | assert(OutsideBlocks.size() != 1 && "Loop already has a preheader!"); |
| 183 | |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 184 | // Split out the loop pre-header |
| 185 | BasicBlock *NewBB = |
| 186 | SplitBlockPredecessors(Header, ".preheader", OutsideBlocks); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 187 | |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 188 | //===--------------------------------------------------------------------===// |
| 189 | // Update analysis results now that we have preformed the transformation |
| 190 | // |
| 191 | |
| 192 | // We know that we have loop information to update... update it now. |
| 193 | if (Loop *Parent = L->getParentLoop()) |
| 194 | Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>()); |
| 195 | |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 196 | DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info |
| 197 | { |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 198 | // The blocks that dominate NewBB are the blocks that dominate Header, |
| 199 | // minus Header, plus NewBB. |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 200 | DominatorSet::DomSetType DomSet = DS.getDominators(Header); |
Chris Lattner | 4d01892 | 2002-09-29 21:41:38 +0000 | [diff] [blame] | 201 | DomSet.insert(NewBB); // We dominate ourself |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 202 | DomSet.erase(Header); // Header does not dominate us... |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 203 | DS.addBasicBlock(NewBB, DomSet); |
Chris Lattner | 4d01892 | 2002-09-29 21:41:38 +0000 | [diff] [blame] | 204 | |
| 205 | // The newly created basic block dominates all nodes dominated by Header. |
| 206 | for (Function::iterator I = Header->getParent()->begin(), |
| 207 | E = Header->getParent()->end(); I != E; ++I) |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 208 | if (DS.dominates(Header, I)) |
| 209 | DS.addDominator(I, NewBB); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 210 | } |
| 211 | |
| 212 | // Update immediate dominator information if we have it... |
| 213 | if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { |
| 214 | // Whatever i-dominated the header node now immediately dominates NewBB |
| 215 | ID->addNewBlock(NewBB, ID->get(Header)); |
| 216 | |
| 217 | // The preheader now is the immediate dominator for the header node... |
| 218 | ID->setImmediateDominator(Header, NewBB); |
| 219 | } |
| 220 | |
| 221 | // Update DominatorTree information if it is active. |
| 222 | if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { |
| 223 | // The immediate dominator of the preheader is the immediate dominator of |
| 224 | // the old header. |
| 225 | // |
| 226 | DominatorTree::Node *HeaderNode = DT->getNode(Header); |
Chris Lattner | 4d01892 | 2002-09-29 21:41:38 +0000 | [diff] [blame] | 227 | DominatorTree::Node *PHNode = DT->createNewNode(NewBB, |
| 228 | HeaderNode->getIDom()); |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 229 | |
| 230 | // Change the header node so that PNHode is the new immediate dominator |
| 231 | DT->changeImmediateDominator(HeaderNode, PHNode); |
| 232 | } |
Chris Lattner | dbf3cd7 | 2003-02-27 20:27:08 +0000 | [diff] [blame] | 233 | |
| 234 | // Update dominance frontier information... |
| 235 | if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { |
| 236 | // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates |
| 237 | // everything that Header does, and it strictly dominates Header in |
| 238 | // addition. |
| 239 | assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?"); |
| 240 | DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second; |
| 241 | NewDFSet.erase(Header); |
| 242 | DF->addBasicBlock(NewBB, NewDFSet); |
| 243 | |
| 244 | // Now we must loop over all of the dominance frontiers in the function, |
| 245 | // replacing occurances of Header with NewBB in some cases. If a block |
| 246 | // dominates a (now) predecessor of NewBB, but did not strictly dominate |
| 247 | // Header, it will have Header in it's DF set, but should now have NewBB in |
| 248 | // its set. |
| 249 | for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) { |
| 250 | // Get all of the dominators of the predecessor... |
| 251 | const DominatorSet::DomSetType &PredDoms = |
| 252 | DS.getDominators(OutsideBlocks[i]); |
| 253 | for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), |
| 254 | PDE = PredDoms.end(); PDI != PDE; ++PDI) { |
| 255 | BasicBlock *PredDom = *PDI; |
| 256 | // If the loop header is in DF(PredDom), then PredDom didn't dominate |
| 257 | // the header but did dominate a predecessor outside of the loop. Now |
| 258 | // we change this entry to include the preheader in the DF instead of |
| 259 | // the header. |
| 260 | DominanceFrontier::iterator DFI = DF->find(PredDom); |
| 261 | assert(DFI != DF->end() && "No dominance frontier for node?"); |
| 262 | if (DFI->second.count(Header)) { |
| 263 | DF->removeFromFrontier(DFI, Header); |
| 264 | DF->addToFrontier(DFI, NewBB); |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) { |
| 272 | DominatorSet &DS = getAnalysis<DominatorSet>(); |
| 273 | assert(!DS.dominates(L->getHeader(), Exit) && |
| 274 | "Loop already dominates exit block??"); |
| 275 | |
| 276 | std::vector<BasicBlock*> LoopBlocks; |
| 277 | for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) |
| 278 | if (L->contains(*I)) |
| 279 | LoopBlocks.push_back(*I); |
| 280 | |
| 281 | BasicBlock *NewBB = |
| 282 | SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks); |
| 283 | |
| 284 | // Update dominator information... The blocks that dominate NewBB are the |
| 285 | // intersection of the dominators of predecessors, plus the block itself. |
| 286 | // The newly created basic block does not dominate anything except itself. |
| 287 | // |
| 288 | DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]); |
| 289 | for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i) |
| 290 | set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i])); |
| 291 | NewBBDomSet.insert(NewBB); // All blocks dominate themselves... |
| 292 | DS.addBasicBlock(NewBB, NewBBDomSet); |
| 293 | |
| 294 | // Update immediate dominator information if we have it... |
| 295 | BasicBlock *NewBBIDom = 0; |
| 296 | if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { |
| 297 | // This block does not strictly dominate anything, so it is not an immediate |
| 298 | // dominator. To find the immediate dominator of the new exit node, we |
| 299 | // trace up the immediate dominators of a predecessor until we find a basic |
| 300 | // block that dominates the exit block. |
| 301 | // |
| 302 | BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor... |
| 303 | while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator... |
| 304 | assert(Dom != 0 && "No shared dominator found???"); |
| 305 | Dom = ID->get(Dom); |
| 306 | } |
| 307 | |
| 308 | // Set the immediate dominator now... |
| 309 | ID->addNewBlock(NewBB, Dom); |
| 310 | NewBBIDom = Dom; // Reuse this if calculating DominatorTree info... |
| 311 | } |
| 312 | |
| 313 | // Update DominatorTree information if it is active. |
| 314 | if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { |
| 315 | // NewBB doesn't dominate anything, so just create a node and link it into |
| 316 | // its immediate dominator. If we don't have ImmediateDominator info |
| 317 | // around, calculate the idom as above. |
| 318 | DominatorTree::Node *NewBBIDomNode; |
| 319 | if (NewBBIDom) { |
| 320 | NewBBIDomNode = DT->getNode(NewBBIDom); |
| 321 | } else { |
| 322 | NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred |
| 323 | while (!NewBBDomSet.count(NewBBIDomNode->getNode())) { |
| 324 | NewBBIDomNode = NewBBIDomNode->getIDom(); |
| 325 | assert(NewBBIDomNode && "No shared dominator found??"); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // Create the new dominator tree node... |
| 330 | DT->createNewNode(NewBB, NewBBIDomNode); |
| 331 | } |
| 332 | |
| 333 | // Update dominance frontier information... |
| 334 | if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { |
| 335 | // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it |
| 336 | // does dominate itself (and there is an edge (NewBB -> Exit)). |
| 337 | DominanceFrontier::DomSetType NewDFSet; |
| 338 | NewDFSet.insert(Exit); |
| 339 | DF->addBasicBlock(NewBB, NewDFSet); |
| 340 | |
| 341 | // Now we must loop over all of the dominance frontiers in the function, |
| 342 | // replacing occurances of Exit with NewBB in some cases. If a block |
| 343 | // dominates a (now) predecessor of NewBB, but did not strictly dominate |
| 344 | // Exit, it will have Exit in it's DF set, but should now have NewBB in its |
| 345 | // set. |
| 346 | for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { |
| 347 | // Get all of the dominators of the predecessor... |
| 348 | const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]); |
| 349 | for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), |
| 350 | PDE = PredDoms.end(); PDI != PDE; ++PDI) { |
| 351 | BasicBlock *PredDom = *PDI; |
| 352 | // Make sure to only rewrite blocks that are part of the loop... |
| 353 | if (L->contains(PredDom)) { |
| 354 | // If the exit node is in DF(PredDom), then PredDom didn't dominate |
| 355 | // Exit but did dominate a predecessor inside of the loop. Now we |
| 356 | // change this entry to include NewBB in the DF instead of Exit. |
| 357 | DominanceFrontier::iterator DFI = DF->find(PredDom); |
| 358 | assert(DFI != DF->end() && "No dominance frontier for node?"); |
| 359 | if (DFI->second.count(Exit)) { |
| 360 | DF->removeFromFrontier(DFI, Exit); |
| 361 | DF->addToFrontier(DFI, NewBB); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | } |
Chris Lattner | 38acf9e | 2002-09-26 16:17:31 +0000 | [diff] [blame] | 368 | } |