Rotate multi-exit loops even if the latch was simplified.
[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/ADT/Statistic.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Transforms/Utils/SSAUpdater.h"
30 #include "llvm/Transforms/Utils/ValueMapper.h"
31 using namespace llvm;
32
33 #define MAX_HEADER_SIZE 16
34
35 STATISTIC(NumRotated, "Number of loops rotated");
36 namespace {
37
38   class LoopRotate : public LoopPass {
39   public:
40     static char ID; // Pass ID, replacement for typeid
41     LoopRotate() : LoopPass(ID) {
42       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
43     }
44
45     // LCSSA form makes instruction renaming easier.
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.addPreserved<DominatorTree>();
48       AU.addRequired<LoopInfo>();
49       AU.addPreserved<LoopInfo>();
50       AU.addRequiredID(LoopSimplifyID);
51       AU.addPreservedID(LoopSimplifyID);
52       AU.addRequiredID(LCSSAID);
53       AU.addPreservedID(LCSSAID);
54       AU.addPreserved<ScalarEvolution>();
55       AU.addRequired<TargetTransformInfo>();
56     }
57
58     bool runOnLoop(Loop *L, LPPassManager &LPM);
59     bool simplifyLoopLatch(Loop *L);
60     bool rotateLoop(Loop *L, bool SimplifiedLatch);
61
62   private:
63     LoopInfo *LI;
64     const TargetTransformInfo *TTI;
65   };
66 }
67
68 char LoopRotate::ID = 0;
69 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
70 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
71 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
72 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
73 INITIALIZE_PASS_DEPENDENCY(LCSSA)
74 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
75
76 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
77
78 /// Rotate Loop L as many times as possible. Return true if
79 /// the loop is rotated at least once.
80 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
81   LI = &getAnalysis<LoopInfo>();
82   TTI = &getAnalysis<TargetTransformInfo>();
83
84   // Simplify the loop latch before attempting to rotate the header
85   // upward. Rotation may not be needed if the loop tail can be folded into the
86   // loop exit.
87   bool SimplifiedLatch = simplifyLoopLatch(L);
88
89   // One loop can be rotated multiple times.
90   bool MadeChange = false;
91   while (rotateLoop(L, SimplifiedLatch)) {
92     MadeChange = true;
93     SimplifiedLatch = false;
94   }
95   return MadeChange;
96 }
97
98 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
99 /// old header into the preheader.  If there were uses of the values produced by
100 /// these instruction that were outside of the loop, we have to insert PHI nodes
101 /// to merge the two values.  Do this now.
102 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
103                                             BasicBlock *OrigPreheader,
104                                             ValueToValueMapTy &ValueMap) {
105   // Remove PHI node entries that are no longer live.
106   BasicBlock::iterator I, E = OrigHeader->end();
107   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
108     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
109
110   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
111   // as necessary.
112   SSAUpdater SSA;
113   for (I = OrigHeader->begin(); I != E; ++I) {
114     Value *OrigHeaderVal = I;
115
116     // If there are no uses of the value (e.g. because it returns void), there
117     // is nothing to rewrite.
118     if (OrigHeaderVal->use_empty())
119       continue;
120
121     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
122
123     // The value now exits in two versions: the initial value in the preheader
124     // and the loop "next" value in the original header.
125     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
126     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
127     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
128
129     // Visit each use of the OrigHeader instruction.
130     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
131          UE = OrigHeaderVal->use_end(); UI != UE; ) {
132       // Grab the use before incrementing the iterator.
133       Use &U = UI.getUse();
134
135       // Increment the iterator before removing the use from the list.
136       ++UI;
137
138       // SSAUpdater can't handle a non-PHI use in the same block as an
139       // earlier def. We can easily handle those cases manually.
140       Instruction *UserInst = cast<Instruction>(U.getUser());
141       if (!isa<PHINode>(UserInst)) {
142         BasicBlock *UserBB = UserInst->getParent();
143
144         // The original users in the OrigHeader are already using the
145         // original definitions.
146         if (UserBB == OrigHeader)
147           continue;
148
149         // Users in the OrigPreHeader need to use the value to which the
150         // original definitions are mapped.
151         if (UserBB == OrigPreheader) {
152           U = OrigPreHeaderVal;
153           continue;
154         }
155       }
156
157       // Anything else can be handled by SSAUpdater.
158       SSA.RewriteUse(U);
159     }
160   }
161 }
162
163 /// Determine whether the instructions in this range my be safely and cheaply
164 /// speculated. This is not an important enough situation to develop complex
165 /// heuristics. We handle a single arithmetic instruction along with any type
166 /// conversions.
167 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
168                                   BasicBlock::iterator End) {
169   bool seenIncrement = false;
170   for (BasicBlock::iterator I = Begin; I != End; ++I) {
171
172     if (!isSafeToSpeculativelyExecute(I))
173       return false;
174
175     if (isa<DbgInfoIntrinsic>(I))
176       continue;
177
178     switch (I->getOpcode()) {
179     default:
180       return false;
181     case Instruction::GetElementPtr:
182       // GEPs are cheap if all indices are constant.
183       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
184         return false;
185       // fall-thru to increment case
186     case Instruction::Add:
187     case Instruction::Sub:
188     case Instruction::And:
189     case Instruction::Or:
190     case Instruction::Xor:
191     case Instruction::Shl:
192     case Instruction::LShr:
193     case Instruction::AShr:
194       if (seenIncrement)
195         return false;
196       seenIncrement = true;
197       break;
198     case Instruction::Trunc:
199     case Instruction::ZExt:
200     case Instruction::SExt:
201       // ignore type conversions
202       break;
203     }
204   }
205   return true;
206 }
207
208 /// Fold the loop tail into the loop exit by speculating the loop tail
209 /// instructions. Typically, this is a single post-increment. In the case of a
210 /// simple 2-block loop, hoisting the increment can be much better than
211 /// duplicating the entire loop header. In the cast of loops with early exits,
212 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
213 /// canonical form so downstream passes can handle it.
214 ///
215 /// I don't believe this invalidates SCEV.
216 bool LoopRotate::simplifyLoopLatch(Loop *L) {
217   BasicBlock *Latch = L->getLoopLatch();
218   if (!Latch || Latch->hasAddressTaken())
219     return false;
220
221   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
222   if (!Jmp || !Jmp->isUnconditional())
223     return false;
224
225   BasicBlock *LastExit = Latch->getSinglePredecessor();
226   if (!LastExit || !L->isLoopExiting(LastExit))
227     return false;
228
229   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
230   if (!BI)
231     return false;
232
233   if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
234     return false;
235
236   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
237         << LastExit->getName() << "\n");
238
239   // Hoist the instructions from Latch into LastExit.
240   LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
241
242   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
243   BasicBlock *Header = Jmp->getSuccessor(0);
244   assert(Header == L->getHeader() && "expected a backward branch");
245
246   // Remove Latch from the CFG so that LastExit becomes the new Latch.
247   BI->setSuccessor(FallThruPath, Header);
248   Latch->replaceSuccessorsPhiUsesWith(LastExit);
249   Jmp->eraseFromParent();
250
251   // Nuke the Latch block.
252   assert(Latch->empty() && "unable to evacuate Latch");
253   LI->removeBlock(Latch);
254   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
255     DT->eraseNode(Latch);
256   Latch->eraseFromParent();
257   return true;
258 }
259
260 /// Rotate loop LP. Return true if the loop is rotated.
261 ///
262 /// \param SimplifiedLatch is true if the latch was just folded into the final
263 /// loop exit. In this case we may want to rotate even though the new latch is
264 /// now an exiting branch. This rotation would have happened had the latch not
265 /// been simplified. However, if SimplifiedLatch is false, then we avoid
266 /// rotating loops in which the latch exits to avoid excessive or endless
267 /// rotation. LoopRotate should be repeatable and converge to a canonical
268 /// form. This property is satisfied because simplifying the loop latch can only
269 /// happen once across multiple invocations of the LoopRotate pass.
270 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
271   // If the loop has only one block then there is not much to rotate.
272   if (L->getBlocks().size() == 1)
273     return false;
274
275   BasicBlock *OrigHeader = L->getHeader();
276   BasicBlock *OrigLatch = L->getLoopLatch();
277
278   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
279   if (BI == 0 || BI->isUnconditional())
280     return false;
281
282   // If the loop header is not one of the loop exiting blocks then
283   // either this loop is already rotated or it is not
284   // suitable for loop rotation transformations.
285   if (!L->isLoopExiting(OrigHeader))
286     return false;
287
288   // If the loop latch already contains a branch that leaves the loop then the
289   // loop is already rotated.
290   if (OrigLatch == 0)
291     return false;
292
293   // Rotate if either the loop latch does *not* exit the loop, or if the loop
294   // latch was just simplified.
295   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
296     return false;
297
298   // Check size of original header and reject loop if it is very big or we can't
299   // duplicate blocks inside it.
300   {
301     CodeMetrics Metrics;
302     Metrics.analyzeBasicBlock(OrigHeader, *TTI);
303     if (Metrics.notDuplicatable) {
304       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non duplicatable"
305             << " instructions: "; L->dump());
306       return false;
307     }
308     if (Metrics.NumInsts > MAX_HEADER_SIZE)
309       return false;
310   }
311
312   // Now, this loop is suitable for rotation.
313   BasicBlock *OrigPreheader = L->getLoopPreheader();
314
315   // If the loop could not be converted to canonical form, it must have an
316   // indirectbr in it, just give up.
317   if (OrigPreheader == 0)
318     return false;
319
320   // Anything ScalarEvolution may know about this loop or the PHI nodes
321   // in its header will soon be invalidated.
322   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
323     SE->forgetLoop(L);
324
325   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
326
327   // Find new Loop header. NewHeader is a Header's one and only successor
328   // that is inside loop.  Header's other successor is outside the
329   // loop.  Otherwise loop is not suitable for rotation.
330   BasicBlock *Exit = BI->getSuccessor(0);
331   BasicBlock *NewHeader = BI->getSuccessor(1);
332   if (L->contains(Exit))
333     std::swap(Exit, NewHeader);
334   assert(NewHeader && "Unable to determine new loop header");
335   assert(L->contains(NewHeader) && !L->contains(Exit) &&
336          "Unable to determine loop header and exit blocks");
337
338   // This code assumes that the new header has exactly one predecessor.
339   // Remove any single-entry PHI nodes in it.
340   assert(NewHeader->getSinglePredecessor() &&
341          "New header doesn't have one pred!");
342   FoldSingleEntryPHINodes(NewHeader);
343
344   // Begin by walking OrigHeader and populating ValueMap with an entry for
345   // each Instruction.
346   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
347   ValueToValueMapTy ValueMap;
348
349   // For PHI nodes, the value available in OldPreHeader is just the
350   // incoming value from OldPreHeader.
351   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
352     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
353
354   // For the rest of the instructions, either hoist to the OrigPreheader if
355   // possible or create a clone in the OldPreHeader if not.
356   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
357   while (I != E) {
358     Instruction *Inst = I++;
359
360     // If the instruction's operands are invariant and it doesn't read or write
361     // memory, then it is safe to hoist.  Doing this doesn't change the order of
362     // execution in the preheader, but does prevent the instruction from
363     // executing in each iteration of the loop.  This means it is safe to hoist
364     // something that might trap, but isn't safe to hoist something that reads
365     // memory (without proving that the loop doesn't write).
366     if (L->hasLoopInvariantOperands(Inst) &&
367         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
368         !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
369         !isa<AllocaInst>(Inst)) {
370       Inst->moveBefore(LoopEntryBranch);
371       continue;
372     }
373
374     // Otherwise, create a duplicate of the instruction.
375     Instruction *C = Inst->clone();
376
377     // Eagerly remap the operands of the instruction.
378     RemapInstruction(C, ValueMap,
379                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
380
381     // With the operands remapped, see if the instruction constant folds or is
382     // otherwise simplifyable.  This commonly occurs because the entry from PHI
383     // nodes allows icmps and other instructions to fold.
384     Value *V = SimplifyInstruction(C);
385     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
386       // If so, then delete the temporary instruction and stick the folded value
387       // in the map.
388       delete C;
389       ValueMap[Inst] = V;
390     } else {
391       // Otherwise, stick the new instruction into the new block!
392       C->setName(Inst->getName());
393       C->insertBefore(LoopEntryBranch);
394       ValueMap[Inst] = C;
395     }
396   }
397
398   // Along with all the other instructions, we just cloned OrigHeader's
399   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
400   // successors by duplicating their incoming values for OrigHeader.
401   TerminatorInst *TI = OrigHeader->getTerminator();
402   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
403     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
404          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
405       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
406
407   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
408   // OrigPreHeader's old terminator (the original branch into the loop), and
409   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
410   LoopEntryBranch->eraseFromParent();
411
412   // If there were any uses of instructions in the duplicated block outside the
413   // loop, update them, inserting PHI nodes as required
414   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
415
416   // NewHeader is now the header of the loop.
417   L->moveToHeader(NewHeader);
418   assert(L->getHeader() == NewHeader && "Latch block is our new header");
419
420
421   // At this point, we've finished our major CFG changes.  As part of cloning
422   // the loop into the preheader we've simplified instructions and the
423   // duplicated conditional branch may now be branching on a constant.  If it is
424   // branching on a constant and if that constant means that we enter the loop,
425   // then we fold away the cond branch to an uncond branch.  This simplifies the
426   // loop in cases important for nested loops, and it also means we don't have
427   // to split as many edges.
428   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
429   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
430   if (!isa<ConstantInt>(PHBI->getCondition()) ||
431       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
432           != NewHeader) {
433     // The conditional branch can't be folded, handle the general case.
434     // Update DominatorTree to reflect the CFG change we just made.  Then split
435     // edges as necessary to preserve LoopSimplify form.
436     if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
437       // Everything that was dominated by the old loop header is now dominated
438       // by the original loop preheader. Conceptually the header was merged
439       // into the preheader, even though we reuse the actual block as a new
440       // loop latch.
441       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
442       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
443                                                    OrigHeaderNode->end());
444       DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
445       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
446         DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
447
448       assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
449       assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
450
451       // Update OrigHeader to be dominated by the new header block.
452       DT->changeImmediateDominator(OrigHeader, OrigLatch);
453     }
454
455     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
456     // thus is not a preheader anymore.
457     // Split the edge to form a real preheader.
458     BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
459     NewPH->setName(NewHeader->getName() + ".lr.ph");
460
461     // Preserve canonical loop form, which means that 'Exit' should have only
462     // one predecessor.
463     BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
464     ExitSplit->moveBefore(Exit);
465   } else {
466     // We can fold the conditional branch in the preheader, this makes things
467     // simpler. The first step is to remove the extra edge to the Exit block.
468     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
469     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
470     NewBI->setDebugLoc(PHBI->getDebugLoc());
471     PHBI->eraseFromParent();
472
473     // With our CFG finalized, update DomTree if it is available.
474     if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
475       // Update OrigHeader to be dominated by the new header block.
476       DT->changeImmediateDominator(NewHeader, OrigPreheader);
477       DT->changeImmediateDominator(OrigHeader, OrigLatch);
478
479       // Brute force incremental dominator tree update. Call
480       // findNearestCommonDominator on all CFG predecessors of each child of the
481       // original header.
482       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
483       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
484                                                    OrigHeaderNode->end());
485       bool Changed;
486       do {
487         Changed = false;
488         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
489           DomTreeNode *Node = HeaderChildren[I];
490           BasicBlock *BB = Node->getBlock();
491
492           pred_iterator PI = pred_begin(BB);
493           BasicBlock *NearestDom = *PI;
494           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
495             NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
496
497           // Remember if this changes the DomTree.
498           if (Node->getIDom()->getBlock() != NearestDom) {
499             DT->changeImmediateDominator(BB, NearestDom);
500             Changed = true;
501           }
502         }
503
504       // If the dominator changed, this may have an effect on other
505       // predecessors, continue until we reach a fixpoint.
506       } while (Changed);
507     }
508   }
509
510   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
511   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
512
513   // Now that the CFG and DomTree are in a consistent state again, try to merge
514   // the OrigHeader block into OrigLatch.  This will succeed if they are
515   // connected by an unconditional branch.  This is just a cleanup so the
516   // emitted code isn't too gross in this common case.
517   MergeBlockIntoPredecessor(OrigHeader, this);
518
519   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
520
521   ++NumRotated;
522   return true;
523 }