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