1b0aa36f9SDavid Green //===----------------- LoopRotationUtils.cpp -----------------------------===//
2b0aa36f9SDavid Green //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b0aa36f9SDavid Green //
7b0aa36f9SDavid Green //===----------------------------------------------------------------------===//
8b0aa36f9SDavid Green //
9b0aa36f9SDavid Green // This file provides utilities to convert a loop into a loop with bottom test.
10b0aa36f9SDavid Green //
11b0aa36f9SDavid Green //===----------------------------------------------------------------------===//
12b0aa36f9SDavid Green 
13b0aa36f9SDavid Green #include "llvm/Transforms/Utils/LoopRotationUtils.h"
14b0aa36f9SDavid Green #include "llvm/ADT/Statistic.h"
15b0aa36f9SDavid Green #include "llvm/Analysis/AssumptionCache.h"
16b0aa36f9SDavid Green #include "llvm/Analysis/CodeMetrics.h"
175f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.h"
18b0aa36f9SDavid Green #include "llvm/Analysis/InstructionSimplify.h"
19a494ae43Sserge-sans-paille #include "llvm/Analysis/LoopInfo.h"
20ad4d0182SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
21ad4d0182SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
22b0aa36f9SDavid Green #include "llvm/Analysis/ScalarEvolution.h"
23b0aa36f9SDavid Green #include "llvm/Analysis/ValueTracking.h"
24b0aa36f9SDavid Green #include "llvm/IR/CFG.h"
250ebf9a8eSOCHyams #include "llvm/IR/DebugInfo.h"
26b0aa36f9SDavid Green #include "llvm/IR/Dominators.h"
27b0aa36f9SDavid Green #include "llvm/IR/IntrinsicInst.h"
28b0aa36f9SDavid Green #include "llvm/Support/CommandLine.h"
29b0aa36f9SDavid Green #include "llvm/Support/Debug.h"
30b0aa36f9SDavid Green #include "llvm/Support/raw_ostream.h"
31b0aa36f9SDavid Green #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32659c7bcdSJeroen Dobbelaere #include "llvm/Transforms/Utils/Cloning.h"
3321a8b605SChijun Sima #include "llvm/Transforms/Utils/Local.h"
34b0aa36f9SDavid Green #include "llvm/Transforms/Utils/SSAUpdater.h"
35b0aa36f9SDavid Green #include "llvm/Transforms/Utils/ValueMapper.h"
36b0aa36f9SDavid Green using namespace llvm;
37b0aa36f9SDavid Green 
38b0aa36f9SDavid Green #define DEBUG_TYPE "loop-rotate"
39b0aa36f9SDavid Green 
40ce4459a0SRoman Lebedev STATISTIC(NumNotRotatedDueToHeaderSize,
41ce4459a0SRoman Lebedev           "Number of loops not rotated due to the header size");
4243ded900SRoman Lebedev STATISTIC(NumInstrsHoisted,
4343ded900SRoman Lebedev           "Number of instructions hoisted into loop preheader");
4443ded900SRoman Lebedev STATISTIC(NumInstrsDuplicated,
4543ded900SRoman Lebedev           "Number of instructions cloned into loop preheader");
46b0aa36f9SDavid Green STATISTIC(NumRotated, "Number of loops rotated");
47b0aa36f9SDavid Green 
482f6987baSFedor Sergeev static cl::opt<bool>
492f6987baSFedor Sergeev     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
502f6987baSFedor Sergeev                 cl::desc("Allow loop rotation multiple times in order to reach "
512f6987baSFedor Sergeev                          "a better latch exit"));
522f6987baSFedor Sergeev 
53b0aa36f9SDavid Green namespace {
54b0aa36f9SDavid Green /// A simple loop rotation transformation.
55b0aa36f9SDavid Green class LoopRotate {
56b0aa36f9SDavid Green   const unsigned MaxHeaderSize;
57b0aa36f9SDavid Green   LoopInfo *LI;
58b0aa36f9SDavid Green   const TargetTransformInfo *TTI;
59b0aa36f9SDavid Green   AssumptionCache *AC;
60b0aa36f9SDavid Green   DominatorTree *DT;
61b0aa36f9SDavid Green   ScalarEvolution *SE;
62ad4d0182SAlina Sbirlea   MemorySSAUpdater *MSSAU;
63b0aa36f9SDavid Green   const SimplifyQuery &SQ;
64585f2699SJin Lin   bool RotationOnly;
65585f2699SJin Lin   bool IsUtilMode;
6683daa497SFlorian Hahn   bool PrepareForLTO;
67b0aa36f9SDavid Green 
68b0aa36f9SDavid Green public:
LoopRotate(unsigned MaxHeaderSize,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly,bool IsUtilMode,bool PrepareForLTO)69b0aa36f9SDavid Green   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
70b0aa36f9SDavid Green              const TargetTransformInfo *TTI, AssumptionCache *AC,
71ad4d0182SAlina Sbirlea              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
7283daa497SFlorian Hahn              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
7383daa497SFlorian Hahn              bool PrepareForLTO)
74b0aa36f9SDavid Green       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
75ad4d0182SAlina Sbirlea         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
7683daa497SFlorian Hahn         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
77b0aa36f9SDavid Green   bool processLoop(Loop *L);
78b0aa36f9SDavid Green 
79b0aa36f9SDavid Green private:
80b0aa36f9SDavid Green   bool rotateLoop(Loop *L, bool SimplifiedLatch);
81b0aa36f9SDavid Green   bool simplifyLoopLatch(Loop *L);
82b0aa36f9SDavid Green };
83b0aa36f9SDavid Green } // end anonymous namespace
84b0aa36f9SDavid Green 
854b698645SAlina Sbirlea /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
864b698645SAlina Sbirlea /// previously exist in the map, and the value was inserted.
InsertNewValueIntoMap(ValueToValueMapTy & VM,Value * K,Value * V)874b698645SAlina Sbirlea static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
884b698645SAlina Sbirlea   bool Inserted = VM.insert({K, V}).second;
894b698645SAlina Sbirlea   assert(Inserted);
904b698645SAlina Sbirlea   (void)Inserted;
914b698645SAlina Sbirlea }
92b0aa36f9SDavid Green /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
93b0aa36f9SDavid Green /// old header into the preheader.  If there were uses of the values produced by
94b0aa36f9SDavid Green /// these instruction that were outside of the loop, we have to insert PHI nodes
95b0aa36f9SDavid Green /// to merge the two values.  Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap,ScalarEvolution * SE,SmallVectorImpl<PHINode * > * InsertedPHIs)96b0aa36f9SDavid Green static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
97b0aa36f9SDavid Green                                             BasicBlock *OrigPreheader,
98b0aa36f9SDavid Green                                             ValueToValueMapTy &ValueMap,
997f93bb4aSBjorn Pettersson                                             ScalarEvolution *SE,
100b0aa36f9SDavid Green                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
101b0aa36f9SDavid Green   // Remove PHI node entries that are no longer live.
102b0aa36f9SDavid Green   BasicBlock::iterator I, E = OrigHeader->end();
103b0aa36f9SDavid Green   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
104b0aa36f9SDavid Green     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
105b0aa36f9SDavid Green 
106b0aa36f9SDavid Green   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
107b0aa36f9SDavid Green   // as necessary.
108b0aa36f9SDavid Green   SSAUpdater SSA(InsertedPHIs);
109b0aa36f9SDavid Green   for (I = OrigHeader->begin(); I != E; ++I) {
110b0aa36f9SDavid Green     Value *OrigHeaderVal = &*I;
111b0aa36f9SDavid Green 
112b0aa36f9SDavid Green     // If there are no uses of the value (e.g. because it returns void), there
113b0aa36f9SDavid Green     // is nothing to rewrite.
114b0aa36f9SDavid Green     if (OrigHeaderVal->use_empty())
115b0aa36f9SDavid Green       continue;
116b0aa36f9SDavid Green 
117b0aa36f9SDavid Green     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
118b0aa36f9SDavid Green 
119b0aa36f9SDavid Green     // The value now exits in two versions: the initial value in the preheader
120b0aa36f9SDavid Green     // and the loop "next" value in the original header.
121b0aa36f9SDavid Green     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
1227f93bb4aSBjorn Pettersson     // Force re-computation of OrigHeaderVal, as some users now need to use the
1237f93bb4aSBjorn Pettersson     // new PHI node.
1247f93bb4aSBjorn Pettersson     if (SE)
1257f93bb4aSBjorn Pettersson       SE->forgetValue(OrigHeaderVal);
126b0aa36f9SDavid Green     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
127b0aa36f9SDavid Green     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
128b0aa36f9SDavid Green 
129b0aa36f9SDavid Green     // Visit each use of the OrigHeader instruction.
1300d182d9dSKazu Hirata     for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
131b0aa36f9SDavid Green       // SSAUpdater can't handle a non-PHI use in the same block as an
132b0aa36f9SDavid Green       // earlier def. We can easily handle those cases manually.
133b0aa36f9SDavid Green       Instruction *UserInst = cast<Instruction>(U.getUser());
134b0aa36f9SDavid Green       if (!isa<PHINode>(UserInst)) {
135b0aa36f9SDavid Green         BasicBlock *UserBB = UserInst->getParent();
136b0aa36f9SDavid Green 
137b0aa36f9SDavid Green         // The original users in the OrigHeader are already using the
138b0aa36f9SDavid Green         // original definitions.
139b0aa36f9SDavid Green         if (UserBB == OrigHeader)
140b0aa36f9SDavid Green           continue;
141b0aa36f9SDavid Green 
142b0aa36f9SDavid Green         // Users in the OrigPreHeader need to use the value to which the
143b0aa36f9SDavid Green         // original definitions are mapped.
144b0aa36f9SDavid Green         if (UserBB == OrigPreheader) {
145b0aa36f9SDavid Green           U = OrigPreHeaderVal;
146b0aa36f9SDavid Green           continue;
147b0aa36f9SDavid Green         }
148b0aa36f9SDavid Green       }
149b0aa36f9SDavid Green 
150b0aa36f9SDavid Green       // Anything else can be handled by SSAUpdater.
151b0aa36f9SDavid Green       SSA.RewriteUse(U);
152b0aa36f9SDavid Green     }
153b0aa36f9SDavid Green 
154b0aa36f9SDavid Green     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
155b0aa36f9SDavid Green     // intrinsics.
156b0aa36f9SDavid Green     SmallVector<DbgValueInst *, 1> DbgValues;
157b0aa36f9SDavid Green     llvm::findDbgValues(DbgValues, OrigHeaderVal);
158b0aa36f9SDavid Green     for (auto &DbgValue : DbgValues) {
159b0aa36f9SDavid Green       // The original users in the OrigHeader are already using the original
160b0aa36f9SDavid Green       // definitions.
161b0aa36f9SDavid Green       BasicBlock *UserBB = DbgValue->getParent();
162b0aa36f9SDavid Green       if (UserBB == OrigHeader)
163b0aa36f9SDavid Green         continue;
164b0aa36f9SDavid Green 
165b0aa36f9SDavid Green       // Users in the OrigPreHeader need to use the value to which the
166b0aa36f9SDavid Green       // original definitions are mapped and anything else can be handled by
167b0aa36f9SDavid Green       // the SSAUpdater. To avoid adding PHINodes, check if the value is
168b0aa36f9SDavid Green       // available in UserBB, if not substitute undef.
169b0aa36f9SDavid Green       Value *NewVal;
170b0aa36f9SDavid Green       if (UserBB == OrigPreheader)
171b0aa36f9SDavid Green         NewVal = OrigPreHeaderVal;
172b0aa36f9SDavid Green       else if (SSA.HasValueForBlock(UserBB))
173b0aa36f9SDavid Green         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
174b0aa36f9SDavid Green       else
175b0aa36f9SDavid Green         NewVal = UndefValue::get(OrigHeaderVal->getType());
176e5d958c4Sgbtozers       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
177b0aa36f9SDavid Green     }
178b0aa36f9SDavid Green   }
179b0aa36f9SDavid Green }
180b0aa36f9SDavid Green 
1812f6987baSFedor Sergeev // Assuming both header and latch are exiting, look for a phi which is only
1822f6987baSFedor Sergeev // used outside the loop (via a LCSSA phi) in the exit from the header.
1832f6987baSFedor Sergeev // This means that rotating the loop can remove the phi.
profitableToRotateLoopExitingLatch(Loop * L)1842f6987baSFedor Sergeev static bool profitableToRotateLoopExitingLatch(Loop *L) {
185f80ebc8dSDavid Green   BasicBlock *Header = L->getHeader();
1862f6987baSFedor Sergeev   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
1872f6987baSFedor Sergeev   assert(BI && BI->isConditional() && "need header with conditional exit");
1882f6987baSFedor Sergeev   BasicBlock *HeaderExit = BI->getSuccessor(0);
189f80ebc8dSDavid Green   if (L->contains(HeaderExit))
1902f6987baSFedor Sergeev     HeaderExit = BI->getSuccessor(1);
191f80ebc8dSDavid Green 
192f80ebc8dSDavid Green   for (auto &Phi : Header->phis()) {
193f80ebc8dSDavid Green     // Look for uses of this phi in the loop/via exits other than the header.
194f80ebc8dSDavid Green     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
195f80ebc8dSDavid Green           return cast<Instruction>(U)->getParent() != HeaderExit;
196f80ebc8dSDavid Green         }))
197f80ebc8dSDavid Green       continue;
198f80ebc8dSDavid Green     return true;
199f80ebc8dSDavid Green   }
2002f6987baSFedor Sergeev   return false;
2012f6987baSFedor Sergeev }
202f80ebc8dSDavid Green 
2032f6987baSFedor Sergeev // Check that latch exit is deoptimizing (which means - very unlikely to happen)
2042f6987baSFedor Sergeev // and there is another exit from the loop which is non-deoptimizing.
2052f6987baSFedor Sergeev // If we rotate latch to that exit our loop has a better chance of being fully
2062f6987baSFedor Sergeev // canonical.
2072f6987baSFedor Sergeev //
2082f6987baSFedor Sergeev // It can give false positives in some rare cases.
canRotateDeoptimizingLatchExit(Loop * L)2092f6987baSFedor Sergeev static bool canRotateDeoptimizingLatchExit(Loop *L) {
2102f6987baSFedor Sergeev   BasicBlock *Latch = L->getLoopLatch();
2112f6987baSFedor Sergeev   assert(Latch && "need latch");
2122f6987baSFedor Sergeev   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
2132f6987baSFedor Sergeev   // Need normal exiting latch.
2142f6987baSFedor Sergeev   if (!BI || !BI->isConditional())
2152f6987baSFedor Sergeev     return false;
2162f6987baSFedor Sergeev 
2172f6987baSFedor Sergeev   BasicBlock *Exit = BI->getSuccessor(1);
2182f6987baSFedor Sergeev   if (L->contains(Exit))
2192f6987baSFedor Sergeev     Exit = BI->getSuccessor(0);
2202f6987baSFedor Sergeev 
2212f6987baSFedor Sergeev   // Latch exit is non-deoptimizing, no need to rotate.
2222f6987baSFedor Sergeev   if (!Exit->getPostdominatingDeoptimizeCall())
2232f6987baSFedor Sergeev     return false;
2242f6987baSFedor Sergeev 
2252f6987baSFedor Sergeev   SmallVector<BasicBlock *, 4> Exits;
2262f6987baSFedor Sergeev   L->getUniqueExitBlocks(Exits);
2272f6987baSFedor Sergeev   if (!Exits.empty()) {
2282f6987baSFedor Sergeev     // There is at least one non-deoptimizing exit.
2292f6987baSFedor Sergeev     //
2302f6987baSFedor Sergeev     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
2312f6987baSFedor Sergeev     // as it can conservatively return false for deoptimizing exits with
2322f6987baSFedor Sergeev     // complex enough control flow down to deoptimize call.
2332f6987baSFedor Sergeev     //
2342f6987baSFedor Sergeev     // That means here we can report success for a case where
2352f6987baSFedor Sergeev     // all exits are deoptimizing but one of them has complex enough
2362f6987baSFedor Sergeev     // control flow (e.g. with loops).
2372f6987baSFedor Sergeev     //
2382f6987baSFedor Sergeev     // That should be a very rare case and false positives for this function
2392f6987baSFedor Sergeev     // have compile-time effect only.
2402f6987baSFedor Sergeev     return any_of(Exits, [](const BasicBlock *BB) {
2412f6987baSFedor Sergeev       return !BB->getPostdominatingDeoptimizeCall();
2422f6987baSFedor Sergeev     });
2432f6987baSFedor Sergeev   }
244f80ebc8dSDavid Green   return false;
245f80ebc8dSDavid Green }
246f80ebc8dSDavid Green 
247b0aa36f9SDavid Green /// Rotate loop LP. Return true if the loop is rotated.
248b0aa36f9SDavid Green ///
249b0aa36f9SDavid Green /// \param SimplifiedLatch is true if the latch was just folded into the final
250b0aa36f9SDavid Green /// loop exit. In this case we may want to rotate even though the new latch is
251b0aa36f9SDavid Green /// now an exiting branch. This rotation would have happened had the latch not
252b0aa36f9SDavid Green /// been simplified. However, if SimplifiedLatch is false, then we avoid
253b0aa36f9SDavid Green /// rotating loops in which the latch exits to avoid excessive or endless
254b0aa36f9SDavid Green /// rotation. LoopRotate should be repeatable and converge to a canonical
255b0aa36f9SDavid Green /// form. This property is satisfied because simplifying the loop latch can only
256b0aa36f9SDavid Green /// happen once across multiple invocations of the LoopRotate pass.
2572f6987baSFedor Sergeev ///
2582f6987baSFedor Sergeev /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
2592f6987baSFedor Sergeev /// so to reach a suitable (non-deoptimizing) exit.
rotateLoop(Loop * L,bool SimplifiedLatch)260b0aa36f9SDavid Green bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
261b0aa36f9SDavid Green   // If the loop has only one block then there is not much to rotate.
262b0aa36f9SDavid Green   if (L->getBlocks().size() == 1)
263b0aa36f9SDavid Green     return false;
264b0aa36f9SDavid Green 
2652f6987baSFedor Sergeev   bool Rotated = false;
2662f6987baSFedor Sergeev   do {
267b0aa36f9SDavid Green     BasicBlock *OrigHeader = L->getHeader();
268b0aa36f9SDavid Green     BasicBlock *OrigLatch = L->getLoopLatch();
269b0aa36f9SDavid Green 
270b0aa36f9SDavid Green     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
271b0aa36f9SDavid Green     if (!BI || BI->isUnconditional())
2722f6987baSFedor Sergeev       return Rotated;
273b0aa36f9SDavid Green 
274b0aa36f9SDavid Green     // If the loop header is not one of the loop exiting blocks then
275b0aa36f9SDavid Green     // either this loop is already rotated or it is not
276b0aa36f9SDavid Green     // suitable for loop rotation transformations.
277b0aa36f9SDavid Green     if (!L->isLoopExiting(OrigHeader))
2782f6987baSFedor Sergeev       return Rotated;
279b0aa36f9SDavid Green 
280b0aa36f9SDavid Green     // If the loop latch already contains a branch that leaves the loop then the
281b0aa36f9SDavid Green     // loop is already rotated.
282b0aa36f9SDavid Green     if (!OrigLatch)
2832f6987baSFedor Sergeev       return Rotated;
284b0aa36f9SDavid Green 
285b0aa36f9SDavid Green     // Rotate if either the loop latch does *not* exit the loop, or if the loop
286f80ebc8dSDavid Green     // latch was just simplified. Or if we think it will be profitable.
287585f2699SJin Lin     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
2882f6987baSFedor Sergeev         !profitableToRotateLoopExitingLatch(L) &&
2892f6987baSFedor Sergeev         !canRotateDeoptimizingLatchExit(L))
2902f6987baSFedor Sergeev       return Rotated;
291b0aa36f9SDavid Green 
292b0aa36f9SDavid Green     // Check size of original header and reject loop if it is very big or we can't
293b0aa36f9SDavid Green     // duplicate blocks inside it.
294b0aa36f9SDavid Green     {
295b0aa36f9SDavid Green       SmallPtrSet<const Value *, 32> EphValues;
296b0aa36f9SDavid Green       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
297b0aa36f9SDavid Green 
298b0aa36f9SDavid Green       CodeMetrics Metrics;
29983daa497SFlorian Hahn       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
300b0aa36f9SDavid Green       if (Metrics.notDuplicatable) {
301d34e60caSNicola Zaghen         LLVM_DEBUG(
302d34e60caSNicola Zaghen                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
303b0aa36f9SDavid Green                    << " instructions: ";
304b0aa36f9SDavid Green                    L->dump());
3052f6987baSFedor Sergeev         return Rotated;
306b0aa36f9SDavid Green       }
307b0aa36f9SDavid Green       if (Metrics.convergent) {
308d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
309b0aa36f9SDavid Green                    "instructions: ";
310b0aa36f9SDavid Green                    L->dump());
3112f6987baSFedor Sergeev         return Rotated;
312b0aa36f9SDavid Green       }
313f85c5079SPhilip Reames       if (!Metrics.NumInsts.isValid()) {
314f85c5079SPhilip Reames         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
315f85c5079SPhilip Reames                    " with invalid cost: ";
316f85c5079SPhilip Reames                    L->dump());
317f85c5079SPhilip Reames         return Rotated;
318f85c5079SPhilip Reames       }
319f85c5079SPhilip Reames       if (*Metrics.NumInsts.getValue() > MaxHeaderSize) {
320398b497cSRoman Lebedev         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
321398b497cSRoman Lebedev                           << Metrics.NumInsts
322398b497cSRoman Lebedev                           << " instructions, which is more than the threshold ("
323398b497cSRoman Lebedev                           << MaxHeaderSize << " instructions): ";
324398b497cSRoman Lebedev                    L->dump());
325ce4459a0SRoman Lebedev         ++NumNotRotatedDueToHeaderSize;
3262f6987baSFedor Sergeev         return Rotated;
327b0aa36f9SDavid Green       }
32883daa497SFlorian Hahn 
32983daa497SFlorian Hahn       // When preparing for LTO, avoid rotating loops with calls that could be
33083daa497SFlorian Hahn       // inlined during the LTO stage.
33183daa497SFlorian Hahn       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
33283daa497SFlorian Hahn         return Rotated;
333398b497cSRoman Lebedev     }
334b0aa36f9SDavid Green 
335b0aa36f9SDavid Green     // Now, this loop is suitable for rotation.
336b0aa36f9SDavid Green     BasicBlock *OrigPreheader = L->getLoopPreheader();
337b0aa36f9SDavid Green 
338b0aa36f9SDavid Green     // If the loop could not be converted to canonical form, it must have an
339b0aa36f9SDavid Green     // indirectbr in it, just give up.
340b0aa36f9SDavid Green     if (!OrigPreheader || !L->hasDedicatedExits())
3412f6987baSFedor Sergeev       return Rotated;
342b0aa36f9SDavid Green 
343b0aa36f9SDavid Green     // Anything ScalarEvolution may know about this loop or the PHI nodes
3445a0a40b8SMax Kazantsev     // in its header will soon be invalidated. We should also invalidate
3455a0a40b8SMax Kazantsev     // all outer loops because insertion and deletion of blocks that happens
3465a0a40b8SMax Kazantsev     // during the rotation may violate invariants related to backedge taken
3475a0a40b8SMax Kazantsev     // infos in them.
348b0aa36f9SDavid Green     if (SE)
34991f48166SMax Kazantsev       SE->forgetTopmostLoop(L);
350b0aa36f9SDavid Green 
351d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
352ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
353ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
354b0aa36f9SDavid Green 
355b0aa36f9SDavid Green     // Find new Loop header. NewHeader is a Header's one and only successor
356b0aa36f9SDavid Green     // that is inside loop.  Header's other successor is outside the
357b0aa36f9SDavid Green     // loop.  Otherwise loop is not suitable for rotation.
358b0aa36f9SDavid Green     BasicBlock *Exit = BI->getSuccessor(0);
359b0aa36f9SDavid Green     BasicBlock *NewHeader = BI->getSuccessor(1);
360b0aa36f9SDavid Green     if (L->contains(Exit))
361b0aa36f9SDavid Green       std::swap(Exit, NewHeader);
362b0aa36f9SDavid Green     assert(NewHeader && "Unable to determine new loop header");
363b0aa36f9SDavid Green     assert(L->contains(NewHeader) && !L->contains(Exit) &&
364b0aa36f9SDavid Green            "Unable to determine loop header and exit blocks");
365b0aa36f9SDavid Green 
366b0aa36f9SDavid Green     // This code assumes that the new header has exactly one predecessor.
367b0aa36f9SDavid Green     // Remove any single-entry PHI nodes in it.
368b0aa36f9SDavid Green     assert(NewHeader->getSinglePredecessor() &&
369b0aa36f9SDavid Green            "New header doesn't have one pred!");
370b0aa36f9SDavid Green     FoldSingleEntryPHINodes(NewHeader);
371b0aa36f9SDavid Green 
372b0aa36f9SDavid Green     // Begin by walking OrigHeader and populating ValueMap with an entry for
373b0aa36f9SDavid Green     // each Instruction.
374b0aa36f9SDavid Green     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
37558a37754SAlina Sbirlea     ValueToValueMapTy ValueMap, ValueMapMSSA;
376b0aa36f9SDavid Green 
377b0aa36f9SDavid Green     // For PHI nodes, the value available in OldPreHeader is just the
378b0aa36f9SDavid Green     // incoming value from OldPreHeader.
379b0aa36f9SDavid Green     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
3804b698645SAlina Sbirlea       InsertNewValueIntoMap(ValueMap, PN,
3814b698645SAlina Sbirlea                             PN->getIncomingValueForBlock(OrigPreheader));
382b0aa36f9SDavid Green 
383b0aa36f9SDavid Green     // For the rest of the instructions, either hoist to the OrigPreheader if
384b0aa36f9SDavid Green     // possible or create a clone in the OldPreHeader if not.
385edb12a83SChandler Carruth     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
386b0aa36f9SDavid Green 
3873bfddc25SStephen Tozer     // Record all debug intrinsics preceding LoopEntryBranch to avoid
3883bfddc25SStephen Tozer     // duplication.
389b0aa36f9SDavid Green     using DbgIntrinsicHash =
3903bfddc25SStephen Tozer         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
391ef72e481SHsiangkai Wang     auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
3923bfddc25SStephen Tozer       auto VarLocOps = D->location_ops();
3933bfddc25SStephen Tozer       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
3943bfddc25SStephen Tozer                D->getVariable()},
395e5d958c4Sgbtozers               D->getExpression()};
396b0aa36f9SDavid Green     };
397b0aa36f9SDavid Green     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
398843d1edaSKazu Hirata     for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
399843d1edaSKazu Hirata       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
400b0aa36f9SDavid Green         DbgIntrinsics.insert(makeHash(DII));
401b0aa36f9SDavid Green       else
402b0aa36f9SDavid Green         break;
403b0aa36f9SDavid Green     }
404b0aa36f9SDavid Green 
405659c7bcdSJeroen Dobbelaere     // Remember the local noalias scope declarations in the header. After the
406659c7bcdSJeroen Dobbelaere     // rotation, they must be duplicated and the scope must be cloned. This
407659c7bcdSJeroen Dobbelaere     // avoids unwanted interaction across iterations.
4088b9df70bSNikita Popov     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
409659c7bcdSJeroen Dobbelaere     for (Instruction &I : *OrigHeader)
410659c7bcdSJeroen Dobbelaere       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
411659c7bcdSJeroen Dobbelaere         NoAliasDeclInstructions.push_back(Decl);
412659c7bcdSJeroen Dobbelaere 
413b0aa36f9SDavid Green     while (I != E) {
414b0aa36f9SDavid Green       Instruction *Inst = &*I++;
415b0aa36f9SDavid Green 
416b0aa36f9SDavid Green       // If the instruction's operands are invariant and it doesn't read or write
417b0aa36f9SDavid Green       // memory, then it is safe to hoist.  Doing this doesn't change the order of
418b0aa36f9SDavid Green       // execution in the preheader, but does prevent the instruction from
419b0aa36f9SDavid Green       // executing in each iteration of the loop.  This means it is safe to hoist
420b0aa36f9SDavid Green       // something that might trap, but isn't safe to hoist something that reads
421b0aa36f9SDavid Green       // memory (without proving that the loop doesn't write).
422b0aa36f9SDavid Green       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
4239ae926b9SChandler Carruth           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
424b0aa36f9SDavid Green           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
425b0aa36f9SDavid Green         Inst->moveBefore(LoopEntryBranch);
42643ded900SRoman Lebedev         ++NumInstrsHoisted;
427b0aa36f9SDavid Green         continue;
428b0aa36f9SDavid Green       }
429b0aa36f9SDavid Green 
430b0aa36f9SDavid Green       // Otherwise, create a duplicate of the instruction.
431b0aa36f9SDavid Green       Instruction *C = Inst->clone();
43243ded900SRoman Lebedev       ++NumInstrsDuplicated;
433b0aa36f9SDavid Green 
434b0aa36f9SDavid Green       // Eagerly remap the operands of the instruction.
435b0aa36f9SDavid Green       RemapInstruction(C, ValueMap,
436b0aa36f9SDavid Green                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
437b0aa36f9SDavid Green 
438b0aa36f9SDavid Green       // Avoid inserting the same intrinsic twice.
439ef72e481SHsiangkai Wang       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
440b0aa36f9SDavid Green         if (DbgIntrinsics.count(makeHash(DII))) {
441b0aa36f9SDavid Green           C->deleteValue();
442b0aa36f9SDavid Green           continue;
443b0aa36f9SDavid Green         }
444b0aa36f9SDavid Green 
445b0aa36f9SDavid Green       // With the operands remapped, see if the instruction constant folds or is
446b0aa36f9SDavid Green       // otherwise simplifyable.  This commonly occurs because the entry from PHI
447b0aa36f9SDavid Green       // nodes allows icmps and other instructions to fold.
448b8c2781fSSimon Moll       Value *V = simplifyInstruction(C, SQ);
449b0aa36f9SDavid Green       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
450b0aa36f9SDavid Green         // If so, then delete the temporary instruction and stick the folded value
451b0aa36f9SDavid Green         // in the map.
4524b698645SAlina Sbirlea         InsertNewValueIntoMap(ValueMap, Inst, V);
453b0aa36f9SDavid Green         if (!C->mayHaveSideEffects()) {
454b0aa36f9SDavid Green           C->deleteValue();
455b0aa36f9SDavid Green           C = nullptr;
456b0aa36f9SDavid Green         }
457b0aa36f9SDavid Green       } else {
4584b698645SAlina Sbirlea         InsertNewValueIntoMap(ValueMap, Inst, C);
459b0aa36f9SDavid Green       }
460b0aa36f9SDavid Green       if (C) {
461b0aa36f9SDavid Green         // Otherwise, stick the new instruction into the new block!
462b0aa36f9SDavid Green         C->setName(Inst->getName());
463b0aa36f9SDavid Green         C->insertBefore(LoopEntryBranch);
464b0aa36f9SDavid Green 
465a6d2a8d6SPhilip Reames         if (auto *II = dyn_cast<AssumeInst>(C))
466b0aa36f9SDavid Green           AC->registerAssumption(II);
46758a37754SAlina Sbirlea         // MemorySSA cares whether the cloned instruction was inserted or not, and
46858a37754SAlina Sbirlea         // not whether it can be remapped to a simplified value.
4694b698645SAlina Sbirlea         if (MSSAU)
4704b698645SAlina Sbirlea           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
471b0aa36f9SDavid Green       }
472b0aa36f9SDavid Green     }
473b0aa36f9SDavid Green 
474659c7bcdSJeroen Dobbelaere     if (!NoAliasDeclInstructions.empty()) {
475659c7bcdSJeroen Dobbelaere       // There are noalias scope declarations:
476659c7bcdSJeroen Dobbelaere       // (general):
477659c7bcdSJeroen Dobbelaere       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
478659c7bcdSJeroen Dobbelaere       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
479659c7bcdSJeroen Dobbelaere       //
480659c7bcdSJeroen Dobbelaere       // with D: llvm.experimental.noalias.scope.decl,
481659c7bcdSJeroen Dobbelaere       //      U: !noalias or !alias.scope depending on D
482659c7bcdSJeroen Dobbelaere       //       ... { D U1 U2 }   can transform into:
483659c7bcdSJeroen Dobbelaere       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
484659c7bcdSJeroen Dobbelaere       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
485659c7bcdSJeroen Dobbelaere       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
486659c7bcdSJeroen Dobbelaere       //
487659c7bcdSJeroen Dobbelaere       // We now want to transform:
488659c7bcdSJeroen Dobbelaere       // (1) -> : ... D' { D U1 U2 D'' }
489659c7bcdSJeroen Dobbelaere       // (2) -> : ... D' U1' { D U2 D'' U1'' }
490659c7bcdSJeroen Dobbelaere       // D: original llvm.experimental.noalias.scope.decl
491659c7bcdSJeroen Dobbelaere       // D', U1': duplicate with replaced scopes
492659c7bcdSJeroen Dobbelaere       // D'', U1'': different duplicate with replaced scopes
493659c7bcdSJeroen Dobbelaere       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
494659c7bcdSJeroen Dobbelaere       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
495659c7bcdSJeroen Dobbelaere 
496659c7bcdSJeroen Dobbelaere       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
497659c7bcdSJeroen Dobbelaere       Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
4988b9df70bSNikita Popov       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
499659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
500659c7bcdSJeroen Dobbelaere                           << *NAD << "\n");
501659c7bcdSJeroen Dobbelaere         Instruction *NewNAD = NAD->clone();
502659c7bcdSJeroen Dobbelaere         NewNAD->insertBefore(NewHeaderInsertionPoint);
503659c7bcdSJeroen Dobbelaere       }
504659c7bcdSJeroen Dobbelaere 
505659c7bcdSJeroen Dobbelaere       // Scopes must now be duplicated, once for OrigHeader and once for
506659c7bcdSJeroen Dobbelaere       // OrigPreHeader'.
507659c7bcdSJeroen Dobbelaere       {
508659c7bcdSJeroen Dobbelaere         auto &Context = NewHeader->getContext();
509659c7bcdSJeroen Dobbelaere 
5108b9df70bSNikita Popov         SmallVector<MDNode *, 8> NoAliasDeclScopes;
5118b9df70bSNikita Popov         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
5128b9df70bSNikita Popov           NoAliasDeclScopes.push_back(NAD->getScopeList());
513659c7bcdSJeroen Dobbelaere 
514659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
515659c7bcdSJeroen Dobbelaere         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
516659c7bcdSJeroen Dobbelaere                                    "h.rot");
517659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(OrigHeader->dump());
518659c7bcdSJeroen Dobbelaere 
519659c7bcdSJeroen Dobbelaere         // Keep the compile time impact low by only adapting the inserted block
520659c7bcdSJeroen Dobbelaere         // of instructions in the OrigPreHeader. This might result in slightly
521659c7bcdSJeroen Dobbelaere         // more aliasing between these instructions and those that were already
522659c7bcdSJeroen Dobbelaere         // present, but it will be much faster when the original PreHeader is
523659c7bcdSJeroen Dobbelaere         // large.
524659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
525659c7bcdSJeroen Dobbelaere         auto *FirstDecl =
526659c7bcdSJeroen Dobbelaere             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
527659c7bcdSJeroen Dobbelaere         auto *LastInst = &OrigPreheader->back();
528659c7bcdSJeroen Dobbelaere         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
529659c7bcdSJeroen Dobbelaere                                    Context, "pre.rot");
530659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(OrigPreheader->dump());
531659c7bcdSJeroen Dobbelaere 
532659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
533659c7bcdSJeroen Dobbelaere         LLVM_DEBUG(NewHeader->dump());
534659c7bcdSJeroen Dobbelaere       }
535659c7bcdSJeroen Dobbelaere     }
536659c7bcdSJeroen Dobbelaere 
537b0aa36f9SDavid Green     // Along with all the other instructions, we just cloned OrigHeader's
538b0aa36f9SDavid Green     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
539b0aa36f9SDavid Green     // successors by duplicating their incoming values for OrigHeader.
54096fc1de7SChandler Carruth     for (BasicBlock *SuccBB : successors(OrigHeader))
541b0aa36f9SDavid Green       for (BasicBlock::iterator BI = SuccBB->begin();
542b0aa36f9SDavid Green            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
543b0aa36f9SDavid Green         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
544b0aa36f9SDavid Green 
545b0aa36f9SDavid Green     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
546b0aa36f9SDavid Green     // OrigPreHeader's old terminator (the original branch into the loop), and
547b0aa36f9SDavid Green     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
548b0aa36f9SDavid Green     LoopEntryBranch->eraseFromParent();
549b0aa36f9SDavid Green 
550ad4d0182SAlina Sbirlea     // Update MemorySSA before the rewrite call below changes the 1:1
55158a37754SAlina Sbirlea     // instruction:cloned_instruction_or_value mapping.
552ad4d0182SAlina Sbirlea     if (MSSAU) {
5534b698645SAlina Sbirlea       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
55458a37754SAlina Sbirlea       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
55558a37754SAlina Sbirlea                                           ValueMapMSSA);
556ad4d0182SAlina Sbirlea     }
557b0aa36f9SDavid Green 
558b0aa36f9SDavid Green     SmallVector<PHINode*, 2> InsertedPHIs;
559b0aa36f9SDavid Green     // If there were any uses of instructions in the duplicated block outside the
560b0aa36f9SDavid Green     // loop, update them, inserting PHI nodes as required
5617f93bb4aSBjorn Pettersson     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
562b0aa36f9SDavid Green                                     &InsertedPHIs);
563b0aa36f9SDavid Green 
564b0aa36f9SDavid Green     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
565b0aa36f9SDavid Green     // previously had debug metadata attached. This keeps the debug info
566b0aa36f9SDavid Green     // up-to-date in the loop body.
567b0aa36f9SDavid Green     if (!InsertedPHIs.empty())
568b0aa36f9SDavid Green       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
569b0aa36f9SDavid Green 
570b0aa36f9SDavid Green     // NewHeader is now the header of the loop.
571b0aa36f9SDavid Green     L->moveToHeader(NewHeader);
572b0aa36f9SDavid Green     assert(L->getHeader() == NewHeader && "Latch block is our new header");
573b0aa36f9SDavid Green 
574b0aa36f9SDavid Green     // Inform DT about changes to the CFG.
575b0aa36f9SDavid Green     if (DT) {
576b0aa36f9SDavid Green       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
577b0aa36f9SDavid Green       // the DT about the removed edge to the OrigHeader (that got removed).
578b0aa36f9SDavid Green       SmallVector<DominatorTree::UpdateType, 3> Updates;
579b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
580b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
581b0aa36f9SDavid Green       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
582ad4d0182SAlina Sbirlea 
583ad4d0182SAlina Sbirlea       if (MSSAU) {
58463aeaf75SAlina Sbirlea         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
585ad4d0182SAlina Sbirlea         if (VerifyMemorySSA)
586ad4d0182SAlina Sbirlea           MSSAU->getMemorySSA()->verifyMemorySSA();
58763aeaf75SAlina Sbirlea       } else {
58863aeaf75SAlina Sbirlea         DT->applyUpdates(Updates);
589ad4d0182SAlina Sbirlea       }
590b0aa36f9SDavid Green     }
591b0aa36f9SDavid Green 
592b0aa36f9SDavid Green     // At this point, we've finished our major CFG changes.  As part of cloning
593b0aa36f9SDavid Green     // the loop into the preheader we've simplified instructions and the
594b0aa36f9SDavid Green     // duplicated conditional branch may now be branching on a constant.  If it is
595b0aa36f9SDavid Green     // branching on a constant and if that constant means that we enter the loop,
596b0aa36f9SDavid Green     // then we fold away the cond branch to an uncond branch.  This simplifies the
597b0aa36f9SDavid Green     // loop in cases important for nested loops, and it also means we don't have
598b0aa36f9SDavid Green     // to split as many edges.
599b0aa36f9SDavid Green     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
600b0aa36f9SDavid Green     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
601b0aa36f9SDavid Green     if (!isa<ConstantInt>(PHBI->getCondition()) ||
602b0aa36f9SDavid Green         PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
603b0aa36f9SDavid Green         NewHeader) {
604b0aa36f9SDavid Green       // The conditional branch can't be folded, handle the general case.
605b0aa36f9SDavid Green       // Split edges as necessary to preserve LoopSimplify form.
606b0aa36f9SDavid Green 
607b0aa36f9SDavid Green       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
608b0aa36f9SDavid Green       // thus is not a preheader anymore.
609b0aa36f9SDavid Green       // Split the edge to form a real preheader.
610b0aa36f9SDavid Green       BasicBlock *NewPH = SplitCriticalEdge(
611b0aa36f9SDavid Green                                             OrigPreheader, NewHeader,
612ad4d0182SAlina Sbirlea                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
613b0aa36f9SDavid Green       NewPH->setName(NewHeader->getName() + ".lr.ph");
614b0aa36f9SDavid Green 
615b0aa36f9SDavid Green       // Preserve canonical loop form, which means that 'Exit' should have only
616b0aa36f9SDavid Green       // one predecessor. Note that Exit could be an exit block for multiple
617b0aa36f9SDavid Green       // nested loops, causing both of the edges to now be critical and need to
618b0aa36f9SDavid Green       // be split.
6195648f717SKazu Hirata       SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
620b0aa36f9SDavid Green       bool SplitLatchEdge = false;
621b0aa36f9SDavid Green       for (BasicBlock *ExitPred : ExitPreds) {
622b0aa36f9SDavid Green         // We only need to split loop exit edges.
623b0aa36f9SDavid Green         Loop *PredLoop = LI->getLoopFor(ExitPred);
624212c8ac2SNick Desaulniers         if (!PredLoop || PredLoop->contains(Exit) ||
625*11079e88SNikita Popov             isa<IndirectBrInst>(ExitPred->getTerminator()))
626b0aa36f9SDavid Green           continue;
627b0aa36f9SDavid Green         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
628b0aa36f9SDavid Green         BasicBlock *ExitSplit = SplitCriticalEdge(
629b0aa36f9SDavid Green                                                   ExitPred, Exit,
630ad4d0182SAlina Sbirlea                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
631b0aa36f9SDavid Green         ExitSplit->moveBefore(Exit);
632b0aa36f9SDavid Green       }
633b0aa36f9SDavid Green       assert(SplitLatchEdge &&
634b0aa36f9SDavid Green              "Despite splitting all preds, failed to split latch exit?");
63506e7de79SFangrui Song       (void)SplitLatchEdge;
636b0aa36f9SDavid Green     } else {
637b0aa36f9SDavid Green       // We can fold the conditional branch in the preheader, this makes things
638b0aa36f9SDavid Green       // simpler. The first step is to remove the extra edge to the Exit block.
639b0aa36f9SDavid Green       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
640b0aa36f9SDavid Green       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
641b0aa36f9SDavid Green       NewBI->setDebugLoc(PHBI->getDebugLoc());
642b0aa36f9SDavid Green       PHBI->eraseFromParent();
643b0aa36f9SDavid Green 
644b0aa36f9SDavid Green       // With our CFG finalized, update DomTree if it is available.
645b0aa36f9SDavid Green       if (DT) DT->deleteEdge(OrigPreheader, Exit);
646ad4d0182SAlina Sbirlea 
647ad4d0182SAlina Sbirlea       // Update MSSA too, if available.
648ad4d0182SAlina Sbirlea       if (MSSAU)
649ad4d0182SAlina Sbirlea         MSSAU->removeEdge(OrigPreheader, Exit);
650b0aa36f9SDavid Green     }
651b0aa36f9SDavid Green 
652b0aa36f9SDavid Green     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
653b0aa36f9SDavid Green     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
654b0aa36f9SDavid Green 
655ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
656ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
657ad4d0182SAlina Sbirlea 
658b0aa36f9SDavid Green     // Now that the CFG and DomTree are in a consistent state again, try to merge
659b0aa36f9SDavid Green     // the OrigHeader block into OrigLatch.  This will succeed if they are
660b0aa36f9SDavid Green     // connected by an unconditional branch.  This is just a cleanup so the
661b0aa36f9SDavid Green     // emitted code isn't too gross in this common case.
66221a8b605SChijun Sima     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
6635a3ef55aSVedant Kumar     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
6645a3ef55aSVedant Kumar     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
6655a3ef55aSVedant Kumar     if (DidMerge)
6665a3ef55aSVedant Kumar       RemoveRedundantDbgInstrs(PredBB);
667ad4d0182SAlina Sbirlea 
668ad4d0182SAlina Sbirlea     if (MSSAU && VerifyMemorySSA)
669ad4d0182SAlina Sbirlea       MSSAU->getMemorySSA()->verifyMemorySSA();
670b0aa36f9SDavid Green 
671d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
672b0aa36f9SDavid Green 
673b0aa36f9SDavid Green     ++NumRotated;
6742f6987baSFedor Sergeev 
6752f6987baSFedor Sergeev     Rotated = true;
6762f6987baSFedor Sergeev     SimplifiedLatch = false;
6772f6987baSFedor Sergeev 
6782f6987baSFedor Sergeev     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
6792f6987baSFedor Sergeev     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
6802f6987baSFedor Sergeev     // TODO: if it becomes a performance bottleneck extend rotation algorithm
6812f6987baSFedor Sergeev     // to handle multiple rotations in one go.
6822f6987baSFedor Sergeev   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
6832f6987baSFedor Sergeev 
6842f6987baSFedor Sergeev 
685b0aa36f9SDavid Green   return true;
686b0aa36f9SDavid Green }
687b0aa36f9SDavid Green 
688b0aa36f9SDavid Green /// Determine whether the instructions in this range may be safely and cheaply
689b0aa36f9SDavid Green /// speculated. This is not an important enough situation to develop complex
690b0aa36f9SDavid Green /// heuristics. We handle a single arithmetic instruction along with any type
691b0aa36f9SDavid Green /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)692b0aa36f9SDavid Green static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
693b0aa36f9SDavid Green                                   BasicBlock::iterator End, Loop *L) {
694b0aa36f9SDavid Green   bool seenIncrement = false;
695b0aa36f9SDavid Green   bool MultiExitLoop = false;
696b0aa36f9SDavid Green 
697b0aa36f9SDavid Green   if (!L->getExitingBlock())
698b0aa36f9SDavid Green     MultiExitLoop = true;
699b0aa36f9SDavid Green 
700b0aa36f9SDavid Green   for (BasicBlock::iterator I = Begin; I != End; ++I) {
701b0aa36f9SDavid Green 
702b0aa36f9SDavid Green     if (!isSafeToSpeculativelyExecute(&*I))
703b0aa36f9SDavid Green       return false;
704b0aa36f9SDavid Green 
705b0aa36f9SDavid Green     if (isa<DbgInfoIntrinsic>(I))
706b0aa36f9SDavid Green       continue;
707b0aa36f9SDavid Green 
708b0aa36f9SDavid Green     switch (I->getOpcode()) {
709b0aa36f9SDavid Green     default:
710b0aa36f9SDavid Green       return false;
711b0aa36f9SDavid Green     case Instruction::GetElementPtr:
712b0aa36f9SDavid Green       // GEPs are cheap if all indices are constant.
713b0aa36f9SDavid Green       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
714b0aa36f9SDavid Green         return false;
715b0aa36f9SDavid Green       // fall-thru to increment case
716b0aa36f9SDavid Green       LLVM_FALLTHROUGH;
717b0aa36f9SDavid Green     case Instruction::Add:
718b0aa36f9SDavid Green     case Instruction::Sub:
719b0aa36f9SDavid Green     case Instruction::And:
720b0aa36f9SDavid Green     case Instruction::Or:
721b0aa36f9SDavid Green     case Instruction::Xor:
722b0aa36f9SDavid Green     case Instruction::Shl:
723b0aa36f9SDavid Green     case Instruction::LShr:
724b0aa36f9SDavid Green     case Instruction::AShr: {
725b0aa36f9SDavid Green       Value *IVOpnd =
726b0aa36f9SDavid Green           !isa<Constant>(I->getOperand(0))
727b0aa36f9SDavid Green               ? I->getOperand(0)
728b0aa36f9SDavid Green               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
729b0aa36f9SDavid Green       if (!IVOpnd)
730b0aa36f9SDavid Green         return false;
731b0aa36f9SDavid Green 
732b0aa36f9SDavid Green       // If increment operand is used outside of the loop, this speculation
733b0aa36f9SDavid Green       // could cause extra live range interference.
734b0aa36f9SDavid Green       if (MultiExitLoop) {
735b0aa36f9SDavid Green         for (User *UseI : IVOpnd->users()) {
736b0aa36f9SDavid Green           auto *UserInst = cast<Instruction>(UseI);
737b0aa36f9SDavid Green           if (!L->contains(UserInst))
738b0aa36f9SDavid Green             return false;
739b0aa36f9SDavid Green         }
740b0aa36f9SDavid Green       }
741b0aa36f9SDavid Green 
742b0aa36f9SDavid Green       if (seenIncrement)
743b0aa36f9SDavid Green         return false;
744b0aa36f9SDavid Green       seenIncrement = true;
745b0aa36f9SDavid Green       break;
746b0aa36f9SDavid Green     }
747b0aa36f9SDavid Green     case Instruction::Trunc:
748b0aa36f9SDavid Green     case Instruction::ZExt:
749b0aa36f9SDavid Green     case Instruction::SExt:
750b0aa36f9SDavid Green       // ignore type conversions
751b0aa36f9SDavid Green       break;
752b0aa36f9SDavid Green     }
753b0aa36f9SDavid Green   }
754b0aa36f9SDavid Green   return true;
755b0aa36f9SDavid Green }
756b0aa36f9SDavid Green 
757b0aa36f9SDavid Green /// Fold the loop tail into the loop exit by speculating the loop tail
758b0aa36f9SDavid Green /// instructions. Typically, this is a single post-increment. In the case of a
759b0aa36f9SDavid Green /// simple 2-block loop, hoisting the increment can be much better than
760b0aa36f9SDavid Green /// duplicating the entire loop header. In the case of loops with early exits,
761b0aa36f9SDavid Green /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
762b0aa36f9SDavid Green /// canonical form so downstream passes can handle it.
763b0aa36f9SDavid Green ///
764b0aa36f9SDavid Green /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)765b0aa36f9SDavid Green bool LoopRotate::simplifyLoopLatch(Loop *L) {
766b0aa36f9SDavid Green   BasicBlock *Latch = L->getLoopLatch();
767b0aa36f9SDavid Green   if (!Latch || Latch->hasAddressTaken())
768b0aa36f9SDavid Green     return false;
769b0aa36f9SDavid Green 
770b0aa36f9SDavid Green   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
771b0aa36f9SDavid Green   if (!Jmp || !Jmp->isUnconditional())
772b0aa36f9SDavid Green     return false;
773b0aa36f9SDavid Green 
774b0aa36f9SDavid Green   BasicBlock *LastExit = Latch->getSinglePredecessor();
775b0aa36f9SDavid Green   if (!LastExit || !L->isLoopExiting(LastExit))
776b0aa36f9SDavid Green     return false;
777b0aa36f9SDavid Green 
778b0aa36f9SDavid Green   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
779b0aa36f9SDavid Green   if (!BI)
780b0aa36f9SDavid Green     return false;
781b0aa36f9SDavid Green 
782b0aa36f9SDavid Green   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
783b0aa36f9SDavid Green     return false;
784b0aa36f9SDavid Green 
785d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
786b0aa36f9SDavid Green                     << LastExit->getName() << "\n");
787b0aa36f9SDavid Green 
7884eb1a573SAlina Sbirlea   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
7894eb1a573SAlina Sbirlea   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
7904eb1a573SAlina Sbirlea                             /*PredecessorWithTwoSuccessors=*/true);
791ad4d0182SAlina Sbirlea 
792ad4d0182SAlina Sbirlea   if (MSSAU && VerifyMemorySSA)
793ad4d0182SAlina Sbirlea     MSSAU->getMemorySSA()->verifyMemorySSA();
794ad4d0182SAlina Sbirlea 
795b0aa36f9SDavid Green   return true;
796b0aa36f9SDavid Green }
797b0aa36f9SDavid Green 
798b0aa36f9SDavid Green /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)799b0aa36f9SDavid Green bool LoopRotate::processLoop(Loop *L) {
800b0aa36f9SDavid Green   // Save the loop metadata.
801b0aa36f9SDavid Green   MDNode *LoopMD = L->getLoopID();
802b0aa36f9SDavid Green 
803585f2699SJin Lin   bool SimplifiedLatch = false;
804585f2699SJin Lin 
805b0aa36f9SDavid Green   // Simplify the loop latch before attempting to rotate the header
806b0aa36f9SDavid Green   // upward. Rotation may not be needed if the loop tail can be folded into the
807b0aa36f9SDavid Green   // loop exit.
808585f2699SJin Lin   if (!RotationOnly)
809585f2699SJin Lin     SimplifiedLatch = simplifyLoopLatch(L);
810b0aa36f9SDavid Green 
811b0aa36f9SDavid Green   bool MadeChange = rotateLoop(L, SimplifiedLatch);
812b0aa36f9SDavid Green   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
813b0aa36f9SDavid Green          "Loop latch should be exiting after loop-rotate.");
814b0aa36f9SDavid Green 
815b0aa36f9SDavid Green   // Restore the loop metadata.
816b0aa36f9SDavid Green   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
817b0aa36f9SDavid Green   if ((MadeChange || SimplifiedLatch) && LoopMD)
818b0aa36f9SDavid Green     L->setLoopID(LoopMD);
819b0aa36f9SDavid Green 
820b0aa36f9SDavid Green   return MadeChange || SimplifiedLatch;
821b0aa36f9SDavid Green }
822b0aa36f9SDavid Green 
823b0aa36f9SDavid Green 
824b0aa36f9SDavid Green /// The utility to convert a loop into a loop with bottom test.
LoopRotation(Loop * L,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly=true,unsigned Threshold=unsigned (-1),bool IsUtilMode=true,bool PrepareForLTO)825585f2699SJin Lin bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
826585f2699SJin Lin                         AssumptionCache *AC, DominatorTree *DT,
827ad4d0182SAlina Sbirlea                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
828ad4d0182SAlina Sbirlea                         const SimplifyQuery &SQ, bool RotationOnly = true,
829585f2699SJin Lin                         unsigned Threshold = unsigned(-1),
83083daa497SFlorian Hahn                         bool IsUtilMode = true, bool PrepareForLTO) {
831ad4d0182SAlina Sbirlea   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
83283daa497SFlorian Hahn                 IsUtilMode, PrepareForLTO);
833b0aa36f9SDavid Green   return LR.processLoop(L);
834b0aa36f9SDavid Green }
835