blob: bcb4257bce76f33bea824d42fe586fef750ed620 [file] [log] [blame]
Devang Patelc4625da2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Patelc4625da2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel32231332007-04-09 16:11:48 +000014#define DEBUG_TYPE "loop-rotate"
Devang Patelc4625da2007-04-07 01:25:15 +000015#include "llvm/Transforms/Scalar.h"
16#include "llvm/Function.h"
Chris Lattnerd9e07972011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chris Lattnerd9ec3572011-01-08 08:24:46 +000018#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Devang Patel990e8662007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Devang Patelc4625da2007-04-07 01:25:15 +000021#include "llvm/Transforms/Utils/Local.h"
Devang Patel990e8662007-07-11 23:47:28 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmane6e37b92009-10-24 23:19:52 +000023#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ccb3652011-01-08 07:21:31 +000024#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000025#include "llvm/Support/Debug.h"
26#include "llvm/ADT/Statistic.h"
Devang Patelc4625da2007-04-07 01:25:15 +000027using namespace llvm;
28
29#define MAX_HEADER_SIZE 16
30
31STATISTIC(NumRotated, "Number of loops rotated");
32namespace {
33
Chris Lattner3e8b6632009-09-02 06:11:42 +000034 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000035 public:
Devang Patel19974732007-05-03 01:11:54 +000036 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000037 LoopRotate() : LoopPass(ID) {
38 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
39 }
Devang Patel794fd752007-05-01 21:15:47 +000040
Devang Patel32231332007-04-09 16:11:48 +000041 // Rotate Loop L as many times as possible. Return true if
42 // loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +000043 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel32231332007-04-09 16:11:48 +000044
45 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000046 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000047 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000048 AU.addRequired<LoopInfo>();
49 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000050 AU.addRequiredID(LoopSimplifyID);
51 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000052 AU.addRequiredID(LCSSAID);
53 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000054 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000055 }
56
57 // Helper functions
58
59 /// Do actual work
Chris Lattner4aefc9b2011-01-08 17:48:33 +000060 bool rotateLoop(Loop *L);
Devang Patelc4625da2007-04-07 01:25:15 +000061
Devang Patel5464b962007-04-09 20:19:46 +000062 /// After loop rotation, loop pre-header has multiple sucessors.
63 /// Insert one forwarding basic block to ensure that loop pre-header
64 /// has only one successor.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000065 void preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
66 BasicBlock *OrigPreHeader,
67 BasicBlock *OrigLatch, BasicBlock *NewHeader,
68 BasicBlock *Exit);
Devang Patel5464b962007-04-09 20:19:46 +000069
Devang Patelc4625da2007-04-07 01:25:15 +000070 private:
Chris Lattner012ca942011-01-08 17:38:45 +000071 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000072 };
Devang Patelc4625da2007-04-07 01:25:15 +000073}
Dan Gohman844731a2008-05-13 00:00:25 +000074
75char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000076INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000077INITIALIZE_PASS_DEPENDENCY(LoopInfo)
78INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
79INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000080INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000081
Daniel Dunbar394f0442008-10-22 23:32:42 +000082Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000083
Devang Patel32231332007-04-09 16:11:48 +000084/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000085/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000086bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000087 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000088
Devang Patelc4625da2007-04-07 01:25:15 +000089 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000090 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000091 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000092 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000093
Chris Lattner012ca942011-01-08 17:38:45 +000094 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000095}
96
Dan Gohman23d9d272007-05-11 21:10:54 +000097/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000098bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +000099 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000100 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000101 return false;
Chris Lattner2aa69082011-01-08 18:06:22 +0000102
103 BasicBlock *OrigHeader = L->getHeader();
104
105 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
106 if (BI == 0 || BI->isUnconditional())
107 return false;
108
Dan Gohmancc4e6052009-06-25 00:22:44 +0000109 // If the loop header is not one of the loop exiting blocks then
110 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000111 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000112 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000113 return false;
114
Devang Patel32231332007-04-09 16:11:48 +0000115 // Updating PHInodes in loops with multiple exits adds complexity.
116 // Keep it simple, and restrict loop rotation to loops with one exit only.
117 // In future, lift this restriction and support for multiple exits if
118 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000119 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000120 L->getExitBlocks(ExitBlocks);
121 if (ExitBlocks.size() > 1)
122 return false;
123
Chris Lattnerd9e07972011-01-02 07:35:53 +0000124 // Check size of original header and reject loop if it is very big.
125 {
126 CodeMetrics Metrics;
127 Metrics.analyzeBasicBlock(OrigHeader);
128 if (Metrics.NumInsts > MAX_HEADER_SIZE)
129 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000130 }
131
Devang Patel990e8662007-07-11 23:47:28 +0000132 // Now, this loop is suitable for rotation.
Chris Lattner2aa69082011-01-08 18:06:22 +0000133 BasicBlock *OrigPreHeader = L->getLoopPreheader();
134 BasicBlock *OrigLatch = L->getLoopLatch();
135 assert(OrigPreHeader && OrigLatch && "Loop not in canonical form?");
Devang Patel990e8662007-07-11 23:47:28 +0000136
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000137 // Anything ScalarEvolution may know about this loop or the PHI nodes
138 // in its header will soon be invalidated.
139 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000140 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000141
Devang Patelc4625da2007-04-07 01:25:15 +0000142 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000143 // that is inside loop. Header's other successor is outside the
144 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000145 BasicBlock *Exit = BI->getSuccessor(0);
146 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000147 if (L->contains(Exit))
148 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000149 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000150 assert(L->contains(NewHeader) && !L->contains(Exit) &&
151 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000152
Dan Gohmancc4e6052009-06-25 00:22:44 +0000153 // This code assumes that the new header has exactly one predecessor.
154 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000155 assert(NewHeader->getSinglePredecessor() &&
156 "New header doesn't have one pred!");
157 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000158
Dan Gohmane6e37b92009-10-24 23:19:52 +0000159 // Begin by walking OrigHeader and populating ValueMap with an entry for
160 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000161 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000162 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000163
Dan Gohmane6e37b92009-10-24 23:19:52 +0000164 // For PHI nodes, the value available in OldPreHeader is just the
165 // incoming value from OldPreHeader.
166 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
167 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000168
Chris Lattner50fb4692010-09-06 01:10:22 +0000169 // For the rest of the instructions, either hoist to the OrigPreheader if
170 // possible or create a clone in the OldPreHeader if not.
Dan Gohmane6e37b92009-10-24 23:19:52 +0000171 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000172 while (I != E) {
173 Instruction *Inst = I++;
174
175 // If the instruction's operands are invariant and it doesn't read or write
176 // memory, then it is safe to hoist. Doing this doesn't change the order of
177 // execution in the preheader, but does prevent the instruction from
178 // executing in each iteration of the loop. This means it is safe to hoist
179 // something that might trap, but isn't safe to hoist something that reads
180 // memory (without proving that the loop doesn't write).
181 if (L->hasLoopInvariantOperands(Inst) &&
182 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
183 !isa<TerminatorInst>(Inst)) {
184 Inst->moveBefore(LoopEntryBranch);
185 continue;
186 }
187
188 // Otherwise, create a duplicate of the instruction.
189 Instruction *C = Inst->clone();
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000190
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000191 // Eagerly remap the operands of the instruction.
192 RemapInstruction(C, ValueMap,
193 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
194
195 // With the operands remapped, see if the instruction constant folds or is
196 // otherwise simplifyable. This commonly occurs because the entry from PHI
197 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000198 Value *V = SimplifyInstruction(C);
199 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000200 // If so, then delete the temporary instruction and stick the folded value
201 // in the map.
202 delete C;
203 ValueMap[Inst] = V;
204 } else {
205 // Otherwise, stick the new instruction into the new block!
206 C->setName(Inst->getName());
207 C->insertBefore(LoopEntryBranch);
208 ValueMap[Inst] = C;
209 }
Devang Patelc4625da2007-04-07 01:25:15 +0000210 }
211
Dan Gohmane6e37b92009-10-24 23:19:52 +0000212 // Along with all the other instructions, we just cloned OrigHeader's
213 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
214 // successors by duplicating their incoming values for OrigHeader.
215 TerminatorInst *TI = OrigHeader->getTerminator();
216 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
217 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
218 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
219 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000220
Dan Gohmane6e37b92009-10-24 23:19:52 +0000221 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
222 // OrigPreHeader's old terminator (the original branch into the loop), and
223 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
224 LoopEntryBranch->eraseFromParent();
225 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
226 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000227
Dan Gohman440e2512009-10-26 15:55:24 +0000228 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
Dan Gohmane6e37b92009-10-24 23:19:52 +0000229 // as necessary.
230 SSAUpdater SSA;
231 for (I = OrigHeader->begin(); I != E; ++I) {
232 Value *OrigHeaderVal = I;
233 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
Devang Patelc4625da2007-04-07 01:25:15 +0000234
Chris Lattner6ccb3652011-01-08 07:21:31 +0000235 // If there are no uses of the value (e.g. because it returns void), there
236 // is nothing to rewrite.
237 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
238 continue;
239
Dan Gohmane6e37b92009-10-24 23:19:52 +0000240 // The value now exits in two versions: the initial value in the preheader
241 // and the loop "next" value in the original header.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000242 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
Dan Gohmane6e37b92009-10-24 23:19:52 +0000243 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
244 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
Devang Patelc4625da2007-04-07 01:25:15 +0000245
Dan Gohmane6e37b92009-10-24 23:19:52 +0000246 // Visit each use of the OrigHeader instruction.
247 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
248 UE = OrigHeaderVal->use_end(); UI != UE; ) {
249 // Grab the use before incrementing the iterator.
250 Use &U = UI.getUse();
Devang Patelc4625da2007-04-07 01:25:15 +0000251
Dan Gohmane6e37b92009-10-24 23:19:52 +0000252 // Increment the iterator before removing the use from the list.
253 ++UI;
254
255 // SSAUpdater can't handle a non-PHI use in the same block as an
256 // earlier def. We can easily handle those cases manually.
257 Instruction *UserInst = cast<Instruction>(U.getUser());
258 if (!isa<PHINode>(UserInst)) {
259 BasicBlock *UserBB = UserInst->getParent();
260
261 // The original users in the OrigHeader are already using the
262 // original definitions.
263 if (UserBB == OrigHeader)
Devang Patel24a1c492007-04-09 16:21:29 +0000264 continue;
265
Dan Gohmane6e37b92009-10-24 23:19:52 +0000266 // Users in the OrigPreHeader need to use the value to which the
267 // original definitions are mapped.
268 if (UserBB == OrigPreHeader) {
269 U = OrigPreHeaderVal;
Devang Patelc4625da2007-04-07 01:25:15 +0000270 continue;
Dan Gohmane6e37b92009-10-24 23:19:52 +0000271 }
Devang Patelc4625da2007-04-07 01:25:15 +0000272 }
273
Dan Gohmane6e37b92009-10-24 23:19:52 +0000274 // Anything else can be handled by SSAUpdater.
275 SSA.RewriteUse(U);
Devang Patelc4625da2007-04-07 01:25:15 +0000276 }
277 }
Devang Patelc4625da2007-04-07 01:25:15 +0000278
Dan Gohmane6e37b92009-10-24 23:19:52 +0000279 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000280 L->moveToHeader(NewHeader);
281
Dan Gohmanfc8042a2010-08-17 17:39:21 +0000282 // Move the original header to the bottom of the loop, where it now more
283 // naturally belongs. This isn't necessary for correctness, and CodeGen can
284 // usually reorder blocks on its own to fix things like this up, but it's
285 // still nice to keep the IR readable.
286 //
287 // The original header should have only one predecessor at this point, since
288 // we checked that the loop had a proper preheader and unique backedge before
289 // we started.
290 assert(OrigHeader->getSinglePredecessor() &&
291 "Original loop header has too many predecessors after loop rotation!");
292 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
293
294 // Also, since this original header only has one predecessor, zap its
295 // PHI nodes, which are now trivial.
296 FoldSingleEntryPHINodes(OrigHeader);
Chris Lattner0e4a1542011-01-08 18:52:51 +0000297
Dan Gohmanfc8042a2010-08-17 17:39:21 +0000298 // TODO: We could just go ahead and merge OrigHeader into its predecessor
299 // at this point, if we don't mind updating dominator info.
300
301 // Establish a new preheader, update dominators, etc.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000302 preserveCanonicalLoopForm(L, OrigHeader, OrigPreHeader, OrigLatch,
303 NewHeader, Exit);
Devang Patel5464b962007-04-09 20:19:46 +0000304
Dan Gohmanfe601042010-06-22 15:08:57 +0000305 ++NumRotated;
Devang Patelc4625da2007-04-07 01:25:15 +0000306 return true;
307}
308
Devang Patel5464b962007-04-09 20:19:46 +0000309
Chris Lattner0e4a1542011-01-08 18:52:51 +0000310/// Update LoopInfo, DominatorTree, and DomFrontiers to reflect the CFG change
311/// we just made. Then split edges as necessary to preserve LoopSimplify form.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000312void LoopRotate::preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
313 BasicBlock *OrigPreHeader,
314 BasicBlock *OrigLatch,
315 BasicBlock *NewHeader,
316 BasicBlock *Exit) {
Chris Lattner0e4a1542011-01-08 18:52:51 +0000317 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patel5464b962007-04-09 20:19:46 +0000318
Duncan Sands1465d612009-01-28 13:14:17 +0000319 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Chris Lattner0e4a1542011-01-08 18:52:51 +0000320 // Since OrigPreheader now has the conditional branch to Exit block, it is
321 // the dominator of Exit.
Devang Patel990e8662007-07-11 23:47:28 +0000322 DT->changeImmediateDominator(Exit, OrigPreHeader);
Chris Lattner0e4a1542011-01-08 18:52:51 +0000323 DT->changeImmediateDominator(NewHeader, OrigPreHeader);
324
325 // Update OrigHeader to be dominated by the new header block.
Devang Patel990e8662007-07-11 23:47:28 +0000326 DT->changeImmediateDominator(OrigHeader, OrigLatch);
327 }
Chris Lattner0e4a1542011-01-08 18:52:51 +0000328
329 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
330 // thus is not a preheader anymore. Split the edge to form a real preheader.
331 BasicBlock *NewPH = SplitCriticalEdge(OrigPreHeader, NewHeader, this);
332 NewPH->setName(NewHeader->getName() + ".lr.ph");
333
334 // Preserve canonical loop form, which means Exit block should have only one
335 // predecessor.
336 SplitCriticalEdge(L->getLoopLatch(), Exit, this);
Devang Patel990e8662007-07-11 23:47:28 +0000337
Chris Lattner2ba25432009-01-26 01:38:24 +0000338 assert(NewHeader && L->getHeader() == NewHeader &&
339 "Invalid loop header after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000340 assert(L->getLoopPreheader() == NewPH &&
Chris Lattner2ba25432009-01-26 01:38:24 +0000341 "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000342 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000343}