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/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/DominanceFrontier.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/InstructionSimplify.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/Transforms/Utils/ValueMapper.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.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);
64 /// After loop rotation, loop pre-header has multiple sucessors.
65 /// Insert one forwarding basic block to ensure that loop pre-header
66 /// has only one successor.
67 void preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
68 BasicBlock *OrigPreHeader,
69 BasicBlock *OrigLatch, BasicBlock *NewHeader,
77 char LoopRotate::ID = 0;
78 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
79 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81 INITIALIZE_PASS_DEPENDENCY(LCSSA)
82 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
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 *L, LPPassManager &LPM) {
89 LI = &getAnalysis<LoopInfo>();
91 // One loop can be rotated multiple times.
92 bool MadeChange = false;
99 /// Rotate loop LP. Return true if the loop is rotated.
100 bool LoopRotate::rotateLoop(Loop *L) {
101 // If the loop has only one block then there is not much to rotate.
102 if (L->getBlocks().size() == 1)
105 BasicBlock *OrigHeader = L->getHeader();
107 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
108 if (BI == 0 || BI->isUnconditional())
111 // If the loop header is not one of the loop exiting blocks then
112 // either this loop is already rotated or it is not
113 // suitable for loop rotation transformations.
114 if (!L->isLoopExiting(OrigHeader))
117 // Updating PHInodes in loops with multiple exits adds complexity.
118 // Keep it simple, and restrict loop rotation to loops with one exit only.
119 // In future, lift this restriction and support for multiple exits if
121 SmallVector<BasicBlock*, 8> ExitBlocks;
122 L->getExitBlocks(ExitBlocks);
123 if (ExitBlocks.size() > 1)
126 // Check size of original header and reject loop if it is very big.
129 Metrics.analyzeBasicBlock(OrigHeader);
130 if (Metrics.NumInsts > MAX_HEADER_SIZE)
134 // Now, this loop is suitable for rotation.
135 BasicBlock *OrigPreHeader = L->getLoopPreheader();
136 BasicBlock *OrigLatch = L->getLoopLatch();
137 assert(OrigPreHeader && OrigLatch && "Loop not in canonical form?");
139 // Anything ScalarEvolution may know about this loop or the PHI nodes
140 // in its header will soon be invalidated.
141 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
144 // Find new Loop header. NewHeader is a Header's one and only successor
145 // that is inside loop. Header's other successor is outside the
146 // loop. Otherwise loop is not suitable for rotation.
147 BasicBlock *Exit = BI->getSuccessor(0);
148 BasicBlock *NewHeader = BI->getSuccessor(1);
149 if (L->contains(Exit))
150 std::swap(Exit, NewHeader);
151 assert(NewHeader && "Unable to determine new loop header");
152 assert(L->contains(NewHeader) && !L->contains(Exit) &&
153 "Unable to determine loop header and exit blocks");
155 // This code assumes that the new header has exactly one predecessor.
156 // Remove any single-entry PHI nodes in it.
157 assert(NewHeader->getSinglePredecessor() &&
158 "New header doesn't have one pred!");
159 FoldSingleEntryPHINodes(NewHeader);
161 // Begin by walking OrigHeader and populating ValueMap with an entry for
163 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
164 ValueToValueMapTy ValueMap;
166 // For PHI nodes, the value available in OldPreHeader is just the
167 // incoming value from OldPreHeader.
168 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
169 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
171 // For the rest of the instructions, either hoist to the OrigPreheader if
172 // possible or create a clone in the OldPreHeader if not.
173 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
175 Instruction *Inst = I++;
177 // If the instruction's operands are invariant and it doesn't read or write
178 // memory, then it is safe to hoist. Doing this doesn't change the order of
179 // execution in the preheader, but does prevent the instruction from
180 // executing in each iteration of the loop. This means it is safe to hoist
181 // something that might trap, but isn't safe to hoist something that reads
182 // memory (without proving that the loop doesn't write).
183 if (L->hasLoopInvariantOperands(Inst) &&
184 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
185 !isa<TerminatorInst>(Inst)) {
186 Inst->moveBefore(LoopEntryBranch);
190 // Otherwise, create a duplicate of the instruction.
191 Instruction *C = Inst->clone();
193 // Eagerly remap the operands of the instruction.
194 RemapInstruction(C, ValueMap,
195 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
197 // With the operands remapped, see if the instruction constant folds or is
198 // otherwise simplifyable. This commonly occurs because the entry from PHI
199 // nodes allows icmps and other instructions to fold.
200 Value *V = SimplifyInstruction(C);
201 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
202 // If so, then delete the temporary instruction and stick the folded value
207 // Otherwise, stick the new instruction into the new block!
208 C->setName(Inst->getName());
209 C->insertBefore(LoopEntryBranch);
214 // Along with all the other instructions, we just cloned OrigHeader's
215 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
216 // successors by duplicating their incoming values for OrigHeader.
217 TerminatorInst *TI = OrigHeader->getTerminator();
218 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
219 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
220 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
221 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
223 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
224 // OrigPreHeader's old terminator (the original branch into the loop), and
225 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
226 LoopEntryBranch->eraseFromParent();
227 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
228 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
230 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
233 for (I = OrigHeader->begin(); I != E; ++I) {
234 Value *OrigHeaderVal = I;
235 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
237 // If there are no uses of the value (e.g. because it returns void), there
238 // is nothing to rewrite.
239 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
242 // The value now exits in two versions: the initial value in the preheader
243 // and the loop "next" value in the original header.
244 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
245 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
246 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
248 // Visit each use of the OrigHeader instruction.
249 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
250 UE = OrigHeaderVal->use_end(); UI != UE; ) {
251 // Grab the use before incrementing the iterator.
252 Use &U = UI.getUse();
254 // Increment the iterator before removing the use from the list.
257 // SSAUpdater can't handle a non-PHI use in the same block as an
258 // earlier def. We can easily handle those cases manually.
259 Instruction *UserInst = cast<Instruction>(U.getUser());
260 if (!isa<PHINode>(UserInst)) {
261 BasicBlock *UserBB = UserInst->getParent();
263 // The original users in the OrigHeader are already using the
264 // original definitions.
265 if (UserBB == OrigHeader)
268 // Users in the OrigPreHeader need to use the value to which the
269 // original definitions are mapped.
270 if (UserBB == OrigPreHeader) {
271 U = OrigPreHeaderVal;
276 // Anything else can be handled by SSAUpdater.
281 // NewHeader is now the header of the loop.
282 L->moveToHeader(NewHeader);
284 // Move the original header to the bottom of the loop, where it now more
285 // naturally belongs. This isn't necessary for correctness, and CodeGen can
286 // usually reorder blocks on its own to fix things like this up, but it's
287 // still nice to keep the IR readable.
289 // The original header should have only one predecessor at this point, since
290 // we checked that the loop had a proper preheader and unique backedge before
292 assert(OrigHeader->getSinglePredecessor() &&
293 "Original loop header has too many predecessors after loop rotation!");
294 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
296 // Also, since this original header only has one predecessor, zap its
297 // PHI nodes, which are now trivial.
298 FoldSingleEntryPHINodes(OrigHeader);
300 // TODO: We could just go ahead and merge OrigHeader into its predecessor
301 // at this point, if we don't mind updating dominator info.
303 // Establish a new preheader, update dominators, etc.
304 preserveCanonicalLoopForm(L, OrigHeader, OrigPreHeader, OrigLatch,
312 /// After loop rotation, loop pre-header has multiple sucessors.
313 /// Insert one forwarding basic block to ensure that loop pre-header
314 /// has only one successor.
315 void LoopRotate::preserveCanonicalLoopForm(Loop *L, BasicBlock *OrigHeader,
316 BasicBlock *OrigPreHeader,
317 BasicBlock *OrigLatch,
318 BasicBlock *NewHeader,
321 // Right now original pre-header has two successors, new header and
322 // exit block. Insert new block between original pre-header and
323 // new header such that loop's new pre-header has only one successor.
324 BasicBlock *NewPreHeader =
325 BasicBlock::Create(OrigHeader->getContext(), "bb.nph",
326 OrigHeader->getParent(), NewHeader);
327 if (Loop *PL = LI->getLoopFor(OrigPreHeader))
328 PL->addBasicBlockToLoop(NewPreHeader, LI->getBase());
329 BranchInst::Create(NewHeader, NewPreHeader);
331 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
332 if (OrigPH_BI->getSuccessor(0) == NewHeader)
333 OrigPH_BI->setSuccessor(0, NewPreHeader);
335 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
336 "Unexpected original pre-header terminator");
337 OrigPH_BI->setSuccessor(1, NewPreHeader);
341 for (BasicBlock::iterator I = NewHeader->begin();
342 (PN = dyn_cast<PHINode>(I)); ++I) {
343 int index = PN->getBasicBlockIndex(OrigPreHeader);
344 assert(index != -1 && "Expected incoming value from Original PreHeader");
345 PN->setIncomingBlock(index, NewPreHeader);
346 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
347 "Expected only one incoming value from Original PreHeader");
350 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
351 DT->addNewBlock(NewPreHeader, OrigPreHeader);
352 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
353 DT->changeImmediateDominator(Exit, OrigPreHeader);
354 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
357 if (L->getHeader() != B) {
358 DomTreeNode *Node = DT->getNode(B);
359 if (Node && Node->getBlock() == OrigHeader)
360 DT->changeImmediateDominator(*BI, L->getHeader());
363 DT->changeImmediateDominator(OrigHeader, OrigLatch);
366 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
367 // New Preheader's dominance frontier is Exit block.
368 DominanceFrontier::DomSetType NewPHSet;
369 NewPHSet.insert(Exit);
370 DF->addBasicBlock(NewPreHeader, NewPHSet);
372 // New Header's dominance frontier now includes itself and Exit block
373 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
374 if (HeadI != DF->end()) {
375 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
377 HeaderSet.insert(L->getHeader());
378 HeaderSet.insert(Exit);
380 DominanceFrontier::DomSetType HeaderSet;
381 HeaderSet.insert(L->getHeader());
382 HeaderSet.insert(Exit);
383 DF->addBasicBlock(L->getHeader(), HeaderSet);
386 // Original header (new Loop Latch)'s dominance frontier is Exit.
387 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
388 if (LatchI != DF->end()) {
389 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
390 LatchSet = LatchI->second;
392 LatchSet.insert(Exit);
394 DominanceFrontier::DomSetType LatchSet;
395 LatchSet.insert(Exit);
396 DF->addBasicBlock(L->getHeader(), LatchSet);
399 // If a loop block dominates new loop latch then add to its frontiers
400 // new header and Exit and remove new latch (which is equal to original
402 BasicBlock *NewLatch = L->getLoopLatch();
404 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
406 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
407 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
410 if (!DT->dominates(B, NewLatch)) continue;
412 DominanceFrontier::iterator BDFI = DF->find(B);
413 if (BDFI != DF->end()) {
414 DominanceFrontier::DomSetType &BSet = BDFI->second;
415 BSet.erase(NewLatch);
416 BSet.insert(L->getHeader());
419 DominanceFrontier::DomSetType BSet;
420 BSet.insert(L->getHeader());
422 DF->addBasicBlock(B, BSet);
428 // Preserve canonical loop form, which means Exit block should
429 // have only one predecessor.
430 SplitEdge(L->getLoopLatch(), Exit, this);
432 assert(NewHeader && L->getHeader() == NewHeader &&
433 "Invalid loop header after loop rotation");
434 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
435 "Invalid loop preheader after loop rotation");
436 assert(L->getLoopLatch() &&
437 "Invalid loop latch after loop rotation");