llvm.org GIT mirror llvm / c4625da
Add loop rotation pass. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@35714 91177308-0d34-0410-b5e6-96231b3b80d8 Devang Patel 12 years ago
2 changed file(s) with 438 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
136136
137137 //===----------------------------------------------------------------------===//
138138 //
139 // LoopRotate - This pass is a simple loop rotating pass.
140 //
141 LoopPass *createLoopRotatePass();
142
143
144 //===----------------------------------------------------------------------===//
145 //
139146 // PromoteMemoryToRegister - This pass is used to promote memory references to
140147 // be register references. A simple example of the transformation performed by
141148 // this pass is:
0 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by Devang Patel and is distributed under
5 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements Loop Rotation Pass.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #define DEBUG_TYPE "loop-rotation"
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include
26
27 using namespace llvm;
28
29 #define MAX_HEADER_SIZE 16
30
31 STATISTIC(NumRotated, "Number of loops rotated");
32 namespace {
33
34 cl::opt
35 RotateThreshold("rotate-threshold", cl::init(200), cl::Hidden,
36 cl::desc("The cut-off point for loop rotating"));
37
38 class VISIBILITY_HIDDEN InsnReplacementData {
39 public:
40 InsnReplacementData(Instruction *O, Instruction *P, Instruction *H)
41 : Original(O), PreHeader(P), Header(H) {}
42 public:
43 Instruction *Original; // Original instruction
44 Instruction *PreHeader; // New pre-header replacement
45 Instruction *Header; // New header replacement
46 };
47
48 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
49
50 public:
51 bool runOnLoop(Loop *L, LPPassManager &LPM);
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.addRequiredID(LCSSAID);
54 AU.addPreservedID(LCSSAID);
55 //AU.addRequired();
56 //AU.addPreserved();
57 }
58
59 // Helper functions
60
61 /// Do actual work
62 bool rotateLoop(Loop *L, LPPassManager &LPM);
63
64 /// Initialize local data
65 void initialize();
66
67 /// Make sure all Exit block PHINodes have required incoming values.
68 /// If incoming value is constant or defined outside the loop then
69 /// PHINode may not have an entry for new pre-header.
70 void updateExitBlock();
71
72 /// Return true if this instruction is used outside original header.
73 bool usedOutsideOriginalHeader(Instruction *In);
74
75 /// Find Replacement information for instruction. Return NULL if it is
76 /// not available.
77 InsnReplacementData *findReplacementData(Instruction *I);
78
79 private:
80
81 Loop *L;
82 BasicBlock *OrigHeader;
83 BasicBlock *OrigPreHeader;
84 BasicBlock *OrigLatch;
85 BasicBlock *NewHeader;
86 BasicBlock *NewPreHeader;
87 BasicBlock *Exit;
88
89 SmallVector RD;
90 };
91
92 RegisterPass X ("loop-rotate", "Rotate Loops");
93 }
94
95 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
96
97 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
98
99 bool RotatedOneLoop = false;
100 initialize();
101
102 // One loop can be rotated multiple times.
103 while (rotateLoop(Lp,LPM)) {
104 RotatedOneLoop = true;
105 initialize();
106 }
107
108 return RotatedOneLoop;
109 }
110
111 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
112
113 L = Lp;
114 if ( NumRotated >= RotateThreshold)
115 return false;
116
117 OrigHeader = L->getHeader();
118 OrigPreHeader = L->getLoopPreheader();
119 OrigLatch = L->getLoopLatch();
120
121 // If loop has only one block then there is not much to rotate.
122 if (L->getBlocks().size() <= 1)
123 return false;
124
125 if (!OrigHeader || !OrigLatch || !OrigPreHeader)
126 return false;
127
128 // If loop header is not one of the loop exit block then
129 // either this loop is already rotated or it is not
130 // suitable for loop rotation transformations.
131 if (!L->isLoopExit(OrigHeader))
132 return false;
133
134 BranchInst *BI = dyn_cast(OrigHeader->getTerminator());
135 if (!BI)
136 return false;
137
138 std::vector ExitBlocks;
139 L->getExitBlocks(ExitBlocks);
140 if (ExitBlocks.size() > 1)
141 return false;
142
143 // Find new Loop header. NewHeader is a Header's one and only successor
144 // that is inside loop. Header's all other successors are out side the
145 // loop. Otherwise loop is not suitable for rotation.
146 for (unsigned index = 0; index < BI->getNumSuccessors(); ++index) {
147 BasicBlock *S = BI->getSuccessor(index);
148 if (L->contains(S)) {
149 if (!NewHeader)
150 NewHeader = S;
151 else
152 // Loop Header has two successors inside loop. This loop is
153 // not suitable for rotation.
154 return false;
155 } else {
156 if (!Exit)
157 Exit = S;
158 else
159 // Loop has multiple exits.
160 return false;
161 }
162 }
163 assert (NewHeader && "Unable to determine new loop header");
164
165 // Check size of original header and reject
166 // loop if it is very big.
167 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
168 return false;
169
170 // Now, this loop is suitable for rotation.
171
172 // Copy Prepare PHI nodes and other instructions from original header
173 // into new pre-header. Unlike original header, new pre-header is
174 // not a member of loop. New pre-header has only one predecessor,
175 // that is original loop pre-header.
176 //
177 // New loop header is one and only successor of original header that
178 // is inside the loop. All other original header successors are outside
179 // the loop. Copy PHI Nodes from original header into new loop header.
180 // Add second incoming value, from new loop pre-header into these phi
181 // nodes. If a value defined in original header is used outside original
182 // header then new loop header will need new phi nodes with two incoming
183 // values, one definition from original header and second definition is
184 // from new loop pre-header (which is a clone of original header definition).
185
186 NewPreHeader = new BasicBlock("bb.nph", OrigHeader->getParent(), OrigHeader);
187 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
188 I != E; ++I) {
189 Instruction *In = I;
190
191 if (PHINode *PN = dyn_cast(I)) {
192
193 // Create new PHI node with one value incoming from OrigPreHeader.
194 // NewPreHeader has only one predecessor, OrigPreHeader.
195 PHINode *NPH = new PHINode(In->getType(), In->getName());
196 NPH->addIncoming(PN->getIncomingValueForBlock(OrigPreHeader),
197 OrigPreHeader);
198 NewPreHeader->getInstList().push_back(NPH);
199
200 // Create new PHI node with two incoming values for NewHeader.
201 // One incoming value is from OrigLatch (through OrigHeader) and
202 // second incoming value is from NewPreHeader.
203 PHINode *NH = new PHINode(In->getType(), In->getName());
204 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
205 NH->addIncoming(NPH, NewPreHeader);
206 NewHeader->getInstList().push_front(NH);
207
208 RD.push_back(InsnReplacementData(In, NPH, NH));
209 } else {
210 // This is not a PHI instruction. Insert its clone into NewPreHeader.
211 // If this instruction is using a value from same basic block then
212 // update it to use value from cloned instruction.
213 Instruction *C = In->clone();
214 C->setName(In->getName());
215 NewPreHeader->getInstList().push_back(C);
216
217 // If this instruction is used outside this basic block then
218 // create new PHINode for this instruction.
219 Instruction *NewHeaderReplacement = NULL;
220 if (usedOutsideOriginalHeader(In)) {
221 PHINode *PN = new PHINode(In->getType(), In->getName());
222 PN->addIncoming(In, OrigHeader);
223 PN->addIncoming(C, NewPreHeader);
224 NewHeader->getInstList().push_front(PN);
225 NewHeaderReplacement = PN;
226 }
227 RD.push_back(InsnReplacementData(In, C, NewHeaderReplacement));
228 }
229 }
230
231 // Update new pre-header.
232 // Rename values that are defined in original header to reflects values
233 // defined in new pre-header.
234 for (SmallVector::iterator
235 I = RD.begin(), E = RD.end(); I != E; ++I) {
236
237 InsnReplacementData IRD = (*I);
238 Instruction *In = IRD.Original;
239 Instruction *C = IRD.PreHeader;
240
241 if (C->getParent() != NewPreHeader)
242 continue;
243
244 // PHINodes uses value from pre-header predecessors.
245 if (isa(In))
246 continue;
247
248 for (unsigned opi = 0; opi < In->getNumOperands(); ++opi) {
249 if (Instruction *OpPhi = dyn_cast(In->getOperand(opi))) {
250 if (InsnReplacementData *D = findReplacementData(OpPhi))
251 C->setOperand(opi, D->PreHeader);
252 }
253 else if (Instruction *OpInsn =
254 dyn_cast(In->getOperand(opi))) {
255 if (InsnReplacementData *D = findReplacementData(OpInsn))
256 C->setOperand(opi, D->PreHeader);
257 }
258 }
259 }
260
261 // Rename uses of original header instructions to reflect their new
262 // definitions (either from new pre-header node or from newly created
263 // new header PHINodes.
264 //
265 // Original header instructions are used in
266 // 1) Original header:
267 //
268 // If instruction is used in non-phi instructions then it is using
269 // defintion from original heder iteself. Do not replace this use
270 // with definition from new header or new pre-header.
271 //
272 // If instruction is used in phi node then it is an incoming
273 // value. Rename its use to reflect new definition from new-preheader
274 // or new header.
275 //
276 // 2) Inside loop but not in original header
277 //
278 // Replace this use to reflect definition from new header.
279 for (SmallVector::iterator
280 I = RD.begin(), E = RD.end(); I != E; ++I) {
281
282 InsnReplacementData IRD = (*I);
283 if (!IRD.Header)
284 continue;
285
286 Instruction *OldPhi = IRD.Original;
287 Instruction *NewPhi = IRD.Header;
288
289 // Before replacing uses, collect them first, so that iterator is
290 // not invalidated.
291 SmallVector AllUses;
292 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
293 UI != UE; ++UI ) {
294 Instruction *U = cast(UI);
295 AllUses.push_back(U);
296 }
297
298 for (SmallVector::iterator UI = AllUses.begin(),
299 UE = AllUses.end(); UI != UE; ++UI) {
300 Instruction *U = *UI;
301 BasicBlock *Parent = U->getParent();
302
303 // Used inside original header
304 if (Parent == OrigHeader) {
305 // Do not rename uses inside original header non-phi instructions.
306 if (!isa(U))
307 continue;
308 PHINode *PU = dyn_cast(U);
309 // Do not rename uses inside original header phi nodes, if the
310 // incoming value is for new header.
311 if (PU->getBasicBlockIndex(NewHeader) != -1
312 && PU->getIncomingValueForBlock(NewHeader) == U)
313 continue;
314
315 U->replaceUsesOfWith(OldPhi, NewPhi);
316 continue;
317 }
318
319 // Used inside loop, but not in original header.
320 if (L->contains(U->getParent())) {
321 if (U != NewPhi )
322 U->replaceUsesOfWith(OldPhi, NewPhi);
323 continue;
324 }
325
326 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
327 assert ( U->getParent() == Exit && "Need to propagate new PHI into Exit blocks");
328 assert (isa(U) && "Use in Exit Block that is not PHINode");
329
330 PHINode *UPhi = cast(U);
331
332 // UPhi already has one incoming argument from original header.
333 // Add second incoming argument from new Pre header.
334
335 UPhi->addIncoming(IRD.PreHeader, NewPreHeader);
336 }
337 }
338
339 /// Make sure all Exit block PHINodes have required incoming values.
340 updateExitBlock();
341
342 // Update CFG
343
344 // Removing incoming branch from loop preheader to original header.
345 // Now original header is inside the loop.
346 OrigHeader->removePredecessor(OrigPreHeader);
347
348 // Establish NewPreHeader as loop preheader. Add unconditional branch
349 // from original loop pre-header to new loop pre-header. Add NewPreHEader
350 // in loop nest.
351 BranchInst *PH_BI = cast(OrigPreHeader->getTerminator());
352 PH_BI->setSuccessor(0, NewPreHeader);
353 LoopInfo &LI = LPM.getAnalysis();
354 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
355 PL->addBasicBlockToLoop(NewPreHeader, LI);
356
357 // Make NewHeader as the new header for the loop.
358 L->moveToHeader(NewHeader);
359
360 NumRotated++;
361 return true;
362 }
363
364
365 /// Make sure all Exit block PHINodes have required incoming values.
366 /// If incoming value is constant or defined outside the loop then
367 /// PHINode may not have an entry for new pre-header.
368 void LoopRotate::updateExitBlock() {
369
370 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
371 I != E; ++I) {
372
373 if (!isa(I))
374 break;
375
376 PHINode *PN = dyn_cast(I);
377
378 if (PN->getBasicBlockIndex(NewPreHeader) == -1) {
379 Value *V = PN->getIncomingValueForBlock(OrigHeader);
380 if (isa(V))
381 PN->addIncoming(V, NewPreHeader);
382 else {
383 InsnReplacementData *IRD = findReplacementData(cast(V));
384 assert (IRD && IRD->PreHeader && "Missing New Preheader Instruction");
385 PN->addIncoming(IRD->PreHeader, NewPreHeader);
386 }
387 }
388 }
389 }
390
391
392 /// Initialize local data
393 void LoopRotate::initialize() {
394 L = NULL;
395 OrigHeader = NULL;
396 OrigPreHeader = NULL;
397 NewHeader = NULL;
398 NewPreHeader = NULL;
399 Exit = NULL;
400
401 RD.clear();
402 }
403
404 /// Return true if this instruction is used outside original header.
405 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
406
407 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
408 UI != UE; ++UI) {
409 Instruction *U = cast(UI);
410 if (U->getParent() != OrigHeader) {
411 if (L->contains(U->getParent()))
412 return true;
413 }
414 }
415
416 return false;
417 }
418
419 /// Find Replacement information for instruction. Return NULL if it is
420 /// not available.
421 InsnReplacementData *LoopRotate::findReplacementData(Instruction *In) {
422
423 // Since RD is small, linear walk is OK.
424 for (SmallVector::iterator
425 I = RD.begin(), E = RD.end(); I != E; ++I)
426 if ((*I).Original == In)
427 return &(*I);
428
429 return NULL;
430 }