1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotate"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SmallVector.h"
30 #define MAX_HEADER_SIZE 16
32 STATISTIC(NumRotated, "Number of loops rotated");
37 RenameData(Instruction *O, Value *P, Instruction *H)
38 : Original(O), PreHeader(P), Header(H) { }
40 Instruction *Original; // Original instruction
41 Value *PreHeader; // Original pre-header replacement
42 Instruction *Header; // New header replacement
45 class LoopRotate : public LoopPass {
47 static char ID; // Pass ID, replacement for typeid
48 LoopRotate() : LoopPass(&ID) {}
50 // Rotate Loop L as many times as possible. Return true if
51 // loop is rotated at least once.
52 bool runOnLoop(Loop *L, LPPassManager &LPM);
54 // LCSSA form makes instruction renaming easier.
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequiredID(LoopSimplifyID);
57 AU.addPreservedID(LoopSimplifyID);
58 AU.addRequiredID(LCSSAID);
59 AU.addPreservedID(LCSSAID);
60 AU.addPreserved<ScalarEvolution>();
61 AU.addPreserved<LoopInfo>();
62 AU.addPreserved<DominatorTree>();
63 AU.addPreserved<DominanceFrontier>();
69 bool rotateLoop(Loop *L, LPPassManager &LPM);
71 /// Initialize local data
74 /// Make sure all Exit block PHINodes have required incoming values.
75 /// If incoming value is constant or defined outside the loop then
76 /// PHINode may not have an entry for original pre-header.
77 void updateExitBlock();
79 /// Return true if this instruction is used outside original header.
80 bool usedOutsideOriginalHeader(Instruction *In);
82 /// Find Replacement information for instruction. Return NULL if it is
84 const RenameData *findReplacementData(Instruction *I);
86 /// After loop rotation, loop pre-header has multiple sucessors.
87 /// Insert one forwarding basic block to ensure that loop pre-header
88 /// has only one successor.
89 void preserveCanonicalLoopForm(LPPassManager &LPM);
94 BasicBlock *OrigHeader;
95 BasicBlock *OrigPreHeader;
96 BasicBlock *OrigLatch;
97 BasicBlock *NewHeader;
99 LPPassManager *LPM_Ptr;
100 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
104 char LoopRotate::ID = 0;
105 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
107 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
109 /// Rotate Loop L as many times as possible. Return true if
110 /// the loop is rotated at least once.
111 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
113 bool RotatedOneLoop = false;
117 // One loop can be rotated multiple times.
118 while (rotateLoop(Lp,LPM)) {
119 RotatedOneLoop = true;
123 return RotatedOneLoop;
126 /// Rotate loop LP. Return true if the loop is rotated.
127 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
130 OrigHeader = L->getHeader();
131 OrigPreHeader = L->getLoopPreheader();
132 OrigLatch = L->getLoopLatch();
134 // If the loop has only one block then there is not much to rotate.
135 if (L->getBlocks().size() == 1)
138 assert(OrigHeader && OrigLatch && OrigPreHeader &&
139 "Loop is not in canonical form");
141 // If the loop header is not one of the loop exiting blocks then
142 // either this loop is already rotated or it is not
143 // suitable for loop rotation transformations.
144 if (!L->isLoopExit(OrigHeader))
147 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
150 assert(BI->isConditional() && "Branch Instruction is not conditional");
152 // Updating PHInodes in loops with multiple exits adds complexity.
153 // Keep it simple, and restrict loop rotation to loops with one exit only.
154 // In future, lift this restriction and support for multiple exits if
156 SmallVector<BasicBlock*, 8> ExitBlocks;
157 L->getExitBlocks(ExitBlocks);
158 if (ExitBlocks.size() > 1)
161 // Check size of original header and reject
162 // loop if it is very big.
165 // FIXME: Use common api to estimate size.
166 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
167 OE = OrigHeader->end(); OI != OE; ++OI) {
168 if (isa<PHINode>(OI))
169 continue; // PHI nodes don't count.
170 if (isa<DbgInfoIntrinsic>(OI))
171 continue; // Debug intrinsics don't count as size.
175 if (Size > MAX_HEADER_SIZE)
178 // Now, this loop is suitable for rotation.
180 // Anything ScalarEvolution may know about this loop or the PHI nodes
181 // in its header will soon be invalidated.
182 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
183 SE->forgetLoopBackedgeTakenCount(L);
185 // Find new Loop header. NewHeader is a Header's one and only successor
186 // that is inside loop. Header's other successor is outside the
187 // loop. Otherwise loop is not suitable for rotation.
188 Exit = BI->getSuccessor(0);
189 NewHeader = BI->getSuccessor(1);
190 if (L->contains(Exit))
191 std::swap(Exit, NewHeader);
192 assert(NewHeader && "Unable to determine new loop header");
193 assert(L->contains(NewHeader) && !L->contains(Exit) &&
194 "Unable to determine loop header and exit blocks");
196 // This code assumes that the new header has exactly one predecessor.
197 // Remove any single-entry PHI nodes in it.
198 assert(NewHeader->getSinglePredecessor() &&
199 "New header doesn't have one pred!");
200 FoldSingleEntryPHINodes(NewHeader);
202 // Copy PHI nodes and other instructions from the original header
203 // into the original pre-header. Unlike the original header, the original
204 // pre-header is not a member of the loop.
206 // The new loop header is the one and only successor of original header that
207 // is inside the loop. All other original header successors are outside
208 // the loop. Copy PHI Nodes from the original header into the new loop header.
209 // Add second incoming value, from original loop pre-header into these phi
210 // nodes. If a value defined in original header is used outside original
211 // header then new loop header will need new phi nodes with two incoming
212 // values, one definition from original header and second definition is
213 // from original loop pre-header.
215 // Remove terminator from Original pre-header. Original pre-header will
216 // receive a clone of original header terminator as a new terminator.
217 OrigPreHeader->getInstList().pop_back();
218 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
220 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
221 // PHI nodes are not copied into original pre-header. Instead their values
222 // are directly propagated.
223 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
225 // Create a new PHI node with two incoming values for NewHeader.
226 // One incoming value is from OrigLatch (through OrigHeader) and the
227 // second incoming value is from original pre-header.
228 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
230 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
231 NH->addIncoming(NPV, OrigPreHeader);
233 // "In" can be replaced by NH at various places.
234 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
237 // Now, handle non-phi instructions.
238 for (; I != E; ++I) {
240 assert(!isa<PHINode>(In) && "PHINode is not expected here");
242 // This is not a PHI instruction. Insert its clone into original pre-header.
243 // If this instruction is using a value from same basic block then
244 // update it to use value from cloned instruction.
245 Instruction *C = In->clone();
246 C->setName(In->getName());
247 OrigPreHeader->getInstList().push_back(C);
249 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
250 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
251 if (!OpInsn) continue; // Ignore non-instruction values.
252 if (const RenameData *D = findReplacementData(OpInsn))
253 C->setOperand(opi, D->PreHeader);
256 // If this instruction is used outside this basic block then
257 // create new PHINode for this instruction.
258 Instruction *NewHeaderReplacement = NULL;
259 if (usedOutsideOriginalHeader(In)) {
260 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
262 PN->addIncoming(In, OrigHeader);
263 PN->addIncoming(C, OrigPreHeader);
264 NewHeaderReplacement = PN;
266 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
269 // Rename uses of original header instructions to reflect their new
270 // definitions (either from original pre-header node or from newly created
271 // new header PHINodes.
273 // Original header instructions are used in
274 // 1) Original header:
276 // If instruction is used in non-phi instructions then it is using
277 // defintion from original heder iteself. Do not replace this use
278 // with definition from new header or original pre-header.
280 // If instruction is used in phi node then it is an incoming
281 // value. Rename its use to reflect new definition from new-preheader
284 // 2) Inside loop but not in original header
286 // Replace this use to reflect definition from new header.
287 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
288 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
290 if (!ILoopHeaderInfo.Header)
293 Instruction *OldPhi = ILoopHeaderInfo.Original;
294 Instruction *NewPhi = ILoopHeaderInfo.Header;
296 // Before replacing uses, collect them first, so that iterator is
298 SmallVector<Instruction *, 16> AllUses;
299 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
301 AllUses.push_back(cast<Instruction>(UI));
303 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
304 UE = AllUses.end(); UI != UE; ++UI) {
305 Instruction *U = *UI;
306 BasicBlock *Parent = U->getParent();
308 // Used inside original header
309 if (Parent == OrigHeader) {
310 // Do not rename uses inside original header non-phi instructions.
311 PHINode *PU = dyn_cast<PHINode>(U);
315 // Do not rename uses inside original header phi nodes, if the
316 // incoming value is for new header.
317 if (PU->getBasicBlockIndex(NewHeader) != -1
318 && PU->getIncomingValueForBlock(NewHeader) == U)
321 U->replaceUsesOfWith(OldPhi, NewPhi);
325 // Used inside loop, but not in original header.
326 if (L->contains(U->getParent())) {
328 U->replaceUsesOfWith(OldPhi, NewPhi);
332 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
333 if (U->getParent() == Exit) {
334 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
336 PHINode *UPhi = cast<PHINode>(U);
337 // UPhi already has one incoming argument from original header.
338 // Add second incoming argument from new Pre header.
339 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
341 // Used outside Exit block. Create a new PHI node in the exit block
342 // to receive the value from the new header and pre-header.
343 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
345 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
346 PN->addIncoming(OldPhi, OrigHeader);
347 U->replaceUsesOfWith(OldPhi, PN);
352 /// Make sure all Exit block PHINodes have required incoming values.
357 // Removing incoming branch from loop preheader to original header.
358 // Now original header is inside the loop.
359 for (BasicBlock::iterator I = OrigHeader->begin();
360 (PN = dyn_cast<PHINode>(I)); ++I)
361 PN->removeIncomingValue(OrigPreHeader);
363 // Make NewHeader as the new header for the loop.
364 L->moveToHeader(NewHeader);
366 preserveCanonicalLoopForm(LPM);
372 /// Make sure all Exit block PHINodes have required incoming values.
373 /// If an incoming value is constant or defined outside the loop then
374 /// PHINode may not have an entry for the original pre-header.
375 void LoopRotate::updateExitBlock() {
378 for (BasicBlock::iterator I = Exit->begin();
379 (PN = dyn_cast<PHINode>(I)); ++I) {
381 // There is already one incoming value from original pre-header block.
382 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
385 const RenameData *ILoopHeaderInfo;
386 Value *V = PN->getIncomingValueForBlock(OrigHeader);
387 if (isa<Instruction>(V) &&
388 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
389 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
390 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
392 PN->addIncoming(V, OrigPreHeader);
397 /// Initialize local data
398 void LoopRotate::initialize() {
401 OrigPreHeader = NULL;
405 LoopHeaderInfo.clear();
408 /// Return true if this instruction is used by any instructions in the loop that
409 /// aren't in original header.
410 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
411 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
413 BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
414 if (UserBB != OrigHeader && L->contains(UserBB))
421 /// Find Replacement information for instruction. Return NULL if it is
423 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
425 // Since LoopHeaderInfo is small, linear walk is OK.
426 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
427 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
428 if (ILoopHeaderInfo.Original == In)
429 return &ILoopHeaderInfo;
434 /// After loop rotation, loop pre-header has multiple sucessors.
435 /// Insert one forwarding basic block to ensure that loop pre-header
436 /// has only one successor.
437 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
439 // Right now original pre-header has two successors, new header and
440 // exit block. Insert new block between original pre-header and
441 // new header such that loop's new pre-header has only one successor.
442 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
444 OrigHeader->getParent(),
446 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
447 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
448 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
449 BranchInst::Create(NewHeader, NewPreHeader);
451 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
452 if (OrigPH_BI->getSuccessor(0) == NewHeader)
453 OrigPH_BI->setSuccessor(0, NewPreHeader);
455 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
456 "Unexpected original pre-header terminator");
457 OrigPH_BI->setSuccessor(1, NewPreHeader);
461 for (BasicBlock::iterator I = NewHeader->begin();
462 (PN = dyn_cast<PHINode>(I)); ++I) {
463 int index = PN->getBasicBlockIndex(OrigPreHeader);
464 assert(index != -1 && "Expected incoming value from Original PreHeader");
465 PN->setIncomingBlock(index, NewPreHeader);
466 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
467 "Expected only one incoming value from Original PreHeader");
470 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
471 DT->addNewBlock(NewPreHeader, OrigPreHeader);
472 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
473 DT->changeImmediateDominator(Exit, OrigPreHeader);
474 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
477 if (L->getHeader() != B) {
478 DomTreeNode *Node = DT->getNode(B);
479 if (Node && Node->getBlock() == OrigHeader)
480 DT->changeImmediateDominator(*BI, L->getHeader());
483 DT->changeImmediateDominator(OrigHeader, OrigLatch);
486 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
487 // New Preheader's dominance frontier is Exit block.
488 DominanceFrontier::DomSetType NewPHSet;
489 NewPHSet.insert(Exit);
490 DF->addBasicBlock(NewPreHeader, NewPHSet);
492 // New Header's dominance frontier now includes itself and Exit block
493 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
494 if (HeadI != DF->end()) {
495 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
497 HeaderSet.insert(L->getHeader());
498 HeaderSet.insert(Exit);
500 DominanceFrontier::DomSetType HeaderSet;
501 HeaderSet.insert(L->getHeader());
502 HeaderSet.insert(Exit);
503 DF->addBasicBlock(L->getHeader(), HeaderSet);
506 // Original header (new Loop Latch)'s dominance frontier is Exit.
507 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
508 if (LatchI != DF->end()) {
509 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
510 LatchSet = LatchI->second;
512 LatchSet.insert(Exit);
514 DominanceFrontier::DomSetType LatchSet;
515 LatchSet.insert(Exit);
516 DF->addBasicBlock(L->getHeader(), LatchSet);
519 // If a loop block dominates new loop latch then add to its frontiers
520 // new header and Exit and remove new latch (which is equal to original
522 BasicBlock *NewLatch = L->getLoopLatch();
524 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
526 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
527 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
530 if (DT->dominates(B, NewLatch)) {
531 DominanceFrontier::iterator BDFI = DF->find(B);
532 if (BDFI != DF->end()) {
533 DominanceFrontier::DomSetType &BSet = BDFI->second;
534 BSet.erase(NewLatch);
535 BSet.insert(L->getHeader());
538 DominanceFrontier::DomSetType BSet;
539 BSet.insert(L->getHeader());
541 DF->addBasicBlock(B, BSet);
548 // Preserve canonical loop form, which means Exit block should
549 // have only one predecessor.
550 SplitEdge(L->getLoopLatch(), Exit, this);
552 assert(NewHeader && L->getHeader() == NewHeader &&
553 "Invalid loop header after loop rotation");
554 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
555 "Invalid loop preheader after loop rotation");
556 assert(L->getLoopLatch() &&
557 "Invalid loop latch after loop rotation");