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