blob: 47dced37c3a4f562d3de58bf3dfeae3e14967178 [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 Patel3fc178f2011-02-14 23:03:23 +000017#include "llvm/IntrinsicInst.h"
Chris Lattnerd9e07972011-01-02 07:35:53 +000018#include "llvm/Analysis/CodeMetrics.h"
Chris Lattnerd9ec3572011-01-08 08:24:46 +000019#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 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000043 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000044 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000045 AU.addRequired<LoopInfo>();
46 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000047 AU.addRequiredID(LoopSimplifyID);
48 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000049 AU.addRequiredID(LCSSAID);
50 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000051 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000052 }
53
Chris Lattnera1ae0c72011-01-08 18:55:50 +000054 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner4aefc9b2011-01-08 17:48:33 +000055 bool rotateLoop(Loop *L);
Devang Patelc4625da2007-04-07 01:25:15 +000056
Devang Patelc4625da2007-04-07 01:25:15 +000057 private:
Chris Lattner012ca942011-01-08 17:38:45 +000058 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000059 };
Devang Patelc4625da2007-04-07 01:25:15 +000060}
Dan Gohman844731a2008-05-13 00:00:25 +000061
62char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000063INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000064INITIALIZE_PASS_DEPENDENCY(LoopInfo)
65INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
66INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000067INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000068
Daniel Dunbar394f0442008-10-22 23:32:42 +000069Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000070
Devang Patel32231332007-04-09 16:11:48 +000071/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000072/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000073bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000074 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000075
Devang Patelc4625da2007-04-07 01:25:15 +000076 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000077 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000078 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000079 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000080
Chris Lattner012ca942011-01-08 17:38:45 +000081 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000082}
83
Chris Lattner64c24db2011-01-08 19:26:33 +000084/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
85/// old header into the preheader. If there were uses of the values produced by
86/// these instruction that were outside of the loop, we have to insert PHI nodes
87/// to merge the two values. Do this now.
88static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
89 BasicBlock *OrigPreheader,
90 ValueToValueMapTy &ValueMap) {
91 // Remove PHI node entries that are no longer live.
92 BasicBlock::iterator I, E = OrigHeader->end();
93 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
94 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
95
96 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
97 // as necessary.
98 SSAUpdater SSA;
99 for (I = OrigHeader->begin(); I != E; ++I) {
100 Value *OrigHeaderVal = I;
101
102 // If there are no uses of the value (e.g. because it returns void), there
103 // is nothing to rewrite.
104 if (OrigHeaderVal->use_empty())
105 continue;
106
107 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
108
109 // The value now exits in two versions: the initial value in the preheader
110 // and the loop "next" value in the original header.
111 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
112 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
113 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
114
115 // Visit each use of the OrigHeader instruction.
116 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
117 UE = OrigHeaderVal->use_end(); UI != UE; ) {
118 // Grab the use before incrementing the iterator.
119 Use &U = UI.getUse();
120
121 // Increment the iterator before removing the use from the list.
122 ++UI;
123
124 // SSAUpdater can't handle a non-PHI use in the same block as an
125 // earlier def. We can easily handle those cases manually.
126 Instruction *UserInst = cast<Instruction>(U.getUser());
127 if (!isa<PHINode>(UserInst)) {
128 BasicBlock *UserBB = UserInst->getParent();
129
130 // The original users in the OrigHeader are already using the
131 // original definitions.
132 if (UserBB == OrigHeader)
133 continue;
134
135 // Users in the OrigPreHeader need to use the value to which the
136 // original definitions are mapped.
137 if (UserBB == OrigPreheader) {
138 U = OrigPreHeaderVal;
139 continue;
140 }
141 }
142
143 // Anything else can be handled by SSAUpdater.
144 SSA.RewriteUse(U);
145 }
146 }
147}
148
Dan Gohman23d9d272007-05-11 21:10:54 +0000149/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000150bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000151 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000152 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000153 return false;
Chris Lattner2aa69082011-01-08 18:06:22 +0000154
155 BasicBlock *OrigHeader = L->getHeader();
156
157 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
158 if (BI == 0 || BI->isUnconditional())
159 return false;
160
Dan Gohmancc4e6052009-06-25 00:22:44 +0000161 // If the loop header is not one of the loop exiting blocks then
162 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000163 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000164 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000165 return false;
166
Devang Patel32231332007-04-09 16:11:48 +0000167 // Updating PHInodes in loops with multiple exits adds complexity.
168 // Keep it simple, and restrict loop rotation to loops with one exit only.
169 // In future, lift this restriction and support for multiple exits if
170 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000171 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000172 L->getExitBlocks(ExitBlocks);
173 if (ExitBlocks.size() > 1)
174 return false;
175
Chris Lattnerd9e07972011-01-02 07:35:53 +0000176 // Check size of original header and reject loop if it is very big.
177 {
178 CodeMetrics Metrics;
179 Metrics.analyzeBasicBlock(OrigHeader);
180 if (Metrics.NumInsts > MAX_HEADER_SIZE)
181 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000182 }
183
Devang Patel990e8662007-07-11 23:47:28 +0000184 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000185 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattner2aa69082011-01-08 18:06:22 +0000186 BasicBlock *OrigLatch = L->getLoopLatch();
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000187
188 // If the loop could not be converted to canonical form, it must have an
189 // indirectbr in it, just give up.
190 if (OrigPreheader == 0 || OrigLatch == 0)
191 return false;
Devang Patel990e8662007-07-11 23:47:28 +0000192
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000193 // Anything ScalarEvolution may know about this loop or the PHI nodes
194 // in its header will soon be invalidated.
195 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000196 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000197
Devang Patelc4625da2007-04-07 01:25:15 +0000198 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000199 // that is inside loop. Header's other successor is outside the
200 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000201 BasicBlock *Exit = BI->getSuccessor(0);
202 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000203 if (L->contains(Exit))
204 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000205 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000206 assert(L->contains(NewHeader) && !L->contains(Exit) &&
207 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000208
Dan Gohmancc4e6052009-06-25 00:22:44 +0000209 // This code assumes that the new header has exactly one predecessor.
210 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000211 assert(NewHeader->getSinglePredecessor() &&
212 "New header doesn't have one pred!");
213 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000214
Dan Gohmane6e37b92009-10-24 23:19:52 +0000215 // Begin by walking OrigHeader and populating ValueMap with an entry for
216 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000217 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000218 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000219
Dan Gohmane6e37b92009-10-24 23:19:52 +0000220 // For PHI nodes, the value available in OldPreHeader is just the
221 // incoming value from OldPreHeader.
222 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattner64c24db2011-01-08 19:26:33 +0000223 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Devang Patelc4625da2007-04-07 01:25:15 +0000224
Chris Lattner50fb4692010-09-06 01:10:22 +0000225 // For the rest of the instructions, either hoist to the OrigPreheader if
226 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000227 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000228 while (I != E) {
229 Instruction *Inst = I++;
230
231 // If the instruction's operands are invariant and it doesn't read or write
232 // memory, then it is safe to hoist. Doing this doesn't change the order of
233 // execution in the preheader, but does prevent the instruction from
234 // executing in each iteration of the loop. This means it is safe to hoist
235 // something that might trap, but isn't safe to hoist something that reads
236 // memory (without proving that the loop doesn't write).
237 if (L->hasLoopInvariantOperands(Inst) &&
238 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Devang Patel3fc178f2011-02-14 23:03:23 +0000239 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst)) {
Chris Lattner50fb4692010-09-06 01:10:22 +0000240 Inst->moveBefore(LoopEntryBranch);
241 continue;
242 }
243
244 // Otherwise, create a duplicate of the instruction.
245 Instruction *C = Inst->clone();
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000246
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000247 // Eagerly remap the operands of the instruction.
248 RemapInstruction(C, ValueMap,
249 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
250
251 // With the operands remapped, see if the instruction constant folds or is
252 // otherwise simplifyable. This commonly occurs because the entry from PHI
253 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000254 Value *V = SimplifyInstruction(C);
255 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000256 // If so, then delete the temporary instruction and stick the folded value
257 // in the map.
258 delete C;
259 ValueMap[Inst] = V;
260 } else {
261 // Otherwise, stick the new instruction into the new block!
262 C->setName(Inst->getName());
263 C->insertBefore(LoopEntryBranch);
264 ValueMap[Inst] = C;
265 }
Devang Patelc4625da2007-04-07 01:25:15 +0000266 }
267
Dan Gohmane6e37b92009-10-24 23:19:52 +0000268 // Along with all the other instructions, we just cloned OrigHeader's
269 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
270 // successors by duplicating their incoming values for OrigHeader.
271 TerminatorInst *TI = OrigHeader->getTerminator();
272 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
273 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
274 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000275 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000276
Dan Gohmane6e37b92009-10-24 23:19:52 +0000277 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
278 // OrigPreHeader's old terminator (the original branch into the loop), and
279 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
280 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000281
Chris Lattner64c24db2011-01-08 19:26:33 +0000282 // If there were any uses of instructions in the duplicated block outside the
283 // loop, update them, inserting PHI nodes as required
284 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000285
Dan Gohmane6e37b92009-10-24 23:19:52 +0000286 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000287 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000288 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000289
Chris Lattner5d373702011-01-08 19:59:06 +0000290
291 // At this point, we've finished our major CFG changes. As part of cloning
292 // the loop into the preheader we've simplified instructions and the
293 // duplicated conditional branch may now be branching on a constant. If it is
294 // branching on a constant and if that constant means that we enter the loop,
295 // then we fold away the cond branch to an uncond branch. This simplifies the
296 // loop in cases important for nested loops, and it also means we don't have
297 // to split as many edges.
298 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
299 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
300 if (!isa<ConstantInt>(PHBI->getCondition()) ||
301 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
302 != NewHeader) {
303 // The conditional branch can't be folded, handle the general case.
304 // Update DominatorTree to reflect the CFG change we just made. Then split
305 // edges as necessary to preserve LoopSimplify form.
306 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
307 // Since OrigPreheader now has the conditional branch to Exit block, it is
308 // the dominator of Exit.
309 DT->changeImmediateDominator(Exit, OrigPreheader);
310 DT->changeImmediateDominator(NewHeader, OrigPreheader);
311
312 // Update OrigHeader to be dominated by the new header block.
313 DT->changeImmediateDominator(OrigHeader, OrigLatch);
314 }
Chris Lattner0e4a1542011-01-08 18:52:51 +0000315
Chris Lattner5d373702011-01-08 19:59:06 +0000316 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
317 // thus is not a preheader anymore. Split the edge to form a real preheader.
318 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
319 NewPH->setName(NewHeader->getName() + ".lr.ph");
320
321 // Preserve canonical loop form, which means that 'Exit' should have only one
322 // predecessor.
323 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
324 ExitSplit->moveBefore(Exit);
325 } else {
326 // We can fold the conditional branch in the preheader, this makes things
327 // simpler. The first step is to remove the extra edge to the Exit block.
328 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelbd5426a2011-04-29 20:38:55 +0000329 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
330 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner5d373702011-01-08 19:59:06 +0000331 PHBI->eraseFromParent();
332
333 // With our CFG finalized, update DomTree if it is available.
334 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
335 // Update OrigHeader to be dominated by the new header block.
336 DT->changeImmediateDominator(NewHeader, OrigPreheader);
337 DT->changeImmediateDominator(OrigHeader, OrigLatch);
338 }
Devang Patel990e8662007-07-11 23:47:28 +0000339 }
Chris Lattner0e4a1542011-01-08 18:52:51 +0000340
Chris Lattner5d373702011-01-08 19:59:06 +0000341 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000342 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000343
Chris Lattner93767fd2011-01-11 07:47:59 +0000344 // Now that the CFG and DomTree are in a consistent state again, try to merge
345 // the OrigHeader block into OrigLatch. This will succeed if they are
346 // connected by an unconditional branch. This is just a cleanup so the
347 // emitted code isn't too gross in this common case.
348 MergeBlockIntoPredecessor(OrigHeader, this);
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000349
350 ++NumRotated;
351 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000352}
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000353