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) {}
40 // Rotate Loop L as many times as possible. Return true if
41 // loop is rotated at least once.
42 bool runOnLoop(Loop *L, LPPassManager &LPM);
44 // LCSSA form makes instruction renaming easier.
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addPreserved<DominatorTree>();
47 AU.addPreserved<DominanceFrontier>();
48 AU.addRequired<LoopInfo>();
49 AU.addPreserved<LoopInfo>();
50 AU.addRequiredID(LoopSimplifyID);
51 AU.addPreservedID(LoopSimplifyID);
52 AU.addRequiredID(LCSSAID);
53 AU.addPreservedID(LCSSAID);
54 AU.addPreserved<ScalarEvolution>();
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 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
83 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
84 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
85 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
86 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
87 INITIALIZE_PASS_DEPENDENCY(LCSSA)
88 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
89 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
91 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
93 /// Rotate Loop L as many times as possible. Return true if
94 /// the loop is rotated at least once.
95 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
97 bool RotatedOneLoop = false;
101 // One loop can be rotated multiple times.
102 while (rotateLoop(Lp,LPM)) {
103 RotatedOneLoop = true;
107 return RotatedOneLoop;
110 /// Rotate loop LP. Return true if the loop is rotated.
111 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
114 OrigPreHeader = L->getLoopPreheader();
115 if (!OrigPreHeader) return false;
117 OrigLatch = L->getLoopLatch();
118 if (!OrigLatch) return false;
120 OrigHeader = L->getHeader();
122 // If the loop has only one block then there is not much to rotate.
123 if (L->getBlocks().size() == 1)
126 // If the loop header is not one of the loop exiting blocks then
127 // either this loop is already rotated or it is not
128 // suitable for loop rotation transformations.
129 if (!L->isLoopExiting(OrigHeader))
132 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
135 assert(BI->isConditional() && "Branch Instruction is not conditional");
137 // Updating PHInodes in loops with multiple exits adds complexity.
138 // Keep it simple, and restrict loop rotation to loops with one exit only.
139 // In future, lift this restriction and support for multiple exits if
141 SmallVector<BasicBlock*, 8> ExitBlocks;
142 L->getExitBlocks(ExitBlocks);
143 if (ExitBlocks.size() > 1)
146 // Check size of original header and reject
147 // loop if it is very big.
150 // FIXME: Use common api to estimate size.
151 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
152 OE = OrigHeader->end(); OI != OE; ++OI) {
153 if (isa<PHINode>(OI))
154 continue; // PHI nodes don't count.
155 if (isa<DbgInfoIntrinsic>(OI))
156 continue; // Debug intrinsics don't count as size.
160 if (Size > MAX_HEADER_SIZE)
163 // Now, this loop is suitable for rotation.
165 // Anything ScalarEvolution may know about this loop or the PHI nodes
166 // in its header will soon be invalidated.
167 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
170 // Find new Loop header. NewHeader is a Header's one and only successor
171 // that is inside loop. Header's other successor is outside the
172 // loop. Otherwise loop is not suitable for rotation.
173 Exit = BI->getSuccessor(0);
174 NewHeader = BI->getSuccessor(1);
175 if (L->contains(Exit))
176 std::swap(Exit, NewHeader);
177 assert(NewHeader && "Unable to determine new loop header");
178 assert(L->contains(NewHeader) && !L->contains(Exit) &&
179 "Unable to determine loop header and exit blocks");
181 // This code assumes that the new header has exactly one predecessor.
182 // Remove any single-entry PHI nodes in it.
183 assert(NewHeader->getSinglePredecessor() &&
184 "New header doesn't have one pred!");
185 FoldSingleEntryPHINodes(NewHeader);
187 // Begin by walking OrigHeader and populating ValueMap with an entry for
189 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
190 DenseMap<const Value *, Value *> ValueMap;
192 // For PHI nodes, the value available in OldPreHeader is just the
193 // incoming value from OldPreHeader.
194 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
195 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
197 // For the rest of the instructions, either hoist to the OrigPreheader if
198 // possible or create a clone in the OldPreHeader if not.
199 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
201 Instruction *Inst = I++;
203 // If the instruction's operands are invariant and it doesn't read or write
204 // memory, then it is safe to hoist. Doing this doesn't change the order of
205 // execution in the preheader, but does prevent the instruction from
206 // executing in each iteration of the loop. This means it is safe to hoist
207 // something that might trap, but isn't safe to hoist something that reads
208 // memory (without proving that the loop doesn't write).
209 if (L->hasLoopInvariantOperands(Inst) &&
210 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
211 !isa<TerminatorInst>(Inst)) {
212 Inst->moveBefore(LoopEntryBranch);
216 // Otherwise, create a duplicate of the instruction.
217 Instruction *C = Inst->clone();
218 C->setName(Inst->getName());
219 C->insertBefore(LoopEntryBranch);
223 // Along with all the other instructions, we just cloned OrigHeader's
224 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
225 // successors by duplicating their incoming values for OrigHeader.
226 TerminatorInst *TI = OrigHeader->getTerminator();
227 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
228 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
229 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
230 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
232 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
233 // OrigPreHeader's old terminator (the original branch into the loop), and
234 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
235 LoopEntryBranch->eraseFromParent();
236 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
237 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
239 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
242 for (I = OrigHeader->begin(); I != E; ++I) {
243 Value *OrigHeaderVal = I;
244 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
246 // The value now exits in two versions: the initial value in the preheader
247 // and the loop "next" value in the original header.
248 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
249 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
250 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
252 // 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();
258 // Increment the iterator before removing the use from the list.
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();
267 // The original users in the OrigHeader are already using the
268 // original definitions.
269 if (UserBB == OrigHeader)
272 // Users in the OrigPreHeader need to use the value to which the
273 // original definitions are mapped.
274 if (UserBB == OrigPreHeader) {
275 U = OrigPreHeaderVal;
280 // Anything else can be handled by SSAUpdater.
285 // NewHeader is now the header of the loop.
286 L->moveToHeader(NewHeader);
288 // 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.
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
296 assert(OrigHeader->getSinglePredecessor() &&
297 "Original loop header has too many predecessors after loop rotation!");
298 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
300 // Also, since this original header only has one predecessor, zap its
301 // PHI nodes, which are now trivial.
302 FoldSingleEntryPHINodes(OrigHeader);
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.
307 // Establish a new preheader, update dominators, etc.
308 preserveCanonicalLoopForm(LPM);
314 /// Initialize local data
315 void LoopRotate::initialize() {
318 OrigPreHeader = NULL;
323 /// After loop rotation, loop pre-header has multiple sucessors.
324 /// Insert one forwarding basic block to ensure that loop pre-header
325 /// has only one successor.
326 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
328 // Right now original pre-header has two successors, new header and
329 // exit block. Insert new block between original pre-header and
330 // new header such that loop's new pre-header has only one successor.
331 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
333 OrigHeader->getParent(),
335 LoopInfo &LI = getAnalysis<LoopInfo>();
336 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
337 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
338 BranchInst::Create(NewHeader, NewPreHeader);
340 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
341 if (OrigPH_BI->getSuccessor(0) == NewHeader)
342 OrigPH_BI->setSuccessor(0, NewPreHeader);
344 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
345 "Unexpected original pre-header terminator");
346 OrigPH_BI->setSuccessor(1, NewPreHeader);
350 for (BasicBlock::iterator I = NewHeader->begin();
351 (PN = dyn_cast<PHINode>(I)); ++I) {
352 int index = PN->getBasicBlockIndex(OrigPreHeader);
353 assert(index != -1 && "Expected incoming value from Original PreHeader");
354 PN->setIncomingBlock(index, NewPreHeader);
355 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
356 "Expected only one incoming value from Original PreHeader");
359 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
360 DT->addNewBlock(NewPreHeader, OrigPreHeader);
361 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
362 DT->changeImmediateDominator(Exit, OrigPreHeader);
363 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
366 if (L->getHeader() != B) {
367 DomTreeNode *Node = DT->getNode(B);
368 if (Node && Node->getBlock() == OrigHeader)
369 DT->changeImmediateDominator(*BI, L->getHeader());
372 DT->changeImmediateDominator(OrigHeader, OrigLatch);
375 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
376 // New Preheader's dominance frontier is Exit block.
377 DominanceFrontier::DomSetType NewPHSet;
378 NewPHSet.insert(Exit);
379 DF->addBasicBlock(NewPreHeader, NewPHSet);
381 // New Header's dominance frontier now includes itself and Exit block
382 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
383 if (HeadI != DF->end()) {
384 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
386 HeaderSet.insert(L->getHeader());
387 HeaderSet.insert(Exit);
389 DominanceFrontier::DomSetType HeaderSet;
390 HeaderSet.insert(L->getHeader());
391 HeaderSet.insert(Exit);
392 DF->addBasicBlock(L->getHeader(), HeaderSet);
395 // Original header (new Loop Latch)'s dominance frontier is Exit.
396 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
397 if (LatchI != DF->end()) {
398 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
399 LatchSet = LatchI->second;
401 LatchSet.insert(Exit);
403 DominanceFrontier::DomSetType LatchSet;
404 LatchSet.insert(Exit);
405 DF->addBasicBlock(L->getHeader(), LatchSet);
408 // If a loop block dominates new loop latch then add to its frontiers
409 // new header and Exit and remove new latch (which is equal to original
411 BasicBlock *NewLatch = L->getLoopLatch();
413 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
415 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
416 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
419 if (DT->dominates(B, NewLatch)) {
420 DominanceFrontier::iterator BDFI = DF->find(B);
421 if (BDFI != DF->end()) {
422 DominanceFrontier::DomSetType &BSet = BDFI->second;
423 BSet.erase(NewLatch);
424 BSet.insert(L->getHeader());
427 DominanceFrontier::DomSetType BSet;
428 BSet.insert(L->getHeader());
430 DF->addBasicBlock(B, BSet);
437 // Preserve canonical loop form, which means Exit block should
438 // have only one predecessor.
439 SplitEdge(L->getLoopLatch(), Exit, this);
441 assert(NewHeader && L->getHeader() == NewHeader &&
442 "Invalid loop header after loop rotation");
443 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
444 "Invalid loop preheader after loop rotation");
445 assert(L->getLoopLatch() &&
446 "Invalid loop latch after loop rotation");