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/LoopPass.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/SSAUpdater.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SmallVector.h"
30 #define MAX_HEADER_SIZE 16
32 STATISTIC(NumRotated, "Number of loops rotated");
35 class LoopRotate : public LoopPass {
37 static char ID; // Pass ID, replacement for typeid
38 LoopRotate() : LoopPass(ID) {
39 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
42 // Rotate Loop L as many times as possible. Return true if
43 // loop is rotated at least once.
44 bool runOnLoop(Loop *L, LPPassManager &LPM);
46 // LCSSA form makes instruction renaming easier.
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<LoopInfo>();
52 AU.addRequiredID(LoopSimplifyID);
53 AU.addPreservedID(LoopSimplifyID);
54 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
56 AU.addPreserved<ScalarEvolution>();
62 bool rotateLoop(Loop *L, LPPassManager &LPM);
64 /// Initialize local data
67 /// 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);
74 BasicBlock *OrigHeader;
75 BasicBlock *OrigPreHeader;
76 BasicBlock *OrigLatch;
77 BasicBlock *NewHeader;
79 LPPassManager *LPM_Ptr;
83 char LoopRotate::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
86 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
87 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
88 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
89 INITIALIZE_PASS_DEPENDENCY(LCSSA)
90 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
91 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
93 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
95 /// Rotate Loop L as many times as possible. Return true if
96 /// the loop is rotated at least once.
97 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
99 bool RotatedOneLoop = false;
103 // One loop can be rotated multiple times.
104 while (rotateLoop(Lp,LPM)) {
105 RotatedOneLoop = true;
109 return RotatedOneLoop;
112 /// Rotate loop LP. Return true if the loop is rotated.
113 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
116 OrigPreHeader = L->getLoopPreheader();
117 if (!OrigPreHeader) return false;
119 OrigLatch = L->getLoopLatch();
120 if (!OrigLatch) return false;
122 OrigHeader = L->getHeader();
124 // If the loop has only one block then there is not much to rotate.
125 if (L->getBlocks().size() == 1)
128 // If the loop header is not one of the loop exiting blocks then
129 // either this loop is already rotated or it is not
130 // suitable for loop rotation transformations.
131 if (!L->isLoopExiting(OrigHeader))
134 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
137 assert(BI->isConditional() && "Branch Instruction is not conditional");
139 // Updating PHInodes in loops with multiple exits adds complexity.
140 // Keep it simple, and restrict loop rotation to loops with one exit only.
141 // In future, lift this restriction and support for multiple exits if
143 SmallVector<BasicBlock*, 8> ExitBlocks;
144 L->getExitBlocks(ExitBlocks);
145 if (ExitBlocks.size() > 1)
148 // Check size of original header and reject
149 // loop if it is very big.
152 // FIXME: Use common api to estimate size.
153 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
154 OE = OrigHeader->end(); OI != OE; ++OI) {
155 if (isa<PHINode>(OI))
156 continue; // PHI nodes don't count.
157 if (isa<DbgInfoIntrinsic>(OI))
158 continue; // Debug intrinsics don't count as size.
162 if (Size > MAX_HEADER_SIZE)
165 // Now, this loop is suitable for rotation.
167 // Anything ScalarEvolution may know about this loop or the PHI nodes
168 // in its header will soon be invalidated.
169 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
172 // Find new Loop header. NewHeader is a Header's one and only successor
173 // that is inside loop. Header's other successor is outside the
174 // loop. Otherwise loop is not suitable for rotation.
175 Exit = BI->getSuccessor(0);
176 NewHeader = BI->getSuccessor(1);
177 if (L->contains(Exit))
178 std::swap(Exit, NewHeader);
179 assert(NewHeader && "Unable to determine new loop header");
180 assert(L->contains(NewHeader) && !L->contains(Exit) &&
181 "Unable to determine loop header and exit blocks");
183 // This code assumes that the new header has exactly one predecessor.
184 // Remove any single-entry PHI nodes in it.
185 assert(NewHeader->getSinglePredecessor() &&
186 "New header doesn't have one pred!");
187 FoldSingleEntryPHINodes(NewHeader);
189 // Begin by walking OrigHeader and populating ValueMap with an entry for
191 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
192 DenseMap<const Value *, Value *> ValueMap;
194 // For PHI nodes, the value available in OldPreHeader is just the
195 // incoming value from OldPreHeader.
196 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
197 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
199 // For the rest of the instructions, either hoist to the OrigPreheader if
200 // possible or create a clone in the OldPreHeader if not.
201 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
203 Instruction *Inst = I++;
205 // If the instruction's operands are invariant and it doesn't read or write
206 // memory, then it is safe to hoist. Doing this doesn't change the order of
207 // execution in the preheader, but does prevent the instruction from
208 // executing in each iteration of the loop. This means it is safe to hoist
209 // something that might trap, but isn't safe to hoist something that reads
210 // memory (without proving that the loop doesn't write).
211 if (L->hasLoopInvariantOperands(Inst) &&
212 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
213 !isa<TerminatorInst>(Inst)) {
214 Inst->moveBefore(LoopEntryBranch);
218 // Otherwise, create a duplicate of the instruction.
219 Instruction *C = Inst->clone();
220 C->setName(Inst->getName());
221 C->insertBefore(LoopEntryBranch);
225 // Along with all the other instructions, we just cloned OrigHeader's
226 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
227 // successors by duplicating their incoming values for OrigHeader.
228 TerminatorInst *TI = OrigHeader->getTerminator();
229 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
230 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
231 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
232 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
234 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
235 // OrigPreHeader's old terminator (the original branch into the loop), and
236 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
237 LoopEntryBranch->eraseFromParent();
238 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
239 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
241 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
244 for (I = OrigHeader->begin(); I != E; ++I) {
245 Value *OrigHeaderVal = I;
246 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
248 // The value now exits in two versions: the initial value in the preheader
249 // and the loop "next" value in the original header.
250 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
251 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
252 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
254 // Visit each use of the OrigHeader instruction.
255 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
256 UE = OrigHeaderVal->use_end(); UI != UE; ) {
257 // Grab the use before incrementing the iterator.
258 Use &U = UI.getUse();
260 // Increment the iterator before removing the use from the list.
263 // SSAUpdater can't handle a non-PHI use in the same block as an
264 // earlier def. We can easily handle those cases manually.
265 Instruction *UserInst = cast<Instruction>(U.getUser());
266 if (!isa<PHINode>(UserInst)) {
267 BasicBlock *UserBB = UserInst->getParent();
269 // The original users in the OrigHeader are already using the
270 // original definitions.
271 if (UserBB == OrigHeader)
274 // Users in the OrigPreHeader need to use the value to which the
275 // original definitions are mapped.
276 if (UserBB == OrigPreHeader) {
277 U = OrigPreHeaderVal;
282 // Anything else can be handled by SSAUpdater.
287 // NewHeader is now the header of the loop.
288 L->moveToHeader(NewHeader);
290 // Move the original header to the bottom of the loop, where it now more
291 // naturally belongs. This isn't necessary for correctness, and CodeGen can
292 // usually reorder blocks on its own to fix things like this up, but it's
293 // still nice to keep the IR readable.
295 // The original header should have only one predecessor at this point, since
296 // we checked that the loop had a proper preheader and unique backedge before
298 assert(OrigHeader->getSinglePredecessor() &&
299 "Original loop header has too many predecessors after loop rotation!");
300 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
302 // Also, since this original header only has one predecessor, zap its
303 // PHI nodes, which are now trivial.
304 FoldSingleEntryPHINodes(OrigHeader);
306 // TODO: We could just go ahead and merge OrigHeader into its predecessor
307 // at this point, if we don't mind updating dominator info.
309 // Establish a new preheader, update dominators, etc.
310 preserveCanonicalLoopForm(LPM);
316 /// Initialize local data
317 void LoopRotate::initialize() {
320 OrigPreHeader = NULL;
325 /// After loop rotation, loop pre-header has multiple sucessors.
326 /// Insert one forwarding basic block to ensure that loop pre-header
327 /// has only one successor.
328 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
330 // Right now original pre-header has two successors, new header and
331 // exit block. Insert new block between original pre-header and
332 // new header such that loop's new pre-header has only one successor.
333 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
335 OrigHeader->getParent(),
337 LoopInfo &LI = getAnalysis<LoopInfo>();
338 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
339 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
340 BranchInst::Create(NewHeader, NewPreHeader);
342 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
343 if (OrigPH_BI->getSuccessor(0) == NewHeader)
344 OrigPH_BI->setSuccessor(0, NewPreHeader);
346 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
347 "Unexpected original pre-header terminator");
348 OrigPH_BI->setSuccessor(1, NewPreHeader);
352 for (BasicBlock::iterator I = NewHeader->begin();
353 (PN = dyn_cast<PHINode>(I)); ++I) {
354 int index = PN->getBasicBlockIndex(OrigPreHeader);
355 assert(index != -1 && "Expected incoming value from Original PreHeader");
356 PN->setIncomingBlock(index, NewPreHeader);
357 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
358 "Expected only one incoming value from Original PreHeader");
361 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
362 DT->addNewBlock(NewPreHeader, OrigPreHeader);
363 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
364 DT->changeImmediateDominator(Exit, OrigPreHeader);
365 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
368 if (L->getHeader() != B) {
369 DomTreeNode *Node = DT->getNode(B);
370 if (Node && Node->getBlock() == OrigHeader)
371 DT->changeImmediateDominator(*BI, L->getHeader());
374 DT->changeImmediateDominator(OrigHeader, OrigLatch);
377 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
378 // New Preheader's dominance frontier is Exit block.
379 DominanceFrontier::DomSetType NewPHSet;
380 NewPHSet.insert(Exit);
381 DF->addBasicBlock(NewPreHeader, NewPHSet);
383 // New Header's dominance frontier now includes itself and Exit block
384 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
385 if (HeadI != DF->end()) {
386 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
388 HeaderSet.insert(L->getHeader());
389 HeaderSet.insert(Exit);
391 DominanceFrontier::DomSetType HeaderSet;
392 HeaderSet.insert(L->getHeader());
393 HeaderSet.insert(Exit);
394 DF->addBasicBlock(L->getHeader(), HeaderSet);
397 // Original header (new Loop Latch)'s dominance frontier is Exit.
398 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
399 if (LatchI != DF->end()) {
400 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
401 LatchSet = LatchI->second;
403 LatchSet.insert(Exit);
405 DominanceFrontier::DomSetType LatchSet;
406 LatchSet.insert(Exit);
407 DF->addBasicBlock(L->getHeader(), LatchSet);
410 // If a loop block dominates new loop latch then add to its frontiers
411 // new header and Exit and remove new latch (which is equal to original
413 BasicBlock *NewLatch = L->getLoopLatch();
415 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
417 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
418 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
421 if (DT->dominates(B, NewLatch)) {
422 DominanceFrontier::iterator BDFI = DF->find(B);
423 if (BDFI != DF->end()) {
424 DominanceFrontier::DomSetType &BSet = BDFI->second;
425 BSet.erase(NewLatch);
426 BSet.insert(L->getHeader());
429 DominanceFrontier::DomSetType BSet;
430 BSet.insert(L->getHeader());
432 DF->addBasicBlock(B, BSet);
439 // Preserve canonical loop form, which means Exit block should
440 // have only one predecessor.
441 SplitEdge(L->getLoopLatch(), Exit, this);
443 assert(NewHeader && L->getHeader() == NewHeader &&
444 "Invalid loop header after loop rotation");
445 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
446 "Invalid loop preheader after loop rotation");
447 assert(L->getLoopLatch() &&
448 "Invalid loop latch after loop rotation");