some cleanups: remove dead arguments and eliminate ivars
[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/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/DominanceFrontier.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/SSAUpdater.h"
25 #include "llvm/Transforms/Utils/ValueMapper.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.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 LoopRotate : public LoopPass {
36   public:
37     static char ID; // Pass ID, replacement for typeid
38     LoopRotate() : LoopPass(ID) {
39       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
40     }
41
42     // Rotate Loop L as many times as possible. Return true if
43     // loop is rotated at least once.
44     bool runOnLoop(Loop *L, LPPassManager &LPM);
45
46     // LCSSA form makes instruction renaming easier.
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       AU.addPreserved<DominatorTree>();
49       AU.addPreserved<DominanceFrontier>();
50       AU.addRequired<LoopInfo>();
51       AU.addPreserved<LoopInfo>();
52       AU.addRequiredID(LoopSimplifyID);
53       AU.addPreservedID(LoopSimplifyID);
54       AU.addRequiredID(LCSSAID);
55       AU.addPreservedID(LCSSAID);
56       AU.addPreserved<ScalarEvolution>();
57     }
58
59     // Helper functions
60
61     /// Do actual work
62     bool rotateLoop(Loop *L);
63     
64     /// After loop rotation, loop pre-header has multiple sucessors.
65     /// Insert one forwarding basic block to ensure that loop pre-header
66     /// has only one successor.
67     void preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
68                                    BasicBlock *OrigPreHeader,
69                                    BasicBlock *OrigLatch, BasicBlock *NewHeader,
70                                    BasicBlock *Exit);
71
72   private:
73     LoopInfo *LI;
74   };
75 }
76   
77 char LoopRotate::ID = 0;
78 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
79 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81 INITIALIZE_PASS_DEPENDENCY(LCSSA)
82 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
83
84 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
85
86 /// Rotate Loop L as many times as possible. Return true if
87 /// the loop is rotated at least once.
88 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
89   LI = &getAnalysis<LoopInfo>();
90
91   // One loop can be rotated multiple times.
92   bool MadeChange = false;
93   while (rotateLoop(L))
94     MadeChange = true;
95
96   return MadeChange;
97 }
98
99 /// Rotate loop LP. Return true if the loop is rotated.
100 bool LoopRotate::rotateLoop(Loop *L) {
101   BasicBlock *OrigPreHeader = L->getLoopPreheader();
102   if (!OrigPreHeader) return false;
103
104   BasicBlock *OrigLatch = L->getLoopLatch();
105   if (!OrigLatch) return false;
106
107   BasicBlock *OrigHeader =  L->getHeader();
108
109   // If the loop has only one block then there is not much to rotate.
110   if (L->getBlocks().size() == 1)
111     return false;
112
113   // If the loop header is not one of the loop exiting blocks then
114   // either this loop is already rotated or it is not
115   // suitable for loop rotation transformations.
116   if (!L->isLoopExiting(OrigHeader))
117     return false;
118
119   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
120   if (!BI)
121     return false;
122   assert(BI->isConditional() && "Branch Instruction is not conditional");
123
124   // Updating PHInodes in loops with multiple exits adds complexity. 
125   // Keep it simple, and restrict loop rotation to loops with one exit only.
126   // In future, lift this restriction and support for multiple exits if
127   // required.
128   SmallVector<BasicBlock*, 8> ExitBlocks;
129   L->getExitBlocks(ExitBlocks);
130   if (ExitBlocks.size() > 1)
131     return false;
132
133   // Check size of original header and reject loop if it is very big.
134   {
135     CodeMetrics Metrics;
136     Metrics.analyzeBasicBlock(OrigHeader);
137     if (Metrics.NumInsts > MAX_HEADER_SIZE)
138       return false;
139   }
140
141   // Now, this loop is suitable for rotation.
142
143   // Anything ScalarEvolution may know about this loop or the PHI nodes
144   // in its header will soon be invalidated.
145   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
146     SE->forgetLoop(L);
147
148   // Find new Loop header. NewHeader is a Header's one and only successor
149   // that is inside loop.  Header's other successor is outside the
150   // loop.  Otherwise loop is not suitable for rotation.
151   BasicBlock *Exit = BI->getSuccessor(0);
152   BasicBlock *NewHeader = BI->getSuccessor(1);
153   if (L->contains(Exit))
154     std::swap(Exit, NewHeader);
155   assert(NewHeader && "Unable to determine new loop header");
156   assert(L->contains(NewHeader) && !L->contains(Exit) && 
157          "Unable to determine loop header and exit blocks");
158   
159   // This code assumes that the new header has exactly one predecessor.
160   // Remove any single-entry PHI nodes in it.
161   assert(NewHeader->getSinglePredecessor() &&
162          "New header doesn't have one pred!");
163   FoldSingleEntryPHINodes(NewHeader);
164
165   // Begin by walking OrigHeader and populating ValueMap with an entry for
166   // each Instruction.
167   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
168   ValueToValueMapTy ValueMap;
169
170   // For PHI nodes, the value available in OldPreHeader is just the
171   // incoming value from OldPreHeader.
172   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
173     ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
174
175   // For the rest of the instructions, either hoist to the OrigPreheader if
176   // possible or create a clone in the OldPreHeader if not.
177   TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
178   while (I != E) {
179     Instruction *Inst = I++;
180     
181     // If the instruction's operands are invariant and it doesn't read or write
182     // memory, then it is safe to hoist.  Doing this doesn't change the order of
183     // execution in the preheader, but does prevent the instruction from
184     // executing in each iteration of the loop.  This means it is safe to hoist
185     // something that might trap, but isn't safe to hoist something that reads
186     // memory (without proving that the loop doesn't write).
187     if (L->hasLoopInvariantOperands(Inst) &&
188         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
189         !isa<TerminatorInst>(Inst)) {
190       Inst->moveBefore(LoopEntryBranch);
191       continue;
192     }
193     
194     // Otherwise, create a duplicate of the instruction.
195     Instruction *C = Inst->clone();
196     
197     // Eagerly remap the operands of the instruction.
198     RemapInstruction(C, ValueMap,
199                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
200     
201     // With the operands remapped, see if the instruction constant folds or is
202     // otherwise simplifyable.  This commonly occurs because the entry from PHI
203     // nodes allows icmps and other instructions to fold.
204     Value *V = SimplifyInstruction(C);
205     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
206       // If so, then delete the temporary instruction and stick the folded value
207       // in the map.
208       delete C;
209       ValueMap[Inst] = V;
210     } else {
211       // Otherwise, stick the new instruction into the new block!
212       C->setName(Inst->getName());
213       C->insertBefore(LoopEntryBranch);
214       ValueMap[Inst] = C;
215     }
216   }
217
218   // Along with all the other instructions, we just cloned OrigHeader's
219   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
220   // successors by duplicating their incoming values for OrigHeader.
221   TerminatorInst *TI = OrigHeader->getTerminator();
222   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
223     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
224          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
225       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
226
227   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
228   // OrigPreHeader's old terminator (the original branch into the loop), and
229   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
230   LoopEntryBranch->eraseFromParent();
231   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
232     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
233
234   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
235   // as necessary.
236   SSAUpdater SSA;
237   for (I = OrigHeader->begin(); I != E; ++I) {
238     Value *OrigHeaderVal = I;
239     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
240
241     // If there are no uses of the value (e.g. because it returns void), there
242     // is nothing to rewrite.
243     if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
244       continue;
245     
246     // The value now exits in two versions: the initial value in the preheader
247     // and the loop "next" value in the original header.
248     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
249     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
250     SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
251
252     // Visit each use of the OrigHeader instruction.
253     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
254          UE = OrigHeaderVal->use_end(); UI != UE; ) {
255       // Grab the use before incrementing the iterator.
256       Use &U = UI.getUse();
257
258       // Increment the iterator before removing the use from the list.
259       ++UI;
260
261       // SSAUpdater can't handle a non-PHI use in the same block as an
262       // earlier def. We can easily handle those cases manually.
263       Instruction *UserInst = cast<Instruction>(U.getUser());
264       if (!isa<PHINode>(UserInst)) {
265         BasicBlock *UserBB = UserInst->getParent();
266
267         // The original users in the OrigHeader are already using the
268         // original definitions.
269         if (UserBB == OrigHeader)
270           continue;
271
272         // Users in the OrigPreHeader need to use the value to which the
273         // original definitions are mapped.
274         if (UserBB == OrigPreHeader) {
275           U = OrigPreHeaderVal;
276           continue;
277         }
278       }
279
280       // Anything else can be handled by SSAUpdater.
281       SSA.RewriteUse(U);
282     }
283   }
284
285   // NewHeader is now the header of the loop.
286   L->moveToHeader(NewHeader);
287
288   // Move the original header to the bottom of the loop, where it now more
289   // naturally belongs. This isn't necessary for correctness, and CodeGen can
290   // usually reorder blocks on its own to fix things like this up, but it's
291   // still nice to keep the IR readable.
292   //
293   // The original header should have only one predecessor at this point, since
294   // we checked that the loop had a proper preheader and unique backedge before
295   // we started.
296   assert(OrigHeader->getSinglePredecessor() &&
297          "Original loop header has too many predecessors after loop rotation!");
298   OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
299
300   // Also, since this original header only has one predecessor, zap its
301   // PHI nodes, which are now trivial.
302   FoldSingleEntryPHINodes(OrigHeader);
303
304   // TODO: We could just go ahead and merge OrigHeader into its predecessor
305   // at this point, if we don't mind updating dominator info.
306
307   // Establish a new preheader, update dominators, etc.
308   preserveCanonicalLoopForm(L, OrigHeader, OrigPreHeader, OrigLatch,
309                             NewHeader, Exit);
310
311   ++NumRotated;
312   return true;
313 }
314
315
316 /// After loop rotation, loop pre-header has multiple sucessors.
317 /// Insert one forwarding basic block to ensure that loop pre-header
318 /// has only one successor.
319 void LoopRotate::preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
320                                            BasicBlock *OrigPreHeader,
321                                            BasicBlock *OrigLatch,
322                                            BasicBlock *NewHeader,
323                                            BasicBlock *Exit) {
324
325   // Right now original pre-header has two successors, new header and
326   // exit block. Insert new block between original pre-header and
327   // new header such that loop's new pre-header has only one successor.
328   BasicBlock *NewPreHeader =
329     BasicBlock::Create(OrigHeader->getContext(), "bb.nph",
330                        OrigHeader->getParent(), NewHeader);
331   LoopInfo &LI = getAnalysis<LoopInfo>();
332   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
333     PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
334   BranchInst::Create(NewHeader, NewPreHeader);
335   
336   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
337   if (OrigPH_BI->getSuccessor(0) == NewHeader)
338     OrigPH_BI->setSuccessor(0, NewPreHeader);
339   else {
340     assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
341            "Unexpected original pre-header terminator");
342     OrigPH_BI->setSuccessor(1, NewPreHeader);
343   }
344
345   PHINode *PN;
346   for (BasicBlock::iterator I = NewHeader->begin();
347        (PN = dyn_cast<PHINode>(I)); ++I) {
348     int index = PN->getBasicBlockIndex(OrigPreHeader);
349     assert(index != -1 && "Expected incoming value from Original PreHeader");
350     PN->setIncomingBlock(index, NewPreHeader);
351     assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 && 
352            "Expected only one incoming value from Original PreHeader");
353   }
354
355   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
356     DT->addNewBlock(NewPreHeader, OrigPreHeader);
357     DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
358     DT->changeImmediateDominator(Exit, OrigPreHeader);
359     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
360          BI != BE; ++BI) {
361       BasicBlock *B = *BI;
362       if (L->getHeader() != B) {
363         DomTreeNode *Node = DT->getNode(B);
364         if (Node && Node->getBlock() == OrigHeader)
365           DT->changeImmediateDominator(*BI, L->getHeader());
366       }
367     }
368     DT->changeImmediateDominator(OrigHeader, OrigLatch);
369   }
370
371   if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
372     // New Preheader's dominance frontier is Exit block.
373     DominanceFrontier::DomSetType NewPHSet;
374     NewPHSet.insert(Exit);
375     DF->addBasicBlock(NewPreHeader, NewPHSet);
376
377     // New Header's dominance frontier now includes itself and Exit block
378     DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
379     if (HeadI != DF->end()) {
380       DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
381       HeaderSet.clear();
382       HeaderSet.insert(L->getHeader());
383       HeaderSet.insert(Exit);
384     } else {
385       DominanceFrontier::DomSetType HeaderSet;
386       HeaderSet.insert(L->getHeader());
387       HeaderSet.insert(Exit);
388       DF->addBasicBlock(L->getHeader(), HeaderSet);
389     }
390
391     // Original header (new Loop Latch)'s dominance frontier is Exit.
392     DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
393     if (LatchI != DF->end()) {
394       DominanceFrontier::DomSetType &LatchSet = LatchI->second;
395       LatchSet = LatchI->second;
396       LatchSet.clear();
397       LatchSet.insert(Exit);
398     } else {
399       DominanceFrontier::DomSetType LatchSet;
400       LatchSet.insert(Exit);
401       DF->addBasicBlock(L->getHeader(), LatchSet);
402     }
403
404     // If a loop block dominates new loop latch then add to its frontiers
405     // new header and Exit and remove new latch (which is equal to original
406     // header).
407     BasicBlock *NewLatch = L->getLoopLatch();
408
409     assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
410
411     if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
412       for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
413            BI != BE; ++BI) {
414         BasicBlock *B = *BI;
415         if (!DT->dominates(B, NewLatch)) continue;
416         
417         DominanceFrontier::iterator BDFI = DF->find(B);
418         if (BDFI != DF->end()) {
419           DominanceFrontier::DomSetType &BSet = BDFI->second;
420           BSet.erase(NewLatch);
421           BSet.insert(L->getHeader());
422           BSet.insert(Exit);
423         } else {
424           DominanceFrontier::DomSetType BSet;
425           BSet.insert(L->getHeader());
426           BSet.insert(Exit);
427           DF->addBasicBlock(B, BSet);
428         }
429       }
430     }
431   }
432
433   // Preserve canonical loop form, which means Exit block should
434   // have only one predecessor.
435   SplitEdge(L->getLoopLatch(), Exit, this);
436
437   assert(NewHeader && L->getHeader() == NewHeader &&
438          "Invalid loop header after loop rotation");
439   assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
440          "Invalid loop preheader after loop rotation");
441   assert(L->getLoopLatch() &&
442          "Invalid loop latch after loop rotation");
443 }