blob: b0ba2581a7e7768db0bd8e46d40bd212efd2c9f8 [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
Chris Lattner4aefc9b2011-01-08 17:48:33 +000062 bool rotateLoop(Loop *L);
Devang Patelc4625da2007-04-07 01:25:15 +000063
Devang Patel5464b962007-04-09 20:19:46 +000064 /// After loop rotation, loop pre-header has multiple sucessors.
65 /// Insert one forwarding basic block to ensure that loop pre-header
66 /// has only one successor.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000067 void preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
68 BasicBlock *OrigPreHeader,
69 BasicBlock *OrigLatch, BasicBlock *NewHeader,
70 BasicBlock *Exit);
Devang Patel5464b962007-04-09 20:19:46 +000071
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 };
Devang Patelc4625da2007-04-07 01:25:15 +000075}
Dan Gohman844731a2008-05-13 00:00:25 +000076
77char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000078INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000079INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000082INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000083
Daniel Dunbar394f0442008-10-22 23:32:42 +000084Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000085
Devang Patel32231332007-04-09 16:11:48 +000086/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000087/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000088bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000089 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000090
Devang Patelc4625da2007-04-07 01:25:15 +000091 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000092 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000093 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000094 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000095
Chris Lattner012ca942011-01-08 17:38:45 +000096 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000097}
98
Dan Gohman23d9d272007-05-11 21:10:54 +000099/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000100bool LoopRotate::rotateLoop(Loop *L) {
101 BasicBlock *OrigPreHeader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000102 if (!OrigPreHeader) return false;
103
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000104 BasicBlock *OrigLatch = L->getLoopLatch();
Dan Gohman03e896b2009-11-05 21:11:53 +0000105 if (!OrigLatch) return false;
106
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000107 BasicBlock *OrigHeader = L->getHeader();
Devang Patelc4625da2007-04-07 01:25:15 +0000108
Dan Gohmancc4e6052009-06-25 00:22:44 +0000109 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000110 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000111 return false;
112
Dan Gohmancc4e6052009-06-25 00:22:44 +0000113 // If the loop header is not one of the loop exiting blocks then
114 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000115 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000116 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000117 return false;
118
119 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
120 if (!BI)
121 return false;
Chris Lattner2ba25432009-01-26 01:38:24 +0000122 assert(BI->isConditional() && "Branch Instruction is not conditional");
Devang Patelc4625da2007-04-07 01:25:15 +0000123
Devang Patel32231332007-04-09 16:11:48 +0000124 // Updating PHInodes in loops with multiple exits adds complexity.
125 // Keep it simple, and restrict loop rotation to loops with one exit only.
126 // In future, lift this restriction and support for multiple exits if
127 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000128 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000129 L->getExitBlocks(ExitBlocks);
130 if (ExitBlocks.size() > 1)
131 return false;
132
Chris Lattnerd9e07972011-01-02 07:35:53 +0000133 // Check size of original header and reject loop if it is very big.
134 {
135 CodeMetrics Metrics;
136 Metrics.analyzeBasicBlock(OrigHeader);
137 if (Metrics.NumInsts > MAX_HEADER_SIZE)
138 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000139 }
140
Devang Patel990e8662007-07-11 23:47:28 +0000141 // Now, this loop is suitable for rotation.
142
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000143 // Anything ScalarEvolution may know about this loop or the PHI nodes
144 // in its header will soon be invalidated.
145 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000146 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000147
Devang Patelc4625da2007-04-07 01:25:15 +0000148 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000149 // that is inside loop. Header's other successor is outside the
150 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000151 BasicBlock *Exit = BI->getSuccessor(0);
152 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000153 if (L->contains(Exit))
154 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000155 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000156 assert(L->contains(NewHeader) && !L->contains(Exit) &&
157 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000158
Dan Gohmancc4e6052009-06-25 00:22:44 +0000159 // This code assumes that the new header has exactly one predecessor.
160 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000161 assert(NewHeader->getSinglePredecessor() &&
162 "New header doesn't have one pred!");
163 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000164
Dan Gohmane6e37b92009-10-24 23:19:52 +0000165 // Begin by walking OrigHeader and populating ValueMap with an entry for
166 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000167 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000168 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000169
Dan Gohmane6e37b92009-10-24 23:19:52 +0000170 // For PHI nodes, the value available in OldPreHeader is just the
171 // incoming value from OldPreHeader.
172 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
173 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000174
Chris Lattner50fb4692010-09-06 01:10:22 +0000175 // For the rest of the instructions, either hoist to the OrigPreheader if
176 // possible or create a clone in the OldPreHeader if not.
Dan Gohmane6e37b92009-10-24 23:19:52 +0000177 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000178 while (I != E) {
179 Instruction *Inst = I++;
180
181 // If the instruction's operands are invariant and it doesn't read or write
182 // memory, then it is safe to hoist. Doing this doesn't change the order of
183 // execution in the preheader, but does prevent the instruction from
184 // executing in each iteration of the loop. This means it is safe to hoist
185 // something that might trap, but isn't safe to hoist something that reads
186 // memory (without proving that the loop doesn't write).
187 if (L->hasLoopInvariantOperands(Inst) &&
188 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
189 !isa<TerminatorInst>(Inst)) {
190 Inst->moveBefore(LoopEntryBranch);
191 continue;
192 }
193
194 // Otherwise, create a duplicate of the instruction.
195 Instruction *C = Inst->clone();
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000196
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000197 // Eagerly remap the operands of the instruction.
198 RemapInstruction(C, ValueMap,
199 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
200
201 // With the operands remapped, see if the instruction constant folds or is
202 // otherwise simplifyable. This commonly occurs because the entry from PHI
203 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000204 Value *V = SimplifyInstruction(C);
205 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000206 // If so, then delete the temporary instruction and stick the folded value
207 // in the map.
208 delete C;
209 ValueMap[Inst] = V;
210 } else {
211 // Otherwise, stick the new instruction into the new block!
212 C->setName(Inst->getName());
213 C->insertBefore(LoopEntryBranch);
214 ValueMap[Inst] = C;
215 }
Devang Patelc4625da2007-04-07 01:25:15 +0000216 }
217
Dan Gohmane6e37b92009-10-24 23:19:52 +0000218 // Along with all the other instructions, we just cloned OrigHeader's
219 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
220 // successors by duplicating their incoming values for OrigHeader.
221 TerminatorInst *TI = OrigHeader->getTerminator();
222 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
223 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
224 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
225 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000226
Dan Gohmane6e37b92009-10-24 23:19:52 +0000227 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
228 // OrigPreHeader's old terminator (the original branch into the loop), and
229 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
230 LoopEntryBranch->eraseFromParent();
231 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
232 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelc4625da2007-04-07 01:25:15 +0000233
Dan Gohman440e2512009-10-26 15:55:24 +0000234 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
Dan Gohmane6e37b92009-10-24 23:19:52 +0000235 // as necessary.
236 SSAUpdater SSA;
237 for (I = OrigHeader->begin(); I != E; ++I) {
238 Value *OrigHeaderVal = I;
239 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
Devang Patelc4625da2007-04-07 01:25:15 +0000240
Chris Lattner6ccb3652011-01-08 07:21:31 +0000241 // If there are no uses of the value (e.g. because it returns void), there
242 // is nothing to rewrite.
243 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
244 continue;
245
Dan Gohmane6e37b92009-10-24 23:19:52 +0000246 // The value now exits in two versions: the initial value in the preheader
247 // and the loop "next" value in the original header.
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000248 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
Dan Gohmane6e37b92009-10-24 23:19:52 +0000249 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
250 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
Devang Patelc4625da2007-04-07 01:25:15 +0000251
Dan Gohmane6e37b92009-10-24 23:19:52 +0000252 // Visit each use of the OrigHeader instruction.
253 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
254 UE = OrigHeaderVal->use_end(); UI != UE; ) {
255 // Grab the use before incrementing the iterator.
256 Use &U = UI.getUse();
Devang Patelc4625da2007-04-07 01:25:15 +0000257
Dan Gohmane6e37b92009-10-24 23:19:52 +0000258 // Increment the iterator before removing the use from the list.
259 ++UI;
260
261 // SSAUpdater can't handle a non-PHI use in the same block as an
262 // earlier def. We can easily handle those cases manually.
263 Instruction *UserInst = cast<Instruction>(U.getUser());
264 if (!isa<PHINode>(UserInst)) {
265 BasicBlock *UserBB = UserInst->getParent();
266
267 // The original users in the OrigHeader are already using the
268 // original definitions.
269 if (UserBB == OrigHeader)
Devang Patel24a1c492007-04-09 16:21:29 +0000270 continue;
271
Dan Gohmane6e37b92009-10-24 23:19:52 +0000272 // Users in the OrigPreHeader need to use the value to which the
273 // original definitions are mapped.
274 if (UserBB == OrigPreHeader) {
275 U = OrigPreHeaderVal;
Devang Patelc4625da2007-04-07 01:25:15 +0000276 continue;
Dan Gohmane6e37b92009-10-24 23:19:52 +0000277 }
Devang Patelc4625da2007-04-07 01:25:15 +0000278 }
279
Dan Gohmane6e37b92009-10-24 23:19:52 +0000280 // Anything else can be handled by SSAUpdater.
281 SSA.RewriteUse(U);
Devang Patelc4625da2007-04-07 01:25:15 +0000282 }
283 }
Devang Patelc4625da2007-04-07 01:25:15 +0000284
Dan Gohmane6e37b92009-10-24 23:19:52 +0000285 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000286 L->moveToHeader(NewHeader);
287
Dan Gohmanfc8042a2010-08-17 17:39:21 +0000288 // Move the original header to the bottom of the loop, where it now more
289 // naturally belongs. This isn't necessary for correctness, and CodeGen can
290 // usually reorder blocks on its own to fix things like this up, but it's
291 // still nice to keep the IR readable.
292 //
293 // The original header should have only one predecessor at this point, since
294 // we checked that the loop had a proper preheader and unique backedge before
295 // we started.
296 assert(OrigHeader->getSinglePredecessor() &&
297 "Original loop header has too many predecessors after loop rotation!");
298 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
299
300 // Also, since this original header only has one predecessor, zap its
301 // PHI nodes, which are now trivial.
302 FoldSingleEntryPHINodes(OrigHeader);
303
304 // TODO: We could just go ahead and merge OrigHeader into its predecessor
305 // at this point, if we don't mind updating dominator info.
306
307 // Establish a new preheader, update dominators, etc.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000308 preserveCanonicalLoopForm(L, OrigHeader, OrigPreHeader, OrigLatch,
309 NewHeader, Exit);
Devang Patel5464b962007-04-09 20:19:46 +0000310
Dan Gohmanfe601042010-06-22 15:08:57 +0000311 ++NumRotated;
Devang Patelc4625da2007-04-07 01:25:15 +0000312 return true;
313}
314
Devang Patel5464b962007-04-09 20:19:46 +0000315
316/// After loop rotation, loop pre-header has multiple sucessors.
317/// Insert one forwarding basic block to ensure that loop pre-header
318/// has only one successor.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000319void LoopRotate::preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
320 BasicBlock *OrigPreHeader,
321 BasicBlock *OrigLatch,
322 BasicBlock *NewHeader,
323 BasicBlock *Exit) {
Devang Patel5464b962007-04-09 20:19:46 +0000324
325 // Right now original pre-header has two successors, new header and
326 // exit block. Insert new block between original pre-header and
327 // new header such that loop's new pre-header has only one successor.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000328 BasicBlock *NewPreHeader =
329 BasicBlock::Create(OrigHeader->getContext(), "bb.nph",
330 OrigHeader->getParent(), NewHeader);
Dan Gohman6a02fc32009-11-05 19:43:25 +0000331 LoopInfo &LI = getAnalysis<LoopInfo>();
Devang Patel5464b962007-04-09 20:19:46 +0000332 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000333 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000334 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000335
336 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
337 if (OrigPH_BI->getSuccessor(0) == NewHeader)
338 OrigPH_BI->setSuccessor(0, NewPreHeader);
339 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000340 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
341 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000342 OrigPH_BI->setSuccessor(1, NewPreHeader);
343 }
Devang Patel5464b962007-04-09 20:19:46 +0000344
Dan Gohmancfb32202009-06-27 21:23:40 +0000345 PHINode *PN;
346 for (BasicBlock::iterator I = NewHeader->begin();
347 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel5464b962007-04-09 20:19:46 +0000348 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000349 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000350 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000351 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
352 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000353 }
354
Duncan Sands1465d612009-01-28 13:14:17 +0000355 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000356 DT->addNewBlock(NewPreHeader, OrigPreHeader);
357 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
358 DT->changeImmediateDominator(Exit, OrigPreHeader);
359 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
360 BI != BE; ++BI) {
361 BasicBlock *B = *BI;
362 if (L->getHeader() != B) {
363 DomTreeNode *Node = DT->getNode(B);
364 if (Node && Node->getBlock() == OrigHeader)
365 DT->changeImmediateDominator(*BI, L->getHeader());
366 }
367 }
368 DT->changeImmediateDominator(OrigHeader, OrigLatch);
369 }
370
Duncan Sands1465d612009-01-28 13:14:17 +0000371 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000372 // New Preheader's dominance frontier is Exit block.
373 DominanceFrontier::DomSetType NewPHSet;
374 NewPHSet.insert(Exit);
375 DF->addBasicBlock(NewPreHeader, NewPHSet);
376
377 // New Header's dominance frontier now includes itself and Exit block
378 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
379 if (HeadI != DF->end()) {
380 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
381 HeaderSet.clear();
382 HeaderSet.insert(L->getHeader());
383 HeaderSet.insert(Exit);
384 } else {
385 DominanceFrontier::DomSetType HeaderSet;
386 HeaderSet.insert(L->getHeader());
387 HeaderSet.insert(Exit);
388 DF->addBasicBlock(L->getHeader(), HeaderSet);
389 }
390
391 // Original header (new Loop Latch)'s dominance frontier is Exit.
392 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
393 if (LatchI != DF->end()) {
394 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
395 LatchSet = LatchI->second;
396 LatchSet.clear();
397 LatchSet.insert(Exit);
398 } else {
399 DominanceFrontier::DomSetType LatchSet;
400 LatchSet.insert(Exit);
401 DF->addBasicBlock(L->getHeader(), LatchSet);
402 }
403
Devang Patelb7f40c12009-08-07 17:16:44 +0000404 // If a loop block dominates new loop latch then add to its frontiers
405 // new header and Exit and remove new latch (which is equal to original
406 // header).
Devang Patel990e8662007-07-11 23:47:28 +0000407 BasicBlock *NewLatch = L->getLoopLatch();
Devang Patelb7f40c12009-08-07 17:16:44 +0000408
409 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
410
411 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
412 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
413 BI != BE; ++BI) {
414 BasicBlock *B = *BI;
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000415 if (!DT->dominates(B, NewLatch)) continue;
416
417 DominanceFrontier::iterator BDFI = DF->find(B);
418 if (BDFI != DF->end()) {
419 DominanceFrontier::DomSetType &BSet = BDFI->second;
420 BSet.erase(NewLatch);
421 BSet.insert(L->getHeader());
422 BSet.insert(Exit);
423 } else {
424 DominanceFrontier::DomSetType BSet;
425 BSet.insert(L->getHeader());
426 BSet.insert(Exit);
427 DF->addBasicBlock(B, BSet);
Devang Patel990e8662007-07-11 23:47:28 +0000428 }
429 }
430 }
431 }
432
433 // Preserve canonical loop form, which means Exit block should
434 // have only one predecessor.
Dan Gohmanc292caf2009-09-09 18:18:18 +0000435 SplitEdge(L->getLoopLatch(), Exit, this);
Devang Patel990e8662007-07-11 23:47:28 +0000436
Chris Lattner2ba25432009-01-26 01:38:24 +0000437 assert(NewHeader && L->getHeader() == NewHeader &&
438 "Invalid loop header after loop rotation");
439 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
440 "Invalid loop preheader after loop rotation");
441 assert(L->getLoopLatch() &&
442 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000443}