1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotation"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/SmallVector.h"
30 #define MAX_HEADER_SIZE 16
32 STATISTIC(NumRotated, "Number of loops rotated");
36 RotateThreshold("rotate-threshold", cl::init(200), cl::Hidden,
37 cl::desc("The cut-off point for loop rotating"));
39 class VISIBILITY_HIDDEN InsnReplacementData {
41 InsnReplacementData(Instruction *O, Instruction *P, Instruction *H)
42 : Original(O), PreHeader(P), Header(H) {}
44 Instruction *Original; // Original instruction
45 Instruction *PreHeader; // New pre-header replacement
46 Instruction *Header; // New header replacement
49 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
52 bool runOnLoop(Loop *L, LPPassManager &LPM);
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
56 //AU.addRequired<LoopInfo>();
57 //AU.addPreserved<LoopInfo>();
63 bool rotateLoop(Loop *L, LPPassManager &LPM);
65 /// Initialize local data
68 /// Make sure all Exit block PHINodes have required incoming values.
69 /// If incoming value is constant or defined outside the loop then
70 /// PHINode may not have an entry for new pre-header.
71 void updateExitBlock();
73 /// Return true if this instruction is used outside original header.
74 bool usedOutsideOriginalHeader(Instruction *In);
76 /// Find Replacement information for instruction. Return NULL if it is
78 InsnReplacementData *findReplacementData(Instruction *I);
83 BasicBlock *OrigHeader;
84 BasicBlock *OrigPreHeader;
85 BasicBlock *OrigLatch;
86 BasicBlock *NewHeader;
87 BasicBlock *NewPreHeader;
90 SmallVector<InsnReplacementData, MAX_HEADER_SIZE> RD;
93 RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
96 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
98 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
100 bool RotatedOneLoop = false;
103 // One loop can be rotated multiple times.
104 while (rotateLoop(Lp,LPM)) {
105 RotatedOneLoop = true;
109 return RotatedOneLoop;
112 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
115 if ( NumRotated >= RotateThreshold)
118 OrigHeader = L->getHeader();
119 OrigPreHeader = L->getLoopPreheader();
120 OrigLatch = L->getLoopLatch();
122 // If loop has only one block then there is not much to rotate.
123 if (L->getBlocks().size() <= 1)
126 if (!OrigHeader || !OrigLatch || !OrigPreHeader)
129 // If loop header is not one of the loop exit block then
130 // either this loop is already rotated or it is not
131 // suitable for loop rotation transformations.
132 if (!L->isLoopExit(OrigHeader))
135 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
139 std::vector<BasicBlock *> ExitBlocks;
140 L->getExitBlocks(ExitBlocks);
141 if (ExitBlocks.size() > 1)
144 // Find new Loop header. NewHeader is a Header's one and only successor
145 // that is inside loop. Header's all other successors are out side the
146 // loop. Otherwise loop is not suitable for rotation.
147 for (unsigned index = 0; index < BI->getNumSuccessors(); ++index) {
148 BasicBlock *S = BI->getSuccessor(index);
149 if (L->contains(S)) {
153 // Loop Header has two successors inside loop. This loop is
154 // not suitable for rotation.
160 // Loop has multiple exits.
164 assert (NewHeader && "Unable to determine new loop header");
166 // Check size of original header and reject
167 // loop if it is very big.
168 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
171 // Now, this loop is suitable for rotation.
173 // Copy Prepare PHI nodes and other instructions from original header
174 // into new pre-header. Unlike original header, new pre-header is
175 // not a member of loop. New pre-header has only one predecessor,
176 // that is original loop pre-header.
178 // New loop header is one and only successor of original header that
179 // is inside the loop. All other original header successors are outside
180 // the loop. Copy PHI Nodes from original header into new loop header.
181 // Add second incoming value, from new loop pre-header into these phi
182 // nodes. If a value defined in original header is used outside original
183 // header then new loop header will need new phi nodes with two incoming
184 // values, one definition from original header and second definition is
185 // from new loop pre-header (which is a clone of original header definition).
187 NewPreHeader = new BasicBlock("bb.nph", OrigHeader->getParent(), OrigHeader);
188 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
192 if (PHINode *PN = dyn_cast<PHINode>(I)) {
194 // Create new PHI node with one value incoming from OrigPreHeader.
195 // NewPreHeader has only one predecessor, OrigPreHeader.
196 PHINode *NPH = new PHINode(In->getType(), In->getName());
197 NPH->addIncoming(PN->getIncomingValueForBlock(OrigPreHeader),
199 NewPreHeader->getInstList().push_back(NPH);
201 // Create new PHI node with two incoming values for NewHeader.
202 // One incoming value is from OrigLatch (through OrigHeader) and
203 // second incoming value is from NewPreHeader.
204 PHINode *NH = new PHINode(In->getType(), In->getName());
205 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
206 NH->addIncoming(NPH, NewPreHeader);
207 NewHeader->getInstList().push_front(NH);
209 RD.push_back(InsnReplacementData(In, NPH, NH));
211 // This is not a PHI instruction. Insert its clone into NewPreHeader.
212 // If this instruction is using a value from same basic block then
213 // update it to use value from cloned instruction.
214 Instruction *C = In->clone();
215 C->setName(In->getName());
216 NewPreHeader->getInstList().push_back(C);
218 // If this instruction is used outside this basic block then
219 // create new PHINode for this instruction.
220 Instruction *NewHeaderReplacement = NULL;
221 if (usedOutsideOriginalHeader(In)) {
222 PHINode *PN = new PHINode(In->getType(), In->getName());
223 PN->addIncoming(In, OrigHeader);
224 PN->addIncoming(C, NewPreHeader);
225 NewHeader->getInstList().push_front(PN);
226 NewHeaderReplacement = PN;
228 RD.push_back(InsnReplacementData(In, C, NewHeaderReplacement));
232 // Update new pre-header.
233 // Rename values that are defined in original header to reflects values
234 // defined in new pre-header.
235 for (SmallVector<InsnReplacementData, MAX_HEADER_SIZE>::iterator
236 I = RD.begin(), E = RD.end(); I != E; ++I) {
238 InsnReplacementData IRD = (*I);
239 Instruction *In = IRD.Original;
240 Instruction *C = IRD.PreHeader;
242 if (C->getParent() != NewPreHeader)
245 // PHINodes uses value from pre-header predecessors.
246 if (isa<PHINode>(In))
249 for (unsigned opi = 0; opi < In->getNumOperands(); ++opi) {
250 if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
251 if (InsnReplacementData *D = findReplacementData(OpPhi))
252 C->setOperand(opi, D->PreHeader);
254 else if (Instruction *OpInsn =
255 dyn_cast<Instruction>(In->getOperand(opi))) {
256 if (InsnReplacementData *D = findReplacementData(OpInsn))
257 C->setOperand(opi, D->PreHeader);
262 // Rename uses of original header instructions to reflect their new
263 // definitions (either from new pre-header node or from newly created
264 // new header PHINodes.
266 // Original header instructions are used in
267 // 1) Original header:
269 // If instruction is used in non-phi instructions then it is using
270 // defintion from original heder iteself. Do not replace this use
271 // with definition from new header or new pre-header.
273 // If instruction is used in phi node then it is an incoming
274 // value. Rename its use to reflect new definition from new-preheader
277 // 2) Inside loop but not in original header
279 // Replace this use to reflect definition from new header.
280 for (SmallVector<InsnReplacementData, MAX_HEADER_SIZE>::iterator
281 I = RD.begin(), E = RD.end(); I != E; ++I) {
283 InsnReplacementData IRD = (*I);
287 Instruction *OldPhi = IRD.Original;
288 Instruction *NewPhi = IRD.Header;
290 // Before replacing uses, collect them first, so that iterator is
292 SmallVector<Instruction *, 16> AllUses;
293 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
295 Instruction *U = cast<Instruction>(UI);
296 AllUses.push_back(U);
299 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
300 UE = AllUses.end(); UI != UE; ++UI) {
301 Instruction *U = *UI;
302 BasicBlock *Parent = U->getParent();
304 // Used inside original header
305 if (Parent == OrigHeader) {
306 // Do not rename uses inside original header non-phi instructions.
307 if (!isa<PHINode>(U))
309 PHINode *PU = dyn_cast<PHINode>(U);
310 // Do not rename uses inside original header phi nodes, if the
311 // incoming value is for new header.
312 if (PU->getBasicBlockIndex(NewHeader) != -1
313 && PU->getIncomingValueForBlock(NewHeader) == U)
316 U->replaceUsesOfWith(OldPhi, NewPhi);
320 // Used inside loop, but not in original header.
321 if (L->contains(U->getParent())) {
323 U->replaceUsesOfWith(OldPhi, NewPhi);
327 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
328 assert ( U->getParent() == Exit && "Need to propagate new PHI into Exit blocks");
329 assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
331 PHINode *UPhi = cast<PHINode>(U);
333 // UPhi already has one incoming argument from original header.
334 // Add second incoming argument from new Pre header.
336 UPhi->addIncoming(IRD.PreHeader, NewPreHeader);
340 /// Make sure all Exit block PHINodes have required incoming values.
345 // Removing incoming branch from loop preheader to original header.
346 // Now original header is inside the loop.
347 OrigHeader->removePredecessor(OrigPreHeader);
349 // Establish NewPreHeader as loop preheader. Add unconditional branch
350 // from original loop pre-header to new loop pre-header. Add NewPreHEader
352 BranchInst *PH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
353 PH_BI->setSuccessor(0, NewPreHeader);
354 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
355 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
356 PL->addBasicBlockToLoop(NewPreHeader, LI);
358 // Make NewHeader as the new header for the loop.
359 L->moveToHeader(NewHeader);
366 /// Make sure all Exit block PHINodes have required incoming values.
367 /// If incoming value is constant or defined outside the loop then
368 /// PHINode may not have an entry for new pre-header.
369 void LoopRotate::updateExitBlock() {
371 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
374 if (!isa<PHINode>(I))
377 PHINode *PN = dyn_cast<PHINode>(I);
379 if (PN->getBasicBlockIndex(NewPreHeader) == -1) {
380 Value *V = PN->getIncomingValueForBlock(OrigHeader);
381 if (isa<Constant>(V))
382 PN->addIncoming(V, NewPreHeader);
384 InsnReplacementData *IRD = findReplacementData(cast<Instruction>(V));
385 assert (IRD && IRD->PreHeader && "Missing New Preheader Instruction");
386 PN->addIncoming(IRD->PreHeader, NewPreHeader);
393 /// Initialize local data
394 void LoopRotate::initialize() {
397 OrigPreHeader = NULL;
405 /// Return true if this instruction is used outside original header.
406 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
408 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
410 Instruction *U = cast<Instruction>(UI);
411 if (U->getParent() != OrigHeader) {
412 if (L->contains(U->getParent()))
420 /// Find Replacement information for instruction. Return NULL if it is
422 InsnReplacementData *LoopRotate::findReplacementData(Instruction *In) {
424 // Since RD is small, linear walk is OK.
425 for (SmallVector<InsnReplacementData, MAX_HEADER_SIZE>::iterator
426 I = RD.begin(), E = RD.end(); I != E; ++I)
427 if ((*I).Original == In)