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/LoopPass.h"
19 #include "llvm/Analysis/InstructionSimplify.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/Transforms/Utils/ValueMapper.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
29 #define MAX_HEADER_SIZE 16
31 STATISTIC(NumRotated, "Number of loops rotated");
34 class LoopRotate : public LoopPass {
36 static char ID; // Pass ID, replacement for typeid
37 LoopRotate() : LoopPass(ID) {
38 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
41 // LCSSA form makes instruction renaming easier.
42 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43 AU.addPreserved<DominatorTree>();
44 AU.addRequired<LoopInfo>();
45 AU.addPreserved<LoopInfo>();
46 AU.addRequiredID(LoopSimplifyID);
47 AU.addPreservedID(LoopSimplifyID);
48 AU.addRequiredID(LCSSAID);
49 AU.addPreservedID(LCSSAID);
50 AU.addPreserved<ScalarEvolution>();
53 bool runOnLoop(Loop *L, LPPassManager &LPM);
54 bool rotateLoop(Loop *L);
61 char LoopRotate::ID = 0;
62 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
63 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
64 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
65 INITIALIZE_PASS_DEPENDENCY(LCSSA)
66 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
68 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
70 /// Rotate Loop L as many times as possible. Return true if
71 /// the loop is rotated at least once.
72 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
73 LI = &getAnalysis<LoopInfo>();
75 // One loop can be rotated multiple times.
76 bool MadeChange = false;
83 /// Rotate loop LP. Return true if the loop is rotated.
84 bool LoopRotate::rotateLoop(Loop *L) {
85 // If the loop has only one block then there is not much to rotate.
86 if (L->getBlocks().size() == 1)
89 BasicBlock *OrigHeader = L->getHeader();
91 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
92 if (BI == 0 || BI->isUnconditional())
95 // If the loop header is not one of the loop exiting blocks then
96 // either this loop is already rotated or it is not
97 // suitable for loop rotation transformations.
98 if (!L->isLoopExiting(OrigHeader))
101 // Updating PHInodes in loops with multiple exits adds complexity.
102 // Keep it simple, and restrict loop rotation to loops with one exit only.
103 // In future, lift this restriction and support for multiple exits if
105 SmallVector<BasicBlock*, 8> ExitBlocks;
106 L->getExitBlocks(ExitBlocks);
107 if (ExitBlocks.size() > 1)
110 // Check size of original header and reject loop if it is very big.
113 Metrics.analyzeBasicBlock(OrigHeader);
114 if (Metrics.NumInsts > MAX_HEADER_SIZE)
118 // Now, this loop is suitable for rotation.
119 BasicBlock *OrigPreHeader = L->getLoopPreheader();
120 BasicBlock *OrigLatch = L->getLoopLatch();
121 assert(OrigPreHeader && OrigLatch && "Loop not in canonical form?");
123 // Anything ScalarEvolution may know about this loop or the PHI nodes
124 // in its header will soon be invalidated.
125 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
128 // Find new Loop header. NewHeader is a Header's one and only successor
129 // that is inside loop. Header's other successor is outside the
130 // loop. Otherwise loop is not suitable for rotation.
131 BasicBlock *Exit = BI->getSuccessor(0);
132 BasicBlock *NewHeader = BI->getSuccessor(1);
133 if (L->contains(Exit))
134 std::swap(Exit, NewHeader);
135 assert(NewHeader && "Unable to determine new loop header");
136 assert(L->contains(NewHeader) && !L->contains(Exit) &&
137 "Unable to determine loop header and exit blocks");
139 // This code assumes that the new header has exactly one predecessor.
140 // Remove any single-entry PHI nodes in it.
141 assert(NewHeader->getSinglePredecessor() &&
142 "New header doesn't have one pred!");
143 FoldSingleEntryPHINodes(NewHeader);
145 // Begin by walking OrigHeader and populating ValueMap with an entry for
147 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
148 ValueToValueMapTy ValueMap;
150 // For PHI nodes, the value available in OldPreHeader is just the
151 // incoming value from OldPreHeader.
152 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
153 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
155 // For the rest of the instructions, either hoist to the OrigPreheader if
156 // possible or create a clone in the OldPreHeader if not.
157 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
159 Instruction *Inst = I++;
161 // If the instruction's operands are invariant and it doesn't read or write
162 // memory, then it is safe to hoist. Doing this doesn't change the order of
163 // execution in the preheader, but does prevent the instruction from
164 // executing in each iteration of the loop. This means it is safe to hoist
165 // something that might trap, but isn't safe to hoist something that reads
166 // memory (without proving that the loop doesn't write).
167 if (L->hasLoopInvariantOperands(Inst) &&
168 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
169 !isa<TerminatorInst>(Inst)) {
170 Inst->moveBefore(LoopEntryBranch);
174 // Otherwise, create a duplicate of the instruction.
175 Instruction *C = Inst->clone();
177 // Eagerly remap the operands of the instruction.
178 RemapInstruction(C, ValueMap,
179 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
181 // With the operands remapped, see if the instruction constant folds or is
182 // otherwise simplifyable. This commonly occurs because the entry from PHI
183 // nodes allows icmps and other instructions to fold.
184 Value *V = SimplifyInstruction(C);
185 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
186 // If so, then delete the temporary instruction and stick the folded value
191 // Otherwise, stick the new instruction into the new block!
192 C->setName(Inst->getName());
193 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 // If there are no uses of the value (e.g. because it returns void), there
222 // is nothing to rewrite.
223 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
226 // The value now exits in two versions: the initial value in the preheader
227 // and the loop "next" value in the original header.
228 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
229 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
230 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
232 // Visit each use of the OrigHeader instruction.
233 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
234 UE = OrigHeaderVal->use_end(); UI != UE; ) {
235 // Grab the use before incrementing the iterator.
236 Use &U = UI.getUse();
238 // Increment the iterator before removing the use from the list.
241 // SSAUpdater can't handle a non-PHI use in the same block as an
242 // earlier def. We can easily handle those cases manually.
243 Instruction *UserInst = cast<Instruction>(U.getUser());
244 if (!isa<PHINode>(UserInst)) {
245 BasicBlock *UserBB = UserInst->getParent();
247 // The original users in the OrigHeader are already using the
248 // original definitions.
249 if (UserBB == OrigHeader)
252 // Users in the OrigPreHeader need to use the value to which the
253 // original definitions are mapped.
254 if (UserBB == OrigPreHeader) {
255 U = OrigPreHeaderVal;
260 // Anything else can be handled by SSAUpdater.
265 // NewHeader is now the header of the loop.
266 L->moveToHeader(NewHeader);
268 // Move the original header to the bottom of the loop, where it now more
269 // naturally belongs. This isn't necessary for correctness, and CodeGen can
270 // usually reorder blocks on its own to fix things like this up, but it's
271 // still nice to keep the IR readable.
273 // The original header should have only one predecessor at this point, since
274 // we checked that the loop had a proper preheader and unique backedge before
276 assert(OrigHeader->getSinglePredecessor() &&
277 "Original loop header has too many predecessors after loop rotation!");
278 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
280 // Also, since this original header only has one predecessor, zap its
281 // PHI nodes, which are now trivial.
282 FoldSingleEntryPHINodes(OrigHeader);
286 // Update DominatorTree to reflect the CFG change we just made. Then split
287 // edges as necessary to preserve LoopSimplify form.
288 assert(L->getHeader() == NewHeader && "Latch block is our new header");
290 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
291 // Since OrigPreheader now has the conditional branch to Exit block, it is
292 // the dominator of Exit.
293 DT->changeImmediateDominator(Exit, OrigPreHeader);
294 DT->changeImmediateDominator(NewHeader, OrigPreHeader);
296 // Update OrigHeader to be dominated by the new header block.
297 DT->changeImmediateDominator(OrigHeader, OrigLatch);
300 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
301 // thus is not a preheader anymore. Split the edge to form a real preheader.
302 BasicBlock *NewPH = SplitCriticalEdge(OrigPreHeader, NewHeader, this);
303 NewPH->setName(NewHeader->getName() + ".lr.ph");
305 // Preserve canonical loop form, which means that 'Exit' should have only one
307 SplitCriticalEdge(L->getLoopLatch(), Exit, this);
309 assert(L->getLoopPreheader() == NewPH &&
310 "Invalid loop preheader after loop rotation");
311 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
314 // TODO: We could just go ahead and merge OrigHeader into its predecessor
315 // at this point, if we don't mind updating dominator info.