1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotate"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/SSAUpdater.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
31 #define MAX_HEADER_SIZE 16
33 STATISTIC(NumRotated, "Number of loops rotated");
36 class LoopRotate : public LoopPass {
38 static char ID; // Pass ID, replacement for typeid
39 LoopRotate() : LoopPass(&ID) {}
41 // Rotate Loop L as many times as possible. Return true if
42 // loop is rotated at least once.
43 bool runOnLoop(Loop *L, LPPassManager &LPM);
45 // LCSSA form makes instruction renaming easier.
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequiredID(LoopSimplifyID);
48 AU.addPreservedID(LoopSimplifyID);
49 AU.addRequiredID(LCSSAID);
50 AU.addPreservedID(LCSSAID);
51 AU.addPreserved<ScalarEvolution>();
52 AU.addPreserved<LoopInfo>();
53 AU.addPreserved<DominatorTree>();
54 AU.addPreserved<DominanceFrontier>();
60 bool rotateLoop(Loop *L, LPPassManager &LPM);
62 /// Initialize local data
65 /// After loop rotation, loop pre-header has multiple sucessors.
66 /// Insert one forwarding basic block to ensure that loop pre-header
67 /// has only one successor.
68 void preserveCanonicalLoopForm(LPPassManager &LPM);
72 BasicBlock *OrigHeader;
73 BasicBlock *OrigPreHeader;
74 BasicBlock *OrigLatch;
75 BasicBlock *NewHeader;
77 LPPassManager *LPM_Ptr;
81 char LoopRotate::ID = 0;
82 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
84 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
86 /// Rotate Loop L as many times as possible. Return true if
87 /// the loop is rotated at least once.
88 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
90 bool RotatedOneLoop = false;
94 // One loop can be rotated multiple times.
95 while (rotateLoop(Lp,LPM)) {
96 RotatedOneLoop = true;
100 return RotatedOneLoop;
103 /// Rotate loop LP. Return true if the loop is rotated.
104 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
107 OrigHeader = L->getHeader();
108 OrigPreHeader = L->getLoopPreheader();
109 OrigLatch = L->getLoopLatch();
111 // If the loop has only one block then there is not much to rotate.
112 if (L->getBlocks().size() == 1)
115 assert(OrigHeader && OrigLatch && OrigPreHeader &&
116 "Loop is not in canonical form");
118 // If the loop header is not one of the loop exiting blocks then
119 // either this loop is already rotated or it is not
120 // suitable for loop rotation transformations.
121 if (!L->isLoopExiting(OrigHeader))
124 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
127 assert(BI->isConditional() && "Branch Instruction is not conditional");
129 // Updating PHInodes in loops with multiple exits adds complexity.
130 // Keep it simple, and restrict loop rotation to loops with one exit only.
131 // In future, lift this restriction and support for multiple exits if
133 SmallVector<BasicBlock*, 8> ExitBlocks;
134 L->getExitBlocks(ExitBlocks);
135 if (ExitBlocks.size() > 1)
138 // Check size of original header and reject
139 // loop if it is very big.
142 // FIXME: Use common api to estimate size.
143 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
144 OE = OrigHeader->end(); OI != OE; ++OI) {
145 if (isa<PHINode>(OI))
146 continue; // PHI nodes don't count.
147 if (isa<DbgInfoIntrinsic>(OI))
148 continue; // Debug intrinsics don't count as size.
152 if (Size > MAX_HEADER_SIZE)
155 // Now, this loop is suitable for rotation.
157 // Anything ScalarEvolution may know about this loop or the PHI nodes
158 // in its header will soon be invalidated.
159 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
162 // Find new Loop header. NewHeader is a Header's one and only successor
163 // that is inside loop. Header's other successor is outside the
164 // loop. Otherwise loop is not suitable for rotation.
165 Exit = BI->getSuccessor(0);
166 NewHeader = BI->getSuccessor(1);
167 if (L->contains(Exit))
168 std::swap(Exit, NewHeader);
169 assert(NewHeader && "Unable to determine new loop header");
170 assert(L->contains(NewHeader) && !L->contains(Exit) &&
171 "Unable to determine loop header and exit blocks");
173 // This code assumes that the new header has exactly one predecessor.
174 // Remove any single-entry PHI nodes in it.
175 assert(NewHeader->getSinglePredecessor() &&
176 "New header doesn't have one pred!");
177 FoldSingleEntryPHINodes(NewHeader);
179 // Begin by walking OrigHeader and populating ValueMap with an entry for
181 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
182 DenseMap<const Value *, Value *> ValueMap;
184 // For PHI nodes, the value available in OldPreHeader is just the
185 // incoming value from OldPreHeader.
186 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
187 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
189 // For the rest of the instructions, create a clone in the OldPreHeader.
190 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
191 for (; I != E; ++I) {
192 Instruction *C = I->clone();
193 C->setName(I->getName());
194 C->insertBefore(LoopEntryBranch);
198 // Along with all the other instructions, we just cloned OrigHeader's
199 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
200 // successors by duplicating their incoming values for OrigHeader.
201 TerminatorInst *TI = OrigHeader->getTerminator();
202 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
204 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
205 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
207 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
208 // OrigPreHeader's old terminator (the original branch into the loop), and
209 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
210 LoopEntryBranch->eraseFromParent();
211 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
212 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
214 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
217 for (I = OrigHeader->begin(); I != E; ++I) {
218 Value *OrigHeaderVal = I;
219 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
221 // The value now exits in two versions: the initial value in the preheader
222 // and the loop "next" value in the original header.
223 SSA.Initialize(OrigHeaderVal);
224 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
225 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
227 // Visit each use of the OrigHeader instruction.
228 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
229 UE = OrigHeaderVal->use_end(); UI != UE; ) {
230 // Grab the use before incrementing the iterator.
231 Use &U = UI.getUse();
233 // Increment the iterator before removing the use from the list.
236 // SSAUpdater can't handle a non-PHI use in the same block as an
237 // earlier def. We can easily handle those cases manually.
238 Instruction *UserInst = cast<Instruction>(U.getUser());
239 if (!isa<PHINode>(UserInst)) {
240 BasicBlock *UserBB = UserInst->getParent();
242 // The original users in the OrigHeader are already using the
243 // original definitions.
244 if (UserBB == OrigHeader)
247 // Users in the OrigPreHeader need to use the value to which the
248 // original definitions are mapped.
249 if (UserBB == OrigPreHeader) {
250 U = OrigPreHeaderVal;
255 // Anything else can be handled by SSAUpdater.
260 // NewHeader is now the header of the loop.
261 L->moveToHeader(NewHeader);
263 preserveCanonicalLoopForm(LPM);
269 /// Initialize local data
270 void LoopRotate::initialize() {
273 OrigPreHeader = NULL;
278 /// After loop rotation, loop pre-header has multiple sucessors.
279 /// Insert one forwarding basic block to ensure that loop pre-header
280 /// has only one successor.
281 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
283 // Right now original pre-header has two successors, new header and
284 // exit block. Insert new block between original pre-header and
285 // new header such that loop's new pre-header has only one successor.
286 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
288 OrigHeader->getParent(),
290 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
291 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
292 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
293 BranchInst::Create(NewHeader, NewPreHeader);
295 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
296 if (OrigPH_BI->getSuccessor(0) == NewHeader)
297 OrigPH_BI->setSuccessor(0, NewPreHeader);
299 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
300 "Unexpected original pre-header terminator");
301 OrigPH_BI->setSuccessor(1, NewPreHeader);
305 for (BasicBlock::iterator I = NewHeader->begin();
306 (PN = dyn_cast<PHINode>(I)); ++I) {
307 int index = PN->getBasicBlockIndex(OrigPreHeader);
308 assert(index != -1 && "Expected incoming value from Original PreHeader");
309 PN->setIncomingBlock(index, NewPreHeader);
310 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
311 "Expected only one incoming value from Original PreHeader");
314 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
315 DT->addNewBlock(NewPreHeader, OrigPreHeader);
316 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
317 DT->changeImmediateDominator(Exit, OrigPreHeader);
318 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
321 if (L->getHeader() != B) {
322 DomTreeNode *Node = DT->getNode(B);
323 if (Node && Node->getBlock() == OrigHeader)
324 DT->changeImmediateDominator(*BI, L->getHeader());
327 DT->changeImmediateDominator(OrigHeader, OrigLatch);
330 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
331 // New Preheader's dominance frontier is Exit block.
332 DominanceFrontier::DomSetType NewPHSet;
333 NewPHSet.insert(Exit);
334 DF->addBasicBlock(NewPreHeader, NewPHSet);
336 // New Header's dominance frontier now includes itself and Exit block
337 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
338 if (HeadI != DF->end()) {
339 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
341 HeaderSet.insert(L->getHeader());
342 HeaderSet.insert(Exit);
344 DominanceFrontier::DomSetType HeaderSet;
345 HeaderSet.insert(L->getHeader());
346 HeaderSet.insert(Exit);
347 DF->addBasicBlock(L->getHeader(), HeaderSet);
350 // Original header (new Loop Latch)'s dominance frontier is Exit.
351 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
352 if (LatchI != DF->end()) {
353 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
354 LatchSet = LatchI->second;
356 LatchSet.insert(Exit);
358 DominanceFrontier::DomSetType LatchSet;
359 LatchSet.insert(Exit);
360 DF->addBasicBlock(L->getHeader(), LatchSet);
363 // If a loop block dominates new loop latch then add to its frontiers
364 // new header and Exit and remove new latch (which is equal to original
366 BasicBlock *NewLatch = L->getLoopLatch();
368 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
370 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
371 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
374 if (DT->dominates(B, NewLatch)) {
375 DominanceFrontier::iterator BDFI = DF->find(B);
376 if (BDFI != DF->end()) {
377 DominanceFrontier::DomSetType &BSet = BDFI->second;
378 BSet.erase(NewLatch);
379 BSet.insert(L->getHeader());
382 DominanceFrontier::DomSetType BSet;
383 BSet.insert(L->getHeader());
385 DF->addBasicBlock(B, BSet);
392 // Preserve canonical loop form, which means Exit block should
393 // have only one predecessor.
394 SplitEdge(L->getLoopLatch(), Exit, this);
396 assert(NewHeader && L->getHeader() == NewHeader &&
397 "Invalid loop header after loop rotation");
398 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
399 "Invalid loop preheader after loop rotation");
400 assert(L->getLoopLatch() &&
401 "Invalid loop latch after loop rotation");