blob: 4b10d1006e7ad15e6f0c5c4de33c5dfc902d6b8e [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"
Devang Patel3f43a702009-03-06 03:51:30 +000017#include "llvm/IntrinsicInst.h"
Devang Patelc4625da2007-04-07 01:25:15 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/LoopPass.h"
Devang Patel990e8662007-07-11 23:47:28 +000020#include "llvm/Analysis/Dominators.h"
21#include "llvm/Analysis/ScalarEvolution.h"
Devang Patelc4625da2007-04-07 01:25:15 +000022#include "llvm/Transforms/Utils/Local.h"
Devang Patel990e8662007-07-11 23:47:28 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Devang Patelc4625da2007-04-07 01:25:15 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/SmallVector.h"
Devang Patelc4625da2007-04-07 01:25:15 +000028using namespace llvm;
29
30#define MAX_HEADER_SIZE 16
31
32STATISTIC(NumRotated, "Number of loops rotated");
33namespace {
34
Chris Lattner3e8b6632009-09-02 06:11:42 +000035 class RenameData {
Devang Patelc4625da2007-04-07 01:25:15 +000036 public:
Devang Patele9881542007-04-09 19:04:21 +000037 RenameData(Instruction *O, Value *P, Instruction *H)
Devang Patel32231332007-04-09 16:11:48 +000038 : Original(O), PreHeader(P), Header(H) { }
Devang Patelc4625da2007-04-07 01:25:15 +000039 public:
40 Instruction *Original; // Original instruction
Devang Patele9881542007-04-09 19:04:21 +000041 Value *PreHeader; // Original pre-header replacement
Devang Patelc4625da2007-04-07 01:25:15 +000042 Instruction *Header; // New header replacement
43 };
Devang Patel32231332007-04-09 16:11:48 +000044
Chris Lattner3e8b6632009-09-02 06:11:42 +000045 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000046 public:
Devang Patel19974732007-05-03 01:11:54 +000047 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000048 LoopRotate() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000049
Devang Patel32231332007-04-09 16:11:48 +000050 // Rotate Loop L as many times as possible. Return true if
51 // loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +000052 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel32231332007-04-09 16:11:48 +000053
54 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000055 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel9d9b2042008-02-15 01:24:49 +000056 AU.addRequiredID(LoopSimplifyID);
57 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000058 AU.addRequiredID(LCSSAID);
59 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000060 AU.addPreserved<ScalarEvolution>();
61 AU.addPreserved<LoopInfo>();
Devang Pateld9a6dcb2007-07-30 20:22:53 +000062 AU.addPreserved<DominatorTree>();
63 AU.addPreserved<DominanceFrontier>();
Devang Patelc4625da2007-04-07 01:25:15 +000064 }
65
66 // Helper functions
67
68 /// Do actual work
69 bool rotateLoop(Loop *L, LPPassManager &LPM);
70
71 /// Initialize local data
72 void initialize();
73
74 /// Make sure all Exit block PHINodes have required incoming values.
75 /// If incoming value is constant or defined outside the loop then
Devang Patele9881542007-04-09 19:04:21 +000076 /// PHINode may not have an entry for original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +000077 void updateExitBlock();
78
79 /// Return true if this instruction is used outside original header.
80 bool usedOutsideOriginalHeader(Instruction *In);
81
82 /// Find Replacement information for instruction. Return NULL if it is
83 /// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +000084 const RenameData *findReplacementData(Instruction *I);
Devang Patelc4625da2007-04-07 01:25:15 +000085
Devang Patel5464b962007-04-09 20:19:46 +000086 /// After loop rotation, loop pre-header has multiple sucessors.
87 /// Insert one forwarding basic block to ensure that loop pre-header
88 /// has only one successor.
89 void preserveCanonicalLoopForm(LPPassManager &LPM);
90
Devang Patelc4625da2007-04-07 01:25:15 +000091 private:
92
93 Loop *L;
94 BasicBlock *OrigHeader;
95 BasicBlock *OrigPreHeader;
96 BasicBlock *OrigLatch;
97 BasicBlock *NewHeader;
Devang Patelc4625da2007-04-07 01:25:15 +000098 BasicBlock *Exit;
Devang Patel990e8662007-07-11 23:47:28 +000099 LPPassManager *LPM_Ptr;
Devang Patel32231332007-04-09 16:11:48 +0000100 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
Devang Patelc4625da2007-04-07 01:25:15 +0000101 };
Devang Patelc4625da2007-04-07 01:25:15 +0000102}
Dan Gohman844731a2008-05-13 00:00:25 +0000103
104char LoopRotate::ID = 0;
105static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
Devang Patelc4625da2007-04-07 01:25:15 +0000106
Daniel Dunbar394f0442008-10-22 23:32:42 +0000107Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +0000108
Devang Patel32231332007-04-09 16:11:48 +0000109/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +0000110/// the loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +0000111bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patel990e8662007-07-11 23:47:28 +0000112
Devang Patelc4625da2007-04-07 01:25:15 +0000113 bool RotatedOneLoop = false;
114 initialize();
Devang Patel990e8662007-07-11 23:47:28 +0000115 LPM_Ptr = &LPM;
Devang Patelc4625da2007-04-07 01:25:15 +0000116
117 // One loop can be rotated multiple times.
118 while (rotateLoop(Lp,LPM)) {
119 RotatedOneLoop = true;
120 initialize();
121 }
122
123 return RotatedOneLoop;
124}
125
Dan Gohman23d9d272007-05-11 21:10:54 +0000126/// Rotate loop LP. Return true if the loop is rotated.
Devang Patelc4625da2007-04-07 01:25:15 +0000127bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patelc4625da2007-04-07 01:25:15 +0000128 L = Lp;
Devang Patelc4625da2007-04-07 01:25:15 +0000129
130 OrigHeader = L->getHeader();
131 OrigPreHeader = L->getLoopPreheader();
132 OrigLatch = L->getLoopLatch();
133
Dan Gohmancc4e6052009-06-25 00:22:44 +0000134 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000135 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000136 return false;
137
Chris Lattner2ba25432009-01-26 01:38:24 +0000138 assert(OrigHeader && OrigLatch && OrigPreHeader &&
139 "Loop is not in canonical form");
Devang Patele9881542007-04-09 19:04:21 +0000140
Dan Gohmancc4e6052009-06-25 00:22:44 +0000141 // If the loop header is not one of the loop exiting blocks then
142 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000143 // suitable for loop rotation transformations.
144 if (!L->isLoopExit(OrigHeader))
145 return false;
146
147 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
148 if (!BI)
149 return false;
Chris Lattner2ba25432009-01-26 01:38:24 +0000150 assert(BI->isConditional() && "Branch Instruction is not conditional");
Devang Patelc4625da2007-04-07 01:25:15 +0000151
Devang Patel32231332007-04-09 16:11:48 +0000152 // Updating PHInodes in loops with multiple exits adds complexity.
153 // Keep it simple, and restrict loop rotation to loops with one exit only.
154 // In future, lift this restriction and support for multiple exits if
155 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000156 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000157 L->getExitBlocks(ExitBlocks);
158 if (ExitBlocks.size() > 1)
159 return false;
160
Devang Patel990e8662007-07-11 23:47:28 +0000161 // Check size of original header and reject
162 // loop if it is very big.
Devang Patel3f43a702009-03-06 03:51:30 +0000163 unsigned Size = 0;
164
165 // FIXME: Use common api to estimate size.
166 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
167 OE = OrigHeader->end(); OI != OE; ++OI) {
168 if (isa<PHINode>(OI))
169 continue; // PHI nodes don't count.
170 if (isa<DbgInfoIntrinsic>(OI))
171 continue; // Debug intrinsics don't count as size.
172 Size++;
173 }
174
175 if (Size > MAX_HEADER_SIZE)
Devang Patel990e8662007-07-11 23:47:28 +0000176 return false;
177
178 // Now, this loop is suitable for rotation.
179
Devang Patelc4625da2007-04-07 01:25:15 +0000180 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000181 // that is inside loop. Header's other successor is outside the
182 // loop. Otherwise loop is not suitable for rotation.
Devang Patel32231332007-04-09 16:11:48 +0000183 Exit = BI->getSuccessor(0);
184 NewHeader = BI->getSuccessor(1);
185 if (L->contains(Exit))
186 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000187 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000188 assert(L->contains(NewHeader) && !L->contains(Exit) &&
189 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000190
Dan Gohmancc4e6052009-06-25 00:22:44 +0000191 // This code assumes that the new header has exactly one predecessor.
192 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000193 assert(NewHeader->getSinglePredecessor() &&
194 "New header doesn't have one pred!");
195 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000196
Dan Gohmancc4e6052009-06-25 00:22:44 +0000197 // Copy PHI nodes and other instructions from the original header
198 // into the original pre-header. Unlike the original header, the original
199 // pre-header is not a member of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000200 //
Dan Gohmancc4e6052009-06-25 00:22:44 +0000201 // The new loop header is the one and only successor of original header that
Devang Patelc4625da2007-04-07 01:25:15 +0000202 // is inside the loop. All other original header successors are outside
Dan Gohmancc4e6052009-06-25 00:22:44 +0000203 // the loop. Copy PHI Nodes from the original header into the new loop header.
Devang Patele9881542007-04-09 19:04:21 +0000204 // Add second incoming value, from original loop pre-header into these phi
Devang Patelc4625da2007-04-07 01:25:15 +0000205 // nodes. If a value defined in original header is used outside original
206 // header then new loop header will need new phi nodes with two incoming
207 // values, one definition from original header and second definition is
Devang Patele9881542007-04-09 19:04:21 +0000208 // from original loop pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000209
Devang Patele9881542007-04-09 19:04:21 +0000210 // Remove terminator from Original pre-header. Original pre-header will
211 // receive a clone of original header terminator as a new terminator.
212 OrigPreHeader->getInstList().pop_back();
Devang Patel32231332007-04-09 16:11:48 +0000213 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000214 PHINode *PN = 0;
Devang Patel4522c8a2007-04-09 17:09:13 +0000215 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patele9881542007-04-09 19:04:21 +0000216 // PHI nodes are not copied into original pre-header. Instead their values
217 // are directly propagated.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000218 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000219
Dan Gohmancc4e6052009-06-25 00:22:44 +0000220 // Create a new PHI node with two incoming values for NewHeader.
221 // One incoming value is from OrigLatch (through OrigHeader) and the
Devang Patele9881542007-04-09 19:04:21 +0000222 // second incoming value is from original pre-header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000223 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
Dan Gohman610c0e22008-06-19 17:37:25 +0000224 NewHeader->begin());
Devang Patel32231332007-04-09 16:11:48 +0000225 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
Devang Patele9881542007-04-09 19:04:21 +0000226 NH->addIncoming(NPV, OrigPreHeader);
Devang Patel32231332007-04-09 16:11:48 +0000227
Devang Patele9881542007-04-09 19:04:21 +0000228 // "In" can be replaced by NH at various places.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000229 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
Devang Patel32231332007-04-09 16:11:48 +0000230 }
Devang Patelc4625da2007-04-07 01:25:15 +0000231
Devang Patel32231332007-04-09 16:11:48 +0000232 // Now, handle non-phi instructions.
233 for (; I != E; ++I) {
234 Instruction *In = I;
Chris Lattner2ba25432009-01-26 01:38:24 +0000235 assert(!isa<PHINode>(In) && "PHINode is not expected here");
Chris Lattnerf6784a32009-01-26 01:57:01 +0000236
Devang Patele9881542007-04-09 19:04:21 +0000237 // This is not a PHI instruction. Insert its clone into original pre-header.
Devang Patel32231332007-04-09 16:11:48 +0000238 // If this instruction is using a value from same basic block then
239 // update it to use value from cloned instruction.
Owen Andersone922c022009-07-22 00:24:57 +0000240 Instruction *C = In->clone(In->getContext());
Owen Anderson6bc41e82008-04-14 17:38:21 +0000241 C->setName(In->getName());
Devang Patele9881542007-04-09 19:04:21 +0000242 OrigPreHeader->getInstList().push_back(C);
243
244 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000245 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
246 if (!OpInsn) continue; // Ignore non-instruction values.
247 if (const RenameData *D = findReplacementData(OpInsn))
248 C->setOperand(opi, D->PreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000249 }
250
Devang Patel32231332007-04-09 16:11:48 +0000251 // If this instruction is used outside this basic block then
252 // create new PHINode for this instruction.
253 Instruction *NewHeaderReplacement = NULL;
254 if (usedOutsideOriginalHeader(In)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000255 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
256 NewHeader->begin());
257 PN->addIncoming(In, OrigHeader);
258 PN->addIncoming(C, OrigPreHeader);
259 NewHeaderReplacement = PN;
Dale Johannesen79602672008-05-01 22:27:44 +0000260 }
Devang Patel32231332007-04-09 16:11:48 +0000261 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
Devang Patelc4625da2007-04-07 01:25:15 +0000262 }
263
Devang Patelc4625da2007-04-07 01:25:15 +0000264 // Rename uses of original header instructions to reflect their new
Devang Patele9881542007-04-09 19:04:21 +0000265 // definitions (either from original pre-header node or from newly created
Devang Patelc4625da2007-04-07 01:25:15 +0000266 // new header PHINodes.
267 //
268 // Original header instructions are used in
269 // 1) Original header:
270 //
271 // If instruction is used in non-phi instructions then it is using
272 // defintion from original heder iteself. Do not replace this use
Devang Patele9881542007-04-09 19:04:21 +0000273 // with definition from new header or original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000274 //
275 // If instruction is used in phi node then it is an incoming
276 // value. Rename its use to reflect new definition from new-preheader
277 // or new header.
278 //
279 // 2) Inside loop but not in original header
280 //
281 // Replace this use to reflect definition from new header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000282 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000283 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
Devang Patelc4625da2007-04-07 01:25:15 +0000284
Devang Patel32231332007-04-09 16:11:48 +0000285 if (!ILoopHeaderInfo.Header)
Devang Patelc4625da2007-04-07 01:25:15 +0000286 continue;
287
Devang Patel32231332007-04-09 16:11:48 +0000288 Instruction *OldPhi = ILoopHeaderInfo.Original;
289 Instruction *NewPhi = ILoopHeaderInfo.Header;
Devang Patelc4625da2007-04-07 01:25:15 +0000290
291 // Before replacing uses, collect them first, so that iterator is
292 // not invalidated.
293 SmallVector<Instruction *, 16> AllUses;
294 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000295 UI != UE; ++UI)
296 AllUses.push_back(cast<Instruction>(UI));
Devang Patelc4625da2007-04-07 01:25:15 +0000297
298 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
299 UE = AllUses.end(); UI != UE; ++UI) {
300 Instruction *U = *UI;
301 BasicBlock *Parent = U->getParent();
302
303 // Used inside original header
304 if (Parent == OrigHeader) {
305 // Do not rename uses inside original header non-phi instructions.
Devang Patelc4625da2007-04-07 01:25:15 +0000306 PHINode *PU = dyn_cast<PHINode>(U);
Devang Patel24a1c492007-04-09 16:21:29 +0000307 if (!PU)
308 continue;
309
Devang Patelc4625da2007-04-07 01:25:15 +0000310 // Do not rename uses inside original header phi nodes, if the
311 // incoming value is for new header.
312 if (PU->getBasicBlockIndex(NewHeader) != -1
313 && PU->getIncomingValueForBlock(NewHeader) == U)
314 continue;
Devang Patel4522c8a2007-04-09 17:09:13 +0000315
Devang Patelc4625da2007-04-07 01:25:15 +0000316 U->replaceUsesOfWith(OldPhi, NewPhi);
317 continue;
318 }
319
320 // Used inside loop, but not in original header.
321 if (L->contains(U->getParent())) {
Devang Patel24a1c492007-04-09 16:21:29 +0000322 if (U != NewPhi)
Devang Patelc4625da2007-04-07 01:25:15 +0000323 U->replaceUsesOfWith(OldPhi, NewPhi);
324 continue;
325 }
Nick Lewycky8f5149e2007-07-07 16:23:34 +0000326
Devang Patel990e8662007-07-11 23:47:28 +0000327 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
328 if (U->getParent() == Exit) {
Chris Lattner2ba25432009-01-26 01:38:24 +0000329 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
Devang Patel990e8662007-07-11 23:47:28 +0000330
331 PHINode *UPhi = cast<PHINode>(U);
332 // UPhi already has one incoming argument from original header.
333 // Add second incoming argument from new Pre header.
334 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
335 } else {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000336 // Used outside Exit block. Create a new PHI node in the exit block
337 // to receive the value from the new header and pre-header.
Dan Gohman610c0e22008-06-19 17:37:25 +0000338 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
339 Exit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000340 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
341 PN->addIncoming(OldPhi, OrigHeader);
Devang Patel990e8662007-07-11 23:47:28 +0000342 U->replaceUsesOfWith(OldPhi, PN);
343 }
Devang Patelc4625da2007-04-07 01:25:15 +0000344 }
345 }
346
347 /// Make sure all Exit block PHINodes have required incoming values.
348 updateExitBlock();
349
350 // Update CFG
351
352 // Removing incoming branch from loop preheader to original header.
353 // Now original header is inside the loop.
Dan Gohmancfb32202009-06-27 21:23:40 +0000354 for (BasicBlock::iterator I = OrigHeader->begin();
355 (PN = dyn_cast<PHINode>(I)); ++I)
356 PN->removeIncomingValue(OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000357
358 // Make NewHeader as the new header for the loop.
359 L->moveToHeader(NewHeader);
360
Devang Patel5464b962007-04-09 20:19:46 +0000361 preserveCanonicalLoopForm(LPM);
362
Devang Patelc4625da2007-04-07 01:25:15 +0000363 NumRotated++;
364 return true;
365}
366
Devang Patelc4625da2007-04-07 01:25:15 +0000367/// Make sure all Exit block PHINodes have required incoming values.
Dan Gohmancc4e6052009-06-25 00:22:44 +0000368/// If an incoming value is constant or defined outside the loop then
369/// PHINode may not have an entry for the original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000370void LoopRotate::updateExitBlock() {
371
Dan Gohmane1047fb2009-06-26 00:35:12 +0000372 PHINode *PN;
Dan Gohman30d670f2009-06-26 00:26:03 +0000373 for (BasicBlock::iterator I = Exit->begin();
Dan Gohmane1047fb2009-06-26 00:35:12 +0000374 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patelc4625da2007-04-07 01:25:15 +0000375
Devang Patele9881542007-04-09 19:04:21 +0000376 // There is already one incoming value from original pre-header block.
377 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
Devang Patel6c361572007-04-09 22:20:10 +0000378 continue;
Devang Patelcfde9592007-04-09 16:41:46 +0000379
Devang Patel4522c8a2007-04-09 17:09:13 +0000380 const RenameData *ILoopHeaderInfo;
Devang Patelcfde9592007-04-09 16:41:46 +0000381 Value *V = PN->getIncomingValueForBlock(OrigHeader);
Dan Gohman30d670f2009-06-26 00:26:03 +0000382 if (isa<Instruction>(V) &&
Devang Patelcfde9592007-04-09 16:41:46 +0000383 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
Chris Lattnere34e9a22007-04-14 23:32:02 +0000384 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
Devang Patele9881542007-04-09 19:04:21 +0000385 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
Devang Patelcfde9592007-04-09 16:41:46 +0000386 } else {
Devang Patele9881542007-04-09 19:04:21 +0000387 PN->addIncoming(V, OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000388 }
389 }
390}
391
Devang Patelc4625da2007-04-07 01:25:15 +0000392/// Initialize local data
393void LoopRotate::initialize() {
394 L = NULL;
395 OrigHeader = NULL;
396 OrigPreHeader = NULL;
397 NewHeader = NULL;
Devang Patelc4625da2007-04-07 01:25:15 +0000398 Exit = NULL;
399
Devang Patel32231332007-04-09 16:11:48 +0000400 LoopHeaderInfo.clear();
Devang Patelc4625da2007-04-07 01:25:15 +0000401}
402
Devang Patel24a1c492007-04-09 16:21:29 +0000403/// Return true if this instruction is used by any instructions in the loop that
404/// aren't in original header.
Devang Patelc4625da2007-04-07 01:25:15 +0000405bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000406 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
407 UI != UE; ++UI) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000408 BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
409 if (UserBB != OrigHeader && L->contains(UserBB))
410 return true;
Devang Patelc4625da2007-04-07 01:25:15 +0000411 }
412
413 return false;
414}
415
416/// Find Replacement information for instruction. Return NULL if it is
417/// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +0000418const RenameData *LoopRotate::findReplacementData(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000419
Devang Patel32231332007-04-09 16:11:48 +0000420 // Since LoopHeaderInfo is small, linear walk is OK.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000421 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000422 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
423 if (ILoopHeaderInfo.Original == In)
424 return &ILoopHeaderInfo;
425 }
Devang Patelc4625da2007-04-07 01:25:15 +0000426 return NULL;
427}
Devang Patel5464b962007-04-09 20:19:46 +0000428
429/// After loop rotation, loop pre-header has multiple sucessors.
430/// Insert one forwarding basic block to ensure that loop pre-header
431/// has only one successor.
432void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
433
434 // Right now original pre-header has two successors, new header and
435 // exit block. Insert new block between original pre-header and
436 // new header such that loop's new pre-header has only one successor.
Owen Anderson1d0be152009-08-13 21:58:54 +0000437 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
438 "bb.nph",
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000439 OrigHeader->getParent(),
Gabor Greif051a9502008-04-06 20:25:17 +0000440 NewHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000441 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
442 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000443 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000444 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000445
446 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
447 if (OrigPH_BI->getSuccessor(0) == NewHeader)
448 OrigPH_BI->setSuccessor(0, NewPreHeader);
449 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000450 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
451 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000452 OrigPH_BI->setSuccessor(1, NewPreHeader);
453 }
Devang Patel5464b962007-04-09 20:19:46 +0000454
Dan Gohmancfb32202009-06-27 21:23:40 +0000455 PHINode *PN;
456 for (BasicBlock::iterator I = NewHeader->begin();
457 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel5464b962007-04-09 20:19:46 +0000458 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000459 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000460 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000461 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
462 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000463 }
464
Duncan Sands1465d612009-01-28 13:14:17 +0000465 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000466 DT->addNewBlock(NewPreHeader, OrigPreHeader);
467 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
468 DT->changeImmediateDominator(Exit, OrigPreHeader);
469 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
470 BI != BE; ++BI) {
471 BasicBlock *B = *BI;
472 if (L->getHeader() != B) {
473 DomTreeNode *Node = DT->getNode(B);
474 if (Node && Node->getBlock() == OrigHeader)
475 DT->changeImmediateDominator(*BI, L->getHeader());
476 }
477 }
478 DT->changeImmediateDominator(OrigHeader, OrigLatch);
479 }
480
Duncan Sands1465d612009-01-28 13:14:17 +0000481 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000482 // New Preheader's dominance frontier is Exit block.
483 DominanceFrontier::DomSetType NewPHSet;
484 NewPHSet.insert(Exit);
485 DF->addBasicBlock(NewPreHeader, NewPHSet);
486
487 // New Header's dominance frontier now includes itself and Exit block
488 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
489 if (HeadI != DF->end()) {
490 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
491 HeaderSet.clear();
492 HeaderSet.insert(L->getHeader());
493 HeaderSet.insert(Exit);
494 } else {
495 DominanceFrontier::DomSetType HeaderSet;
496 HeaderSet.insert(L->getHeader());
497 HeaderSet.insert(Exit);
498 DF->addBasicBlock(L->getHeader(), HeaderSet);
499 }
500
501 // Original header (new Loop Latch)'s dominance frontier is Exit.
502 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
503 if (LatchI != DF->end()) {
504 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
505 LatchSet = LatchI->second;
506 LatchSet.clear();
507 LatchSet.insert(Exit);
508 } else {
509 DominanceFrontier::DomSetType LatchSet;
510 LatchSet.insert(Exit);
511 DF->addBasicBlock(L->getHeader(), LatchSet);
512 }
513
Devang Patelb7f40c12009-08-07 17:16:44 +0000514 // If a loop block dominates new loop latch then add to its frontiers
515 // new header and Exit and remove new latch (which is equal to original
516 // header).
Devang Patel990e8662007-07-11 23:47:28 +0000517 BasicBlock *NewLatch = L->getLoopLatch();
Devang Patelb7f40c12009-08-07 17:16:44 +0000518
519 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
520
521 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
522 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
523 BI != BE; ++BI) {
524 BasicBlock *B = *BI;
525 if (DT->dominates(B, NewLatch)) {
526 DominanceFrontier::iterator BDFI = DF->find(B);
527 if (BDFI != DF->end()) {
528 DominanceFrontier::DomSetType &BSet = BDFI->second;
529 BSet.erase(NewLatch);
530 BSet.insert(L->getHeader());
531 BSet.insert(Exit);
532 } else {
533 DominanceFrontier::DomSetType BSet;
534 BSet.insert(L->getHeader());
535 BSet.insert(Exit);
536 DF->addBasicBlock(B, BSet);
537 }
Devang Patel990e8662007-07-11 23:47:28 +0000538 }
539 }
540 }
541 }
542
543 // Preserve canonical loop form, which means Exit block should
544 // have only one predecessor.
545 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
546
547 // Preserve LCSSA.
Dan Gohmancfb32202009-06-27 21:23:40 +0000548 for (BasicBlock::iterator I = Exit->begin();
549 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel990e8662007-07-11 23:47:28 +0000550 unsigned N = PN->getNumIncomingValues();
Dan Gohmancfb32202009-06-27 21:23:40 +0000551 for (unsigned index = 0; index != N; ++index)
Devang Patel990e8662007-07-11 23:47:28 +0000552 if (PN->getIncomingBlock(index) == NExit) {
Dan Gohman610c0e22008-06-19 17:37:25 +0000553 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
554 NExit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000555 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
556 PN->setIncomingValue(index, NewPN);
557 PN->setIncomingBlock(index, NExit);
Dan Gohman610c0e22008-06-19 17:37:25 +0000558 break;
Devang Patel990e8662007-07-11 23:47:28 +0000559 }
560 }
561
Chris Lattner2ba25432009-01-26 01:38:24 +0000562 assert(NewHeader && L->getHeader() == NewHeader &&
563 "Invalid loop header after loop rotation");
564 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
565 "Invalid loop preheader after loop rotation");
566 assert(L->getLoopLatch() &&
567 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000568}