blob: 428e0f2a1f0e6ac377b9a57cfa251882bd7254f3 [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/DominanceFrontier.h"
19#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Devang Patel990e8662007-07-11 23:47:28 +000021#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"
Dan Gohmane6e37b92009-10-24 23:19:52 +000024#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ccb3652011-01-08 07:21:31 +000025#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000026#include "llvm/Support/Debug.h"
27#include "llvm/ADT/Statistic.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 LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000036 public:
Devang Patel19974732007-05-03 01:11:54 +000037 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000038 LoopRotate() : LoopPass(ID) {
39 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
40 }
Devang Patel794fd752007-05-01 21:15:47 +000041
Devang Patel32231332007-04-09 16:11:48 +000042 // Rotate Loop L as many times as possible. Return true if
43 // loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +000044 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel32231332007-04-09 16:11:48 +000045
46 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000047 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000048 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000052 AU.addRequiredID(LoopSimplifyID);
53 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000054 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000056 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000057 }
58
59 // Helper functions
60
61 /// Do actual work
62 bool rotateLoop(Loop *L, LPPassManager &LPM);
63
64 /// Initialize local data
65 void initialize();
66
Devang Patel5464b962007-04-09 20:19:46 +000067 /// After loop rotation, loop pre-header has multiple sucessors.
68 /// Insert one forwarding basic block to ensure that loop pre-header
69 /// has only one successor.
70 void preserveCanonicalLoopForm(LPPassManager &LPM);
71
Devang Patelc4625da2007-04-07 01:25:15 +000072 private:
Chris Lattner012ca942011-01-08 17:38:45 +000073 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000074 Loop *L;
75 BasicBlock *OrigHeader;
76 BasicBlock *OrigPreHeader;
77 BasicBlock *OrigLatch;
78 BasicBlock *NewHeader;
Devang Patelc4625da2007-04-07 01:25:15 +000079 BasicBlock *Exit;
Devang Patel990e8662007-07-11 23:47:28 +000080 LPPassManager *LPM_Ptr;
Devang Patelc4625da2007-04-07 01:25:15 +000081 };
Devang Patelc4625da2007-04-07 01:25:15 +000082}
Dan Gohman844731a2008-05-13 00:00:25 +000083
84char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000085INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000086INITIALIZE_PASS_DEPENDENCY(LoopInfo)
87INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
88INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000089INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000090
Daniel Dunbar394f0442008-10-22 23:32:42 +000091Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000092
Chris Lattner012ca942011-01-08 17:38:45 +000093/// Initialize local data
94void LoopRotate::initialize() {
95 L = NULL;
96 OrigHeader = NULL;
97 OrigPreHeader = NULL;
98 NewHeader = NULL;
99 Exit = NULL;
100}
101
Devang Patel32231332007-04-09 16:11:48 +0000102/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +0000103/// the loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +0000104bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +0000105 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +0000106
Devang Patelc4625da2007-04-07 01:25:15 +0000107 initialize();
Devang Patel990e8662007-07-11 23:47:28 +0000108 LPM_Ptr = &LPM;
Devang Patelc4625da2007-04-07 01:25:15 +0000109
110 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +0000111 bool MadeChange = false;
Devang Patelc4625da2007-04-07 01:25:15 +0000112 while (rotateLoop(Lp,LPM)) {
Chris Lattner012ca942011-01-08 17:38:45 +0000113 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +0000114 initialize();
115 }
116
Chris Lattner012ca942011-01-08 17:38:45 +0000117 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +0000118}
119
Dan Gohman23d9d272007-05-11 21:10:54 +0000120/// Rotate loop LP. Return true if the loop is rotated.
Devang Patelc4625da2007-04-07 01:25:15 +0000121bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patelc4625da2007-04-07 01:25:15 +0000122 L = Lp;
Devang Patelc4625da2007-04-07 01:25:15 +0000123
Devang Patelc4625da2007-04-07 01:25:15 +0000124 OrigPreHeader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000125 if (!OrigPreHeader) return false;
126
Devang Patelc4625da2007-04-07 01:25:15 +0000127 OrigLatch = L->getLoopLatch();
Dan Gohman03e896b2009-11-05 21:11:53 +0000128 if (!OrigLatch) return false;
129
130 OrigHeader = L->getHeader();
Devang Patelc4625da2007-04-07 01:25:15 +0000131
Dan Gohmancc4e6052009-06-25 00:22:44 +0000132 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000133 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000134 return false;
135
Dan Gohmancc4e6052009-06-25 00:22:44 +0000136 // If the loop header is not one of the loop exiting blocks then
137 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000138 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000139 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000140 return false;
141
142 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
143 if (!BI)
144 return false;
Chris Lattner2ba25432009-01-26 01:38:24 +0000145 assert(BI->isConditional() && "Branch Instruction is not conditional");
Devang Patelc4625da2007-04-07 01:25:15 +0000146
Devang Patel32231332007-04-09 16:11:48 +0000147 // Updating PHInodes in loops with multiple exits adds complexity.
148 // Keep it simple, and restrict loop rotation to loops with one exit only.
149 // In future, lift this restriction and support for multiple exits if
150 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000151 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000152 L->getExitBlocks(ExitBlocks);
153 if (ExitBlocks.size() > 1)
154 return false;
155
Chris Lattnerd9e07972011-01-02 07:35:53 +0000156 // Check size of original header and reject loop if it is very big.
157 {
158 CodeMetrics Metrics;
159 Metrics.analyzeBasicBlock(OrigHeader);
160 if (Metrics.NumInsts > MAX_HEADER_SIZE)
161 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000162 }
163
Devang Patel990e8662007-07-11 23:47:28 +0000164 // Now, this loop is suitable for rotation.
165
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000166 // Anything ScalarEvolution may know about this loop or the PHI nodes
167 // in its header will soon be invalidated.
168 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000169 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000170
Devang Patelc4625da2007-04-07 01:25:15 +0000171 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000172 // that is inside loop. Header's other successor is outside the
173 // loop. Otherwise loop is not suitable for rotation.
Devang Patel32231332007-04-09 16:11:48 +0000174 Exit = BI->getSuccessor(0);
175 NewHeader = BI->getSuccessor(1);
176 if (L->contains(Exit))
177 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000178 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000179 assert(L->contains(NewHeader) && !L->contains(Exit) &&
180 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000181
Dan Gohmancc4e6052009-06-25 00:22:44 +0000182 // This code assumes that the new header has exactly one predecessor.
183 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000184 assert(NewHeader->getSinglePredecessor() &&
185 "New header doesn't have one pred!");
186 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000187
Dan Gohmane6e37b92009-10-24 23:19:52 +0000188 // Begin by walking OrigHeader and populating ValueMap with an entry for
189 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000190 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000191 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000192
Dan Gohmane6e37b92009-10-24 23:19:52 +0000193 // For PHI nodes, the value available in OldPreHeader is just the
194 // incoming value from OldPreHeader.
195 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
196 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000197
Chris Lattner50fb4692010-09-06 01:10:22 +0000198 // For the rest of the instructions, either hoist to the OrigPreheader if
199 // possible or create a clone in the OldPreHeader if not.
Dan Gohmane6e37b92009-10-24 23:19:52 +0000200 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000201 while (I != E) {
202 Instruction *Inst = I++;
203
204 // If the instruction's operands are invariant and it doesn't read or write
205 // memory, then it is safe to hoist. Doing this doesn't change the order of
206 // execution in the preheader, but does prevent the instruction from
207 // executing in each iteration of the loop. This means it is safe to hoist
208 // something that might trap, but isn't safe to hoist something that reads
209 // memory (without proving that the loop doesn't write).
210 if (L->hasLoopInvariantOperands(Inst) &&
211 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
212 !isa<TerminatorInst>(Inst)) {
213 Inst->moveBefore(LoopEntryBranch);
214 continue;
215 }
216
217 // Otherwise, create a duplicate of the instruction.
218 Instruction *C = Inst->clone();
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000219
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000220 // Eagerly remap the operands of the instruction.
221 RemapInstruction(C, ValueMap,
222 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
223
224 // With the operands remapped, see if the instruction constant folds or is
225 // otherwise simplifyable. This commonly occurs because the entry from PHI
226 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000227 Value *V = SimplifyInstruction(C);
228 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000229 // If so, then delete the temporary instruction and stick the folded value
230 // in the map.
231 delete C;
232 ValueMap[Inst] = V;
233 } else {
234 // Otherwise, stick the new instruction into the new block!
235 C->setName(Inst->getName());
236 C->insertBefore(LoopEntryBranch);
237 ValueMap[Inst] = C;
238 }
Devang Patelc4625da2007-04-07 01:25:15 +0000239 }
240
Dan Gohmane6e37b92009-10-24 23:19:52 +0000241 // Along with all the other instructions, we just cloned OrigHeader's
242 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
243 // successors by duplicating their incoming values for OrigHeader.
244 TerminatorInst *TI = OrigHeader->getTerminator();
245 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
246 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
247 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
248 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000249
Dan Gohmane6e37b92009-10-24 23:19:52 +0000250 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
251 // OrigPreHeader's old terminator (the original branch into the loop), and
252 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
253 LoopEntryBranch->eraseFromParent();
254 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
255 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000256
Dan Gohman440e2512009-10-26 15:55:24 +0000257 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
Dan Gohmane6e37b92009-10-24 23:19:52 +0000258 // as necessary.
259 SSAUpdater SSA;
260 for (I = OrigHeader->begin(); I != E; ++I) {
261 Value *OrigHeaderVal = I;
262 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
Devang Patelc4625da2007-04-07 01:25:15 +0000263
Chris Lattner6ccb3652011-01-08 07:21:31 +0000264 // If there are no uses of the value (e.g. because it returns void), there
265 // is nothing to rewrite.
266 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
267 continue;
268
Dan Gohmane6e37b92009-10-24 23:19:52 +0000269 // The value now exits in two versions: the initial value in the preheader
270 // and the loop "next" value in the original header.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000271 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
Dan Gohmane6e37b92009-10-24 23:19:52 +0000272 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
273 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
Devang Patelc4625da2007-04-07 01:25:15 +0000274
Dan Gohmane6e37b92009-10-24 23:19:52 +0000275 // Visit each use of the OrigHeader instruction.
276 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
277 UE = OrigHeaderVal->use_end(); UI != UE; ) {
278 // Grab the use before incrementing the iterator.
279 Use &U = UI.getUse();
Devang Patelc4625da2007-04-07 01:25:15 +0000280
Dan Gohmane6e37b92009-10-24 23:19:52 +0000281 // Increment the iterator before removing the use from the list.
282 ++UI;
283
284 // SSAUpdater can't handle a non-PHI use in the same block as an
285 // earlier def. We can easily handle those cases manually.
286 Instruction *UserInst = cast<Instruction>(U.getUser());
287 if (!isa<PHINode>(UserInst)) {
288 BasicBlock *UserBB = UserInst->getParent();
289
290 // The original users in the OrigHeader are already using the
291 // original definitions.
292 if (UserBB == OrigHeader)
Devang Patel24a1c492007-04-09 16:21:29 +0000293 continue;
294
Dan Gohmane6e37b92009-10-24 23:19:52 +0000295 // Users in the OrigPreHeader need to use the value to which the
296 // original definitions are mapped.
297 if (UserBB == OrigPreHeader) {
298 U = OrigPreHeaderVal;
Devang Patelc4625da2007-04-07 01:25:15 +0000299 continue;
Dan Gohmane6e37b92009-10-24 23:19:52 +0000300 }
Devang Patelc4625da2007-04-07 01:25:15 +0000301 }
302
Dan Gohmane6e37b92009-10-24 23:19:52 +0000303 // Anything else can be handled by SSAUpdater.
304 SSA.RewriteUse(U);
Devang Patelc4625da2007-04-07 01:25:15 +0000305 }
306 }
Devang Patelc4625da2007-04-07 01:25:15 +0000307
Dan Gohmane6e37b92009-10-24 23:19:52 +0000308 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000309 L->moveToHeader(NewHeader);
310
Dan Gohmanfc8042a2010-08-17 17:39:21 +0000311 // Move the original header to the bottom of the loop, where it now more
312 // naturally belongs. This isn't necessary for correctness, and CodeGen can
313 // usually reorder blocks on its own to fix things like this up, but it's
314 // still nice to keep the IR readable.
315 //
316 // The original header should have only one predecessor at this point, since
317 // we checked that the loop had a proper preheader and unique backedge before
318 // we started.
319 assert(OrigHeader->getSinglePredecessor() &&
320 "Original loop header has too many predecessors after loop rotation!");
321 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
322
323 // Also, since this original header only has one predecessor, zap its
324 // PHI nodes, which are now trivial.
325 FoldSingleEntryPHINodes(OrigHeader);
326
327 // TODO: We could just go ahead and merge OrigHeader into its predecessor
328 // at this point, if we don't mind updating dominator info.
329
330 // Establish a new preheader, update dominators, etc.
Devang Patel5464b962007-04-09 20:19:46 +0000331 preserveCanonicalLoopForm(LPM);
332
Dan Gohmanfe601042010-06-22 15:08:57 +0000333 ++NumRotated;
Devang Patelc4625da2007-04-07 01:25:15 +0000334 return true;
335}
336
Devang Patel5464b962007-04-09 20:19:46 +0000337
338/// After loop rotation, loop pre-header has multiple sucessors.
339/// Insert one forwarding basic block to ensure that loop pre-header
340/// has only one successor.
341void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
342
343 // Right now original pre-header has two successors, new header and
344 // exit block. Insert new block between original pre-header and
345 // new header such that loop's new pre-header has only one successor.
Owen Anderson1d0be152009-08-13 21:58:54 +0000346 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
347 "bb.nph",
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000348 OrigHeader->getParent(),
Gabor Greif051a9502008-04-06 20:25:17 +0000349 NewHeader);
Dan Gohman6a02fc32009-11-05 19:43:25 +0000350 LoopInfo &LI = getAnalysis<LoopInfo>();
Devang Patel5464b962007-04-09 20:19:46 +0000351 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000352 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000353 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000354
355 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
356 if (OrigPH_BI->getSuccessor(0) == NewHeader)
357 OrigPH_BI->setSuccessor(0, NewPreHeader);
358 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000359 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
360 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000361 OrigPH_BI->setSuccessor(1, NewPreHeader);
362 }
Devang Patel5464b962007-04-09 20:19:46 +0000363
Dan Gohmancfb32202009-06-27 21:23:40 +0000364 PHINode *PN;
365 for (BasicBlock::iterator I = NewHeader->begin();
366 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel5464b962007-04-09 20:19:46 +0000367 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000368 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000369 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000370 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
371 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000372 }
373
Duncan Sands1465d612009-01-28 13:14:17 +0000374 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000375 DT->addNewBlock(NewPreHeader, OrigPreHeader);
376 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
377 DT->changeImmediateDominator(Exit, OrigPreHeader);
378 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
379 BI != BE; ++BI) {
380 BasicBlock *B = *BI;
381 if (L->getHeader() != B) {
382 DomTreeNode *Node = DT->getNode(B);
383 if (Node && Node->getBlock() == OrigHeader)
384 DT->changeImmediateDominator(*BI, L->getHeader());
385 }
386 }
387 DT->changeImmediateDominator(OrigHeader, OrigLatch);
388 }
389
Duncan Sands1465d612009-01-28 13:14:17 +0000390 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000391 // New Preheader's dominance frontier is Exit block.
392 DominanceFrontier::DomSetType NewPHSet;
393 NewPHSet.insert(Exit);
394 DF->addBasicBlock(NewPreHeader, NewPHSet);
395
396 // New Header's dominance frontier now includes itself and Exit block
397 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
398 if (HeadI != DF->end()) {
399 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
400 HeaderSet.clear();
401 HeaderSet.insert(L->getHeader());
402 HeaderSet.insert(Exit);
403 } else {
404 DominanceFrontier::DomSetType HeaderSet;
405 HeaderSet.insert(L->getHeader());
406 HeaderSet.insert(Exit);
407 DF->addBasicBlock(L->getHeader(), HeaderSet);
408 }
409
410 // Original header (new Loop Latch)'s dominance frontier is Exit.
411 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
412 if (LatchI != DF->end()) {
413 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
414 LatchSet = LatchI->second;
415 LatchSet.clear();
416 LatchSet.insert(Exit);
417 } else {
418 DominanceFrontier::DomSetType LatchSet;
419 LatchSet.insert(Exit);
420 DF->addBasicBlock(L->getHeader(), LatchSet);
421 }
422
Devang Patelb7f40c12009-08-07 17:16:44 +0000423 // If a loop block dominates new loop latch then add to its frontiers
424 // new header and Exit and remove new latch (which is equal to original
425 // header).
Devang Patel990e8662007-07-11 23:47:28 +0000426 BasicBlock *NewLatch = L->getLoopLatch();
Devang Patelb7f40c12009-08-07 17:16:44 +0000427
428 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
429
430 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
431 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
432 BI != BE; ++BI) {
433 BasicBlock *B = *BI;
434 if (DT->dominates(B, NewLatch)) {
435 DominanceFrontier::iterator BDFI = DF->find(B);
436 if (BDFI != DF->end()) {
437 DominanceFrontier::DomSetType &BSet = BDFI->second;
438 BSet.erase(NewLatch);
439 BSet.insert(L->getHeader());
440 BSet.insert(Exit);
441 } else {
442 DominanceFrontier::DomSetType BSet;
443 BSet.insert(L->getHeader());
444 BSet.insert(Exit);
445 DF->addBasicBlock(B, BSet);
446 }
Devang Patel990e8662007-07-11 23:47:28 +0000447 }
448 }
449 }
450 }
451
452 // Preserve canonical loop form, which means Exit block should
453 // have only one predecessor.
Dan Gohmanc292caf2009-09-09 18:18:18 +0000454 SplitEdge(L->getLoopLatch(), Exit, this);
Devang Patel990e8662007-07-11 23:47:28 +0000455
Chris Lattner2ba25432009-01-26 01:38:24 +0000456 assert(NewHeader && L->getHeader() == NewHeader &&
457 "Invalid loop header after loop rotation");
458 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
459 "Invalid loop preheader after loop rotation");
460 assert(L->getLoopLatch() &&
461 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000462}