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