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