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