blob: a0882301332d61012c89581b97539d8b686e1fd9 [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
Devang Patel32231332007-04-09 16:11:48 +000035 class VISIBILITY_HIDDEN 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
Devang Patelc4625da2007-04-07 01:25:15 +000045 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
46
47 public:
Devang Patel19974732007-05-03 01:11:54 +000048 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000049 LoopRotate() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000050
Devang Patel32231332007-04-09 16:11:48 +000051 // Rotate Loop L as many times as possible. Return true if
52 // loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +000053 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel32231332007-04-09 16:11:48 +000054
55 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel9d9b2042008-02-15 01:24:49 +000057 AU.addRequiredID(LoopSimplifyID);
58 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000059 AU.addRequiredID(LCSSAID);
60 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000061 AU.addPreserved<ScalarEvolution>();
62 AU.addPreserved<LoopInfo>();
Devang Pateld9a6dcb2007-07-30 20:22:53 +000063 AU.addPreserved<DominatorTree>();
64 AU.addPreserved<DominanceFrontier>();
Devang Patelc4625da2007-04-07 01:25:15 +000065 }
66
67 // Helper functions
68
69 /// Do actual work
70 bool rotateLoop(Loop *L, LPPassManager &LPM);
71
72 /// Initialize local data
73 void initialize();
74
75 /// Make sure all Exit block PHINodes have required incoming values.
76 /// If incoming value is constant or defined outside the loop then
Devang Patele9881542007-04-09 19:04:21 +000077 /// PHINode may not have an entry for original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +000078 void updateExitBlock();
79
80 /// Return true if this instruction is used outside original header.
81 bool usedOutsideOriginalHeader(Instruction *In);
82
83 /// Find Replacement information for instruction. Return NULL if it is
84 /// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +000085 const RenameData *findReplacementData(Instruction *I);
Devang Patelc4625da2007-04-07 01:25:15 +000086
Devang Patel5464b962007-04-09 20:19:46 +000087 /// After loop rotation, loop pre-header has multiple sucessors.
88 /// Insert one forwarding basic block to ensure that loop pre-header
89 /// has only one successor.
90 void preserveCanonicalLoopForm(LPPassManager &LPM);
91
Devang Patelc4625da2007-04-07 01:25:15 +000092 private:
93
94 Loop *L;
95 BasicBlock *OrigHeader;
96 BasicBlock *OrigPreHeader;
97 BasicBlock *OrigLatch;
98 BasicBlock *NewHeader;
Devang Patelc4625da2007-04-07 01:25:15 +000099 BasicBlock *Exit;
Devang Patel990e8662007-07-11 23:47:28 +0000100 LPPassManager *LPM_Ptr;
Devang Patel32231332007-04-09 16:11:48 +0000101 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
Devang Patelc4625da2007-04-07 01:25:15 +0000102 };
Devang Patelc4625da2007-04-07 01:25:15 +0000103}
Dan Gohman844731a2008-05-13 00:00:25 +0000104
105char LoopRotate::ID = 0;
106static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
Devang Patelc4625da2007-04-07 01:25:15 +0000107
Daniel Dunbar394f0442008-10-22 23:32:42 +0000108Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +0000109
Devang Patel32231332007-04-09 16:11:48 +0000110/// Rotate Loop L as many times as possible. Return true if
111/// loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +0000112bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patel990e8662007-07-11 23:47:28 +0000113
Devang Patelc4625da2007-04-07 01:25:15 +0000114 bool RotatedOneLoop = false;
115 initialize();
Devang Patel990e8662007-07-11 23:47:28 +0000116 LPM_Ptr = &LPM;
Devang Patelc4625da2007-04-07 01:25:15 +0000117
118 // One loop can be rotated multiple times.
119 while (rotateLoop(Lp,LPM)) {
120 RotatedOneLoop = true;
121 initialize();
122 }
123
124 return RotatedOneLoop;
125}
126
Dan Gohman23d9d272007-05-11 21:10:54 +0000127/// Rotate loop LP. Return true if the loop is rotated.
Devang Patelc4625da2007-04-07 01:25:15 +0000128bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patelc4625da2007-04-07 01:25:15 +0000129 L = Lp;
Devang Patelc4625da2007-04-07 01:25:15 +0000130
131 OrigHeader = L->getHeader();
132 OrigPreHeader = L->getLoopPreheader();
133 OrigLatch = L->getLoopLatch();
134
135 // If loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000136 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000137 return false;
138
Chris Lattner2ba25432009-01-26 01:38:24 +0000139 assert(OrigHeader && OrigLatch && OrigPreHeader &&
140 "Loop is not in canonical form");
Devang Patele9881542007-04-09 19:04:21 +0000141
Devang Patelc4625da2007-04-07 01:25:15 +0000142 // If loop header is not one of the loop exit block then
143 // either this loop is already rotated or it is not
144 // suitable for loop rotation transformations.
145 if (!L->isLoopExit(OrigHeader))
146 return false;
147
148 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
149 if (!BI)
150 return false;
Chris Lattner2ba25432009-01-26 01:38:24 +0000151 assert(BI->isConditional() && "Branch Instruction is not conditional");
Devang Patelc4625da2007-04-07 01:25:15 +0000152
Devang Patel32231332007-04-09 16:11:48 +0000153 // Updating PHInodes in loops with multiple exits adds complexity.
154 // Keep it simple, and restrict loop rotation to loops with one exit only.
155 // In future, lift this restriction and support for multiple exits if
156 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000157 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000158 L->getExitBlocks(ExitBlocks);
159 if (ExitBlocks.size() > 1)
160 return false;
161
Devang Patel990e8662007-07-11 23:47:28 +0000162 // Check size of original header and reject
163 // loop if it is very big.
Devang Patel3f43a702009-03-06 03:51:30 +0000164 unsigned Size = 0;
165
166 // FIXME: Use common api to estimate size.
167 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
168 OE = OrigHeader->end(); OI != OE; ++OI) {
169 if (isa<PHINode>(OI))
170 continue; // PHI nodes don't count.
171 if (isa<DbgInfoIntrinsic>(OI))
172 continue; // Debug intrinsics don't count as size.
173 Size++;
174 }
175
176 if (Size > MAX_HEADER_SIZE)
Devang Patel990e8662007-07-11 23:47:28 +0000177 return false;
178
179 // Now, this loop is suitable for rotation.
180
Devang Patelc4625da2007-04-07 01:25:15 +0000181 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000182 // that is inside loop. Header's other successor is outside the
183 // loop. Otherwise loop is not suitable for rotation.
Devang Patel32231332007-04-09 16:11:48 +0000184 Exit = BI->getSuccessor(0);
185 NewHeader = BI->getSuccessor(1);
186 if (L->contains(Exit))
187 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000188 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000189 assert(L->contains(NewHeader) && !L->contains(Exit) &&
190 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000191
192 // This code assumes that new header has exactly one predecessor. Remove any
193 // single entry PHI nodes in it.
194 assert(NewHeader->getSinglePredecessor() &&
195 "New header doesn't have one pred!");
196 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000197
Devang Patel32231332007-04-09 16:11:48 +0000198 // Copy PHI nodes and other instructions from original header
Devang Patele9881542007-04-09 19:04:21 +0000199 // into original pre-header. Unlike original header, original pre-header is
200 // not a member of loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000201 //
202 // New loop header is one and only successor of original header that
203 // is inside the loop. All other original header successors are outside
204 // the loop. Copy PHI Nodes from original header into new loop header.
Devang Patele9881542007-04-09 19:04:21 +0000205 // Add second incoming value, from original loop pre-header into these phi
Devang Patelc4625da2007-04-07 01:25:15 +0000206 // nodes. If a value defined in original header is used outside original
207 // header then new loop header will need new phi nodes with two incoming
208 // values, one definition from original header and second definition is
Devang Patele9881542007-04-09 19:04:21 +0000209 // from original loop pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000210
Devang Patele9881542007-04-09 19:04:21 +0000211 // Remove terminator from Original pre-header. Original pre-header will
212 // receive a clone of original header terminator as a new terminator.
213 OrigPreHeader->getInstList().pop_back();
Devang Patel32231332007-04-09 16:11:48 +0000214 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000215 PHINode *PN = 0;
Devang Patel4522c8a2007-04-09 17:09:13 +0000216 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patele9881542007-04-09 19:04:21 +0000217 // PHI nodes are not copied into original pre-header. Instead their values
218 // are directly propagated.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000219 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000220
Devang Patel32231332007-04-09 16:11:48 +0000221 // Create new PHI node with two incoming values for NewHeader.
222 // One incoming value is from OrigLatch (through OrigHeader) and
Devang Patele9881542007-04-09 19:04:21 +0000223 // second incoming value is from original pre-header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000224 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
Dan Gohman610c0e22008-06-19 17:37:25 +0000225 NewHeader->begin());
Devang Patel32231332007-04-09 16:11:48 +0000226 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
Devang Patele9881542007-04-09 19:04:21 +0000227 NH->addIncoming(NPV, OrigPreHeader);
Devang Patel32231332007-04-09 16:11:48 +0000228
Devang Patele9881542007-04-09 19:04:21 +0000229 // "In" can be replaced by NH at various places.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000230 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
Devang Patel32231332007-04-09 16:11:48 +0000231 }
Devang Patelc4625da2007-04-07 01:25:15 +0000232
Devang Patel32231332007-04-09 16:11:48 +0000233 // Now, handle non-phi instructions.
234 for (; I != E; ++I) {
235 Instruction *In = I;
Chris Lattner2ba25432009-01-26 01:38:24 +0000236 assert(!isa<PHINode>(In) && "PHINode is not expected here");
Chris Lattnerf6784a32009-01-26 01:57:01 +0000237
Devang Patele9881542007-04-09 19:04:21 +0000238 // This is not a PHI instruction. Insert its clone into original pre-header.
Devang Patel32231332007-04-09 16:11:48 +0000239 // If this instruction is using a value from same basic block then
240 // update it to use value from cloned instruction.
241 Instruction *C = In->clone();
Owen Anderson6bc41e82008-04-14 17:38:21 +0000242 C->setName(In->getName());
Devang Patele9881542007-04-09 19:04:21 +0000243 OrigPreHeader->getInstList().push_back(C);
244
245 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000246 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
247 if (!OpInsn) continue; // Ignore non-instruction values.
248 if (const RenameData *D = findReplacementData(OpInsn))
249 C->setOperand(opi, D->PreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000250 }
251
Devang Patel32231332007-04-09 16:11:48 +0000252 // If this instruction is used outside this basic block then
253 // create new PHINode for this instruction.
254 Instruction *NewHeaderReplacement = NULL;
255 if (usedOutsideOriginalHeader(In)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000256 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
257 NewHeader->begin());
258 PN->addIncoming(In, OrigHeader);
259 PN->addIncoming(C, OrigPreHeader);
260 NewHeaderReplacement = PN;
Dale Johannesen79602672008-05-01 22:27:44 +0000261 }
Devang Patel32231332007-04-09 16:11:48 +0000262 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
Devang Patelc4625da2007-04-07 01:25:15 +0000263 }
264
Devang Patelc4625da2007-04-07 01:25:15 +0000265 // Rename uses of original header instructions to reflect their new
Devang Patele9881542007-04-09 19:04:21 +0000266 // definitions (either from original pre-header node or from newly created
Devang Patelc4625da2007-04-07 01:25:15 +0000267 // new header PHINodes.
268 //
269 // Original header instructions are used in
270 // 1) Original header:
271 //
272 // If instruction is used in non-phi instructions then it is using
273 // defintion from original heder iteself. Do not replace this use
Devang Patele9881542007-04-09 19:04:21 +0000274 // with definition from new header or original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000275 //
276 // If instruction is used in phi node then it is an incoming
277 // value. Rename its use to reflect new definition from new-preheader
278 // or new header.
279 //
280 // 2) Inside loop but not in original header
281 //
282 // Replace this use to reflect definition from new header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000283 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000284 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
Devang Patelc4625da2007-04-07 01:25:15 +0000285
Devang Patel32231332007-04-09 16:11:48 +0000286 if (!ILoopHeaderInfo.Header)
Devang Patelc4625da2007-04-07 01:25:15 +0000287 continue;
288
Devang Patel32231332007-04-09 16:11:48 +0000289 Instruction *OldPhi = ILoopHeaderInfo.Original;
290 Instruction *NewPhi = ILoopHeaderInfo.Header;
Devang Patelc4625da2007-04-07 01:25:15 +0000291
292 // Before replacing uses, collect them first, so that iterator is
293 // not invalidated.
294 SmallVector<Instruction *, 16> AllUses;
295 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000296 UI != UE; ++UI)
297 AllUses.push_back(cast<Instruction>(UI));
Devang Patelc4625da2007-04-07 01:25:15 +0000298
299 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
300 UE = AllUses.end(); UI != UE; ++UI) {
301 Instruction *U = *UI;
302 BasicBlock *Parent = U->getParent();
303
304 // Used inside original header
305 if (Parent == OrigHeader) {
306 // Do not rename uses inside original header non-phi instructions.
Devang Patelc4625da2007-04-07 01:25:15 +0000307 PHINode *PU = dyn_cast<PHINode>(U);
Devang Patel24a1c492007-04-09 16:21:29 +0000308 if (!PU)
309 continue;
310
Devang Patelc4625da2007-04-07 01:25:15 +0000311 // Do not rename uses inside original header phi nodes, if the
312 // incoming value is for new header.
313 if (PU->getBasicBlockIndex(NewHeader) != -1
314 && PU->getIncomingValueForBlock(NewHeader) == U)
315 continue;
Devang Patel4522c8a2007-04-09 17:09:13 +0000316
Devang Patelc4625da2007-04-07 01:25:15 +0000317 U->replaceUsesOfWith(OldPhi, NewPhi);
318 continue;
319 }
320
321 // Used inside loop, but not in original header.
322 if (L->contains(U->getParent())) {
Devang Patel24a1c492007-04-09 16:21:29 +0000323 if (U != NewPhi)
Devang Patelc4625da2007-04-07 01:25:15 +0000324 U->replaceUsesOfWith(OldPhi, NewPhi);
325 continue;
326 }
Nick Lewycky8f5149e2007-07-07 16:23:34 +0000327
Devang Patel990e8662007-07-11 23:47:28 +0000328 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
329 if (U->getParent() == Exit) {
Chris Lattner2ba25432009-01-26 01:38:24 +0000330 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
Devang Patel990e8662007-07-11 23:47:28 +0000331
332 PHINode *UPhi = cast<PHINode>(U);
333 // UPhi already has one incoming argument from original header.
334 // Add second incoming argument from new Pre header.
335 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
336 } else {
337 // Used outside Exit block. Create a new PHI node from exit block
338 // to receive value from ne new header ane pre header.
Dan Gohman610c0e22008-06-19 17:37:25 +0000339 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
340 Exit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000341 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
342 PN->addIncoming(OldPhi, OrigHeader);
Devang Patel990e8662007-07-11 23:47:28 +0000343 U->replaceUsesOfWith(OldPhi, PN);
344 }
Devang Patelc4625da2007-04-07 01:25:15 +0000345 }
346 }
347
348 /// Make sure all Exit block PHINodes have required incoming values.
349 updateExitBlock();
350
351 // Update CFG
352
353 // Removing incoming branch from loop preheader to original header.
354 // Now original header is inside the loop.
Devang Patele9881542007-04-09 19:04:21 +0000355 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000356 I != E; ++I)
357 if (PHINode *PN = dyn_cast<PHINode>(I))
358 PN->removeIncomingValue(OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000359
360 // Make NewHeader as the new header for the loop.
361 L->moveToHeader(NewHeader);
362
Devang Patel5464b962007-04-09 20:19:46 +0000363 preserveCanonicalLoopForm(LPM);
364
Devang Patelc4625da2007-04-07 01:25:15 +0000365 NumRotated++;
366 return true;
367}
368
Devang Patelc4625da2007-04-07 01:25:15 +0000369/// Make sure all Exit block PHINodes have required incoming values.
370/// If incoming value is constant or defined outside the loop then
Devang Patele9881542007-04-09 19:04:21 +0000371/// PHINode may not have an entry for original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000372void LoopRotate::updateExitBlock() {
373
374 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
375 I != E; ++I) {
376
Devang Patelc4625da2007-04-07 01:25:15 +0000377 PHINode *PN = dyn_cast<PHINode>(I);
Devang Patel24a1c492007-04-09 16:21:29 +0000378 if (!PN)
379 break;
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);
387 if (isa<Instruction>(V) &&
388 (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.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000442 BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph",
443 OrigHeader->getParent(),
Gabor Greif051a9502008-04-06 20:25:17 +0000444 NewHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000445 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
446 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000447 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000448 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000449
450 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
451 if (OrigPH_BI->getSuccessor(0) == NewHeader)
452 OrigPH_BI->setSuccessor(0, NewPreHeader);
453 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000454 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
455 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000456 OrigPH_BI->setSuccessor(1, NewPreHeader);
457 }
458
459 for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
460 I != E; ++I) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000461 PHINode *PN = dyn_cast<PHINode>(I);
Devang Patel5464b962007-04-09 20:19:46 +0000462 if (!PN)
463 break;
464
465 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000466 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000467 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000468 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
469 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000470 }
471
Duncan Sands1465d612009-01-28 13:14:17 +0000472 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000473 DT->addNewBlock(NewPreHeader, OrigPreHeader);
474 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
475 DT->changeImmediateDominator(Exit, OrigPreHeader);
476 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
477 BI != BE; ++BI) {
478 BasicBlock *B = *BI;
479 if (L->getHeader() != B) {
480 DomTreeNode *Node = DT->getNode(B);
481 if (Node && Node->getBlock() == OrigHeader)
482 DT->changeImmediateDominator(*BI, L->getHeader());
483 }
484 }
485 DT->changeImmediateDominator(OrigHeader, OrigLatch);
486 }
487
Duncan Sands1465d612009-01-28 13:14:17 +0000488 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000489 // New Preheader's dominance frontier is Exit block.
490 DominanceFrontier::DomSetType NewPHSet;
491 NewPHSet.insert(Exit);
492 DF->addBasicBlock(NewPreHeader, NewPHSet);
493
494 // New Header's dominance frontier now includes itself and Exit block
495 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
496 if (HeadI != DF->end()) {
497 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
498 HeaderSet.clear();
499 HeaderSet.insert(L->getHeader());
500 HeaderSet.insert(Exit);
501 } else {
502 DominanceFrontier::DomSetType HeaderSet;
503 HeaderSet.insert(L->getHeader());
504 HeaderSet.insert(Exit);
505 DF->addBasicBlock(L->getHeader(), HeaderSet);
506 }
507
508 // Original header (new Loop Latch)'s dominance frontier is Exit.
509 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
510 if (LatchI != DF->end()) {
511 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
512 LatchSet = LatchI->second;
513 LatchSet.clear();
514 LatchSet.insert(Exit);
515 } else {
516 DominanceFrontier::DomSetType LatchSet;
517 LatchSet.insert(Exit);
518 DF->addBasicBlock(L->getHeader(), LatchSet);
519 }
520
521 // If a loop block dominates new loop latch then its frontier is
522 // new header and Exit.
523 BasicBlock *NewLatch = L->getLoopLatch();
Duncan Sands1465d612009-01-28 13:14:17 +0000524 DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patel990e8662007-07-11 23:47:28 +0000525 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
526 BI != BE; ++BI) {
527 BasicBlock *B = *BI;
528 if (DT->dominates(B, NewLatch)) {
529 DominanceFrontier::iterator BDFI = DF->find(B);
530 if (BDFI != DF->end()) {
531 DominanceFrontier::DomSetType &BSet = BDFI->second;
532 BSet = BDFI->second;
533 BSet.clear();
534 BSet.insert(L->getHeader());
535 BSet.insert(Exit);
536 } else {
537 DominanceFrontier::DomSetType BSet;
538 BSet.insert(L->getHeader());
539 BSet.insert(Exit);
540 DF->addBasicBlock(B, BSet);
541 }
542 }
543 }
544 }
545
546 // Preserve canonical loop form, which means Exit block should
547 // have only one predecessor.
548 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
549
550 // Preserve LCSSA.
551 BasicBlock::iterator I = Exit->begin(), E = Exit->end();
552 PHINode *PN = NULL;
553 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel990e8662007-07-11 23:47:28 +0000554 unsigned N = PN->getNumIncomingValues();
555 for (unsigned index = 0; index < N; ++index)
556 if (PN->getIncomingBlock(index) == NExit) {
Dan Gohman610c0e22008-06-19 17:37:25 +0000557 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
558 NExit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000559 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
560 PN->setIncomingValue(index, NewPN);
561 PN->setIncomingBlock(index, NExit);
Dan Gohman610c0e22008-06-19 17:37:25 +0000562 break;
Devang Patel990e8662007-07-11 23:47:28 +0000563 }
564 }
565
Chris Lattner2ba25432009-01-26 01:38:24 +0000566 assert(NewHeader && L->getHeader() == NewHeader &&
567 "Invalid loop header after loop rotation");
568 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
569 "Invalid loop preheader after loop rotation");
570 assert(L->getLoopLatch() &&
571 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000572}