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 #include "llvm/Transforms/Scalar/LoopRotation.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/GlobalsModRef.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/LoopPassManager.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #include "llvm/Transforms/Utils/SSAUpdater.h"
41 #include "llvm/Transforms/Utils/ValueMapper.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "loop-rotate"
45 
46 static cl::opt<unsigned>
47 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
48        cl::desc("The default maximum header size for automatic loop rotation"));
49 
50 STATISTIC(NumRotated, "Number of loops rotated");
51 
52 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
53 /// old header into the preheader.  If there were uses of the values produced by
54 /// these instruction that were outside of the loop, we have to insert PHI nodes
55 /// to merge the two values.  Do this now.
56 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
57                                             BasicBlock *OrigPreheader,
58                                             ValueToValueMapTy &ValueMap) {
59   // Remove PHI node entries that are no longer live.
60   BasicBlock::iterator I, E = OrigHeader->end();
61   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
62     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
63 
64   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
65   // as necessary.
66   SSAUpdater SSA;
67   for (I = OrigHeader->begin(); I != E; ++I) {
68     Value *OrigHeaderVal = &*I;
69 
70     // If there are no uses of the value (e.g. because it returns void), there
71     // is nothing to rewrite.
72     if (OrigHeaderVal->use_empty())
73       continue;
74 
75     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
76 
77     // The value now exits in two versions: the initial value in the preheader
78     // and the loop "next" value in the original header.
79     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
80     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
81     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
82 
83     // Visit each use of the OrigHeader instruction.
84     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
85          UE = OrigHeaderVal->use_end(); UI != UE; ) {
86       // Grab the use before incrementing the iterator.
87       Use &U = *UI;
88 
89       // Increment the iterator before removing the use from the list.
90       ++UI;
91 
92       // SSAUpdater can't handle a non-PHI use in the same block as an
93       // earlier def. We can easily handle those cases manually.
94       Instruction *UserInst = cast<Instruction>(U.getUser());
95       if (!isa<PHINode>(UserInst)) {
96         BasicBlock *UserBB = UserInst->getParent();
97 
98         // The original users in the OrigHeader are already using the
99         // original definitions.
100         if (UserBB == OrigHeader)
101           continue;
102 
103         // Users in the OrigPreHeader need to use the value to which the
104         // original definitions are mapped.
105         if (UserBB == OrigPreheader) {
106           U = OrigPreHeaderVal;
107           continue;
108         }
109       }
110 
111       // Anything else can be handled by SSAUpdater.
112       SSA.RewriteUse(U);
113     }
114 
115     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
116     // intrinsics.
117     LLVMContext &C = OrigHeader->getContext();
118     if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
119       if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
120         for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E; ) {
121           // Grab the use before incrementing the iterator. Otherwise, altering
122           // the Use will invalidate the iterator.
123           Use &U = *UI++;
124           DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
125           if (!UserInst) continue;
126 
127           // The original users in the OrigHeader are already using the original
128           // definitions.
129           BasicBlock *UserBB = UserInst->getParent();
130           if (UserBB == OrigHeader)
131             continue;
132 
133           // Users in the OrigPreHeader need to use the value to which the
134           // original definitions are mapped and anything else can be handled by
135           // the SSAUpdater. To avoid adding PHINodes, check if the value is
136           // available in UserBB, if not substitute undef.
137           Value *NewVal;
138           if (UserBB == OrigPreheader)
139             NewVal = OrigPreHeaderVal;
140           else if (SSA.HasValueForBlock(UserBB))
141             NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
142           else
143             NewVal = UndefValue::get(OrigHeaderVal->getType());
144           U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
145         }
146       }
147     }
148   }
149 }
150 
151 /// Rotate loop LP. Return true if the loop is rotated.
152 ///
153 /// \param SimplifiedLatch is true if the latch was just folded into the final
154 /// loop exit. In this case we may want to rotate even though the new latch is
155 /// now an exiting branch. This rotation would have happened had the latch not
156 /// been simplified. However, if SimplifiedLatch is false, then we avoid
157 /// rotating loops in which the latch exits to avoid excessive or endless
158 /// rotation. LoopRotate should be repeatable and converge to a canonical
159 /// form. This property is satisfied because simplifying the loop latch can only
160 /// happen once across multiple invocations of the LoopRotate pass.
161 static bool rotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
162                        const TargetTransformInfo *TTI, AssumptionCache *AC,
163                        DominatorTree *DT, ScalarEvolution *SE,
164                        bool SimplifiedLatch) {
165   // If the loop has only one block then there is not much to rotate.
166   if (L->getBlocks().size() == 1)
167     return false;
168 
169   BasicBlock *OrigHeader = L->getHeader();
170   BasicBlock *OrigLatch = L->getLoopLatch();
171 
172   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
173   if (!BI || BI->isUnconditional())
174     return false;
175 
176   // If the loop header is not one of the loop exiting blocks then
177   // either this loop is already rotated or it is not
178   // suitable for loop rotation transformations.
179   if (!L->isLoopExiting(OrigHeader))
180     return false;
181 
182   // If the loop latch already contains a branch that leaves the loop then the
183   // loop is already rotated.
184   if (!OrigLatch)
185     return false;
186 
187   // Rotate if either the loop latch does *not* exit the loop, or if the loop
188   // latch was just simplified.
189   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
190     return false;
191 
192   // Check size of original header and reject loop if it is very big or we can't
193   // duplicate blocks inside it.
194   {
195     SmallPtrSet<const Value *, 32> EphValues;
196     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
197 
198     CodeMetrics Metrics;
199     Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
200     if (Metrics.notDuplicatable) {
201       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
202             << " instructions: "; L->dump());
203       return false;
204     }
205     if (Metrics.convergent) {
206       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
207                       "instructions: "; L->dump());
208       return false;
209     }
210     if (Metrics.NumInsts > MaxHeaderSize)
211       return false;
212   }
213 
214   // Now, this loop is suitable for rotation.
215   BasicBlock *OrigPreheader = L->getLoopPreheader();
216 
217   // If the loop could not be converted to canonical form, it must have an
218   // indirectbr in it, just give up.
219   if (!OrigPreheader)
220     return false;
221 
222   // Anything ScalarEvolution may know about this loop or the PHI nodes
223   // in its header will soon be invalidated.
224   if (SE)
225     SE->forgetLoop(L);
226 
227   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
228 
229   // Find new Loop header. NewHeader is a Header's one and only successor
230   // that is inside loop.  Header's other successor is outside the
231   // loop.  Otherwise loop is not suitable for rotation.
232   BasicBlock *Exit = BI->getSuccessor(0);
233   BasicBlock *NewHeader = BI->getSuccessor(1);
234   if (L->contains(Exit))
235     std::swap(Exit, NewHeader);
236   assert(NewHeader && "Unable to determine new loop header");
237   assert(L->contains(NewHeader) && !L->contains(Exit) &&
238          "Unable to determine loop header and exit blocks");
239 
240   // This code assumes that the new header has exactly one predecessor.
241   // Remove any single-entry PHI nodes in it.
242   assert(NewHeader->getSinglePredecessor() &&
243          "New header doesn't have one pred!");
244   FoldSingleEntryPHINodes(NewHeader);
245 
246   // Begin by walking OrigHeader and populating ValueMap with an entry for
247   // each Instruction.
248   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
249   ValueToValueMapTy ValueMap;
250 
251   // For PHI nodes, the value available in OldPreHeader is just the
252   // incoming value from OldPreHeader.
253   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
254     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
255 
256   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
257 
258   // For the rest of the instructions, either hoist to the OrigPreheader if
259   // possible or create a clone in the OldPreHeader if not.
260   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
261   while (I != E) {
262     Instruction *Inst = &*I++;
263 
264     // If the instruction's operands are invariant and it doesn't read or write
265     // memory, then it is safe to hoist.  Doing this doesn't change the order of
266     // execution in the preheader, but does prevent the instruction from
267     // executing in each iteration of the loop.  This means it is safe to hoist
268     // something that might trap, but isn't safe to hoist something that reads
269     // memory (without proving that the loop doesn't write).
270     if (L->hasLoopInvariantOperands(Inst) &&
271         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
272         !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
273         !isa<AllocaInst>(Inst)) {
274       Inst->moveBefore(LoopEntryBranch);
275       continue;
276     }
277 
278     // Otherwise, create a duplicate of the instruction.
279     Instruction *C = Inst->clone();
280 
281     // Eagerly remap the operands of the instruction.
282     RemapInstruction(C, ValueMap,
283                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
284 
285     // With the operands remapped, see if the instruction constant folds or is
286     // otherwise simplifyable.  This commonly occurs because the entry from PHI
287     // nodes allows icmps and other instructions to fold.
288     // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
289     Value *V = SimplifyInstruction(C, DL);
290     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
291       // If so, then delete the temporary instruction and stick the folded value
292       // in the map.
293       delete C;
294       ValueMap[Inst] = V;
295     } else {
296       // Otherwise, stick the new instruction into the new block!
297       C->setName(Inst->getName());
298       C->insertBefore(LoopEntryBranch);
299       ValueMap[Inst] = C;
300     }
301   }
302 
303   // Along with all the other instructions, we just cloned OrigHeader's
304   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
305   // successors by duplicating their incoming values for OrigHeader.
306   TerminatorInst *TI = OrigHeader->getTerminator();
307   for (BasicBlock *SuccBB : TI->successors())
308     for (BasicBlock::iterator BI = SuccBB->begin();
309          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
310       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
311 
312   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
313   // OrigPreHeader's old terminator (the original branch into the loop), and
314   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
315   LoopEntryBranch->eraseFromParent();
316 
317   // If there were any uses of instructions in the duplicated block outside the
318   // loop, update them, inserting PHI nodes as required
319   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
320 
321   // NewHeader is now the header of the loop.
322   L->moveToHeader(NewHeader);
323   assert(L->getHeader() == NewHeader && "Latch block is our new header");
324 
325 
326   // At this point, we've finished our major CFG changes.  As part of cloning
327   // the loop into the preheader we've simplified instructions and the
328   // duplicated conditional branch may now be branching on a constant.  If it is
329   // branching on a constant and if that constant means that we enter the loop,
330   // then we fold away the cond branch to an uncond branch.  This simplifies the
331   // loop in cases important for nested loops, and it also means we don't have
332   // to split as many edges.
333   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
334   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
335   if (!isa<ConstantInt>(PHBI->getCondition()) ||
336       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
337           != NewHeader) {
338     // The conditional branch can't be folded, handle the general case.
339     // Update DominatorTree to reflect the CFG change we just made.  Then split
340     // edges as necessary to preserve LoopSimplify form.
341     if (DT) {
342       // Everything that was dominated by the old loop header is now dominated
343       // by the original loop preheader. Conceptually the header was merged
344       // into the preheader, even though we reuse the actual block as a new
345       // loop latch.
346       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
347       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
348                                                    OrigHeaderNode->end());
349       DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
350       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
351         DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
352 
353       assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
354       assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
355 
356       // Update OrigHeader to be dominated by the new header block.
357       DT->changeImmediateDominator(OrigHeader, OrigLatch);
358     }
359 
360     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
361     // thus is not a preheader anymore.
362     // Split the edge to form a real preheader.
363     BasicBlock *NewPH = SplitCriticalEdge(
364         OrigPreheader, NewHeader,
365         CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
366     NewPH->setName(NewHeader->getName() + ".lr.ph");
367 
368     // Preserve canonical loop form, which means that 'Exit' should have only
369     // one predecessor. Note that Exit could be an exit block for multiple
370     // nested loops, causing both of the edges to now be critical and need to
371     // be split.
372     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
373     bool SplitLatchEdge = false;
374     for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
375                                                  PE = ExitPreds.end();
376          PI != PE; ++PI) {
377       // We only need to split loop exit edges.
378       Loop *PredLoop = LI->getLoopFor(*PI);
379       if (!PredLoop || PredLoop->contains(Exit))
380         continue;
381       if (isa<IndirectBrInst>((*PI)->getTerminator()))
382         continue;
383       SplitLatchEdge |= L->getLoopLatch() == *PI;
384       BasicBlock *ExitSplit = SplitCriticalEdge(
385           *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
386       ExitSplit->moveBefore(Exit);
387     }
388     assert(SplitLatchEdge &&
389            "Despite splitting all preds, failed to split latch exit?");
390   } else {
391     // We can fold the conditional branch in the preheader, this makes things
392     // simpler. The first step is to remove the extra edge to the Exit block.
393     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
394     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
395     NewBI->setDebugLoc(PHBI->getDebugLoc());
396     PHBI->eraseFromParent();
397 
398     // With our CFG finalized, update DomTree if it is available.
399     if (DT) {
400       // Update OrigHeader to be dominated by the new header block.
401       DT->changeImmediateDominator(NewHeader, OrigPreheader);
402       DT->changeImmediateDominator(OrigHeader, OrigLatch);
403 
404       // Brute force incremental dominator tree update. Call
405       // findNearestCommonDominator on all CFG predecessors of each child of the
406       // original header.
407       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
408       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
409                                                    OrigHeaderNode->end());
410       bool Changed;
411       do {
412         Changed = false;
413         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
414           DomTreeNode *Node = HeaderChildren[I];
415           BasicBlock *BB = Node->getBlock();
416 
417           pred_iterator PI = pred_begin(BB);
418           BasicBlock *NearestDom = *PI;
419           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
420             NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
421 
422           // Remember if this changes the DomTree.
423           if (Node->getIDom()->getBlock() != NearestDom) {
424             DT->changeImmediateDominator(BB, NearestDom);
425             Changed = true;
426           }
427         }
428 
429       // If the dominator changed, this may have an effect on other
430       // predecessors, continue until we reach a fixpoint.
431       } while (Changed);
432     }
433   }
434 
435   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
436   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
437 
438   // Now that the CFG and DomTree are in a consistent state again, try to merge
439   // the OrigHeader block into OrigLatch.  This will succeed if they are
440   // connected by an unconditional branch.  This is just a cleanup so the
441   // emitted code isn't too gross in this common case.
442   MergeBlockIntoPredecessor(OrigHeader, DT, LI);
443 
444   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
445 
446   ++NumRotated;
447   return true;
448 }
449 
450 /// Determine whether the instructions in this range may be safely and cheaply
451 /// speculated. This is not an important enough situation to develop complex
452 /// heuristics. We handle a single arithmetic instruction along with any type
453 /// conversions.
454 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
455                                   BasicBlock::iterator End, Loop *L) {
456   bool seenIncrement = false;
457   bool MultiExitLoop = false;
458 
459   if (!L->getExitingBlock())
460     MultiExitLoop = true;
461 
462   for (BasicBlock::iterator I = Begin; I != End; ++I) {
463 
464     if (!isSafeToSpeculativelyExecute(&*I))
465       return false;
466 
467     if (isa<DbgInfoIntrinsic>(I))
468       continue;
469 
470     switch (I->getOpcode()) {
471     default:
472       return false;
473     case Instruction::GetElementPtr:
474       // GEPs are cheap if all indices are constant.
475       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
476         return false;
477       // fall-thru to increment case
478     case Instruction::Add:
479     case Instruction::Sub:
480     case Instruction::And:
481     case Instruction::Or:
482     case Instruction::Xor:
483     case Instruction::Shl:
484     case Instruction::LShr:
485     case Instruction::AShr: {
486       Value *IVOpnd = !isa<Constant>(I->getOperand(0))
487                           ? I->getOperand(0)
488                           : !isa<Constant>(I->getOperand(1))
489                                 ? I->getOperand(1)
490                                 : nullptr;
491       if (!IVOpnd)
492         return false;
493 
494       // If increment operand is used outside of the loop, this speculation
495       // could cause extra live range interference.
496       if (MultiExitLoop) {
497         for (User *UseI : IVOpnd->users()) {
498           auto *UserInst = cast<Instruction>(UseI);
499           if (!L->contains(UserInst))
500             return false;
501         }
502       }
503 
504       if (seenIncrement)
505         return false;
506       seenIncrement = true;
507       break;
508     }
509     case Instruction::Trunc:
510     case Instruction::ZExt:
511     case Instruction::SExt:
512       // ignore type conversions
513       break;
514     }
515   }
516   return true;
517 }
518 
519 /// Fold the loop tail into the loop exit by speculating the loop tail
520 /// instructions. Typically, this is a single post-increment. In the case of a
521 /// simple 2-block loop, hoisting the increment can be much better than
522 /// duplicating the entire loop header. In the case of loops with early exits,
523 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
524 /// canonical form so downstream passes can handle it.
525 ///
526 /// I don't believe this invalidates SCEV.
527 static bool simplifyLoopLatch(Loop *L, LoopInfo *LI, DominatorTree *DT) {
528   BasicBlock *Latch = L->getLoopLatch();
529   if (!Latch || Latch->hasAddressTaken())
530     return false;
531 
532   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
533   if (!Jmp || !Jmp->isUnconditional())
534     return false;
535 
536   BasicBlock *LastExit = Latch->getSinglePredecessor();
537   if (!LastExit || !L->isLoopExiting(LastExit))
538     return false;
539 
540   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
541   if (!BI)
542     return false;
543 
544   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
545     return false;
546 
547   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
548         << LastExit->getName() << "\n");
549 
550   // Hoist the instructions from Latch into LastExit.
551   LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
552                                  Latch->begin(), Jmp->getIterator());
553 
554   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
555   BasicBlock *Header = Jmp->getSuccessor(0);
556   assert(Header == L->getHeader() && "expected a backward branch");
557 
558   // Remove Latch from the CFG so that LastExit becomes the new Latch.
559   BI->setSuccessor(FallThruPath, Header);
560   Latch->replaceSuccessorsPhiUsesWith(LastExit);
561   Jmp->eraseFromParent();
562 
563   // Nuke the Latch block.
564   assert(Latch->empty() && "unable to evacuate Latch");
565   LI->removeBlock(Latch);
566   if (DT)
567     DT->eraseNode(Latch);
568   Latch->eraseFromParent();
569   return true;
570 }
571 
572 /// Rotate \c L as many times as possible. Return true if the loop is rotated
573 /// at least once.
574 static bool iterativelyRotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
575                                   const TargetTransformInfo *TTI,
576                                   AssumptionCache *AC, DominatorTree *DT,
577                                   ScalarEvolution *SE) {
578   // Save the loop metadata.
579   MDNode *LoopMD = L->getLoopID();
580 
581   // Simplify the loop latch before attempting to rotate the header
582   // upward. Rotation may not be needed if the loop tail can be folded into the
583   // loop exit.
584   bool SimplifiedLatch = simplifyLoopLatch(L, LI, DT);
585 
586   // One loop can be rotated multiple times.
587   bool MadeChange = false;
588   while (rotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE, SimplifiedLatch)) {
589     MadeChange = true;
590     SimplifiedLatch = false;
591   }
592 
593   // Restore the loop metadata.
594   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
595   if ((MadeChange || SimplifiedLatch) && LoopMD)
596     L->setLoopID(LoopMD);
597 
598   return MadeChange;
599 }
600 
601 LoopRotatePass::LoopRotatePass() : MaxHeaderSize(DefaultRotationThreshold) {}
602 
603 PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) {
604   auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
605   Function *F = L.getHeader()->getParent();
606 
607   auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
608   const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
609   auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F);
610   assert((LI && TTI && AC) && "Analyses for loop rotation not available");
611 
612   // Optional analyses.
613   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
614   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
615 
616   bool Changed = iterativelyRotateLoop(&L, MaxHeaderSize, LI, TTI, AC, DT, SE);
617   if (!Changed)
618     return PreservedAnalyses::all();
619   return getLoopPassPreservedAnalyses();
620 }
621 
622 namespace {
623 
624 class LoopRotateLegacyPass : public LoopPass {
625   unsigned MaxHeaderSize;
626 
627 public:
628   static char ID; // Pass ID, replacement for typeid
629   LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
630     initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
631     if (SpecifiedMaxHeaderSize == -1)
632       MaxHeaderSize = DefaultRotationThreshold;
633     else
634       MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
635   }
636 
637   // LCSSA form makes instruction renaming easier.
638   void getAnalysisUsage(AnalysisUsage &AU) const override {
639     AU.addRequired<AssumptionCacheTracker>();
640     AU.addRequired<TargetTransformInfoWrapperPass>();
641     getLoopAnalysisUsage(AU);
642   }
643 
644   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
645     if (skipLoop(L))
646       return false;
647     Function &F = *L->getHeader()->getParent();
648 
649     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
650     const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
651     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
652     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
653     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
654     auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
655     auto *SE = SEWP ? &SEWP->getSE() : nullptr;
656 
657     return iterativelyRotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE);
658   }
659 };
660 }
661 
662 char LoopRotateLegacyPass::ID = 0;
663 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
664                       false, false)
665 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
666 INITIALIZE_PASS_DEPENDENCY(LoopPass)
667 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
668 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
669                     false, false)
670 
671 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
672   return new LoopRotateLegacyPass(MaxHeaderSize);
673 }
674