blob: d1c975f2e998afc09a15ce259ea1ce21893fcfd8 [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/LoopPass.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Devang Patel990e8662007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Devang Patelc4625da2007-04-07 01:25:15 +000021#include "llvm/Transforms/Utils/Local.h"
Devang Patel990e8662007-07-11 23:47:28 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmane6e37b92009-10-24 23:19:52 +000023#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ccb3652011-01-08 07:21:31 +000024#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000025#include "llvm/Support/Debug.h"
26#include "llvm/ADT/Statistic.h"
Devang Patelc4625da2007-04-07 01:25:15 +000027using namespace llvm;
28
29#define MAX_HEADER_SIZE 16
30
31STATISTIC(NumRotated, "Number of loops rotated");
32namespace {
33
Chris Lattner3e8b6632009-09-02 06:11:42 +000034 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000035 public:
Devang Patel19974732007-05-03 01:11:54 +000036 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000037 LoopRotate() : LoopPass(ID) {
38 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
39 }
Devang Patel794fd752007-05-01 21:15:47 +000040
Devang Patel32231332007-04-09 16:11:48 +000041 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000042 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000043 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000044 AU.addRequired<LoopInfo>();
45 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000046 AU.addRequiredID(LoopSimplifyID);
47 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000048 AU.addRequiredID(LCSSAID);
49 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000050 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000051 }
52
Chris Lattnera1ae0c72011-01-08 18:55:50 +000053 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner4aefc9b2011-01-08 17:48:33 +000054 bool rotateLoop(Loop *L);
Devang Patelc4625da2007-04-07 01:25:15 +000055
Devang Patelc4625da2007-04-07 01:25:15 +000056 private:
Chris Lattner012ca942011-01-08 17:38:45 +000057 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000058 };
Devang Patelc4625da2007-04-07 01:25:15 +000059}
Dan Gohman844731a2008-05-13 00:00:25 +000060
61char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000062INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000063INITIALIZE_PASS_DEPENDENCY(LoopInfo)
64INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
65INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000066INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000067
Daniel Dunbar394f0442008-10-22 23:32:42 +000068Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000069
Devang Patel32231332007-04-09 16:11:48 +000070/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000071/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000072bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000073 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000074
Devang Patelc4625da2007-04-07 01:25:15 +000075 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000076 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000077 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000078 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000079
Chris Lattner012ca942011-01-08 17:38:45 +000080 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000081}
82
Chris Lattner64c24db2011-01-08 19:26:33 +000083/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
84/// old header into the preheader. If there were uses of the values produced by
85/// these instruction that were outside of the loop, we have to insert PHI nodes
86/// to merge the two values. Do this now.
87static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
88 BasicBlock *OrigPreheader,
89 ValueToValueMapTy &ValueMap) {
90 // Remove PHI node entries that are no longer live.
91 BasicBlock::iterator I, E = OrigHeader->end();
92 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
93 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
94
95 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
96 // as necessary.
97 SSAUpdater SSA;
98 for (I = OrigHeader->begin(); I != E; ++I) {
99 Value *OrigHeaderVal = I;
100
101 // If there are no uses of the value (e.g. because it returns void), there
102 // is nothing to rewrite.
103 if (OrigHeaderVal->use_empty())
104 continue;
105
106 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
107
108 // The value now exits in two versions: the initial value in the preheader
109 // and the loop "next" value in the original header.
110 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
111 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
112 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
113
114 // Visit each use of the OrigHeader instruction.
115 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
116 UE = OrigHeaderVal->use_end(); UI != UE; ) {
117 // Grab the use before incrementing the iterator.
118 Use &U = UI.getUse();
119
120 // Increment the iterator before removing the use from the list.
121 ++UI;
122
123 // SSAUpdater can't handle a non-PHI use in the same block as an
124 // earlier def. We can easily handle those cases manually.
125 Instruction *UserInst = cast<Instruction>(U.getUser());
126 if (!isa<PHINode>(UserInst)) {
127 BasicBlock *UserBB = UserInst->getParent();
128
129 // The original users in the OrigHeader are already using the
130 // original definitions.
131 if (UserBB == OrigHeader)
132 continue;
133
134 // Users in the OrigPreHeader need to use the value to which the
135 // original definitions are mapped.
136 if (UserBB == OrigPreheader) {
137 U = OrigPreHeaderVal;
138 continue;
139 }
140 }
141
142 // Anything else can be handled by SSAUpdater.
143 SSA.RewriteUse(U);
144 }
145 }
146}
147
Dan Gohman23d9d272007-05-11 21:10:54 +0000148/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000149bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000150 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000151 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000152 return false;
Chris Lattner2aa69082011-01-08 18:06:22 +0000153
154 BasicBlock *OrigHeader = L->getHeader();
155
156 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
157 if (BI == 0 || BI->isUnconditional())
158 return false;
159
Dan Gohmancc4e6052009-06-25 00:22:44 +0000160 // If the loop header is not one of the loop exiting blocks then
161 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000162 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000163 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000164 return false;
165
Devang Patel32231332007-04-09 16:11:48 +0000166 // Updating PHInodes in loops with multiple exits adds complexity.
167 // Keep it simple, and restrict loop rotation to loops with one exit only.
168 // In future, lift this restriction and support for multiple exits if
169 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000170 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000171 L->getExitBlocks(ExitBlocks);
172 if (ExitBlocks.size() > 1)
173 return false;
174
Chris Lattnerd9e07972011-01-02 07:35:53 +0000175 // Check size of original header and reject loop if it is very big.
176 {
177 CodeMetrics Metrics;
178 Metrics.analyzeBasicBlock(OrigHeader);
179 if (Metrics.NumInsts > MAX_HEADER_SIZE)
180 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000181 }
182
Devang Patel990e8662007-07-11 23:47:28 +0000183 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000184 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattner2aa69082011-01-08 18:06:22 +0000185 BasicBlock *OrigLatch = L->getLoopLatch();
Chris Lattner64c24db2011-01-08 19:26:33 +0000186 assert(OrigPreheader && OrigLatch && "Loop not in canonical form?");
Devang Patel990e8662007-07-11 23:47:28 +0000187
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000188 // Anything ScalarEvolution may know about this loop or the PHI nodes
189 // in its header will soon be invalidated.
190 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000191 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000192
Devang Patelc4625da2007-04-07 01:25:15 +0000193 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000194 // that is inside loop. Header's other successor is outside the
195 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000196 BasicBlock *Exit = BI->getSuccessor(0);
197 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000198 if (L->contains(Exit))
199 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000200 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000201 assert(L->contains(NewHeader) && !L->contains(Exit) &&
202 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000203
Dan Gohmancc4e6052009-06-25 00:22:44 +0000204 // This code assumes that the new header has exactly one predecessor.
205 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000206 assert(NewHeader->getSinglePredecessor() &&
207 "New header doesn't have one pred!");
208 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000209
Dan Gohmane6e37b92009-10-24 23:19:52 +0000210 // Begin by walking OrigHeader and populating ValueMap with an entry for
211 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000212 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000213 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000214
Dan Gohmane6e37b92009-10-24 23:19:52 +0000215 // For PHI nodes, the value available in OldPreHeader is just the
216 // incoming value from OldPreHeader.
217 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattner64c24db2011-01-08 19:26:33 +0000218 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Devang Patelc4625da2007-04-07 01:25:15 +0000219
Chris Lattner50fb4692010-09-06 01:10:22 +0000220 // For the rest of the instructions, either hoist to the OrigPreheader if
221 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000222 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000223 while (I != E) {
224 Instruction *Inst = I++;
225
226 // If the instruction's operands are invariant and it doesn't read or write
227 // memory, then it is safe to hoist. Doing this doesn't change the order of
228 // execution in the preheader, but does prevent the instruction from
229 // executing in each iteration of the loop. This means it is safe to hoist
230 // something that might trap, but isn't safe to hoist something that reads
231 // memory (without proving that the loop doesn't write).
232 if (L->hasLoopInvariantOperands(Inst) &&
233 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
234 !isa<TerminatorInst>(Inst)) {
235 Inst->moveBefore(LoopEntryBranch);
236 continue;
237 }
238
239 // Otherwise, create a duplicate of the instruction.
240 Instruction *C = Inst->clone();
Chris Lattnerb5fa5fc2011-01-08 08:15:20 +0000241
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000242 // Eagerly remap the operands of the instruction.
243 RemapInstruction(C, ValueMap,
244 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
245
246 // With the operands remapped, see if the instruction constant folds or is
247 // otherwise simplifyable. This commonly occurs because the entry from PHI
248 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000249 Value *V = SimplifyInstruction(C);
250 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000251 // If so, then delete the temporary instruction and stick the folded value
252 // in the map.
253 delete C;
254 ValueMap[Inst] = V;
255 } else {
256 // Otherwise, stick the new instruction into the new block!
257 C->setName(Inst->getName());
258 C->insertBefore(LoopEntryBranch);
259 ValueMap[Inst] = C;
260 }
Devang Patelc4625da2007-04-07 01:25:15 +0000261 }
262
Dan Gohmane6e37b92009-10-24 23:19:52 +0000263 // Along with all the other instructions, we just cloned OrigHeader's
264 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
265 // successors by duplicating their incoming values for OrigHeader.
266 TerminatorInst *TI = OrigHeader->getTerminator();
267 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
268 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
269 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000270 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000271
Dan Gohmane6e37b92009-10-24 23:19:52 +0000272 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
273 // OrigPreHeader's old terminator (the original branch into the loop), and
274 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
275 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000276
Chris Lattner64c24db2011-01-08 19:26:33 +0000277 // If there were any uses of instructions in the duplicated block outside the
278 // loop, update them, inserting PHI nodes as required
279 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000280
Dan Gohmane6e37b92009-10-24 23:19:52 +0000281 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000282 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000283 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000284
Chris Lattner5d373702011-01-08 19:59:06 +0000285
286 // At this point, we've finished our major CFG changes. As part of cloning
287 // the loop into the preheader we've simplified instructions and the
288 // duplicated conditional branch may now be branching on a constant. If it is
289 // branching on a constant and if that constant means that we enter the loop,
290 // then we fold away the cond branch to an uncond branch. This simplifies the
291 // loop in cases important for nested loops, and it also means we don't have
292 // to split as many edges.
293 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
294 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
295 if (!isa<ConstantInt>(PHBI->getCondition()) ||
296 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
297 != NewHeader) {
298 // The conditional branch can't be folded, handle the general case.
299 // Update DominatorTree to reflect the CFG change we just made. Then split
300 // edges as necessary to preserve LoopSimplify form.
301 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
302 // Since OrigPreheader now has the conditional branch to Exit block, it is
303 // the dominator of Exit.
304 DT->changeImmediateDominator(Exit, OrigPreheader);
305 DT->changeImmediateDominator(NewHeader, OrigPreheader);
306
307 // Update OrigHeader to be dominated by the new header block.
308 DT->changeImmediateDominator(OrigHeader, OrigLatch);
309 }
Chris Lattner0e4a1542011-01-08 18:52:51 +0000310
Chris Lattner5d373702011-01-08 19:59:06 +0000311 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
312 // thus is not a preheader anymore. Split the edge to form a real preheader.
313 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
314 NewPH->setName(NewHeader->getName() + ".lr.ph");
315
316 // Preserve canonical loop form, which means that 'Exit' should have only one
317 // predecessor.
318 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
319 ExitSplit->moveBefore(Exit);
320 } else {
321 // We can fold the conditional branch in the preheader, this makes things
322 // simpler. The first step is to remove the extra edge to the Exit block.
323 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
324 BranchInst::Create(NewHeader, PHBI);
325 PHBI->eraseFromParent();
326
327 // With our CFG finalized, update DomTree if it is available.
328 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
329 // Update OrigHeader to be dominated by the new header block.
330 DT->changeImmediateDominator(NewHeader, OrigPreheader);
331 DT->changeImmediateDominator(OrigHeader, OrigLatch);
332 }
Devang Patel990e8662007-07-11 23:47:28 +0000333 }
Chris Lattner0e4a1542011-01-08 18:52:51 +0000334
Chris Lattner5d373702011-01-08 19:59:06 +0000335 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000336 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000337
Chris Lattner883401a2011-01-08 19:10:28 +0000338 // Now that the CFG and DomTree are in a consistent state again, merge the
339 // OrigHeader block into OrigLatch. We know that they are joined by an
340 // unconditional branch. This is just a cleanup so the emitted code isn't
341 // too gross.
342 bool DidIt = MergeBlockIntoPredecessor(OrigHeader, this);
343 assert(DidIt && "Block merge failed??"); (void)DidIt;
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000344
345 ++NumRotated;
346 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000347}
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000348