blob: 3506ac343d594d400c3de99746e1c33bff2ec9d9 [file] [log] [blame]
Devang Patelf42389f2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelf42389f2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Justin Bognerd0d23412016-05-03 22:02:31 +000014#include "llvm/Transforms/Scalar/LoopRotation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Chandler Carruth08eebe22015-07-23 09:34:01 +000016#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000017#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000018#include "llvm/Analysis/BasicAliasAnalysis.h"
Chris Lattner679572e2011-01-02 07:35:53 +000019#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000020#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/LoopPass.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000023#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000031#include "llvm/IR/Module.h"
Owen Anderson115aa162014-05-26 08:58:51 +000032#include "llvm/Support/CommandLine.h"
Devang Patelf42389f2007-04-07 01:25:15 +000033#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/Support/raw_ostream.h"
Justin Bognerd0d23412016-05-03 22:02:31 +000035#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000036#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
41#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000042using namespace llvm;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "loop-rotate"
45
Sebastian Popdfb66a12016-06-14 14:44:05 +000046static cl::opt<unsigned> DefaultRotationThreshold(
47 "rotation-max-header-size", cl::init(16), cl::Hidden,
48 cl::desc("The default maximum header size for automatic loop rotation"));
Devang Patelf42389f2007-04-07 01:25:15 +000049
50STATISTIC(NumRotated, "Number of loops rotated");
Devang Patelf42389f2007-04-07 01:25:15 +000051
Benjamin Kramer4d098922016-07-10 11:28:51 +000052namespace {
Sebastian Popdfb66a12016-06-14 14:44:05 +000053/// A simple loop rotation transformation.
54class LoopRotate {
55 const unsigned MaxHeaderSize;
56 LoopInfo *LI;
57 const TargetTransformInfo *TTI;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 AssumptionCache *AC;
Sebastian Popdfb66a12016-06-14 14:44:05 +000059 DominatorTree *DT;
60 ScalarEvolution *SE;
Daniel Berlin62aee142017-04-26 13:52:18 +000061 const SimplifyQuery &SQ;
Sebastian Popdfb66a12016-06-14 14:44:05 +000062
63public:
64 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000065 const TargetTransformInfo *TTI, AssumptionCache *AC,
Daniel Berlin62aee142017-04-26 13:52:18 +000066 DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
67 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
68 SQ(SQ) {}
Sebastian Popdfb66a12016-06-14 14:44:05 +000069 bool processLoop(Loop *L);
70
71private:
72 bool rotateLoop(Loop *L, bool SimplifiedLatch);
73 bool simplifyLoopLatch(Loop *L);
74};
Benjamin Kramer4d098922016-07-10 11:28:51 +000075} // end anonymous namespace
Sebastian Popdfb66a12016-06-14 14:44:05 +000076
Chris Lattner30f318e2011-01-08 19:26:33 +000077/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
78/// old header into the preheader. If there were uses of the values produced by
79/// these instruction that were outside of the loop, we have to insert PHI nodes
80/// to merge the two values. Do this now.
81static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
82 BasicBlock *OrigPreheader,
Sam Parker0f4db382017-03-08 09:56:22 +000083 ValueToValueMapTy &ValueMap,
84 SmallVectorImpl<PHINode*> *InsertedPHIs) {
Chris Lattner30f318e2011-01-08 19:26:33 +000085 // Remove PHI node entries that are no longer live.
86 BasicBlock::iterator I, E = OrigHeader->end();
87 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
88 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +000089
Chris Lattner30f318e2011-01-08 19:26:33 +000090 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
91 // as necessary.
Sam Parker0f4db382017-03-08 09:56:22 +000092 SSAUpdater SSA(InsertedPHIs);
Chris Lattner30f318e2011-01-08 19:26:33 +000093 for (I = OrigHeader->begin(); I != E; ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +000094 Value *OrigHeaderVal = &*I;
Andrew Tricka20f1982012-02-14 00:00:19 +000095
Chris Lattner30f318e2011-01-08 19:26:33 +000096 // If there are no uses of the value (e.g. because it returns void), there
97 // is nothing to rewrite.
98 if (OrigHeaderVal->use_empty())
99 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000100
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000101 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
Chris Lattner30f318e2011-01-08 19:26:33 +0000102
103 // The value now exits in two versions: the initial value in the preheader
104 // and the loop "next" value in the original header.
105 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
106 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
107 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000108
Chris Lattner30f318e2011-01-08 19:26:33 +0000109 // Visit each use of the OrigHeader instruction.
110 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
Sebastian Popdfb66a12016-06-14 14:44:05 +0000111 UE = OrigHeaderVal->use_end();
112 UI != UE;) {
Chris Lattner30f318e2011-01-08 19:26:33 +0000113 // Grab the use before incrementing the iterator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000114 Use &U = *UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000115
Chris Lattner30f318e2011-01-08 19:26:33 +0000116 // Increment the iterator before removing the use from the list.
117 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000118
Chris Lattner30f318e2011-01-08 19:26:33 +0000119 // SSAUpdater can't handle a non-PHI use in the same block as an
120 // earlier def. We can easily handle those cases manually.
121 Instruction *UserInst = cast<Instruction>(U.getUser());
122 if (!isa<PHINode>(UserInst)) {
123 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000124
Chris Lattner30f318e2011-01-08 19:26:33 +0000125 // The original users in the OrigHeader are already using the
126 // original definitions.
127 if (UserBB == OrigHeader)
128 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000129
Chris Lattner30f318e2011-01-08 19:26:33 +0000130 // Users in the OrigPreHeader need to use the value to which the
131 // original definitions are mapped.
132 if (UserBB == OrigPreheader) {
133 U = OrigPreHeaderVal;
134 continue;
135 }
136 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000137
Chris Lattner30f318e2011-01-08 19:26:33 +0000138 // Anything else can be handled by SSAUpdater.
139 SSA.RewriteUse(U);
140 }
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000141
142 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
143 // intrinsics.
144 LLVMContext &C = OrigHeader->getContext();
145 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
146 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000147 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000148 // Grab the use before incrementing the iterator. Otherwise, altering
149 // the Use will invalidate the iterator.
150 Use &U = *UI++;
151 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
Sebastian Popdfb66a12016-06-14 14:44:05 +0000152 if (!UserInst)
153 continue;
Chuang-Yu Cheng175741d2016-05-10 09:45:44 +0000154
155 // The original users in the OrigHeader are already using the original
156 // definitions.
157 BasicBlock *UserBB = UserInst->getParent();
158 if (UserBB == OrigHeader)
159 continue;
160
161 // Users in the OrigPreHeader need to use the value to which the
162 // original definitions are mapped and anything else can be handled by
163 // the SSAUpdater. To avoid adding PHINodes, check if the value is
164 // available in UserBB, if not substitute undef.
165 Value *NewVal;
166 if (UserBB == OrigPreheader)
167 NewVal = OrigPreHeaderVal;
168 else if (SSA.HasValueForBlock(UserBB))
169 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
170 else
171 NewVal = UndefValue::get(OrigHeaderVal->getType());
172 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
173 }
174 }
175 }
Chris Lattner30f318e2011-01-08 19:26:33 +0000176 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000177}
Chris Lattner30f318e2011-01-08 19:26:33 +0000178
Sam Parker0f4db382017-03-08 09:56:22 +0000179/// Propagate dbg.value intrinsics through the newly inserted Phis.
180static void insertDebugValues(BasicBlock *OrigHeader,
181 SmallVectorImpl<PHINode*> &InsertedPHIs) {
182 ValueToValueMapTy DbgValueMap;
183
184 // Map existing PHI nodes to their dbg.values.
185 for (auto &I : *OrigHeader) {
186 if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
187 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
188 DbgValueMap.insert({Loc, DbgII});
189 }
190 }
191
192 // Then iterate through the new PHIs and look to see if they use one of the
193 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
194 // propagate the info through the new PHI.
195 LLVMContext &C = OrigHeader->getContext();
196 for (auto PHI : InsertedPHIs) {
197 for (auto VI : PHI->operand_values()) {
198 auto V = DbgValueMap.find(VI);
199 if (V != DbgValueMap.end()) {
200 auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
201 Instruction *NewDbgII = DbgII->clone();
202 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
203 NewDbgII->setOperand(0, PhiMAV);
204 BasicBlock *Parent = PHI->getParent();
205 NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
206 }
207 }
208 }
209}
210
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000211/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000212///
213/// \param SimplifiedLatch is true if the latch was just folded into the final
214/// loop exit. In this case we may want to rotate even though the new latch is
215/// now an exiting branch. This rotation would have happened had the latch not
216/// been simplified. However, if SimplifiedLatch is false, then we avoid
217/// rotating loops in which the latch exits to avoid excessive or endless
218/// rotation. LoopRotate should be repeatable and converge to a canonical
219/// form. This property is satisfied because simplifying the loop latch can only
220/// happen once across multiple invocations of the LoopRotate pass.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000221bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000222 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000223 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000224 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000225
Chris Lattner7fab23b2011-01-08 18:06:22 +0000226 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000227 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000228
Chris Lattner7fab23b2011-01-08 18:06:22 +0000229 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000230 if (!BI || BI->isUnconditional())
Chris Lattner7fab23b2011-01-08 18:06:22 +0000231 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000232
Dan Gohman091e4402009-06-25 00:22:44 +0000233 // If the loop header is not one of the loop exiting blocks then
234 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000235 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000236 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000237 return false;
238
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000239 // If the loop latch already contains a branch that leaves the loop then the
240 // loop is already rotated.
Craig Topperf40110f2014-04-25 05:29:35 +0000241 if (!OrigLatch)
Andrew Trick9c72b072013-05-06 17:58:18 +0000242 return false;
243
244 // Rotate if either the loop latch does *not* exit the loop, or if the loop
245 // latch was just simplified.
246 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000247 return false;
248
James Molloy4f6fb952012-12-20 16:04:27 +0000249 // Check size of original header and reject loop if it is very big or we can't
250 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000251 {
Hal Finkel57f03dd2014-09-07 13:49:57 +0000252 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000253 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000254
Chris Lattner679572e2011-01-02 07:35:53 +0000255 CodeMetrics Metrics;
Hal Finkel57f03dd2014-09-07 13:49:57 +0000256 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
James Molloy4f6fb952012-12-20 16:04:27 +0000257 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000258 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
Sebastian Popdfb66a12016-06-14 14:44:05 +0000259 << " instructions: ";
260 L->dump());
James Molloy4f6fb952012-12-20 16:04:27 +0000261 return false;
262 }
Justin Lebardf04d2a2016-02-12 21:01:33 +0000263 if (Metrics.convergent) {
264 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000265 "instructions: ";
266 L->dump());
Justin Lebardf04d2a2016-02-12 21:01:33 +0000267 return false;
268 }
Owen Anderson115aa162014-05-26 08:58:51 +0000269 if (Metrics.NumInsts > MaxHeaderSize)
Chris Lattner679572e2011-01-02 07:35:53 +0000270 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000271 }
272
Devang Patelfac4d1f2007-07-11 23:47:28 +0000273 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000274 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000275
Chris Lattner88974f42011-04-09 07:25:58 +0000276 // If the loop could not be converted to canonical form, it must have an
277 // indirectbr in it, just give up.
Craig Topperf40110f2014-04-25 05:29:35 +0000278 if (!OrigPreheader)
Chris Lattner88974f42011-04-09 07:25:58 +0000279 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000280
Dan Gohmanfc20b672009-09-27 15:37:03 +0000281 // Anything ScalarEvolution may know about this loop or the PHI nodes
282 // in its header will soon be invalidated.
Justin Bogner6291b582015-12-14 23:22:48 +0000283 if (SE)
284 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000285
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000286 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
287
Devang Patelf42389f2007-04-07 01:25:15 +0000288 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000289 // that is inside loop. Header's other successor is outside the
290 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000291 BasicBlock *Exit = BI->getSuccessor(0);
292 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000293 if (L->contains(Exit))
294 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000295 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000296 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000297 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000298
Dan Gohman091e4402009-06-25 00:22:44 +0000299 // This code assumes that the new header has exactly one predecessor.
300 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000301 assert(NewHeader->getSinglePredecessor() &&
302 "New header doesn't have one pred!");
303 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000304
Dan Gohmanb9797942009-10-24 23:19:52 +0000305 // Begin by walking OrigHeader and populating ValueMap with an entry for
306 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000307 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000308 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000309
Dan Gohmanb9797942009-10-24 23:19:52 +0000310 // For PHI nodes, the value available in OldPreHeader is just the
311 // incoming value from OldPreHeader.
312 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000313 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000314
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000315 // For the rest of the instructions, either hoist to the OrigPreheader if
316 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000317 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000318 while (I != E) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000319 Instruction *Inst = &*I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000320
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000321 // If the instruction's operands are invariant and it doesn't read or write
322 // memory, then it is safe to hoist. Doing this doesn't change the order of
323 // execution in the preheader, but does prevent the instruction from
324 // executing in each iteration of the loop. This means it is safe to hoist
325 // something that might trap, but isn't safe to hoist something that reads
326 // memory (without proving that the loop doesn't write).
Sebastian Popdfb66a12016-06-14 14:44:05 +0000327 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
328 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
329 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000330 Inst->moveBefore(LoopEntryBranch);
331 continue;
332 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000333
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000334 // Otherwise, create a duplicate of the instruction.
335 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000336
Chris Lattner8c5defd2011-01-08 08:24:46 +0000337 // Eagerly remap the operands of the instruction.
338 RemapInstruction(C, ValueMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000339 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Tricka20f1982012-02-14 00:00:19 +0000340
Chris Lattner8c5defd2011-01-08 08:24:46 +0000341 // With the operands remapped, see if the instruction constant folds or is
342 // otherwise simplifyable. This commonly occurs because the entry from PHI
343 // nodes allows icmps and other instructions to fold.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000344 Value *V = SimplifyInstruction(C, SQ);
Chris Lattner25ba40a2011-01-08 17:38:45 +0000345 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000346 // If so, then delete the temporary instruction and stick the folded value
347 // in the map.
Chris Lattner8c5defd2011-01-08 08:24:46 +0000348 ValueMap[Inst] = V;
David Majnemerb8da3a22016-06-25 00:04:10 +0000349 if (!C->mayHaveSideEffects()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +0000350 C->deleteValue();
David Majnemerb8da3a22016-06-25 00:04:10 +0000351 C = nullptr;
352 }
Chris Lattner8c5defd2011-01-08 08:24:46 +0000353 } else {
David Majnemerb8da3a22016-06-25 00:04:10 +0000354 ValueMap[Inst] = C;
355 }
356 if (C) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000357 // Otherwise, stick the new instruction into the new block!
358 C->setName(Inst->getName());
359 C->insertBefore(LoopEntryBranch);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000360
361 if (auto *II = dyn_cast<IntrinsicInst>(C))
362 if (II->getIntrinsicID() == Intrinsic::assume)
363 AC->registerAssumption(II);
Chris Lattner8c5defd2011-01-08 08:24:46 +0000364 }
Devang Patelf42389f2007-04-07 01:25:15 +0000365 }
366
Dan Gohmanb9797942009-10-24 23:19:52 +0000367 // Along with all the other instructions, we just cloned OrigHeader's
368 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
369 // successors by duplicating their incoming values for OrigHeader.
370 TerminatorInst *TI = OrigHeader->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +0000371 for (BasicBlock *SuccBB : TI->successors())
372 for (BasicBlock::iterator BI = SuccBB->begin();
Dan Gohmanb9797942009-10-24 23:19:52 +0000373 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000374 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000375
Dan Gohmanb9797942009-10-24 23:19:52 +0000376 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
377 // OrigPreHeader's old terminator (the original branch into the loop), and
378 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
379 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000380
Sam Parker0f4db382017-03-08 09:56:22 +0000381
382 SmallVector<PHINode*, 2> InsertedPHIs;
Chris Lattner30f318e2011-01-08 19:26:33 +0000383 // If there were any uses of instructions in the duplicated block outside the
384 // loop, update them, inserting PHI nodes as required
Sam Parker0f4db382017-03-08 09:56:22 +0000385 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
386 &InsertedPHIs);
387
388 // Attach dbg.value intrinsics to the new phis if that phi uses a value that
389 // previously had debug metadata attached. This keeps the debug info
390 // up-to-date in the loop body.
391 if (!InsertedPHIs.empty())
392 insertDebugValues(OrigHeader, InsertedPHIs);
Devang Patelf42389f2007-04-07 01:25:15 +0000393
Dan Gohmanb9797942009-10-24 23:19:52 +0000394 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000395 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000396 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000397
Chris Lattner59c82f82011-01-08 19:59:06 +0000398 // At this point, we've finished our major CFG changes. As part of cloning
399 // the loop into the preheader we've simplified instructions and the
400 // duplicated conditional branch may now be branching on a constant. If it is
401 // branching on a constant and if that constant means that we enter the loop,
402 // then we fold away the cond branch to an uncond branch. This simplifies the
403 // loop in cases important for nested loops, and it also means we don't have
404 // to split as many edges.
405 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
406 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
407 if (!isa<ConstantInt>(PHBI->getCondition()) ||
Sebastian Popdfb66a12016-06-14 14:44:05 +0000408 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
409 NewHeader) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000410 // The conditional branch can't be folded, handle the general case.
411 // Update DominatorTree to reflect the CFG change we just made. Then split
412 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth94209092015-01-18 02:08:05 +0000413 if (DT) {
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000414 // Everything that was dominated by the old loop header is now dominated
415 // by the original loop preheader. Conceptually the header was merged
416 // into the preheader, even though we reuse the actual block as a new
417 // loop latch.
Chandler Carruth94209092015-01-18 02:08:05 +0000418 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000419 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
420 OrigHeaderNode->end());
Chandler Carruth94209092015-01-18 02:08:05 +0000421 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000422 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth94209092015-01-18 02:08:05 +0000423 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000424
Chandler Carruth94209092015-01-18 02:08:05 +0000425 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
426 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000427
Chris Lattner59c82f82011-01-08 19:59:06 +0000428 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000429 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000430 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000431
Chris Lattner59c82f82011-01-08 19:59:06 +0000432 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000433 // thus is not a preheader anymore.
434 // Split the edge to form a real preheader.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000435 BasicBlock *NewPH = SplitCriticalEdge(
436 OrigPreheader, NewHeader,
437 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chris Lattner59c82f82011-01-08 19:59:06 +0000438 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000439
Nadav Rotem465834c2012-07-24 10:51:42 +0000440 // Preserve canonical loop form, which means that 'Exit' should have only
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000441 // one predecessor. Note that Exit could be an exit block for multiple
442 // nested loops, causing both of the edges to now be critical and need to
443 // be split.
444 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
445 bool SplitLatchEdge = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000446 for (BasicBlock *ExitPred : ExitPreds) {
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000447 // We only need to split loop exit edges.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000448 Loop *PredLoop = LI->getLoopFor(ExitPred);
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000449 if (!PredLoop || PredLoop->contains(Exit))
450 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000451 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
Benjamin Kramer911d5b32015-02-20 20:49:25 +0000452 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000453 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000454 BasicBlock *ExitSplit = SplitCriticalEdge(
Benjamin Kramer135f7352016-06-26 12:28:59 +0000455 ExitPred, Exit,
456 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000457 ExitSplit->moveBefore(Exit);
458 }
459 assert(SplitLatchEdge &&
460 "Despite splitting all preds, failed to split latch exit?");
Chris Lattner59c82f82011-01-08 19:59:06 +0000461 } else {
462 // We can fold the conditional branch in the preheader, this makes things
463 // simpler. The first step is to remove the extra edge to the Exit block.
464 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000465 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
466 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000467 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000468
Chris Lattner59c82f82011-01-08 19:59:06 +0000469 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth94209092015-01-18 02:08:05 +0000470 if (DT) {
Chris Lattner59c82f82011-01-08 19:59:06 +0000471 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth94209092015-01-18 02:08:05 +0000472 DT->changeImmediateDominator(NewHeader, OrigPreheader);
473 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000474
475 // Brute force incremental dominator tree update. Call
476 // findNearestCommonDominator on all CFG predecessors of each child of the
477 // original header.
Chandler Carruth94209092015-01-18 02:08:05 +0000478 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000479 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
480 OrigHeaderNode->end());
481 bool Changed;
482 do {
483 Changed = false;
484 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
485 DomTreeNode *Node = HeaderChildren[I];
486 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000487
Jakub Kuderskib323f4f2017-07-12 18:42:16 +0000488 BasicBlock *NearestDom = nullptr;
489 for (BasicBlock *Pred : predecessors(BB)) {
490 // Consider only reachable basic blocks.
491 if (!DT->getNode(Pred))
492 continue;
493
494 if (!NearestDom) {
495 NearestDom = Pred;
496 continue;
497 }
498
499 NearestDom = DT->findNearestCommonDominator(NearestDom, Pred);
500 assert(NearestDom && "No NearestCommonDominator found");
501 }
502
503 assert(NearestDom && "Nearest dominator not found");
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000504
505 // Remember if this changes the DomTree.
506 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth94209092015-01-18 02:08:05 +0000507 DT->changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000508 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000509 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000510 }
511
Sebastian Popdfb66a12016-06-14 14:44:05 +0000512 // If the dominator changed, this may have an effect on other
513 // predecessors, continue until we reach a fixpoint.
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000514 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000515 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000516 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000517
Chris Lattner59c82f82011-01-08 19:59:06 +0000518 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000519 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000520
Chris Lattner63fe78d2011-01-11 07:47:59 +0000521 // Now that the CFG and DomTree are in a consistent state again, try to merge
522 // the OrigHeader block into OrigLatch. This will succeed if they are
523 // connected by an unconditional branch. This is just a cleanup so the
524 // emitted code isn't too gross in this common case.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000525 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
Andrew Tricka20f1982012-02-14 00:00:19 +0000526
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000527 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
528
Chris Lattnerfee37c52011-01-08 18:55:50 +0000529 ++NumRotated;
530 return true;
Devang Patel85419782007-04-09 20:19:46 +0000531}
Justin Bognera7300452015-12-14 23:22:44 +0000532
533/// Determine whether the instructions in this range may be safely and cheaply
534/// speculated. This is not an important enough situation to develop complex
535/// heuristics. We handle a single arithmetic instruction along with any type
536/// conversions.
537static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
538 BasicBlock::iterator End, Loop *L) {
539 bool seenIncrement = false;
540 bool MultiExitLoop = false;
541
542 if (!L->getExitingBlock())
543 MultiExitLoop = true;
544
545 for (BasicBlock::iterator I = Begin; I != End; ++I) {
546
547 if (!isSafeToSpeculativelyExecute(&*I))
548 return false;
549
550 if (isa<DbgInfoIntrinsic>(I))
551 continue;
552
553 switch (I->getOpcode()) {
554 default:
555 return false;
556 case Instruction::GetElementPtr:
557 // GEPs are cheap if all indices are constant.
558 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
559 return false;
Justin Bognerb03fd122016-08-17 05:10:15 +0000560 // fall-thru to increment case
561 LLVM_FALLTHROUGH;
Justin Bognera7300452015-12-14 23:22:44 +0000562 case Instruction::Add:
563 case Instruction::Sub:
564 case Instruction::And:
565 case Instruction::Or:
566 case Instruction::Xor:
567 case Instruction::Shl:
568 case Instruction::LShr:
569 case Instruction::AShr: {
Sebastian Popdfb66a12016-06-14 14:44:05 +0000570 Value *IVOpnd =
571 !isa<Constant>(I->getOperand(0))
572 ? I->getOperand(0)
573 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
Justin Bognera7300452015-12-14 23:22:44 +0000574 if (!IVOpnd)
575 return false;
576
577 // If increment operand is used outside of the loop, this speculation
578 // could cause extra live range interference.
579 if (MultiExitLoop) {
580 for (User *UseI : IVOpnd->users()) {
581 auto *UserInst = cast<Instruction>(UseI);
582 if (!L->contains(UserInst))
583 return false;
584 }
585 }
586
587 if (seenIncrement)
588 return false;
589 seenIncrement = true;
590 break;
591 }
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 // ignore type conversions
596 break;
597 }
598 }
599 return true;
600}
601
602/// Fold the loop tail into the loop exit by speculating the loop tail
603/// instructions. Typically, this is a single post-increment. In the case of a
604/// simple 2-block loop, hoisting the increment can be much better than
605/// duplicating the entire loop header. In the case of loops with early exits,
606/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
607/// canonical form so downstream passes can handle it.
608///
609/// I don't believe this invalidates SCEV.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000610bool LoopRotate::simplifyLoopLatch(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000611 BasicBlock *Latch = L->getLoopLatch();
612 if (!Latch || Latch->hasAddressTaken())
613 return false;
614
615 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
616 if (!Jmp || !Jmp->isUnconditional())
617 return false;
618
619 BasicBlock *LastExit = Latch->getSinglePredecessor();
620 if (!LastExit || !L->isLoopExiting(LastExit))
621 return false;
622
623 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
624 if (!BI)
625 return false;
626
627 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
628 return false;
629
630 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
Sebastian Popdfb66a12016-06-14 14:44:05 +0000631 << LastExit->getName() << "\n");
Justin Bognera7300452015-12-14 23:22:44 +0000632
633 // Hoist the instructions from Latch into LastExit.
634 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
635 Latch->begin(), Jmp->getIterator());
636
637 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
638 BasicBlock *Header = Jmp->getSuccessor(0);
639 assert(Header == L->getHeader() && "expected a backward branch");
640
641 // Remove Latch from the CFG so that LastExit becomes the new Latch.
642 BI->setSuccessor(FallThruPath, Header);
643 Latch->replaceSuccessorsPhiUsesWith(LastExit);
644 Jmp->eraseFromParent();
645
646 // Nuke the Latch block.
647 assert(Latch->empty() && "unable to evacuate Latch");
648 LI->removeBlock(Latch);
649 if (DT)
650 DT->eraseNode(Latch);
651 Latch->eraseFromParent();
652 return true;
653}
654
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000655/// Rotate \c L, and return true if any modification was made.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000656bool LoopRotate::processLoop(Loop *L) {
Justin Bognera7300452015-12-14 23:22:44 +0000657 // Save the loop metadata.
658 MDNode *LoopMD = L->getLoopID();
659
Justin Bognera7300452015-12-14 23:22:44 +0000660 // Simplify the loop latch before attempting to rotate the header
661 // upward. Rotation may not be needed if the loop tail can be folded into the
662 // loop exit.
Sebastian Popdfb66a12016-06-14 14:44:05 +0000663 bool SimplifiedLatch = simplifyLoopLatch(L);
Justin Bognera7300452015-12-14 23:22:44 +0000664
Sebastian Popdfb66a12016-06-14 14:44:05 +0000665 bool MadeChange = rotateLoop(L, SimplifiedLatch);
Michael Zolotukhinb98294d2016-06-10 22:03:56 +0000666 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
667 "Loop latch should be exiting after loop-rotate.");
Justin Bognera7300452015-12-14 23:22:44 +0000668
669 // Restore the loop metadata.
670 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
671 if ((MadeChange || SimplifiedLatch) && LoopMD)
672 L->setLoopID(LoopMD);
673
674 return MadeChange;
675}
Justin Bogner6291b582015-12-14 23:22:48 +0000676
Chandler Carruthe3f50642016-12-22 06:59:15 +0000677LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
678 : EnableHeaderDuplication(EnableHeaderDuplication) {}
Justin Bognerd0d23412016-05-03 22:02:31 +0000679
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000680PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
681 LoopStandardAnalysisResults &AR,
682 LPMUpdater &) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000683 int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
Daniel Berlin62aee142017-04-26 13:52:18 +0000684 const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
Daniel Berlin98a1de82017-04-28 22:05:55 +0000685 const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000686 LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
Daniel Berlin98a1de82017-04-28 22:05:55 +0000687 SQ);
Justin Bognerd0d23412016-05-03 22:02:31 +0000688
Sebastian Popdfb66a12016-06-14 14:44:05 +0000689 bool Changed = LR.processLoop(&L);
Justin Bognerd0d23412016-05-03 22:02:31 +0000690 if (!Changed)
691 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000692
Justin Bognerd0d23412016-05-03 22:02:31 +0000693 return getLoopPassPreservedAnalyses();
694}
695
Justin Bogner6291b582015-12-14 23:22:48 +0000696namespace {
697
Justin Bognerd0d23412016-05-03 22:02:31 +0000698class LoopRotateLegacyPass : public LoopPass {
Justin Bogner6291b582015-12-14 23:22:48 +0000699 unsigned MaxHeaderSize;
700
701public:
702 static char ID; // Pass ID, replacement for typeid
Justin Bognerd0d23412016-05-03 22:02:31 +0000703 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
704 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
Justin Bogner6291b582015-12-14 23:22:48 +0000705 if (SpecifiedMaxHeaderSize == -1)
706 MaxHeaderSize = DefaultRotationThreshold;
707 else
708 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
709 }
710
711 // LCSSA form makes instruction renaming easier.
712 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000713 AU.addRequired<AssumptionCacheTracker>();
Justin Bogner6291b582015-12-14 23:22:48 +0000714 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000715 getLoopAnalysisUsage(AU);
Justin Bogner6291b582015-12-14 23:22:48 +0000716 }
717
718 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000719 if (skipLoop(L))
Justin Bogner6291b582015-12-14 23:22:48 +0000720 return false;
721 Function &F = *L->getHeader()->getParent();
722
723 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
724 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000725 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Justin Bogner6291b582015-12-14 23:22:48 +0000726 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
727 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
728 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
729 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
Daniel Berlin98a1de82017-04-28 22:05:55 +0000730 const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
731 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
Sebastian Popdfb66a12016-06-14 14:44:05 +0000732 return LR.processLoop(L);
Justin Bogner6291b582015-12-14 23:22:48 +0000733 }
734};
735}
736
Justin Bognerd0d23412016-05-03 22:02:31 +0000737char LoopRotateLegacyPass::ID = 0;
738INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
739 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000740INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000741INITIALIZE_PASS_DEPENDENCY(LoopPass)
742INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Sebastian Popdfb66a12016-06-14 14:44:05 +0000743INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
744 false)
Justin Bogner6291b582015-12-14 23:22:48 +0000745
746Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
Justin Bognerd0d23412016-05-03 22:02:31 +0000747 return new LoopRotateLegacyPass(MaxHeaderSize);
Justin Bogner6291b582015-12-14 23:22:48 +0000748}