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