Tell ScalarEvolution to forget everything it knows about a loop before
[oota-llvm.git] / lib / Transforms / Scalar / LoopRotation.cpp
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Rotation Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
28 using namespace llvm;
29
30 #define MAX_HEADER_SIZE 16
31
32 STATISTIC(NumRotated, "Number of loops rotated");
33 namespace {
34
35   class RenameData {
36   public:
37     RenameData(Instruction *O, Value *P, Instruction *H) 
38       : Original(O), PreHeader(P), Header(H) { }
39   public:
40     Instruction *Original; // Original instruction
41     Value *PreHeader; // Original pre-header replacement
42     Instruction *Header; // New header replacement
43   };
44   
45   class LoopRotate : public LoopPass {
46   public:
47     static char ID; // Pass ID, replacement for typeid
48     LoopRotate() : LoopPass(&ID) {}
49
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);
53
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>();
64     }
65
66     // Helper functions
67
68     /// Do actual work
69     bool rotateLoop(Loop *L, LPPassManager &LPM);
70     
71     /// Initialize local data
72     void initialize();
73
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();
78
79     /// Return true if this instruction is used outside original header.
80     bool usedOutsideOriginalHeader(Instruction *In);
81
82     /// Find Replacement information for instruction. Return NULL if it is
83     /// not available.
84     const RenameData *findReplacementData(Instruction *I);
85
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);
90
91   private:
92
93     Loop *L;
94     BasicBlock *OrigHeader;
95     BasicBlock *OrigPreHeader;
96     BasicBlock *OrigLatch;
97     BasicBlock *NewHeader;
98     BasicBlock *Exit;
99     LPPassManager *LPM_Ptr;
100     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
101   };
102 }
103   
104 char LoopRotate::ID = 0;
105 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
106
107 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
108
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) {
112
113   bool RotatedOneLoop = false;
114   initialize();
115   LPM_Ptr = &LPM;
116
117   // One loop can be rotated multiple times.
118   while (rotateLoop(Lp,LPM)) {
119     RotatedOneLoop = true;
120     initialize();
121   }
122
123   return RotatedOneLoop;
124 }
125
126 /// Rotate loop LP. Return true if the loop is rotated.
127 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
128   L = Lp;
129
130   OrigHeader =  L->getHeader();
131   OrigPreHeader = L->getLoopPreheader();
132   OrigLatch = L->getLoopLatch();
133
134   // If the loop has only one block then there is not much to rotate.
135   if (L->getBlocks().size() == 1)
136     return false;
137
138   assert(OrigHeader && OrigLatch && OrigPreHeader &&
139          "Loop is not in canonical form");
140
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))
145     return false;
146
147   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
148   if (!BI)
149     return false;
150   assert(BI->isConditional() && "Branch Instruction is not conditional");
151
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
155   // required.
156   SmallVector<BasicBlock*, 8> ExitBlocks;
157   L->getExitBlocks(ExitBlocks);
158   if (ExitBlocks.size() > 1)
159     return false;
160
161   // Check size of original header and reject
162   // loop if it is very big.
163   unsigned Size = 0;
164   
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.
172       Size++;
173   }
174
175   if (Size > MAX_HEADER_SIZE)
176     return false;
177
178   // Now, this loop is suitable for rotation.
179
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);
184
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");
195   
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);
201
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.
205   //
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.
214
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();
219   PHINode *PN = 0;
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);
224
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(),
229                                   NewHeader->begin());
230     NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
231     NH->addIncoming(NPV, OrigPreHeader);
232     
233     // "In" can be replaced by NH at various places.
234     LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
235   }
236
237   // Now, handle non-phi instructions.
238   for (; I != E; ++I) {
239     Instruction *In = I;
240     assert(!isa<PHINode>(In) && "PHINode is not expected here");
241     
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);
248
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);
254     }
255
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(),
261                                     NewHeader->begin());
262       PN->addIncoming(In, OrigHeader);
263       PN->addIncoming(C, OrigPreHeader);
264       NewHeaderReplacement = PN;
265     }
266     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
267   }
268
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.
272   //
273   // Original header instructions are used in
274   // 1) Original header:
275   //
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.
279   //
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
282   //    or new header.
283   //
284   // 2) Inside loop but not in original header
285   //
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];
289
290     if (!ILoopHeaderInfo.Header)
291       continue;
292
293     Instruction *OldPhi = ILoopHeaderInfo.Original;
294     Instruction *NewPhi = ILoopHeaderInfo.Header;
295
296     // Before replacing uses, collect them first, so that iterator is
297     // not invalidated.
298     SmallVector<Instruction *, 16> AllUses;
299     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
300          UI != UE; ++UI)
301       AllUses.push_back(cast<Instruction>(UI));
302
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();
307
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);
312         if (!PU)
313           continue;
314
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)
319           continue;
320         
321        U->replaceUsesOfWith(OldPhi, NewPhi);
322        continue;
323       }
324
325       // Used inside loop, but not in original header.
326       if (L->contains(U->getParent())) {
327         if (U != NewPhi)
328           U->replaceUsesOfWith(OldPhi, NewPhi);
329         continue;
330       }
331       
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");
335         
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);
340       } else {
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(),
344                                       Exit->begin());
345         PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
346         PN->addIncoming(OldPhi, OrigHeader);
347         U->replaceUsesOfWith(OldPhi, PN);
348       }
349     }
350   }
351   
352   /// Make sure all Exit block PHINodes have required incoming values.
353   updateExitBlock();
354
355   // Update CFG
356
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);
362
363   // Make NewHeader as the new header for the loop.
364   L->moveToHeader(NewHeader);
365
366   preserveCanonicalLoopForm(LPM);
367
368   NumRotated++;
369   return true;
370 }
371
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() {
376
377   PHINode *PN;
378   for (BasicBlock::iterator I = Exit->begin();
379        (PN = dyn_cast<PHINode>(I)); ++I) {
380
381     // There is already one incoming value from original pre-header block.
382     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
383       continue;
384
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);
391     } else {
392       PN->addIncoming(V, OrigPreHeader);
393     }
394   }
395 }
396
397 /// Initialize local data
398 void LoopRotate::initialize() {
399   L = NULL;
400   OrigHeader = NULL;
401   OrigPreHeader = NULL;
402   NewHeader = NULL;
403   Exit = NULL;
404
405   LoopHeaderInfo.clear();
406 }
407
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();
412        UI != UE; ++UI) {
413     BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
414     if (UserBB != OrigHeader && L->contains(UserBB))
415       return true;
416   }
417
418   return false;
419 }
420
421 /// Find Replacement information for instruction. Return NULL if it is
422 /// not available.
423 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
424
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;
430   }
431   return NULL;
432 }
433
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) {
438
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(),
443                                                 "bb.nph",
444                                                 OrigHeader->getParent(), 
445                                                 NewHeader);
446   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
447   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
448     PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
449   BranchInst::Create(NewHeader, NewPreHeader);
450   
451   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
452   if (OrigPH_BI->getSuccessor(0) == NewHeader)
453     OrigPH_BI->setSuccessor(0, NewPreHeader);
454   else {
455     assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
456            "Unexpected original pre-header terminator");
457     OrigPH_BI->setSuccessor(1, NewPreHeader);
458   }
459
460   PHINode *PN;
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");
468   }
469
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();
475          BI != BE; ++BI) {
476       BasicBlock *B = *BI;
477       if (L->getHeader() != B) {
478         DomTreeNode *Node = DT->getNode(B);
479         if (Node && Node->getBlock() == OrigHeader)
480           DT->changeImmediateDominator(*BI, L->getHeader());
481       }
482     }
483     DT->changeImmediateDominator(OrigHeader, OrigLatch);
484   }
485
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);
491
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;
496       HeaderSet.clear();
497       HeaderSet.insert(L->getHeader());
498       HeaderSet.insert(Exit);
499     } else {
500       DominanceFrontier::DomSetType HeaderSet;
501       HeaderSet.insert(L->getHeader());
502       HeaderSet.insert(Exit);
503       DF->addBasicBlock(L->getHeader(), HeaderSet);
504     }
505
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;
511       LatchSet.clear();
512       LatchSet.insert(Exit);
513     } else {
514       DominanceFrontier::DomSetType LatchSet;
515       LatchSet.insert(Exit);
516       DF->addBasicBlock(L->getHeader(), LatchSet);
517     }
518
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
521     // header).
522     BasicBlock *NewLatch = L->getLoopLatch();
523
524     assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
525
526     if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
527       for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
528            BI != BE; ++BI) {
529         BasicBlock *B = *BI;
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());
536             BSet.insert(Exit);
537           } else {
538             DominanceFrontier::DomSetType BSet;
539             BSet.insert(L->getHeader());
540             BSet.insert(Exit);
541             DF->addBasicBlock(B, BSet);
542           }
543         }
544       }
545     }
546   }
547
548   // Preserve canonical loop form, which means Exit block should
549   // have only one predecessor.
550   SplitEdge(L->getLoopLatch(), Exit, this);
551
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");
558 }