1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotate"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
32 #define MAX_HEADER_SIZE 16
34 STATISTIC(NumRotated, "Number of loops rotated");
37 class VISIBILITY_HIDDEN RenameData {
39 RenameData(Instruction *O, Value *P, Instruction *H)
40 : Original(O), PreHeader(P), Header(H) { }
42 Instruction *Original; // Original instruction
43 Value *PreHeader; // Original pre-header replacement
44 Instruction *Header; // New header replacement
47 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
50 static char ID; // Pass ID, replacement for typeid
51 LoopRotate() : LoopPass((intptr_t)&ID) {}
53 // Rotate Loop L as many times as possible. Return true if
54 // loop is rotated at least once.
55 bool runOnLoop(Loop *L, LPPassManager &LPM);
57 // LCSSA form makes instruction renaming easier.
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequiredID(LCSSAID);
60 AU.addPreservedID(LCSSAID);
61 AU.addPreserved<ScalarEvolution>();
62 AU.addPreserved<LoopInfo>();
63 AU.addRequiredID(LoopSimplifyID);
64 AU.addPreservedID(LoopSimplifyID);
70 bool rotateLoop(Loop *L, LPPassManager &LPM);
72 /// Initialize local data
75 /// Make sure all Exit block PHINodes have required incoming values.
76 /// If incoming value is constant or defined outside the loop then
77 /// PHINode may not have an entry for original pre-header.
78 void updateExitBlock();
80 /// Return true if this instruction is used outside original header.
81 bool usedOutsideOriginalHeader(Instruction *In);
83 /// Find Replacement information for instruction. Return NULL if it is
85 const RenameData *findReplacementData(Instruction *I);
87 /// After loop rotation, loop pre-header has multiple sucessors.
88 /// Insert one forwarding basic block to ensure that loop pre-header
89 /// has only one successor.
90 void preserveCanonicalLoopForm(LPPassManager &LPM);
95 BasicBlock *OrigHeader;
96 BasicBlock *OrigPreHeader;
97 BasicBlock *OrigLatch;
98 BasicBlock *NewHeader;
100 LPPassManager *LPM_Ptr;
101 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
104 char LoopRotate::ID = 0;
105 RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
108 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
110 /// Rotate Loop L as many times as possible. Return true if
111 /// loop is rotated at least once.
112 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
114 bool RotatedOneLoop = false;
118 // One loop can be rotated multiple times.
119 while (rotateLoop(Lp,LPM)) {
120 RotatedOneLoop = true;
124 return RotatedOneLoop;
127 /// Rotate loop LP. Return true if the loop is rotated.
128 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
132 OrigHeader = L->getHeader();
133 OrigPreHeader = L->getLoopPreheader();
134 OrigLatch = L->getLoopLatch();
136 // If loop has only one block then there is not much to rotate.
137 if (L->getBlocks().size() == 1)
140 assert (OrigHeader && OrigLatch && OrigPreHeader &&
141 "Loop is not in canonical form");
143 // If loop header is not one of the loop exit block then
144 // either this loop is already rotated or it is not
145 // suitable for loop rotation transformations.
146 if (!L->isLoopExit(OrigHeader))
149 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
152 assert (BI->isConditional() && "Branch Instruction is not condiitional");
154 // Updating PHInodes in loops with multiple exits adds complexity.
155 // Keep it simple, and restrict loop rotation to loops with one exit only.
156 // In future, lift this restriction and support for multiple exits if
158 std::vector<BasicBlock *> ExitBlocks;
159 L->getExitBlocks(ExitBlocks);
160 if (ExitBlocks.size() > 1)
163 // Check size of original header and reject
164 // loop if it is very big.
165 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
168 // Now, this loop is suitable for rotation.
170 // Find new Loop header. NewHeader is a Header's one and only successor
171 // that is inside loop. Header's other successor is out side the
172 // loop. Otherwise loop is not suitable for rotation.
173 Exit = BI->getSuccessor(0);
174 NewHeader = BI->getSuccessor(1);
175 if (L->contains(Exit))
176 std::swap(Exit, NewHeader);
177 assert (NewHeader && "Unable to determine new loop header");
178 assert(L->contains(NewHeader) && !L->contains(Exit) &&
179 "Unable to determine loop header and exit blocks");
181 // Copy PHI nodes and other instructions from original header
182 // into original pre-header. Unlike original header, original pre-header is
183 // not a member of loop.
185 // New loop header is one and only successor of original header that
186 // is inside the loop. All other original header successors are outside
187 // the loop. Copy PHI Nodes from original header into new loop header.
188 // Add second incoming value, from original loop pre-header into these phi
189 // nodes. If a value defined in original header is used outside original
190 // header then new loop header will need new phi nodes with two incoming
191 // values, one definition from original header and second definition is
192 // from original loop pre-header.
194 // Remove terminator from Original pre-header. Original pre-header will
195 // receive a clone of original header terminator as a new terminator.
196 OrigPreHeader->getInstList().pop_back();
197 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
199 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
202 // PHI nodes are not copied into original pre-header. Instead their values
203 // are directly propagated.
204 Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
206 // Create new PHI node with two incoming values for NewHeader.
207 // One incoming value is from OrigLatch (through OrigHeader) and
208 // second incoming value is from original pre-header.
209 PHINode *NH = new PHINode(In->getType(), In->getName());
210 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
211 NH->addIncoming(NPV, OrigPreHeader);
212 NewHeader->getInstList().push_front(NH);
214 // "In" can be replaced by NH at various places.
215 LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
218 // Now, handle non-phi instructions.
219 for (; I != E; ++I) {
222 assert (!isa<PHINode>(In) && "PHINode is not expected here");
223 // This is not a PHI instruction. Insert its clone into original pre-header.
224 // If this instruction is using a value from same basic block then
225 // update it to use value from cloned instruction.
226 Instruction *C = In->clone();
227 C->setName(In->getName());
228 OrigPreHeader->getInstList().push_back(C);
230 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
231 if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
232 if (const RenameData *D = findReplacementData(OpPhi)) {
233 // This is using values from original header PHI node.
234 // Here, directly used incoming value from original pre-header.
235 C->setOperand(opi, D->PreHeader);
238 else if (Instruction *OpInsn =
239 dyn_cast<Instruction>(In->getOperand(opi))) {
240 if (const RenameData *D = findReplacementData(OpInsn))
241 C->setOperand(opi, D->PreHeader);
246 // If this instruction is used outside this basic block then
247 // create new PHINode for this instruction.
248 Instruction *NewHeaderReplacement = NULL;
249 if (usedOutsideOriginalHeader(In)) {
250 PHINode *PN = new PHINode(In->getType(), In->getName());
251 PN->addIncoming(In, OrigHeader);
252 PN->addIncoming(C, OrigPreHeader);
253 NewHeader->getInstList().push_front(PN);
254 NewHeaderReplacement = PN;
257 // "In" can be replaced by NPH or NH at various places.
258 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
261 // Rename uses of original header instructions to reflect their new
262 // definitions (either from original pre-header node or from newly created
263 // new header PHINodes.
265 // Original header instructions are used in
266 // 1) Original header:
268 // If instruction is used in non-phi instructions then it is using
269 // defintion from original heder iteself. Do not replace this use
270 // with definition from new header or original pre-header.
272 // If instruction is used in phi node then it is an incoming
273 // value. Rename its use to reflect new definition from new-preheader
276 // 2) Inside loop but not in original header
278 // Replace this use to reflect definition from new header.
279 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
280 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
282 if (!ILoopHeaderInfo.Header)
285 Instruction *OldPhi = ILoopHeaderInfo.Original;
286 Instruction *NewPhi = ILoopHeaderInfo.Header;
288 // Before replacing uses, collect them first, so that iterator is
290 SmallVector<Instruction *, 16> AllUses;
291 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
293 Instruction *U = cast<Instruction>(UI);
294 AllUses.push_back(U);
297 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
298 UE = AllUses.end(); UI != UE; ++UI) {
299 Instruction *U = *UI;
300 BasicBlock *Parent = U->getParent();
302 // Used inside original header
303 if (Parent == OrigHeader) {
304 // Do not rename uses inside original header non-phi instructions.
305 PHINode *PU = dyn_cast<PHINode>(U);
309 // Do not rename uses inside original header phi nodes, if the
310 // incoming value is for new header.
311 if (PU->getBasicBlockIndex(NewHeader) != -1
312 && PU->getIncomingValueForBlock(NewHeader) == U)
315 U->replaceUsesOfWith(OldPhi, NewPhi);
319 // Used inside loop, but not in original header.
320 if (L->contains(U->getParent())) {
322 U->replaceUsesOfWith(OldPhi, NewPhi);
326 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
327 if (U->getParent() == Exit) {
328 assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
330 PHINode *UPhi = cast<PHINode>(U);
331 // UPhi already has one incoming argument from original header.
332 // Add second incoming argument from new Pre header.
333 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
335 // Used outside Exit block. Create a new PHI node from exit block
336 // to receive value from ne new header ane pre header.
337 PHINode *PN = new PHINode(U->getType(), U->getName());
338 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
339 PN->addIncoming(OldPhi, OrigHeader);
340 Exit->getInstList().push_front(PN);
341 U->replaceUsesOfWith(OldPhi, PN);
346 /// Make sure all Exit block PHINodes have required incoming values.
351 // Removing incoming branch from loop preheader to original header.
352 // Now original header is inside the loop.
353 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
356 PHINode *PN = dyn_cast<PHINode>(In);
360 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 incoming value is constant or defined outside the loop then
374 /// PHINode may not have an entry for original pre-header.
375 void LoopRotate::updateExitBlock() {
377 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
380 PHINode *PN = dyn_cast<PHINode>(I);
384 // There is already one incoming value from original pre-header block.
385 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
388 const RenameData *ILoopHeaderInfo;
389 Value *V = PN->getIncomingValueForBlock(OrigHeader);
390 if (isa<Instruction>(V) &&
391 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
392 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
393 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
395 PN->addIncoming(V, OrigPreHeader);
400 /// Initialize local data
401 void LoopRotate::initialize() {
404 OrigPreHeader = NULL;
408 LoopHeaderInfo.clear();
411 /// Return true if this instruction is used by any instructions in the loop that
412 /// aren't in original header.
413 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
415 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
417 Instruction *U = cast<Instruction>(UI);
418 if (U->getParent() != OrigHeader) {
419 if (L->contains(U->getParent()))
427 /// Find Replacement information for instruction. Return NULL if it is
429 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
431 // Since LoopHeaderInfo is small, linear walk is OK.
432 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
433 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
434 if (ILoopHeaderInfo.Original == In)
435 return &ILoopHeaderInfo;
440 /// After loop rotation, loop pre-header has multiple sucessors.
441 /// Insert one forwarding basic block to ensure that loop pre-header
442 /// has only one successor.
443 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
445 // Right now original pre-header has two successors, new header and
446 // exit block. Insert new block between original pre-header and
447 // new header such that loop's new pre-header has only one successor.
448 BasicBlock *NewPreHeader = new BasicBlock("bb.nph", OrigHeader->getParent(),
450 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
451 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
452 PL->addBasicBlockToLoop(NewPreHeader, LI);
453 new BranchInst(NewHeader, NewPreHeader);
455 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
456 if (OrigPH_BI->getSuccessor(0) == NewHeader)
457 OrigPH_BI->setSuccessor(0, NewPreHeader);
459 assert (OrigPH_BI->getSuccessor(1) == NewHeader &&
460 "Unexpected original pre-header terminator");
461 OrigPH_BI->setSuccessor(1, NewPreHeader);
464 for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
467 PHINode *PN = dyn_cast<PHINode>(In);
471 int index = PN->getBasicBlockIndex(OrigPreHeader);
472 assert (index != -1 && "Expected incoming value from Original PreHeader");
473 PN->setIncomingBlock(index, NewPreHeader);
474 assert (PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
475 "Expected only one incoming value from Original PreHeader");
478 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
479 DT->addNewBlock(NewPreHeader, OrigPreHeader);
480 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
481 DT->changeImmediateDominator(Exit, OrigPreHeader);
482 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
485 if (L->getHeader() != B) {
486 DomTreeNode *Node = DT->getNode(B);
487 if (Node && Node->getBlock() == OrigHeader)
488 DT->changeImmediateDominator(*BI, L->getHeader());
491 DT->changeImmediateDominator(OrigHeader, OrigLatch);
494 if(DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
496 // New Preheader's dominance frontier is Exit block.
497 DominanceFrontier::DomSetType NewPHSet;
498 NewPHSet.insert(Exit);
499 DF->addBasicBlock(NewPreHeader, NewPHSet);
501 // New Header's dominance frontier now includes itself and Exit block
502 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
503 if (HeadI != DF->end()) {
504 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
506 HeaderSet.insert(L->getHeader());
507 HeaderSet.insert(Exit);
509 DominanceFrontier::DomSetType HeaderSet;
510 HeaderSet.insert(L->getHeader());
511 HeaderSet.insert(Exit);
512 DF->addBasicBlock(L->getHeader(), HeaderSet);
515 // Original header (new Loop Latch)'s dominance frontier is Exit.
516 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
517 if (LatchI != DF->end()) {
518 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
519 LatchSet = LatchI->second;
521 LatchSet.insert(Exit);
523 DominanceFrontier::DomSetType LatchSet;
524 LatchSet.insert(Exit);
525 DF->addBasicBlock(L->getHeader(), LatchSet);
528 // If a loop block dominates new loop latch then its frontier is
529 // new header and Exit.
530 BasicBlock *NewLatch = L->getLoopLatch();
531 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
532 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
535 if (DT->dominates(B, NewLatch)) {
536 DominanceFrontier::iterator BDFI = DF->find(B);
537 if (BDFI != DF->end()) {
538 DominanceFrontier::DomSetType &BSet = BDFI->second;
541 BSet.insert(L->getHeader());
544 DominanceFrontier::DomSetType BSet;
545 BSet.insert(L->getHeader());
547 DF->addBasicBlock(B, BSet);
553 // Preserve canonical loop form, which means Exit block should
554 // have only one predecessor.
555 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
558 BasicBlock::iterator I = Exit->begin(), E = Exit->end();
560 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
561 PHINode *NewPN = new PHINode(PN->getType(), PN->getName());
562 unsigned N = PN->getNumIncomingValues();
563 for (unsigned index = 0; index < N; ++index)
564 if (PN->getIncomingBlock(index) == NExit) {
565 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
566 PN->setIncomingValue(index, NewPN);
567 PN->setIncomingBlock(index, NExit);
568 NExit->getInstList().push_front(NewPN);
572 assert (NewHeader && L->getHeader() == NewHeader
573 && "Invalid loop header after loop rotation");
574 assert (NewPreHeader && L->getLoopPreheader() == NewPreHeader
575 && "Invalid loop preheader after loop rotation");
576 assert (L->getLoopLatch()
577 && "Invalid loop latch after loop rotation");