xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1eb11fae6SDimitry Andric //===----------------- LoopRotationUtils.cpp -----------------------------===//
2eb11fae6SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6eb11fae6SDimitry Andric //
7eb11fae6SDimitry Andric //===----------------------------------------------------------------------===//
8eb11fae6SDimitry Andric //
9eb11fae6SDimitry Andric // This file provides utilities to convert a loop into a loop with bottom test.
10eb11fae6SDimitry Andric //
11eb11fae6SDimitry Andric //===----------------------------------------------------------------------===//
12eb11fae6SDimitry Andric 
13eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/LoopRotationUtils.h"
14eb11fae6SDimitry Andric #include "llvm/ADT/Statistic.h"
15eb11fae6SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
16eb11fae6SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
17e6d15924SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
18eb11fae6SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
19145449b1SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
20d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
21d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
22eb11fae6SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
23eb11fae6SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
24eb11fae6SDimitry Andric #include "llvm/IR/CFG.h"
25344a3780SDimitry Andric #include "llvm/IR/DebugInfo.h"
26eb11fae6SDimitry Andric #include "llvm/IR/Dominators.h"
27eb11fae6SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
28b1c73532SDimitry Andric #include "llvm/IR/MDBuilder.h"
29b1c73532SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
30eb11fae6SDimitry Andric #include "llvm/Support/CommandLine.h"
31eb11fae6SDimitry Andric #include "llvm/Support/Debug.h"
32eb11fae6SDimitry Andric #include "llvm/Support/raw_ostream.h"
33eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34b60736ecSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
35d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
36eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
37eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
38eb11fae6SDimitry Andric using namespace llvm;
39eb11fae6SDimitry Andric 
40eb11fae6SDimitry Andric #define DEBUG_TYPE "loop-rotate"
41eb11fae6SDimitry Andric 
42b60736ecSDimitry Andric STATISTIC(NumNotRotatedDueToHeaderSize,
43b60736ecSDimitry Andric           "Number of loops not rotated due to the header size");
44344a3780SDimitry Andric STATISTIC(NumInstrsHoisted,
45344a3780SDimitry Andric           "Number of instructions hoisted into loop preheader");
46344a3780SDimitry Andric STATISTIC(NumInstrsDuplicated,
47344a3780SDimitry Andric           "Number of instructions cloned into loop preheader");
48eb11fae6SDimitry Andric STATISTIC(NumRotated, "Number of loops rotated");
49eb11fae6SDimitry Andric 
50cfca06d7SDimitry Andric static cl::opt<bool>
51cfca06d7SDimitry Andric     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
52cfca06d7SDimitry Andric                 cl::desc("Allow loop rotation multiple times in order to reach "
53cfca06d7SDimitry Andric                          "a better latch exit"));
54cfca06d7SDimitry Andric 
55b1c73532SDimitry Andric // Probability that a rotated loop has zero trip count / is never entered.
56b1c73532SDimitry Andric static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
57b1c73532SDimitry Andric 
58eb11fae6SDimitry Andric namespace {
59eb11fae6SDimitry Andric /// A simple loop rotation transformation.
60eb11fae6SDimitry Andric class LoopRotate {
61eb11fae6SDimitry Andric   const unsigned MaxHeaderSize;
62eb11fae6SDimitry Andric   LoopInfo *LI;
63eb11fae6SDimitry Andric   const TargetTransformInfo *TTI;
64eb11fae6SDimitry Andric   AssumptionCache *AC;
65eb11fae6SDimitry Andric   DominatorTree *DT;
66eb11fae6SDimitry Andric   ScalarEvolution *SE;
67d8e91e46SDimitry Andric   MemorySSAUpdater *MSSAU;
68eb11fae6SDimitry Andric   const SimplifyQuery &SQ;
69eb11fae6SDimitry Andric   bool RotationOnly;
70eb11fae6SDimitry Andric   bool IsUtilMode;
71b60736ecSDimitry Andric   bool PrepareForLTO;
72eb11fae6SDimitry Andric 
73eb11fae6SDimitry Andric 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)74eb11fae6SDimitry Andric   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
75eb11fae6SDimitry Andric              const TargetTransformInfo *TTI, AssumptionCache *AC,
76d8e91e46SDimitry Andric              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
77b60736ecSDimitry Andric              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
78b60736ecSDimitry Andric              bool PrepareForLTO)
79eb11fae6SDimitry Andric       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
80d8e91e46SDimitry Andric         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
81b60736ecSDimitry Andric         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
82eb11fae6SDimitry Andric   bool processLoop(Loop *L);
83eb11fae6SDimitry Andric 
84eb11fae6SDimitry Andric private:
85eb11fae6SDimitry Andric   bool rotateLoop(Loop *L, bool SimplifiedLatch);
86eb11fae6SDimitry Andric   bool simplifyLoopLatch(Loop *L);
87eb11fae6SDimitry Andric };
88eb11fae6SDimitry Andric } // end anonymous namespace
89eb11fae6SDimitry Andric 
90706b4fc4SDimitry Andric /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
91706b4fc4SDimitry Andric /// previously exist in the map, and the value was inserted.
InsertNewValueIntoMap(ValueToValueMapTy & VM,Value * K,Value * V)92706b4fc4SDimitry Andric static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
93706b4fc4SDimitry Andric   bool Inserted = VM.insert({K, V}).second;
94706b4fc4SDimitry Andric   assert(Inserted);
95706b4fc4SDimitry Andric   (void)Inserted;
96706b4fc4SDimitry Andric }
97eb11fae6SDimitry Andric /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
98eb11fae6SDimitry Andric /// old header into the preheader.  If there were uses of the values produced by
99eb11fae6SDimitry Andric /// these instruction that were outside of the loop, we have to insert PHI nodes
100eb11fae6SDimitry Andric /// to merge the two values.  Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap,ScalarEvolution * SE,SmallVectorImpl<PHINode * > * InsertedPHIs)101eb11fae6SDimitry Andric static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
102eb11fae6SDimitry Andric                                             BasicBlock *OrigPreheader,
103eb11fae6SDimitry Andric                                             ValueToValueMapTy &ValueMap,
104c0981da4SDimitry Andric                                             ScalarEvolution *SE,
105eb11fae6SDimitry Andric                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
106eb11fae6SDimitry Andric   // Remove PHI node entries that are no longer live.
107eb11fae6SDimitry Andric   BasicBlock::iterator I, E = OrigHeader->end();
108eb11fae6SDimitry Andric   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
109eb11fae6SDimitry Andric     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
110eb11fae6SDimitry Andric 
111eb11fae6SDimitry Andric   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
112eb11fae6SDimitry Andric   // as necessary.
113eb11fae6SDimitry Andric   SSAUpdater SSA(InsertedPHIs);
114eb11fae6SDimitry Andric   for (I = OrigHeader->begin(); I != E; ++I) {
115eb11fae6SDimitry Andric     Value *OrigHeaderVal = &*I;
116eb11fae6SDimitry Andric 
117eb11fae6SDimitry Andric     // If there are no uses of the value (e.g. because it returns void), there
118eb11fae6SDimitry Andric     // is nothing to rewrite.
119eb11fae6SDimitry Andric     if (OrigHeaderVal->use_empty())
120eb11fae6SDimitry Andric       continue;
121eb11fae6SDimitry Andric 
122eb11fae6SDimitry Andric     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
123eb11fae6SDimitry Andric 
124eb11fae6SDimitry Andric     // The value now exits in two versions: the initial value in the preheader
125eb11fae6SDimitry Andric     // and the loop "next" value in the original header.
126eb11fae6SDimitry Andric     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127c0981da4SDimitry Andric     // Force re-computation of OrigHeaderVal, as some users now need to use the
128c0981da4SDimitry Andric     // new PHI node.
129c0981da4SDimitry Andric     if (SE)
130c0981da4SDimitry Andric       SE->forgetValue(OrigHeaderVal);
131eb11fae6SDimitry Andric     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
132eb11fae6SDimitry Andric     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
133eb11fae6SDimitry Andric 
134eb11fae6SDimitry Andric     // Visit each use of the OrigHeader instruction.
135c0981da4SDimitry Andric     for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
136eb11fae6SDimitry Andric       // SSAUpdater can't handle a non-PHI use in the same block as an
137eb11fae6SDimitry Andric       // earlier def. We can easily handle those cases manually.
138eb11fae6SDimitry Andric       Instruction *UserInst = cast<Instruction>(U.getUser());
139eb11fae6SDimitry Andric       if (!isa<PHINode>(UserInst)) {
140eb11fae6SDimitry Andric         BasicBlock *UserBB = UserInst->getParent();
141eb11fae6SDimitry Andric 
142eb11fae6SDimitry Andric         // The original users in the OrigHeader are already using the
143eb11fae6SDimitry Andric         // original definitions.
144eb11fae6SDimitry Andric         if (UserBB == OrigHeader)
145eb11fae6SDimitry Andric           continue;
146eb11fae6SDimitry Andric 
147eb11fae6SDimitry Andric         // Users in the OrigPreHeader need to use the value to which the
148eb11fae6SDimitry Andric         // original definitions are mapped.
149eb11fae6SDimitry Andric         if (UserBB == OrigPreheader) {
150eb11fae6SDimitry Andric           U = OrigPreHeaderVal;
151eb11fae6SDimitry Andric           continue;
152eb11fae6SDimitry Andric         }
153eb11fae6SDimitry Andric       }
154eb11fae6SDimitry Andric 
155eb11fae6SDimitry Andric       // Anything else can be handled by SSAUpdater.
156eb11fae6SDimitry Andric       SSA.RewriteUse(U);
157eb11fae6SDimitry Andric     }
158eb11fae6SDimitry Andric 
159eb11fae6SDimitry Andric     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
160eb11fae6SDimitry Andric     // intrinsics.
161eb11fae6SDimitry Andric     SmallVector<DbgValueInst *, 1> DbgValues;
162ac9a064cSDimitry Andric     SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
163ac9a064cSDimitry Andric     llvm::findDbgValues(DbgValues, OrigHeaderVal, &DbgVariableRecords);
164eb11fae6SDimitry Andric     for (auto &DbgValue : DbgValues) {
165eb11fae6SDimitry Andric       // The original users in the OrigHeader are already using the original
166eb11fae6SDimitry Andric       // definitions.
167eb11fae6SDimitry Andric       BasicBlock *UserBB = DbgValue->getParent();
168eb11fae6SDimitry Andric       if (UserBB == OrigHeader)
169eb11fae6SDimitry Andric         continue;
170eb11fae6SDimitry Andric 
171eb11fae6SDimitry Andric       // Users in the OrigPreHeader need to use the value to which the
172eb11fae6SDimitry Andric       // original definitions are mapped and anything else can be handled by
173eb11fae6SDimitry Andric       // the SSAUpdater. To avoid adding PHINodes, check if the value is
174eb11fae6SDimitry Andric       // available in UserBB, if not substitute undef.
175eb11fae6SDimitry Andric       Value *NewVal;
176eb11fae6SDimitry Andric       if (UserBB == OrigPreheader)
177eb11fae6SDimitry Andric         NewVal = OrigPreHeaderVal;
178eb11fae6SDimitry Andric       else if (SSA.HasValueForBlock(UserBB))
179eb11fae6SDimitry Andric         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
180eb11fae6SDimitry Andric       else
181eb11fae6SDimitry Andric         NewVal = UndefValue::get(OrigHeaderVal->getType());
182344a3780SDimitry Andric       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
183eb11fae6SDimitry Andric     }
184b1c73532SDimitry Andric 
185b1c73532SDimitry Andric     // RemoveDIs: duplicate implementation for non-instruction debug-info
186ac9a064cSDimitry Andric     // storage in DbgVariableRecords.
187ac9a064cSDimitry Andric     for (DbgVariableRecord *DVR : DbgVariableRecords) {
188b1c73532SDimitry Andric       // The original users in the OrigHeader are already using the original
189b1c73532SDimitry Andric       // definitions.
190ac9a064cSDimitry Andric       BasicBlock *UserBB = DVR->getMarker()->getParent();
191b1c73532SDimitry Andric       if (UserBB == OrigHeader)
192b1c73532SDimitry Andric         continue;
193b1c73532SDimitry Andric 
194b1c73532SDimitry Andric       // Users in the OrigPreHeader need to use the value to which the
195b1c73532SDimitry Andric       // original definitions are mapped and anything else can be handled by
196b1c73532SDimitry Andric       // the SSAUpdater. To avoid adding PHINodes, check if the value is
197b1c73532SDimitry Andric       // available in UserBB, if not substitute undef.
198b1c73532SDimitry Andric       Value *NewVal;
199b1c73532SDimitry Andric       if (UserBB == OrigPreheader)
200b1c73532SDimitry Andric         NewVal = OrigPreHeaderVal;
201b1c73532SDimitry Andric       else if (SSA.HasValueForBlock(UserBB))
202b1c73532SDimitry Andric         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
203b1c73532SDimitry Andric       else
204b1c73532SDimitry Andric         NewVal = UndefValue::get(OrigHeaderVal->getType());
205ac9a064cSDimitry Andric       DVR->replaceVariableLocationOp(OrigHeaderVal, NewVal);
206b1c73532SDimitry Andric     }
207eb11fae6SDimitry Andric   }
208eb11fae6SDimitry Andric }
209eb11fae6SDimitry Andric 
210cfca06d7SDimitry Andric // Assuming both header and latch are exiting, look for a phi which is only
211cfca06d7SDimitry Andric // used outside the loop (via a LCSSA phi) in the exit from the header.
212cfca06d7SDimitry Andric // This means that rotating the loop can remove the phi.
profitableToRotateLoopExitingLatch(Loop * L)213cfca06d7SDimitry Andric static bool profitableToRotateLoopExitingLatch(Loop *L) {
214eb11fae6SDimitry Andric   BasicBlock *Header = L->getHeader();
215cfca06d7SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
216cfca06d7SDimitry Andric   assert(BI && BI->isConditional() && "need header with conditional exit");
217cfca06d7SDimitry Andric   BasicBlock *HeaderExit = BI->getSuccessor(0);
218eb11fae6SDimitry Andric   if (L->contains(HeaderExit))
219cfca06d7SDimitry Andric     HeaderExit = BI->getSuccessor(1);
220eb11fae6SDimitry Andric 
221eb11fae6SDimitry Andric   for (auto &Phi : Header->phis()) {
222eb11fae6SDimitry Andric     // Look for uses of this phi in the loop/via exits other than the header.
223eb11fae6SDimitry Andric     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
224eb11fae6SDimitry Andric           return cast<Instruction>(U)->getParent() != HeaderExit;
225eb11fae6SDimitry Andric         }))
226eb11fae6SDimitry Andric       continue;
227eb11fae6SDimitry Andric     return true;
228eb11fae6SDimitry Andric   }
229cfca06d7SDimitry Andric   return false;
230cfca06d7SDimitry Andric }
231eb11fae6SDimitry Andric 
232cfca06d7SDimitry Andric // Check that latch exit is deoptimizing (which means - very unlikely to happen)
233cfca06d7SDimitry Andric // and there is another exit from the loop which is non-deoptimizing.
234cfca06d7SDimitry Andric // If we rotate latch to that exit our loop has a better chance of being fully
235cfca06d7SDimitry Andric // canonical.
236cfca06d7SDimitry Andric //
237cfca06d7SDimitry Andric // It can give false positives in some rare cases.
canRotateDeoptimizingLatchExit(Loop * L)238cfca06d7SDimitry Andric static bool canRotateDeoptimizingLatchExit(Loop *L) {
239cfca06d7SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
240cfca06d7SDimitry Andric   assert(Latch && "need latch");
241cfca06d7SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
242cfca06d7SDimitry Andric   // Need normal exiting latch.
243cfca06d7SDimitry Andric   if (!BI || !BI->isConditional())
244cfca06d7SDimitry Andric     return false;
245cfca06d7SDimitry Andric 
246cfca06d7SDimitry Andric   BasicBlock *Exit = BI->getSuccessor(1);
247cfca06d7SDimitry Andric   if (L->contains(Exit))
248cfca06d7SDimitry Andric     Exit = BI->getSuccessor(0);
249cfca06d7SDimitry Andric 
250cfca06d7SDimitry Andric   // Latch exit is non-deoptimizing, no need to rotate.
251cfca06d7SDimitry Andric   if (!Exit->getPostdominatingDeoptimizeCall())
252cfca06d7SDimitry Andric     return false;
253cfca06d7SDimitry Andric 
254cfca06d7SDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
255cfca06d7SDimitry Andric   L->getUniqueExitBlocks(Exits);
256cfca06d7SDimitry Andric   if (!Exits.empty()) {
257cfca06d7SDimitry Andric     // There is at least one non-deoptimizing exit.
258cfca06d7SDimitry Andric     //
259cfca06d7SDimitry Andric     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
260cfca06d7SDimitry Andric     // as it can conservatively return false for deoptimizing exits with
261cfca06d7SDimitry Andric     // complex enough control flow down to deoptimize call.
262cfca06d7SDimitry Andric     //
263cfca06d7SDimitry Andric     // That means here we can report success for a case where
264cfca06d7SDimitry Andric     // all exits are deoptimizing but one of them has complex enough
265cfca06d7SDimitry Andric     // control flow (e.g. with loops).
266cfca06d7SDimitry Andric     //
267cfca06d7SDimitry Andric     // That should be a very rare case and false positives for this function
268cfca06d7SDimitry Andric     // have compile-time effect only.
269cfca06d7SDimitry Andric     return any_of(Exits, [](const BasicBlock *BB) {
270cfca06d7SDimitry Andric       return !BB->getPostdominatingDeoptimizeCall();
271cfca06d7SDimitry Andric     });
272cfca06d7SDimitry Andric   }
273eb11fae6SDimitry Andric   return false;
274eb11fae6SDimitry Andric }
275eb11fae6SDimitry Andric 
updateBranchWeights(BranchInst & PreHeaderBI,BranchInst & LoopBI,bool HasConditionalPreHeader,bool SuccsSwapped)276b1c73532SDimitry Andric static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
277b1c73532SDimitry Andric                                 bool HasConditionalPreHeader,
278b1c73532SDimitry Andric                                 bool SuccsSwapped) {
279b1c73532SDimitry Andric   MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
280b1c73532SDimitry Andric   if (WeightMD == nullptr)
281b1c73532SDimitry Andric     return;
282b1c73532SDimitry Andric 
283b1c73532SDimitry Andric   // LoopBI should currently be a clone of PreHeaderBI with the same
284b1c73532SDimitry Andric   // metadata. But we double check to make sure we don't have a degenerate case
285b1c73532SDimitry Andric   // where instsimplify changed the instructions.
286b1c73532SDimitry Andric   if (WeightMD != getBranchWeightMDNode(LoopBI))
287b1c73532SDimitry Andric     return;
288b1c73532SDimitry Andric 
289b1c73532SDimitry Andric   SmallVector<uint32_t, 2> Weights;
290ac9a064cSDimitry Andric   extractFromBranchWeightMD32(WeightMD, Weights);
291b1c73532SDimitry Andric   if (Weights.size() != 2)
292b1c73532SDimitry Andric     return;
293b1c73532SDimitry Andric   uint32_t OrigLoopExitWeight = Weights[0];
294b1c73532SDimitry Andric   uint32_t OrigLoopBackedgeWeight = Weights[1];
295b1c73532SDimitry Andric 
296b1c73532SDimitry Andric   if (SuccsSwapped)
297b1c73532SDimitry Andric     std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
298b1c73532SDimitry Andric 
299b1c73532SDimitry Andric   // Update branch weights. Consider the following edge-counts:
300b1c73532SDimitry Andric   //
301b1c73532SDimitry Andric   //    |  |--------             |
302b1c73532SDimitry Andric   //    V  V       |             V
303b1c73532SDimitry Andric   //   Br i1 ...   |            Br i1 ...
304b1c73532SDimitry Andric   //   |       |   |            |     |
305b1c73532SDimitry Andric   //  x|      y|   |  becomes:  |   y0|  |-----
306b1c73532SDimitry Andric   //   V       V   |            |     V  V    |
307b1c73532SDimitry Andric   // Exit    Loop  |            |    Loop     |
308b1c73532SDimitry Andric   //           |   |            |   Br i1 ... |
309b1c73532SDimitry Andric   //           -----            |   |      |  |
310b1c73532SDimitry Andric   //                          x0| x1|   y1 |  |
311b1c73532SDimitry Andric   //                            V   V      ----
312b1c73532SDimitry Andric   //                            Exit
313b1c73532SDimitry Andric   //
314b1c73532SDimitry Andric   // The following must hold:
315b1c73532SDimitry Andric   //  -  x == x0 + x1        # counts to "exit" must stay the same.
316b1c73532SDimitry Andric   //  - y0 == x - x0 == x1   # how often loop was entered at all.
317b1c73532SDimitry Andric   //  - y1 == y - y0         # How often loop was repeated (after first iter.).
318b1c73532SDimitry Andric   //
319b1c73532SDimitry Andric   // We cannot generally deduce how often we had a zero-trip count loop so we
320b1c73532SDimitry Andric   // have to make a guess for how to distribute x among the new x0 and x1.
321b1c73532SDimitry Andric 
322b1c73532SDimitry Andric   uint32_t ExitWeight0;    // aka x0
323b1c73532SDimitry Andric   uint32_t ExitWeight1;    // aka x1
324b1c73532SDimitry Andric   uint32_t EnterWeight;    // aka y0
325b1c73532SDimitry Andric   uint32_t LoopBackWeight; // aka y1
326b1c73532SDimitry Andric   if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
327b1c73532SDimitry Andric     ExitWeight0 = 0;
328b1c73532SDimitry Andric     if (HasConditionalPreHeader) {
329b1c73532SDimitry Andric       // Here we cannot know how many 0-trip count loops we have, so we guess:
330b1c73532SDimitry Andric       if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
331b1c73532SDimitry Andric         // If the loop count is bigger than the exit count then we set
332b1c73532SDimitry Andric         // probabilities as if 0-trip count nearly never happens.
333b1c73532SDimitry Andric         ExitWeight0 = ZeroTripCountWeights[0];
334b1c73532SDimitry Andric         // Scale up counts if necessary so we can match `ZeroTripCountWeights`
335b1c73532SDimitry Andric         // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
336b1c73532SDimitry Andric         while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
337b1c73532SDimitry Andric           // ... but don't overflow.
338b1c73532SDimitry Andric           uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
339b1c73532SDimitry Andric           if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
340b1c73532SDimitry Andric               (OrigLoopExitWeight & HighBit) != 0)
341b1c73532SDimitry Andric             break;
342b1c73532SDimitry Andric           OrigLoopBackedgeWeight <<= 1;
343b1c73532SDimitry Andric           OrigLoopExitWeight <<= 1;
344b1c73532SDimitry Andric         }
345b1c73532SDimitry Andric       } else {
346b1c73532SDimitry Andric         // If there's a higher exit-count than backedge-count then we set
347b1c73532SDimitry Andric         // probabilities as if there are only 0-trip and 1-trip cases.
348b1c73532SDimitry Andric         ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
349b1c73532SDimitry Andric       }
350ac9a064cSDimitry Andric     } else {
351ac9a064cSDimitry Andric       // Theoretically, if the loop body must be executed at least once, the
352ac9a064cSDimitry Andric       // backedge count must be not less than exit count. However the branch
353ac9a064cSDimitry Andric       // weight collected by sampling-based PGO may be not very accurate due to
354ac9a064cSDimitry Andric       // sampling. Therefore this workaround is required here to avoid underflow
355ac9a064cSDimitry Andric       // of unsigned in following update of branch weight.
356ac9a064cSDimitry Andric       if (OrigLoopExitWeight > OrigLoopBackedgeWeight)
357ac9a064cSDimitry Andric         OrigLoopBackedgeWeight = OrigLoopExitWeight;
358b1c73532SDimitry Andric     }
359ac9a064cSDimitry Andric     assert(OrigLoopExitWeight >= ExitWeight0 && "Bad branch weight");
360b1c73532SDimitry Andric     ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
361b1c73532SDimitry Andric     EnterWeight = ExitWeight1;
362ac9a064cSDimitry Andric     assert(OrigLoopBackedgeWeight >= EnterWeight && "Bad branch weight");
363b1c73532SDimitry Andric     LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
364b1c73532SDimitry Andric   } else if (OrigLoopExitWeight == 0) {
365b1c73532SDimitry Andric     if (OrigLoopBackedgeWeight == 0) {
366b1c73532SDimitry Andric       // degenerate case... keep everything zero...
367b1c73532SDimitry Andric       ExitWeight0 = 0;
368b1c73532SDimitry Andric       ExitWeight1 = 0;
369b1c73532SDimitry Andric       EnterWeight = 0;
370b1c73532SDimitry Andric       LoopBackWeight = 0;
371b1c73532SDimitry Andric     } else {
372b1c73532SDimitry Andric       // Special case "LoopExitWeight == 0" weights which behaves like an
373b1c73532SDimitry Andric       // endless where we don't want loop-enttry (y0) to be the same as
374b1c73532SDimitry Andric       // loop-exit (x1).
375b1c73532SDimitry Andric       ExitWeight0 = 0;
376b1c73532SDimitry Andric       ExitWeight1 = 0;
377b1c73532SDimitry Andric       EnterWeight = 1;
378b1c73532SDimitry Andric       LoopBackWeight = OrigLoopBackedgeWeight;
379b1c73532SDimitry Andric     }
380b1c73532SDimitry Andric   } else {
381b1c73532SDimitry Andric     // loop is never entered.
382b1c73532SDimitry Andric     assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
383b1c73532SDimitry Andric     ExitWeight0 = 1;
384b1c73532SDimitry Andric     ExitWeight1 = 1;
385b1c73532SDimitry Andric     EnterWeight = 0;
386b1c73532SDimitry Andric     LoopBackWeight = 0;
387b1c73532SDimitry Andric   }
388b1c73532SDimitry Andric 
389b1c73532SDimitry Andric   const uint32_t LoopBIWeights[] = {
390b1c73532SDimitry Andric       SuccsSwapped ? LoopBackWeight : ExitWeight1,
391b1c73532SDimitry Andric       SuccsSwapped ? ExitWeight1 : LoopBackWeight,
392b1c73532SDimitry Andric   };
393ac9a064cSDimitry Andric   setBranchWeights(LoopBI, LoopBIWeights, /*IsExpected=*/false);
394b1c73532SDimitry Andric   if (HasConditionalPreHeader) {
395b1c73532SDimitry Andric     const uint32_t PreHeaderBIWeights[] = {
396b1c73532SDimitry Andric         SuccsSwapped ? EnterWeight : ExitWeight0,
397b1c73532SDimitry Andric         SuccsSwapped ? ExitWeight0 : EnterWeight,
398b1c73532SDimitry Andric     };
399ac9a064cSDimitry Andric     setBranchWeights(PreHeaderBI, PreHeaderBIWeights, /*IsExpected=*/false);
400b1c73532SDimitry Andric   }
401b1c73532SDimitry Andric }
402b1c73532SDimitry Andric 
403eb11fae6SDimitry Andric /// Rotate loop LP. Return true if the loop is rotated.
404eb11fae6SDimitry Andric ///
405eb11fae6SDimitry Andric /// \param SimplifiedLatch is true if the latch was just folded into the final
406eb11fae6SDimitry Andric /// loop exit. In this case we may want to rotate even though the new latch is
407eb11fae6SDimitry Andric /// now an exiting branch. This rotation would have happened had the latch not
408eb11fae6SDimitry Andric /// been simplified. However, if SimplifiedLatch is false, then we avoid
409eb11fae6SDimitry Andric /// rotating loops in which the latch exits to avoid excessive or endless
410eb11fae6SDimitry Andric /// rotation. LoopRotate should be repeatable and converge to a canonical
411eb11fae6SDimitry Andric /// form. This property is satisfied because simplifying the loop latch can only
412eb11fae6SDimitry Andric /// happen once across multiple invocations of the LoopRotate pass.
413cfca06d7SDimitry Andric ///
414cfca06d7SDimitry Andric /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
415cfca06d7SDimitry Andric /// so to reach a suitable (non-deoptimizing) exit.
rotateLoop(Loop * L,bool SimplifiedLatch)416eb11fae6SDimitry Andric bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
417eb11fae6SDimitry Andric   // If the loop has only one block then there is not much to rotate.
418eb11fae6SDimitry Andric   if (L->getBlocks().size() == 1)
419eb11fae6SDimitry Andric     return false;
420eb11fae6SDimitry Andric 
421cfca06d7SDimitry Andric   bool Rotated = false;
422cfca06d7SDimitry Andric   do {
423eb11fae6SDimitry Andric     BasicBlock *OrigHeader = L->getHeader();
424eb11fae6SDimitry Andric     BasicBlock *OrigLatch = L->getLoopLatch();
425eb11fae6SDimitry Andric 
426eb11fae6SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
427eb11fae6SDimitry Andric     if (!BI || BI->isUnconditional())
428cfca06d7SDimitry Andric       return Rotated;
429eb11fae6SDimitry Andric 
430eb11fae6SDimitry Andric     // If the loop header is not one of the loop exiting blocks then
431eb11fae6SDimitry Andric     // either this loop is already rotated or it is not
432eb11fae6SDimitry Andric     // suitable for loop rotation transformations.
433eb11fae6SDimitry Andric     if (!L->isLoopExiting(OrigHeader))
434cfca06d7SDimitry Andric       return Rotated;
435eb11fae6SDimitry Andric 
436eb11fae6SDimitry Andric     // If the loop latch already contains a branch that leaves the loop then the
437eb11fae6SDimitry Andric     // loop is already rotated.
438eb11fae6SDimitry Andric     if (!OrigLatch)
439cfca06d7SDimitry Andric       return Rotated;
440eb11fae6SDimitry Andric 
441eb11fae6SDimitry Andric     // Rotate if either the loop latch does *not* exit the loop, or if the loop
442eb11fae6SDimitry Andric     // latch was just simplified. Or if we think it will be profitable.
443eb11fae6SDimitry Andric     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
444cfca06d7SDimitry Andric         !profitableToRotateLoopExitingLatch(L) &&
445cfca06d7SDimitry Andric         !canRotateDeoptimizingLatchExit(L))
446cfca06d7SDimitry Andric       return Rotated;
447eb11fae6SDimitry Andric 
448eb11fae6SDimitry Andric     // Check size of original header and reject loop if it is very big or we can't
449eb11fae6SDimitry Andric     // duplicate blocks inside it.
450eb11fae6SDimitry Andric     {
451eb11fae6SDimitry Andric       SmallPtrSet<const Value *, 32> EphValues;
452eb11fae6SDimitry Andric       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
453eb11fae6SDimitry Andric 
454eb11fae6SDimitry Andric       CodeMetrics Metrics;
455b60736ecSDimitry Andric       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
456eb11fae6SDimitry Andric       if (Metrics.notDuplicatable) {
457eb11fae6SDimitry Andric         LLVM_DEBUG(
458eb11fae6SDimitry Andric                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
459eb11fae6SDimitry Andric                    << " instructions: ";
460eb11fae6SDimitry Andric                    L->dump());
461cfca06d7SDimitry Andric         return Rotated;
462eb11fae6SDimitry Andric       }
463ac9a064cSDimitry Andric       if (Metrics.Convergence != ConvergenceKind::None) {
464eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
465eb11fae6SDimitry Andric                    "instructions: ";
466eb11fae6SDimitry Andric                    L->dump());
467cfca06d7SDimitry Andric         return Rotated;
468eb11fae6SDimitry Andric       }
469145449b1SDimitry Andric       if (!Metrics.NumInsts.isValid()) {
470145449b1SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
471145449b1SDimitry Andric                    " with invalid cost: ";
472145449b1SDimitry Andric                    L->dump());
473145449b1SDimitry Andric         return Rotated;
474145449b1SDimitry Andric       }
475e3b55780SDimitry Andric       if (Metrics.NumInsts > MaxHeaderSize) {
476cfca06d7SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
477cfca06d7SDimitry Andric                           << Metrics.NumInsts
478cfca06d7SDimitry Andric                           << " instructions, which is more than the threshold ("
479cfca06d7SDimitry Andric                           << MaxHeaderSize << " instructions): ";
480cfca06d7SDimitry Andric                    L->dump());
481b60736ecSDimitry Andric         ++NumNotRotatedDueToHeaderSize;
482cfca06d7SDimitry Andric         return Rotated;
483cfca06d7SDimitry Andric       }
484b60736ecSDimitry Andric 
485b60736ecSDimitry Andric       // When preparing for LTO, avoid rotating loops with calls that could be
486b60736ecSDimitry Andric       // inlined during the LTO stage.
487b60736ecSDimitry Andric       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
488b60736ecSDimitry Andric         return Rotated;
489eb11fae6SDimitry Andric     }
490eb11fae6SDimitry Andric 
491eb11fae6SDimitry Andric     // Now, this loop is suitable for rotation.
492eb11fae6SDimitry Andric     BasicBlock *OrigPreheader = L->getLoopPreheader();
493eb11fae6SDimitry Andric 
494eb11fae6SDimitry Andric     // If the loop could not be converted to canonical form, it must have an
495eb11fae6SDimitry Andric     // indirectbr in it, just give up.
496eb11fae6SDimitry Andric     if (!OrigPreheader || !L->hasDedicatedExits())
497cfca06d7SDimitry Andric       return Rotated;
498eb11fae6SDimitry Andric 
499eb11fae6SDimitry Andric     // Anything ScalarEvolution may know about this loop or the PHI nodes
500eb11fae6SDimitry Andric     // in its header will soon be invalidated. We should also invalidate
501eb11fae6SDimitry Andric     // all outer loops because insertion and deletion of blocks that happens
502eb11fae6SDimitry Andric     // during the rotation may violate invariants related to backedge taken
503eb11fae6SDimitry Andric     // infos in them.
504e3b55780SDimitry Andric     if (SE) {
505eb11fae6SDimitry Andric       SE->forgetTopmostLoop(L);
506e3b55780SDimitry Andric       // We may hoist some instructions out of loop. In case if they were cached
507e3b55780SDimitry Andric       // as "loop variant" or "loop computable", these caches must be dropped.
508e3b55780SDimitry Andric       // We also may fold basic blocks, so cached block dispositions also need
509e3b55780SDimitry Andric       // to be dropped.
510e3b55780SDimitry Andric       SE->forgetBlockAndLoopDispositions();
511e3b55780SDimitry Andric     }
512eb11fae6SDimitry Andric 
513eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
514d8e91e46SDimitry Andric     if (MSSAU && VerifyMemorySSA)
515d8e91e46SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
516eb11fae6SDimitry Andric 
517eb11fae6SDimitry Andric     // Find new Loop header. NewHeader is a Header's one and only successor
518eb11fae6SDimitry Andric     // that is inside loop.  Header's other successor is outside the
519eb11fae6SDimitry Andric     // loop.  Otherwise loop is not suitable for rotation.
520eb11fae6SDimitry Andric     BasicBlock *Exit = BI->getSuccessor(0);
521eb11fae6SDimitry Andric     BasicBlock *NewHeader = BI->getSuccessor(1);
522b1c73532SDimitry Andric     bool BISuccsSwapped = L->contains(Exit);
523b1c73532SDimitry Andric     if (BISuccsSwapped)
524eb11fae6SDimitry Andric       std::swap(Exit, NewHeader);
525eb11fae6SDimitry Andric     assert(NewHeader && "Unable to determine new loop header");
526eb11fae6SDimitry Andric     assert(L->contains(NewHeader) && !L->contains(Exit) &&
527eb11fae6SDimitry Andric            "Unable to determine loop header and exit blocks");
528eb11fae6SDimitry Andric 
529eb11fae6SDimitry Andric     // This code assumes that the new header has exactly one predecessor.
530eb11fae6SDimitry Andric     // Remove any single-entry PHI nodes in it.
531eb11fae6SDimitry Andric     assert(NewHeader->getSinglePredecessor() &&
532eb11fae6SDimitry Andric            "New header doesn't have one pred!");
533eb11fae6SDimitry Andric     FoldSingleEntryPHINodes(NewHeader);
534eb11fae6SDimitry Andric 
535eb11fae6SDimitry Andric     // Begin by walking OrigHeader and populating ValueMap with an entry for
536eb11fae6SDimitry Andric     // each Instruction.
537eb11fae6SDimitry Andric     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
538e6d15924SDimitry Andric     ValueToValueMapTy ValueMap, ValueMapMSSA;
539eb11fae6SDimitry Andric 
540eb11fae6SDimitry Andric     // For PHI nodes, the value available in OldPreHeader is just the
541eb11fae6SDimitry Andric     // incoming value from OldPreHeader.
542eb11fae6SDimitry Andric     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
543706b4fc4SDimitry Andric       InsertNewValueIntoMap(ValueMap, PN,
544706b4fc4SDimitry Andric                             PN->getIncomingValueForBlock(OrigPreheader));
545eb11fae6SDimitry Andric 
546eb11fae6SDimitry Andric     // For the rest of the instructions, either hoist to the OrigPreheader if
547eb11fae6SDimitry Andric     // possible or create a clone in the OldPreHeader if not.
548d8e91e46SDimitry Andric     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
549eb11fae6SDimitry Andric 
550344a3780SDimitry Andric     // Record all debug intrinsics preceding LoopEntryBranch to avoid
551344a3780SDimitry Andric     // duplication.
552eb11fae6SDimitry Andric     using DbgIntrinsicHash =
553344a3780SDimitry Andric         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
554b1c73532SDimitry Andric     auto makeHash = [](auto *D) -> DbgIntrinsicHash {
555344a3780SDimitry Andric       auto VarLocOps = D->location_ops();
556344a3780SDimitry Andric       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
557344a3780SDimitry Andric                D->getVariable()},
558344a3780SDimitry Andric               D->getExpression()};
559eb11fae6SDimitry Andric     };
560b1c73532SDimitry Andric 
561eb11fae6SDimitry Andric     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
562c0981da4SDimitry Andric     for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
563b1c73532SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
564eb11fae6SDimitry Andric         DbgIntrinsics.insert(makeHash(DII));
565ac9a064cSDimitry Andric         // Until RemoveDIs supports dbg.declares in DbgVariableRecord format,
566ac9a064cSDimitry Andric         // we'll need to collect DbgVariableRecords attached to any other debug
567ac9a064cSDimitry Andric         // intrinsics.
568ac9a064cSDimitry Andric         for (const DbgVariableRecord &DVR :
569ac9a064cSDimitry Andric              filterDbgVars(DII->getDbgRecordRange()))
570ac9a064cSDimitry Andric           DbgIntrinsics.insert(makeHash(&DVR));
571b1c73532SDimitry Andric       } else {
572eb11fae6SDimitry Andric         break;
573eb11fae6SDimitry Andric       }
574b1c73532SDimitry Andric     }
575b1c73532SDimitry Andric 
576ac9a064cSDimitry Andric     // Build DbgVariableRecord hashes for DbgVariableRecords attached to the
577ac9a064cSDimitry Andric     // terminator, which isn't considered in the loop above.
578ac9a064cSDimitry Andric     for (const DbgVariableRecord &DVR :
579ac9a064cSDimitry Andric          filterDbgVars(OrigPreheader->getTerminator()->getDbgRecordRange()))
580ac9a064cSDimitry Andric       DbgIntrinsics.insert(makeHash(&DVR));
581eb11fae6SDimitry Andric 
582b60736ecSDimitry Andric     // Remember the local noalias scope declarations in the header. After the
583b60736ecSDimitry Andric     // rotation, they must be duplicated and the scope must be cloned. This
584b60736ecSDimitry Andric     // avoids unwanted interaction across iterations.
585b60736ecSDimitry Andric     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
586b60736ecSDimitry Andric     for (Instruction &I : *OrigHeader)
587b60736ecSDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
588b60736ecSDimitry Andric         NoAliasDeclInstructions.push_back(Decl);
589b60736ecSDimitry Andric 
590b1c73532SDimitry Andric     Module *M = OrigHeader->getModule();
591b1c73532SDimitry Andric 
592ac9a064cSDimitry Andric     // Track the next DbgRecord to clone. If we have a sequence where an
593b1c73532SDimitry Andric     // instruction is hoisted instead of being cloned:
594ac9a064cSDimitry Andric     //    DbgRecord blah
595b1c73532SDimitry Andric     //    %foo = add i32 0, 0
596ac9a064cSDimitry Andric     //    DbgRecord xyzzy
597b1c73532SDimitry Andric     //    %bar = call i32 @foobar()
598ac9a064cSDimitry Andric     // where %foo is hoisted, then the DbgRecord "blah" will be seen twice, once
599b1c73532SDimitry Andric     // attached to %foo, then when %foo his hoisted it will "fall down" onto the
600b1c73532SDimitry Andric     // function call:
601ac9a064cSDimitry Andric     //    DbgRecord blah
602ac9a064cSDimitry Andric     //    DbgRecord xyzzy
603b1c73532SDimitry Andric     //    %bar = call i32 @foobar()
604b1c73532SDimitry Andric     // causing it to appear attached to the call too.
605b1c73532SDimitry Andric     //
606b1c73532SDimitry Andric     // To avoid this, cloneDebugInfoFrom takes an optional "start cloning from
607ac9a064cSDimitry Andric     // here" position to account for this behaviour. We point it at any
608ac9a064cSDimitry Andric     // DbgRecords on the next instruction, here labelled xyzzy, before we hoist
609ac9a064cSDimitry Andric     // %foo. Later, we only only clone DbgRecords from that position (xyzzy)
610ac9a064cSDimitry Andric     // onwards, which avoids cloning DbgRecord "blah" multiple times. (Stored as
611ac9a064cSDimitry Andric     // a range because it gives us a natural way of testing whether
612ac9a064cSDimitry Andric     //  there were DbgRecords on the next instruction before we hoisted things).
613ac9a064cSDimitry Andric     iterator_range<DbgRecord::self_iterator> NextDbgInsts =
614ac9a064cSDimitry Andric         (I != E) ? I->getDbgRecordRange() : DbgMarker::getEmptyDbgRecordRange();
615b1c73532SDimitry Andric 
616eb11fae6SDimitry Andric     while (I != E) {
617eb11fae6SDimitry Andric       Instruction *Inst = &*I++;
618eb11fae6SDimitry Andric 
619eb11fae6SDimitry Andric       // If the instruction's operands are invariant and it doesn't read or write
620eb11fae6SDimitry Andric       // memory, then it is safe to hoist.  Doing this doesn't change the order of
621eb11fae6SDimitry Andric       // execution in the preheader, but does prevent the instruction from
622eb11fae6SDimitry Andric       // executing in each iteration of the loop.  This means it is safe to hoist
623eb11fae6SDimitry Andric       // something that might trap, but isn't safe to hoist something that reads
624eb11fae6SDimitry Andric       // memory (without proving that the loop doesn't write).
625eb11fae6SDimitry Andric       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
626d8e91e46SDimitry Andric           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
627ac9a064cSDimitry Andric           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst) &&
628ac9a064cSDimitry Andric           // It is not safe to hoist the value of these instructions in
629ac9a064cSDimitry Andric           // coroutines, as the addresses of otherwise eligible variables (e.g.
630ac9a064cSDimitry Andric           // thread-local variables and errno) may change if the coroutine is
631ac9a064cSDimitry Andric           // resumed in a different thread.Therefore, we disable this
632ac9a064cSDimitry Andric           // optimization for correctness. However, this may block other correct
633ac9a064cSDimitry Andric           // optimizations.
634ac9a064cSDimitry Andric           // FIXME: This should be reverted once we have a better model for
635ac9a064cSDimitry Andric           // memory access in coroutines.
636ac9a064cSDimitry Andric           !Inst->getFunction()->isPresplitCoroutine()) {
637b1c73532SDimitry Andric 
638ac9a064cSDimitry Andric         if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat &&
639ac9a064cSDimitry Andric             !NextDbgInsts.empty()) {
640b1c73532SDimitry Andric           auto DbgValueRange =
641ac9a064cSDimitry Andric               LoopEntryBranch->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
642ac9a064cSDimitry Andric           RemapDbgRecordRange(M, DbgValueRange, ValueMap,
643b1c73532SDimitry Andric                               RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
644b1c73532SDimitry Andric           // Erase anything we've seen before.
645ac9a064cSDimitry Andric           for (DbgVariableRecord &DVR :
646ac9a064cSDimitry Andric                make_early_inc_range(filterDbgVars(DbgValueRange)))
647ac9a064cSDimitry Andric             if (DbgIntrinsics.count(makeHash(&DVR)))
648ac9a064cSDimitry Andric               DVR.eraseFromParent();
649b1c73532SDimitry Andric         }
650b1c73532SDimitry Andric 
651ac9a064cSDimitry Andric         NextDbgInsts = I->getDbgRecordRange();
652ac9a064cSDimitry Andric 
653eb11fae6SDimitry Andric         Inst->moveBefore(LoopEntryBranch);
654b1c73532SDimitry Andric 
655344a3780SDimitry Andric         ++NumInstrsHoisted;
656eb11fae6SDimitry Andric         continue;
657eb11fae6SDimitry Andric       }
658eb11fae6SDimitry Andric 
659eb11fae6SDimitry Andric       // Otherwise, create a duplicate of the instruction.
660eb11fae6SDimitry Andric       Instruction *C = Inst->clone();
6617fa27ce4SDimitry Andric       C->insertBefore(LoopEntryBranch);
6627fa27ce4SDimitry Andric 
663344a3780SDimitry Andric       ++NumInstrsDuplicated;
664eb11fae6SDimitry Andric 
665ac9a064cSDimitry Andric       if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat &&
666ac9a064cSDimitry Andric           !NextDbgInsts.empty()) {
667ac9a064cSDimitry Andric         auto Range = C->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
668ac9a064cSDimitry Andric         RemapDbgRecordRange(M, Range, ValueMap,
669b1c73532SDimitry Andric                             RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
670ac9a064cSDimitry Andric         NextDbgInsts = DbgMarker::getEmptyDbgRecordRange();
671b1c73532SDimitry Andric         // Erase anything we've seen before.
672ac9a064cSDimitry Andric         for (DbgVariableRecord &DVR :
673ac9a064cSDimitry Andric              make_early_inc_range(filterDbgVars(Range)))
674ac9a064cSDimitry Andric           if (DbgIntrinsics.count(makeHash(&DVR)))
675ac9a064cSDimitry Andric             DVR.eraseFromParent();
676b1c73532SDimitry Andric       }
677b1c73532SDimitry Andric 
678eb11fae6SDimitry Andric       // Eagerly remap the operands of the instruction.
679eb11fae6SDimitry Andric       RemapInstruction(C, ValueMap,
680eb11fae6SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
681eb11fae6SDimitry Andric 
682eb11fae6SDimitry Andric       // Avoid inserting the same intrinsic twice.
683d8e91e46SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
684eb11fae6SDimitry Andric         if (DbgIntrinsics.count(makeHash(DII))) {
6857fa27ce4SDimitry Andric           C->eraseFromParent();
686eb11fae6SDimitry Andric           continue;
687eb11fae6SDimitry Andric         }
688eb11fae6SDimitry Andric 
689eb11fae6SDimitry Andric       // With the operands remapped, see if the instruction constant folds or is
690eb11fae6SDimitry Andric       // otherwise simplifyable.  This commonly occurs because the entry from PHI
691eb11fae6SDimitry Andric       // nodes allows icmps and other instructions to fold.
692145449b1SDimitry Andric       Value *V = simplifyInstruction(C, SQ);
693eb11fae6SDimitry Andric       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
694eb11fae6SDimitry Andric         // If so, then delete the temporary instruction and stick the folded value
695eb11fae6SDimitry Andric         // in the map.
696706b4fc4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, V);
697eb11fae6SDimitry Andric         if (!C->mayHaveSideEffects()) {
6987fa27ce4SDimitry Andric           C->eraseFromParent();
699eb11fae6SDimitry Andric           C = nullptr;
700eb11fae6SDimitry Andric         }
701eb11fae6SDimitry Andric       } else {
702706b4fc4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, C);
703eb11fae6SDimitry Andric       }
704eb11fae6SDimitry Andric       if (C) {
705eb11fae6SDimitry Andric         // Otherwise, stick the new instruction into the new block!
706eb11fae6SDimitry Andric         C->setName(Inst->getName());
707eb11fae6SDimitry Andric 
708344a3780SDimitry Andric         if (auto *II = dyn_cast<AssumeInst>(C))
709eb11fae6SDimitry Andric           AC->registerAssumption(II);
710e6d15924SDimitry Andric         // MemorySSA cares whether the cloned instruction was inserted or not, and
711e6d15924SDimitry Andric         // not whether it can be remapped to a simplified value.
712706b4fc4SDimitry Andric         if (MSSAU)
713706b4fc4SDimitry Andric           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
714eb11fae6SDimitry Andric       }
715eb11fae6SDimitry Andric     }
716eb11fae6SDimitry Andric 
717b60736ecSDimitry Andric     if (!NoAliasDeclInstructions.empty()) {
718b60736ecSDimitry Andric       // There are noalias scope declarations:
719b60736ecSDimitry Andric       // (general):
720b60736ecSDimitry Andric       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
721b60736ecSDimitry Andric       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
722b60736ecSDimitry Andric       //
723b60736ecSDimitry Andric       // with D: llvm.experimental.noalias.scope.decl,
724b60736ecSDimitry Andric       //      U: !noalias or !alias.scope depending on D
725b60736ecSDimitry Andric       //       ... { D U1 U2 }   can transform into:
726b60736ecSDimitry Andric       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
727b60736ecSDimitry Andric       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
728b60736ecSDimitry Andric       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
729b60736ecSDimitry Andric       //
730b60736ecSDimitry Andric       // We now want to transform:
731b60736ecSDimitry Andric       // (1) -> : ... D' { D U1 U2 D'' }
732b60736ecSDimitry Andric       // (2) -> : ... D' U1' { D U2 D'' U1'' }
733b60736ecSDimitry Andric       // D: original llvm.experimental.noalias.scope.decl
734b60736ecSDimitry Andric       // D', U1': duplicate with replaced scopes
735b60736ecSDimitry Andric       // D'', U1'': different duplicate with replaced scopes
736b60736ecSDimitry Andric       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
737b60736ecSDimitry Andric       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
738b60736ecSDimitry Andric 
739b60736ecSDimitry Andric       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
740312c0ed1SDimitry Andric       BasicBlock::iterator NewHeaderInsertionPoint =
741312c0ed1SDimitry Andric           NewHeader->getFirstNonPHIIt();
742b60736ecSDimitry Andric       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
743b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
744b60736ecSDimitry Andric                           << *NAD << "\n");
745b60736ecSDimitry Andric         Instruction *NewNAD = NAD->clone();
746312c0ed1SDimitry Andric         NewNAD->insertBefore(*NewHeader, NewHeaderInsertionPoint);
747b60736ecSDimitry Andric       }
748b60736ecSDimitry Andric 
749b60736ecSDimitry Andric       // Scopes must now be duplicated, once for OrigHeader and once for
750b60736ecSDimitry Andric       // OrigPreHeader'.
751b60736ecSDimitry Andric       {
752b60736ecSDimitry Andric         auto &Context = NewHeader->getContext();
753b60736ecSDimitry Andric 
754b60736ecSDimitry Andric         SmallVector<MDNode *, 8> NoAliasDeclScopes;
755b60736ecSDimitry Andric         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
756b60736ecSDimitry Andric           NoAliasDeclScopes.push_back(NAD->getScopeList());
757b60736ecSDimitry Andric 
758b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
759b60736ecSDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
760b60736ecSDimitry Andric                                    "h.rot");
761b60736ecSDimitry Andric         LLVM_DEBUG(OrigHeader->dump());
762b60736ecSDimitry Andric 
763b60736ecSDimitry Andric         // Keep the compile time impact low by only adapting the inserted block
764b60736ecSDimitry Andric         // of instructions in the OrigPreHeader. This might result in slightly
765b60736ecSDimitry Andric         // more aliasing between these instructions and those that were already
766b60736ecSDimitry Andric         // present, but it will be much faster when the original PreHeader is
767b60736ecSDimitry Andric         // large.
768b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
769b60736ecSDimitry Andric         auto *FirstDecl =
770b60736ecSDimitry Andric             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
771b60736ecSDimitry Andric         auto *LastInst = &OrigPreheader->back();
772b60736ecSDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
773b60736ecSDimitry Andric                                    Context, "pre.rot");
774b60736ecSDimitry Andric         LLVM_DEBUG(OrigPreheader->dump());
775b60736ecSDimitry Andric 
776b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
777b60736ecSDimitry Andric         LLVM_DEBUG(NewHeader->dump());
778b60736ecSDimitry Andric       }
779b60736ecSDimitry Andric     }
780b60736ecSDimitry Andric 
781eb11fae6SDimitry Andric     // Along with all the other instructions, we just cloned OrigHeader's
782eb11fae6SDimitry Andric     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
783eb11fae6SDimitry Andric     // successors by duplicating their incoming values for OrigHeader.
784d8e91e46SDimitry Andric     for (BasicBlock *SuccBB : successors(OrigHeader))
785eb11fae6SDimitry Andric       for (BasicBlock::iterator BI = SuccBB->begin();
786eb11fae6SDimitry Andric            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
787eb11fae6SDimitry Andric         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
788eb11fae6SDimitry Andric 
789eb11fae6SDimitry Andric     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
790eb11fae6SDimitry Andric     // OrigPreHeader's old terminator (the original branch into the loop), and
791eb11fae6SDimitry Andric     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
792eb11fae6SDimitry Andric     LoopEntryBranch->eraseFromParent();
793ac9a064cSDimitry Andric     OrigPreheader->flushTerminatorDbgRecords();
794eb11fae6SDimitry Andric 
795d8e91e46SDimitry Andric     // Update MemorySSA before the rewrite call below changes the 1:1
796e6d15924SDimitry Andric     // instruction:cloned_instruction_or_value mapping.
797d8e91e46SDimitry Andric     if (MSSAU) {
798706b4fc4SDimitry Andric       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
799e6d15924SDimitry Andric       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
800e6d15924SDimitry Andric                                           ValueMapMSSA);
801d8e91e46SDimitry Andric     }
802eb11fae6SDimitry Andric 
803eb11fae6SDimitry Andric     SmallVector<PHINode*, 2> InsertedPHIs;
804eb11fae6SDimitry Andric     // If there were any uses of instructions in the duplicated block outside the
805eb11fae6SDimitry Andric     // loop, update them, inserting PHI nodes as required
806c0981da4SDimitry Andric     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
807eb11fae6SDimitry Andric                                     &InsertedPHIs);
808eb11fae6SDimitry Andric 
809eb11fae6SDimitry Andric     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
810eb11fae6SDimitry Andric     // previously had debug metadata attached. This keeps the debug info
811eb11fae6SDimitry Andric     // up-to-date in the loop body.
812eb11fae6SDimitry Andric     if (!InsertedPHIs.empty())
813eb11fae6SDimitry Andric       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
814eb11fae6SDimitry Andric 
815eb11fae6SDimitry Andric     // NewHeader is now the header of the loop.
816eb11fae6SDimitry Andric     L->moveToHeader(NewHeader);
817eb11fae6SDimitry Andric     assert(L->getHeader() == NewHeader && "Latch block is our new header");
818eb11fae6SDimitry Andric 
819eb11fae6SDimitry Andric     // Inform DT about changes to the CFG.
820eb11fae6SDimitry Andric     if (DT) {
821eb11fae6SDimitry Andric       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
822eb11fae6SDimitry Andric       // the DT about the removed edge to the OrigHeader (that got removed).
823eb11fae6SDimitry Andric       SmallVector<DominatorTree::UpdateType, 3> Updates;
824eb11fae6SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
825eb11fae6SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
826eb11fae6SDimitry Andric       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
827d8e91e46SDimitry Andric 
828d8e91e46SDimitry Andric       if (MSSAU) {
829b60736ecSDimitry Andric         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
830d8e91e46SDimitry Andric         if (VerifyMemorySSA)
831d8e91e46SDimitry Andric           MSSAU->getMemorySSA()->verifyMemorySSA();
832b60736ecSDimitry Andric       } else {
833b60736ecSDimitry Andric         DT->applyUpdates(Updates);
834d8e91e46SDimitry Andric       }
835eb11fae6SDimitry Andric     }
836eb11fae6SDimitry Andric 
837eb11fae6SDimitry Andric     // At this point, we've finished our major CFG changes.  As part of cloning
838eb11fae6SDimitry Andric     // the loop into the preheader we've simplified instructions and the
839eb11fae6SDimitry Andric     // duplicated conditional branch may now be branching on a constant.  If it is
840eb11fae6SDimitry Andric     // branching on a constant and if that constant means that we enter the loop,
841eb11fae6SDimitry Andric     // then we fold away the cond branch to an uncond branch.  This simplifies the
842eb11fae6SDimitry Andric     // loop in cases important for nested loops, and it also means we don't have
843eb11fae6SDimitry Andric     // to split as many edges.
844eb11fae6SDimitry Andric     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
845eb11fae6SDimitry Andric     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
846b1c73532SDimitry Andric     const Value *Cond = PHBI->getCondition();
847b1c73532SDimitry Andric     const bool HasConditionalPreHeader =
848b1c73532SDimitry Andric         !isa<ConstantInt>(Cond) ||
849b1c73532SDimitry Andric         PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
850b1c73532SDimitry Andric 
851b1c73532SDimitry Andric     updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
852b1c73532SDimitry Andric 
853b1c73532SDimitry Andric     if (HasConditionalPreHeader) {
854eb11fae6SDimitry Andric       // The conditional branch can't be folded, handle the general case.
855eb11fae6SDimitry Andric       // Split edges as necessary to preserve LoopSimplify form.
856eb11fae6SDimitry Andric 
857eb11fae6SDimitry Andric       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
858eb11fae6SDimitry Andric       // thus is not a preheader anymore.
859eb11fae6SDimitry Andric       // Split the edge to form a real preheader.
860eb11fae6SDimitry Andric       BasicBlock *NewPH = SplitCriticalEdge(
861eb11fae6SDimitry Andric                                             OrigPreheader, NewHeader,
862d8e91e46SDimitry Andric                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
863eb11fae6SDimitry Andric       NewPH->setName(NewHeader->getName() + ".lr.ph");
864eb11fae6SDimitry Andric 
865eb11fae6SDimitry Andric       // Preserve canonical loop form, which means that 'Exit' should have only
866eb11fae6SDimitry Andric       // one predecessor. Note that Exit could be an exit block for multiple
867eb11fae6SDimitry Andric       // nested loops, causing both of the edges to now be critical and need to
868eb11fae6SDimitry Andric       // be split.
869c0981da4SDimitry Andric       SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
870eb11fae6SDimitry Andric       bool SplitLatchEdge = false;
871eb11fae6SDimitry Andric       for (BasicBlock *ExitPred : ExitPreds) {
872eb11fae6SDimitry Andric         // We only need to split loop exit edges.
873eb11fae6SDimitry Andric         Loop *PredLoop = LI->getLoopFor(ExitPred);
874e6d15924SDimitry Andric         if (!PredLoop || PredLoop->contains(Exit) ||
8754b4fe385SDimitry Andric             isa<IndirectBrInst>(ExitPred->getTerminator()))
876eb11fae6SDimitry Andric           continue;
877eb11fae6SDimitry Andric         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
878eb11fae6SDimitry Andric         BasicBlock *ExitSplit = SplitCriticalEdge(
879eb11fae6SDimitry Andric                                                   ExitPred, Exit,
880d8e91e46SDimitry Andric                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
881eb11fae6SDimitry Andric         ExitSplit->moveBefore(Exit);
882eb11fae6SDimitry Andric       }
883eb11fae6SDimitry Andric       assert(SplitLatchEdge &&
884eb11fae6SDimitry Andric              "Despite splitting all preds, failed to split latch exit?");
885344a3780SDimitry Andric       (void)SplitLatchEdge;
886eb11fae6SDimitry Andric     } else {
887eb11fae6SDimitry Andric       // We can fold the conditional branch in the preheader, this makes things
888eb11fae6SDimitry Andric       // simpler. The first step is to remove the extra edge to the Exit block.
889eb11fae6SDimitry Andric       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
890ac9a064cSDimitry Andric       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI->getIterator());
891eb11fae6SDimitry Andric       NewBI->setDebugLoc(PHBI->getDebugLoc());
892eb11fae6SDimitry Andric       PHBI->eraseFromParent();
893eb11fae6SDimitry Andric 
894eb11fae6SDimitry Andric       // With our CFG finalized, update DomTree if it is available.
895eb11fae6SDimitry Andric       if (DT) DT->deleteEdge(OrigPreheader, Exit);
896d8e91e46SDimitry Andric 
897d8e91e46SDimitry Andric       // Update MSSA too, if available.
898d8e91e46SDimitry Andric       if (MSSAU)
899d8e91e46SDimitry Andric         MSSAU->removeEdge(OrigPreheader, Exit);
900eb11fae6SDimitry Andric     }
901eb11fae6SDimitry Andric 
902eb11fae6SDimitry Andric     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
903eb11fae6SDimitry Andric     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
904eb11fae6SDimitry Andric 
905d8e91e46SDimitry Andric     if (MSSAU && VerifyMemorySSA)
906d8e91e46SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
907d8e91e46SDimitry Andric 
908eb11fae6SDimitry Andric     // Now that the CFG and DomTree are in a consistent state again, try to merge
909eb11fae6SDimitry Andric     // the OrigHeader block into OrigLatch.  This will succeed if they are
910eb11fae6SDimitry Andric     // connected by an unconditional branch.  This is just a cleanup so the
911eb11fae6SDimitry Andric     // emitted code isn't too gross in this common case.
912d8e91e46SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
913b60736ecSDimitry Andric     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
914b60736ecSDimitry Andric     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
915b60736ecSDimitry Andric     if (DidMerge)
916b60736ecSDimitry Andric       RemoveRedundantDbgInstrs(PredBB);
917d8e91e46SDimitry Andric 
918d8e91e46SDimitry Andric     if (MSSAU && VerifyMemorySSA)
919d8e91e46SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
920eb11fae6SDimitry Andric 
921eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
922eb11fae6SDimitry Andric 
923eb11fae6SDimitry Andric     ++NumRotated;
924cfca06d7SDimitry Andric 
925cfca06d7SDimitry Andric     Rotated = true;
926cfca06d7SDimitry Andric     SimplifiedLatch = false;
927cfca06d7SDimitry Andric 
928cfca06d7SDimitry Andric     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
929cfca06d7SDimitry Andric     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
930cfca06d7SDimitry Andric     // TODO: if it becomes a performance bottleneck extend rotation algorithm
931cfca06d7SDimitry Andric     // to handle multiple rotations in one go.
932cfca06d7SDimitry Andric   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
933cfca06d7SDimitry Andric 
934cfca06d7SDimitry Andric 
935eb11fae6SDimitry Andric   return true;
936eb11fae6SDimitry Andric }
937eb11fae6SDimitry Andric 
938eb11fae6SDimitry Andric /// Determine whether the instructions in this range may be safely and cheaply
939eb11fae6SDimitry Andric /// speculated. This is not an important enough situation to develop complex
940eb11fae6SDimitry Andric /// heuristics. We handle a single arithmetic instruction along with any type
941eb11fae6SDimitry Andric /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)942eb11fae6SDimitry Andric static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
943eb11fae6SDimitry Andric                                   BasicBlock::iterator End, Loop *L) {
944eb11fae6SDimitry Andric   bool seenIncrement = false;
945eb11fae6SDimitry Andric   bool MultiExitLoop = false;
946eb11fae6SDimitry Andric 
947eb11fae6SDimitry Andric   if (!L->getExitingBlock())
948eb11fae6SDimitry Andric     MultiExitLoop = true;
949eb11fae6SDimitry Andric 
950eb11fae6SDimitry Andric   for (BasicBlock::iterator I = Begin; I != End; ++I) {
951eb11fae6SDimitry Andric 
952eb11fae6SDimitry Andric     if (!isSafeToSpeculativelyExecute(&*I))
953eb11fae6SDimitry Andric       return false;
954eb11fae6SDimitry Andric 
955eb11fae6SDimitry Andric     if (isa<DbgInfoIntrinsic>(I))
956eb11fae6SDimitry Andric       continue;
957eb11fae6SDimitry Andric 
958eb11fae6SDimitry Andric     switch (I->getOpcode()) {
959eb11fae6SDimitry Andric     default:
960eb11fae6SDimitry Andric       return false;
961eb11fae6SDimitry Andric     case Instruction::GetElementPtr:
962eb11fae6SDimitry Andric       // GEPs are cheap if all indices are constant.
963eb11fae6SDimitry Andric       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
964eb11fae6SDimitry Andric         return false;
965eb11fae6SDimitry Andric       // fall-thru to increment case
966e3b55780SDimitry Andric       [[fallthrough]];
967eb11fae6SDimitry Andric     case Instruction::Add:
968eb11fae6SDimitry Andric     case Instruction::Sub:
969eb11fae6SDimitry Andric     case Instruction::And:
970eb11fae6SDimitry Andric     case Instruction::Or:
971eb11fae6SDimitry Andric     case Instruction::Xor:
972eb11fae6SDimitry Andric     case Instruction::Shl:
973eb11fae6SDimitry Andric     case Instruction::LShr:
974eb11fae6SDimitry Andric     case Instruction::AShr: {
975eb11fae6SDimitry Andric       Value *IVOpnd =
976eb11fae6SDimitry Andric           !isa<Constant>(I->getOperand(0))
977eb11fae6SDimitry Andric               ? I->getOperand(0)
978eb11fae6SDimitry Andric               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
979eb11fae6SDimitry Andric       if (!IVOpnd)
980eb11fae6SDimitry Andric         return false;
981eb11fae6SDimitry Andric 
982eb11fae6SDimitry Andric       // If increment operand is used outside of the loop, this speculation
983eb11fae6SDimitry Andric       // could cause extra live range interference.
984eb11fae6SDimitry Andric       if (MultiExitLoop) {
985eb11fae6SDimitry Andric         for (User *UseI : IVOpnd->users()) {
986eb11fae6SDimitry Andric           auto *UserInst = cast<Instruction>(UseI);
987eb11fae6SDimitry Andric           if (!L->contains(UserInst))
988eb11fae6SDimitry Andric             return false;
989eb11fae6SDimitry Andric         }
990eb11fae6SDimitry Andric       }
991eb11fae6SDimitry Andric 
992eb11fae6SDimitry Andric       if (seenIncrement)
993eb11fae6SDimitry Andric         return false;
994eb11fae6SDimitry Andric       seenIncrement = true;
995eb11fae6SDimitry Andric       break;
996eb11fae6SDimitry Andric     }
997eb11fae6SDimitry Andric     case Instruction::Trunc:
998eb11fae6SDimitry Andric     case Instruction::ZExt:
999eb11fae6SDimitry Andric     case Instruction::SExt:
1000eb11fae6SDimitry Andric       // ignore type conversions
1001eb11fae6SDimitry Andric       break;
1002eb11fae6SDimitry Andric     }
1003eb11fae6SDimitry Andric   }
1004eb11fae6SDimitry Andric   return true;
1005eb11fae6SDimitry Andric }
1006eb11fae6SDimitry Andric 
1007eb11fae6SDimitry Andric /// Fold the loop tail into the loop exit by speculating the loop tail
1008eb11fae6SDimitry Andric /// instructions. Typically, this is a single post-increment. In the case of a
1009eb11fae6SDimitry Andric /// simple 2-block loop, hoisting the increment can be much better than
1010eb11fae6SDimitry Andric /// duplicating the entire loop header. In the case of loops with early exits,
1011eb11fae6SDimitry Andric /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
1012eb11fae6SDimitry Andric /// canonical form so downstream passes can handle it.
1013eb11fae6SDimitry Andric ///
1014eb11fae6SDimitry Andric /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)1015eb11fae6SDimitry Andric bool LoopRotate::simplifyLoopLatch(Loop *L) {
1016eb11fae6SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
1017eb11fae6SDimitry Andric   if (!Latch || Latch->hasAddressTaken())
1018eb11fae6SDimitry Andric     return false;
1019eb11fae6SDimitry Andric 
1020eb11fae6SDimitry Andric   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
1021eb11fae6SDimitry Andric   if (!Jmp || !Jmp->isUnconditional())
1022eb11fae6SDimitry Andric     return false;
1023eb11fae6SDimitry Andric 
1024eb11fae6SDimitry Andric   BasicBlock *LastExit = Latch->getSinglePredecessor();
1025eb11fae6SDimitry Andric   if (!LastExit || !L->isLoopExiting(LastExit))
1026eb11fae6SDimitry Andric     return false;
1027eb11fae6SDimitry Andric 
1028eb11fae6SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
1029eb11fae6SDimitry Andric   if (!BI)
1030eb11fae6SDimitry Andric     return false;
1031eb11fae6SDimitry Andric 
1032eb11fae6SDimitry Andric   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
1033eb11fae6SDimitry Andric     return false;
1034eb11fae6SDimitry Andric 
1035eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
1036eb11fae6SDimitry Andric                     << LastExit->getName() << "\n");
1037eb11fae6SDimitry Andric 
10381d5ae102SDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
10391d5ae102SDimitry Andric   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
10401d5ae102SDimitry Andric                             /*PredecessorWithTwoSuccessors=*/true);
1041d8e91e46SDimitry Andric 
1042e3b55780SDimitry Andric     if (SE) {
1043e3b55780SDimitry Andric       // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
1044e3b55780SDimitry Andric       SE->forgetBlockAndLoopDispositions();
1045e3b55780SDimitry Andric     }
1046e3b55780SDimitry Andric 
1047d8e91e46SDimitry Andric   if (MSSAU && VerifyMemorySSA)
1048d8e91e46SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
1049d8e91e46SDimitry Andric 
1050eb11fae6SDimitry Andric   return true;
1051eb11fae6SDimitry Andric }
1052eb11fae6SDimitry Andric 
1053eb11fae6SDimitry Andric /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)1054eb11fae6SDimitry Andric bool LoopRotate::processLoop(Loop *L) {
1055eb11fae6SDimitry Andric   // Save the loop metadata.
1056eb11fae6SDimitry Andric   MDNode *LoopMD = L->getLoopID();
1057eb11fae6SDimitry Andric 
1058eb11fae6SDimitry Andric   bool SimplifiedLatch = false;
1059eb11fae6SDimitry Andric 
1060eb11fae6SDimitry Andric   // Simplify the loop latch before attempting to rotate the header
1061eb11fae6SDimitry Andric   // upward. Rotation may not be needed if the loop tail can be folded into the
1062eb11fae6SDimitry Andric   // loop exit.
1063eb11fae6SDimitry Andric   if (!RotationOnly)
1064eb11fae6SDimitry Andric     SimplifiedLatch = simplifyLoopLatch(L);
1065eb11fae6SDimitry Andric 
1066eb11fae6SDimitry Andric   bool MadeChange = rotateLoop(L, SimplifiedLatch);
1067eb11fae6SDimitry Andric   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
1068eb11fae6SDimitry Andric          "Loop latch should be exiting after loop-rotate.");
1069eb11fae6SDimitry Andric 
1070eb11fae6SDimitry Andric   // Restore the loop metadata.
1071eb11fae6SDimitry Andric   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
1072eb11fae6SDimitry Andric   if ((MadeChange || SimplifiedLatch) && LoopMD)
1073eb11fae6SDimitry Andric     L->setLoopID(LoopMD);
1074eb11fae6SDimitry Andric 
1075eb11fae6SDimitry Andric   return MadeChange || SimplifiedLatch;
1076eb11fae6SDimitry Andric }
1077eb11fae6SDimitry Andric 
1078eb11fae6SDimitry Andric 
1079eb11fae6SDimitry Andric /// 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)1080eb11fae6SDimitry Andric bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
1081eb11fae6SDimitry Andric                         AssumptionCache *AC, DominatorTree *DT,
1082d8e91e46SDimitry Andric                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
1083d8e91e46SDimitry Andric                         const SimplifyQuery &SQ, bool RotationOnly = true,
1084eb11fae6SDimitry Andric                         unsigned Threshold = unsigned(-1),
1085b60736ecSDimitry Andric                         bool IsUtilMode = true, bool PrepareForLTO) {
1086d8e91e46SDimitry Andric   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
1087b60736ecSDimitry Andric                 IsUtilMode, PrepareForLTO);
1088eb11fae6SDimitry Andric   return LR.processLoop(L);
1089eb11fae6SDimitry Andric }
1090