blob: 70c69bb1dae0016735483fc40806cf2288ef668a [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
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000180 // Anything ScalarEvolution may know about this loop or the PHI nodes
181 // in its header will soon be invalidated.
182 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
183 SE->forgetLoopBackedgeTakenCount(L);
184
Devang Patelc4625da2007-04-07 01:25:15 +0000185 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000186 // that is inside loop. Header's other successor is outside the
187 // loop. Otherwise loop is not suitable for rotation.
Devang Patel32231332007-04-09 16:11:48 +0000188 Exit = BI->getSuccessor(0);
189 NewHeader = BI->getSuccessor(1);
190 if (L->contains(Exit))
191 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000192 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000193 assert(L->contains(NewHeader) && !L->contains(Exit) &&
194 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000195
Dan Gohmancc4e6052009-06-25 00:22:44 +0000196 // This code assumes that the new header has exactly one predecessor.
197 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000198 assert(NewHeader->getSinglePredecessor() &&
199 "New header doesn't have one pred!");
200 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000201
Dan Gohmancc4e6052009-06-25 00:22:44 +0000202 // Copy PHI nodes and other instructions from the original header
203 // into the original pre-header. Unlike the original header, the original
204 // pre-header is not a member of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000205 //
Dan Gohmancc4e6052009-06-25 00:22:44 +0000206 // The new loop header is the one and only successor of original header that
Devang Patelc4625da2007-04-07 01:25:15 +0000207 // is inside the loop. All other original header successors are outside
Dan Gohmancc4e6052009-06-25 00:22:44 +0000208 // the loop. Copy PHI Nodes from the original header into the new loop header.
Devang Patele9881542007-04-09 19:04:21 +0000209 // Add second incoming value, from original loop pre-header into these phi
Devang Patelc4625da2007-04-07 01:25:15 +0000210 // nodes. If a value defined in original header is used outside original
211 // header then new loop header will need new phi nodes with two incoming
212 // values, one definition from original header and second definition is
Devang Patele9881542007-04-09 19:04:21 +0000213 // from original loop pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000214
Devang Patele9881542007-04-09 19:04:21 +0000215 // Remove terminator from Original pre-header. Original pre-header will
216 // receive a clone of original header terminator as a new terminator.
217 OrigPreHeader->getInstList().pop_back();
Devang Patel32231332007-04-09 16:11:48 +0000218 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000219 PHINode *PN = 0;
Devang Patel4522c8a2007-04-09 17:09:13 +0000220 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patele9881542007-04-09 19:04:21 +0000221 // PHI nodes are not copied into original pre-header. Instead their values
222 // are directly propagated.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000223 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000224
Dan Gohmancc4e6052009-06-25 00:22:44 +0000225 // Create a new PHI node with two incoming values for NewHeader.
226 // One incoming value is from OrigLatch (through OrigHeader) and the
Devang Patele9881542007-04-09 19:04:21 +0000227 // second incoming value is from original pre-header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000228 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
Dan Gohman610c0e22008-06-19 17:37:25 +0000229 NewHeader->begin());
Devang Patel32231332007-04-09 16:11:48 +0000230 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
Devang Patele9881542007-04-09 19:04:21 +0000231 NH->addIncoming(NPV, OrigPreHeader);
Devang Patel32231332007-04-09 16:11:48 +0000232
Devang Patele9881542007-04-09 19:04:21 +0000233 // "In" can be replaced by NH at various places.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000234 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
Devang Patel32231332007-04-09 16:11:48 +0000235 }
Devang Patelc4625da2007-04-07 01:25:15 +0000236
Devang Patel32231332007-04-09 16:11:48 +0000237 // Now, handle non-phi instructions.
238 for (; I != E; ++I) {
239 Instruction *In = I;
Chris Lattner2ba25432009-01-26 01:38:24 +0000240 assert(!isa<PHINode>(In) && "PHINode is not expected here");
Chris Lattnerf6784a32009-01-26 01:57:01 +0000241
Devang Patele9881542007-04-09 19:04:21 +0000242 // This is not a PHI instruction. Insert its clone into original pre-header.
Devang Patel32231332007-04-09 16:11:48 +0000243 // If this instruction is using a value from same basic block then
244 // update it to use value from cloned instruction.
Nick Lewycky67760642009-09-27 07:38:41 +0000245 Instruction *C = In->clone();
Owen Anderson6bc41e82008-04-14 17:38:21 +0000246 C->setName(In->getName());
Devang Patele9881542007-04-09 19:04:21 +0000247 OrigPreHeader->getInstList().push_back(C);
248
249 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000250 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
251 if (!OpInsn) continue; // Ignore non-instruction values.
252 if (const RenameData *D = findReplacementData(OpInsn))
253 C->setOperand(opi, D->PreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000254 }
255
Devang Patel32231332007-04-09 16:11:48 +0000256 // If this instruction is used outside this basic block then
257 // create new PHINode for this instruction.
258 Instruction *NewHeaderReplacement = NULL;
259 if (usedOutsideOriginalHeader(In)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000260 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
261 NewHeader->begin());
262 PN->addIncoming(In, OrigHeader);
263 PN->addIncoming(C, OrigPreHeader);
264 NewHeaderReplacement = PN;
Dale Johannesen79602672008-05-01 22:27:44 +0000265 }
Devang Patel32231332007-04-09 16:11:48 +0000266 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
Devang Patelc4625da2007-04-07 01:25:15 +0000267 }
268
Devang Patelc4625da2007-04-07 01:25:15 +0000269 // Rename uses of original header instructions to reflect their new
Devang Patele9881542007-04-09 19:04:21 +0000270 // definitions (either from original pre-header node or from newly created
Devang Patelc4625da2007-04-07 01:25:15 +0000271 // new header PHINodes.
272 //
273 // Original header instructions are used in
274 // 1) Original header:
275 //
276 // If instruction is used in non-phi instructions then it is using
277 // defintion from original heder iteself. Do not replace this use
Devang Patele9881542007-04-09 19:04:21 +0000278 // with definition from new header or original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000279 //
280 // If instruction is used in phi node then it is an incoming
281 // value. Rename its use to reflect new definition from new-preheader
282 // or new header.
283 //
284 // 2) Inside loop but not in original header
285 //
286 // Replace this use to reflect definition from new header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000287 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000288 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
Devang Patelc4625da2007-04-07 01:25:15 +0000289
Devang Patel32231332007-04-09 16:11:48 +0000290 if (!ILoopHeaderInfo.Header)
Devang Patelc4625da2007-04-07 01:25:15 +0000291 continue;
292
Devang Patel32231332007-04-09 16:11:48 +0000293 Instruction *OldPhi = ILoopHeaderInfo.Original;
294 Instruction *NewPhi = ILoopHeaderInfo.Header;
Devang Patelc4625da2007-04-07 01:25:15 +0000295
296 // Before replacing uses, collect them first, so that iterator is
297 // not invalidated.
298 SmallVector<Instruction *, 16> AllUses;
299 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000300 UI != UE; ++UI)
301 AllUses.push_back(cast<Instruction>(UI));
Devang Patelc4625da2007-04-07 01:25:15 +0000302
303 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
304 UE = AllUses.end(); UI != UE; ++UI) {
305 Instruction *U = *UI;
306 BasicBlock *Parent = U->getParent();
307
308 // Used inside original header
309 if (Parent == OrigHeader) {
310 // Do not rename uses inside original header non-phi instructions.
Devang Patelc4625da2007-04-07 01:25:15 +0000311 PHINode *PU = dyn_cast<PHINode>(U);
Devang Patel24a1c492007-04-09 16:21:29 +0000312 if (!PU)
313 continue;
314
Devang Patelc4625da2007-04-07 01:25:15 +0000315 // Do not rename uses inside original header phi nodes, if the
316 // incoming value is for new header.
317 if (PU->getBasicBlockIndex(NewHeader) != -1
318 && PU->getIncomingValueForBlock(NewHeader) == U)
319 continue;
Devang Patel4522c8a2007-04-09 17:09:13 +0000320
Devang Patelc4625da2007-04-07 01:25:15 +0000321 U->replaceUsesOfWith(OldPhi, NewPhi);
322 continue;
323 }
324
325 // Used inside loop, but not in original header.
326 if (L->contains(U->getParent())) {
Devang Patel24a1c492007-04-09 16:21:29 +0000327 if (U != NewPhi)
Devang Patelc4625da2007-04-07 01:25:15 +0000328 U->replaceUsesOfWith(OldPhi, NewPhi);
329 continue;
330 }
Nick Lewycky8f5149e2007-07-07 16:23:34 +0000331
Devang Patel990e8662007-07-11 23:47:28 +0000332 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
333 if (U->getParent() == Exit) {
Chris Lattner2ba25432009-01-26 01:38:24 +0000334 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
Devang Patel990e8662007-07-11 23:47:28 +0000335
336 PHINode *UPhi = cast<PHINode>(U);
337 // UPhi already has one incoming argument from original header.
338 // Add second incoming argument from new Pre header.
339 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
340 } else {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000341 // Used outside Exit block. Create a new PHI node in the exit block
342 // to receive the value from the new header and pre-header.
Dan Gohman610c0e22008-06-19 17:37:25 +0000343 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
344 Exit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000345 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
346 PN->addIncoming(OldPhi, OrigHeader);
Devang Patel990e8662007-07-11 23:47:28 +0000347 U->replaceUsesOfWith(OldPhi, PN);
348 }
Devang Patelc4625da2007-04-07 01:25:15 +0000349 }
350 }
351
352 /// Make sure all Exit block PHINodes have required incoming values.
353 updateExitBlock();
354
355 // Update CFG
356
357 // Removing incoming branch from loop preheader to original header.
358 // Now original header is inside the loop.
Dan Gohmancfb32202009-06-27 21:23:40 +0000359 for (BasicBlock::iterator I = OrigHeader->begin();
360 (PN = dyn_cast<PHINode>(I)); ++I)
361 PN->removeIncomingValue(OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000362
363 // Make NewHeader as the new header for the loop.
364 L->moveToHeader(NewHeader);
365
Devang Patel5464b962007-04-09 20:19:46 +0000366 preserveCanonicalLoopForm(LPM);
367
Devang Patelc4625da2007-04-07 01:25:15 +0000368 NumRotated++;
369 return true;
370}
371
Devang Patelc4625da2007-04-07 01:25:15 +0000372/// Make sure all Exit block PHINodes have required incoming values.
Dan Gohmancc4e6052009-06-25 00:22:44 +0000373/// If an incoming value is constant or defined outside the loop then
374/// PHINode may not have an entry for the original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000375void LoopRotate::updateExitBlock() {
376
Dan Gohmane1047fb2009-06-26 00:35:12 +0000377 PHINode *PN;
Dan Gohman30d670f2009-06-26 00:26:03 +0000378 for (BasicBlock::iterator I = Exit->begin();
Dan Gohmane1047fb2009-06-26 00:35:12 +0000379 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patelc4625da2007-04-07 01:25:15 +0000380
Devang Patele9881542007-04-09 19:04:21 +0000381 // There is already one incoming value from original pre-header block.
382 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
Devang Patel6c361572007-04-09 22:20:10 +0000383 continue;
Devang Patelcfde9592007-04-09 16:41:46 +0000384
Devang Patel4522c8a2007-04-09 17:09:13 +0000385 const RenameData *ILoopHeaderInfo;
Devang Patelcfde9592007-04-09 16:41:46 +0000386 Value *V = PN->getIncomingValueForBlock(OrigHeader);
Dan Gohman30d670f2009-06-26 00:26:03 +0000387 if (isa<Instruction>(V) &&
Devang Patelcfde9592007-04-09 16:41:46 +0000388 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
Chris Lattnere34e9a22007-04-14 23:32:02 +0000389 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
Devang Patele9881542007-04-09 19:04:21 +0000390 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
Devang Patelcfde9592007-04-09 16:41:46 +0000391 } else {
Devang Patele9881542007-04-09 19:04:21 +0000392 PN->addIncoming(V, OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000393 }
394 }
395}
396
Devang Patelc4625da2007-04-07 01:25:15 +0000397/// Initialize local data
398void LoopRotate::initialize() {
399 L = NULL;
400 OrigHeader = NULL;
401 OrigPreHeader = NULL;
402 NewHeader = NULL;
Devang Patelc4625da2007-04-07 01:25:15 +0000403 Exit = NULL;
404
Devang Patel32231332007-04-09 16:11:48 +0000405 LoopHeaderInfo.clear();
Devang Patelc4625da2007-04-07 01:25:15 +0000406}
407
Devang Patel24a1c492007-04-09 16:21:29 +0000408/// Return true if this instruction is used by any instructions in the loop that
409/// aren't in original header.
Devang Patelc4625da2007-04-07 01:25:15 +0000410bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000411 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
412 UI != UE; ++UI) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000413 BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
414 if (UserBB != OrigHeader && L->contains(UserBB))
415 return true;
Devang Patelc4625da2007-04-07 01:25:15 +0000416 }
417
418 return false;
419}
420
421/// Find Replacement information for instruction. Return NULL if it is
422/// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +0000423const RenameData *LoopRotate::findReplacementData(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000424
Devang Patel32231332007-04-09 16:11:48 +0000425 // Since LoopHeaderInfo is small, linear walk is OK.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000426 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000427 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
428 if (ILoopHeaderInfo.Original == In)
429 return &ILoopHeaderInfo;
430 }
Devang Patelc4625da2007-04-07 01:25:15 +0000431 return NULL;
432}
Devang Patel5464b962007-04-09 20:19:46 +0000433
434/// After loop rotation, loop pre-header has multiple sucessors.
435/// Insert one forwarding basic block to ensure that loop pre-header
436/// has only one successor.
437void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
438
439 // Right now original pre-header has two successors, new header and
440 // exit block. Insert new block between original pre-header and
441 // new header such that loop's new pre-header has only one successor.
Owen Anderson1d0be152009-08-13 21:58:54 +0000442 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
443 "bb.nph",
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000444 OrigHeader->getParent(),
Gabor Greif051a9502008-04-06 20:25:17 +0000445 NewHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000446 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
447 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000448 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000449 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000450
451 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
452 if (OrigPH_BI->getSuccessor(0) == NewHeader)
453 OrigPH_BI->setSuccessor(0, NewPreHeader);
454 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000455 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
456 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000457 OrigPH_BI->setSuccessor(1, NewPreHeader);
458 }
Devang Patel5464b962007-04-09 20:19:46 +0000459
Dan Gohmancfb32202009-06-27 21:23:40 +0000460 PHINode *PN;
461 for (BasicBlock::iterator I = NewHeader->begin();
462 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel5464b962007-04-09 20:19:46 +0000463 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000464 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000465 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000466 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
467 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000468 }
469
Duncan Sands1465d612009-01-28 13:14:17 +0000470 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000471 DT->addNewBlock(NewPreHeader, OrigPreHeader);
472 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
473 DT->changeImmediateDominator(Exit, OrigPreHeader);
474 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
475 BI != BE; ++BI) {
476 BasicBlock *B = *BI;
477 if (L->getHeader() != B) {
478 DomTreeNode *Node = DT->getNode(B);
479 if (Node && Node->getBlock() == OrigHeader)
480 DT->changeImmediateDominator(*BI, L->getHeader());
481 }
482 }
483 DT->changeImmediateDominator(OrigHeader, OrigLatch);
484 }
485
Duncan Sands1465d612009-01-28 13:14:17 +0000486 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000487 // New Preheader's dominance frontier is Exit block.
488 DominanceFrontier::DomSetType NewPHSet;
489 NewPHSet.insert(Exit);
490 DF->addBasicBlock(NewPreHeader, NewPHSet);
491
492 // New Header's dominance frontier now includes itself and Exit block
493 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
494 if (HeadI != DF->end()) {
495 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
496 HeaderSet.clear();
497 HeaderSet.insert(L->getHeader());
498 HeaderSet.insert(Exit);
499 } else {
500 DominanceFrontier::DomSetType HeaderSet;
501 HeaderSet.insert(L->getHeader());
502 HeaderSet.insert(Exit);
503 DF->addBasicBlock(L->getHeader(), HeaderSet);
504 }
505
506 // Original header (new Loop Latch)'s dominance frontier is Exit.
507 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
508 if (LatchI != DF->end()) {
509 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
510 LatchSet = LatchI->second;
511 LatchSet.clear();
512 LatchSet.insert(Exit);
513 } else {
514 DominanceFrontier::DomSetType LatchSet;
515 LatchSet.insert(Exit);
516 DF->addBasicBlock(L->getHeader(), LatchSet);
517 }
518
Devang Patelb7f40c12009-08-07 17:16:44 +0000519 // If a loop block dominates new loop latch then add to its frontiers
520 // new header and Exit and remove new latch (which is equal to original
521 // header).
Devang Patel990e8662007-07-11 23:47:28 +0000522 BasicBlock *NewLatch = L->getLoopLatch();
Devang Patelb7f40c12009-08-07 17:16:44 +0000523
524 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
525
526 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
527 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
528 BI != BE; ++BI) {
529 BasicBlock *B = *BI;
530 if (DT->dominates(B, NewLatch)) {
531 DominanceFrontier::iterator BDFI = DF->find(B);
532 if (BDFI != DF->end()) {
533 DominanceFrontier::DomSetType &BSet = BDFI->second;
534 BSet.erase(NewLatch);
535 BSet.insert(L->getHeader());
536 BSet.insert(Exit);
537 } else {
538 DominanceFrontier::DomSetType BSet;
539 BSet.insert(L->getHeader());
540 BSet.insert(Exit);
541 DF->addBasicBlock(B, BSet);
542 }
Devang Patel990e8662007-07-11 23:47:28 +0000543 }
544 }
545 }
546 }
547
548 // Preserve canonical loop form, which means Exit block should
549 // have only one predecessor.
Dan Gohmanc292caf2009-09-09 18:18:18 +0000550 SplitEdge(L->getLoopLatch(), Exit, this);
Devang Patel990e8662007-07-11 23:47:28 +0000551
Chris Lattner2ba25432009-01-26 01:38:24 +0000552 assert(NewHeader && L->getHeader() == NewHeader &&
553 "Invalid loop header after loop rotation");
554 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
555 "Invalid loop preheader after loop rotation");
556 assert(L->getLoopLatch() &&
557 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000558}