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"
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(&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(LoopSimplifyID);
60 AU.addPreservedID(LoopSimplifyID);
61 AU.addRequiredID(LCSSAID);
62 AU.addPreservedID(LCSSAID);
63 AU.addPreserved<ScalarEvolution>();
64 AU.addPreserved<LoopInfo>();
65 AU.addPreserved<DominatorTree>();
66 AU.addPreserved<DominanceFrontier>();
72 bool rotateLoop(Loop *L, LPPassManager &LPM);
74 /// Initialize local data
77 /// Make sure all Exit block PHINodes have required incoming values.
78 /// If incoming value is constant or defined outside the loop then
79 /// PHINode may not have an entry for original pre-header.
80 void updateExitBlock();
82 /// Return true if this instruction is used outside original header.
83 bool usedOutsideOriginalHeader(Instruction *In);
85 /// Find Replacement information for instruction. Return NULL if it is
87 const RenameData *findReplacementData(Instruction *I);
89 /// After loop rotation, loop pre-header has multiple sucessors.
90 /// Insert one forwarding basic block to ensure that loop pre-header
91 /// has only one successor.
92 void preserveCanonicalLoopForm(LPPassManager &LPM);
97 BasicBlock *OrigHeader;
98 BasicBlock *OrigPreHeader;
99 BasicBlock *OrigLatch;
100 BasicBlock *NewHeader;
102 LPPassManager *LPM_Ptr;
103 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
107 char LoopRotate::ID = 0;
108 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
110 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
112 /// Rotate Loop L as many times as possible. Return true if
113 /// loop is rotated at least once.
114 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
116 bool RotatedOneLoop = false;
120 // One loop can be rotated multiple times.
121 while (rotateLoop(Lp,LPM)) {
122 RotatedOneLoop = true;
126 return RotatedOneLoop;
129 /// Rotate loop LP. Return true if the loop is rotated.
130 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
133 OrigHeader = L->getHeader();
134 OrigPreHeader = L->getLoopPreheader();
135 OrigLatch = L->getLoopLatch();
137 // If loop has only one block then there is not much to rotate.
138 if (L->getBlocks().size() == 1)
141 assert(OrigHeader && OrigLatch && OrigPreHeader &&
142 "Loop is not in canonical form");
144 // If loop header is not one of the loop exit block then
145 // either this loop is already rotated or it is not
146 // suitable for loop rotation transformations.
147 if (!L->isLoopExit(OrigHeader))
150 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
153 assert(BI->isConditional() && "Branch Instruction is not conditional");
155 // Updating PHInodes in loops with multiple exits adds complexity.
156 // Keep it simple, and restrict loop rotation to loops with one exit only.
157 // In future, lift this restriction and support for multiple exits if
159 SmallVector<BasicBlock*, 8> ExitBlocks;
160 L->getExitBlocks(ExitBlocks);
161 if (ExitBlocks.size() > 1)
164 // Check size of original header and reject
165 // loop if it is very big.
166 if (OrigHeader->size() > MAX_HEADER_SIZE)
169 // Now, this loop is suitable for rotation.
171 // Find new Loop header. NewHeader is a Header's one and only successor
172 // that is inside loop. Header's other successor is outside the
173 // loop. Otherwise loop is not suitable for rotation.
174 Exit = BI->getSuccessor(0);
175 NewHeader = BI->getSuccessor(1);
176 if (L->contains(Exit))
177 std::swap(Exit, NewHeader);
178 assert(NewHeader && "Unable to determine new loop header");
179 assert(L->contains(NewHeader) && !L->contains(Exit) &&
180 "Unable to determine loop header and exit blocks");
182 // Copy PHI nodes and other instructions from original header
183 // into original pre-header. Unlike original header, original pre-header is
184 // not a member of loop.
186 // New loop header is one and only successor of original header that
187 // is inside the loop. All other original header successors are outside
188 // the loop. Copy PHI Nodes from original header into new loop header.
189 // Add second incoming value, from original loop pre-header into these phi
190 // nodes. If a value defined in original header is used outside original
191 // header then new loop header will need new phi nodes with two incoming
192 // values, one definition from original header and second definition is
193 // from original loop pre-header.
195 // Remove terminator from Original pre-header. Original pre-header will
196 // receive a clone of original header terminator as a new terminator.
197 OrigPreHeader->getInstList().pop_back();
198 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
200 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
201 // PHI nodes are not copied into original pre-header. Instead their values
202 // are directly propagated.
203 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
205 // Create new PHI node with two incoming values for NewHeader.
206 // One incoming value is from OrigLatch (through OrigHeader) and
207 // second incoming value is from original pre-header.
208 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
210 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
211 NH->addIncoming(NPV, OrigPreHeader);
213 // "In" can be replaced by NH at various places.
214 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
217 // Now, handle non-phi instructions.
218 for (; I != E; ++I) {
220 assert(!isa<PHINode>(In) && "PHINode is not expected here");
222 // This is not a PHI instruction. Insert its clone into original pre-header.
223 // If this instruction is using a value from same basic block then
224 // update it to use value from cloned instruction.
225 Instruction *C = In->clone();
226 C->setName(In->getName());
227 OrigPreHeader->getInstList().push_back(C);
229 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
230 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
231 if (!OpInsn) continue; // Ignore non-instruction values.
232 if (const RenameData *D = findReplacementData(OpInsn))
233 C->setOperand(opi, D->PreHeader);
236 // If this instruction is used outside this basic block then
237 // create new PHINode for this instruction.
238 Instruction *NewHeaderReplacement = NULL;
239 if (usedOutsideOriginalHeader(In)) {
240 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
242 PN->addIncoming(In, OrigHeader);
243 PN->addIncoming(C, OrigPreHeader);
244 NewHeaderReplacement = PN;
246 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
249 // Rename uses of original header instructions to reflect their new
250 // definitions (either from original pre-header node or from newly created
251 // new header PHINodes.
253 // Original header instructions are used in
254 // 1) Original header:
256 // If instruction is used in non-phi instructions then it is using
257 // defintion from original heder iteself. Do not replace this use
258 // with definition from new header or original pre-header.
260 // If instruction is used in phi node then it is an incoming
261 // value. Rename its use to reflect new definition from new-preheader
264 // 2) Inside loop but not in original header
266 // Replace this use to reflect definition from new header.
267 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
268 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
270 if (!ILoopHeaderInfo.Header)
273 Instruction *OldPhi = ILoopHeaderInfo.Original;
274 Instruction *NewPhi = ILoopHeaderInfo.Header;
276 // Before replacing uses, collect them first, so that iterator is
278 SmallVector<Instruction *, 16> AllUses;
279 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
281 AllUses.push_back(cast<Instruction>(UI));
283 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
284 UE = AllUses.end(); UI != UE; ++UI) {
285 Instruction *U = *UI;
286 BasicBlock *Parent = U->getParent();
288 // Used inside original header
289 if (Parent == OrigHeader) {
290 // Do not rename uses inside original header non-phi instructions.
291 PHINode *PU = dyn_cast<PHINode>(U);
295 // Do not rename uses inside original header phi nodes, if the
296 // incoming value is for new header.
297 if (PU->getBasicBlockIndex(NewHeader) != -1
298 && PU->getIncomingValueForBlock(NewHeader) == U)
301 U->replaceUsesOfWith(OldPhi, NewPhi);
305 // Used inside loop, but not in original header.
306 if (L->contains(U->getParent())) {
308 U->replaceUsesOfWith(OldPhi, NewPhi);
312 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
313 if (U->getParent() == Exit) {
314 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
316 PHINode *UPhi = cast<PHINode>(U);
317 // UPhi already has one incoming argument from original header.
318 // Add second incoming argument from new Pre header.
319 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
321 // Used outside Exit block. Create a new PHI node from exit block
322 // to receive value from ne new header ane pre header.
323 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
325 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
326 PN->addIncoming(OldPhi, OrigHeader);
327 U->replaceUsesOfWith(OldPhi, PN);
332 /// Make sure all Exit block PHINodes have required incoming values.
337 // Removing incoming branch from loop preheader to original header.
338 // Now original header is inside the loop.
339 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
341 if (PHINode *PN = dyn_cast<PHINode>(I))
342 PN->removeIncomingValue(OrigPreHeader);
344 // Make NewHeader as the new header for the loop.
345 L->moveToHeader(NewHeader);
347 preserveCanonicalLoopForm(LPM);
353 /// Make sure all Exit block PHINodes have required incoming values.
354 /// If incoming value is constant or defined outside the loop then
355 /// PHINode may not have an entry for original pre-header.
356 void LoopRotate::updateExitBlock() {
358 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
361 PHINode *PN = dyn_cast<PHINode>(I);
365 // There is already one incoming value from original pre-header block.
366 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
369 const RenameData *ILoopHeaderInfo;
370 Value *V = PN->getIncomingValueForBlock(OrigHeader);
371 if (isa<Instruction>(V) &&
372 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
373 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
374 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
376 PN->addIncoming(V, OrigPreHeader);
381 /// Initialize local data
382 void LoopRotate::initialize() {
385 OrigPreHeader = NULL;
389 LoopHeaderInfo.clear();
392 /// Return true if this instruction is used by any instructions in the loop that
393 /// aren't in original header.
394 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
395 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
397 BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
398 if (UserBB != OrigHeader && L->contains(UserBB))
405 /// Find Replacement information for instruction. Return NULL if it is
407 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
409 // Since LoopHeaderInfo is small, linear walk is OK.
410 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
411 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
412 if (ILoopHeaderInfo.Original == In)
413 return &ILoopHeaderInfo;
418 /// After loop rotation, loop pre-header has multiple sucessors.
419 /// Insert one forwarding basic block to ensure that loop pre-header
420 /// has only one successor.
421 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
423 // Right now original pre-header has two successors, new header and
424 // exit block. Insert new block between original pre-header and
425 // new header such that loop's new pre-header has only one successor.
426 BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph",
427 OrigHeader->getParent(),
429 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
430 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
431 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
432 BranchInst::Create(NewHeader, NewPreHeader);
434 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
435 if (OrigPH_BI->getSuccessor(0) == NewHeader)
436 OrigPH_BI->setSuccessor(0, NewPreHeader);
438 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
439 "Unexpected original pre-header terminator");
440 OrigPH_BI->setSuccessor(1, NewPreHeader);
443 for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
445 PHINode *PN = dyn_cast<PHINode>(I);
449 int index = PN->getBasicBlockIndex(OrigPreHeader);
450 assert(index != -1 && "Expected incoming value from Original PreHeader");
451 PN->setIncomingBlock(index, NewPreHeader);
452 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
453 "Expected only one incoming value from Original PreHeader");
456 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
457 DT->addNewBlock(NewPreHeader, OrigPreHeader);
458 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
459 DT->changeImmediateDominator(Exit, OrigPreHeader);
460 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
463 if (L->getHeader() != B) {
464 DomTreeNode *Node = DT->getNode(B);
465 if (Node && Node->getBlock() == OrigHeader)
466 DT->changeImmediateDominator(*BI, L->getHeader());
469 DT->changeImmediateDominator(OrigHeader, OrigLatch);
472 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
473 // New Preheader's dominance frontier is Exit block.
474 DominanceFrontier::DomSetType NewPHSet;
475 NewPHSet.insert(Exit);
476 DF->addBasicBlock(NewPreHeader, NewPHSet);
478 // New Header's dominance frontier now includes itself and Exit block
479 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
480 if (HeadI != DF->end()) {
481 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
483 HeaderSet.insert(L->getHeader());
484 HeaderSet.insert(Exit);
486 DominanceFrontier::DomSetType HeaderSet;
487 HeaderSet.insert(L->getHeader());
488 HeaderSet.insert(Exit);
489 DF->addBasicBlock(L->getHeader(), HeaderSet);
492 // Original header (new Loop Latch)'s dominance frontier is Exit.
493 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
494 if (LatchI != DF->end()) {
495 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
496 LatchSet = LatchI->second;
498 LatchSet.insert(Exit);
500 DominanceFrontier::DomSetType LatchSet;
501 LatchSet.insert(Exit);
502 DF->addBasicBlock(L->getHeader(), LatchSet);
505 // If a loop block dominates new loop latch then its frontier is
506 // new header and Exit.
507 BasicBlock *NewLatch = L->getLoopLatch();
508 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
509 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
512 if (DT->dominates(B, NewLatch)) {
513 DominanceFrontier::iterator BDFI = DF->find(B);
514 if (BDFI != DF->end()) {
515 DominanceFrontier::DomSetType &BSet = BDFI->second;
518 BSet.insert(L->getHeader());
521 DominanceFrontier::DomSetType BSet;
522 BSet.insert(L->getHeader());
524 DF->addBasicBlock(B, BSet);
530 // Preserve canonical loop form, which means Exit block should
531 // have only one predecessor.
532 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
535 BasicBlock::iterator I = Exit->begin(), E = Exit->end();
537 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
538 unsigned N = PN->getNumIncomingValues();
539 for (unsigned index = 0; index < N; ++index)
540 if (PN->getIncomingBlock(index) == NExit) {
541 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
543 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
544 PN->setIncomingValue(index, NewPN);
545 PN->setIncomingBlock(index, NExit);
550 assert(NewHeader && L->getHeader() == NewHeader &&
551 "Invalid loop header after loop rotation");
552 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
553 "Invalid loop preheader after loop rotation");
554 assert(L->getLoopLatch() &&
555 "Invalid loop latch after loop rotation");