blob: e62fcb932b27cb196606f9191270290550aa4837 [file] [log] [blame]
Devang Patelbc5fe632007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelbc5fe632007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
Devang Patel3719d4f2007-08-07 23:17:52 +000017#include "llvm/Function.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000018#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel95fd7172007-08-08 21:39:47 +000020#include "llvm/Analysis/Dominators.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000021#include "llvm/Support/Compiler.h"
22#include "llvm/ADT/Statistic.h"
23
24using namespace llvm;
25
26STATISTIC(NumIndexSplit, "Number of loops index split");
27
28namespace {
29
30 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
31
32 public:
33 static char ID; // Pass ID, replacement for typeid
34 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35
36 // Index split Loop L. Return true if loop is split.
37 bool runOnLoop(Loop *L, LPPassManager &LPM);
38
39 void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<ScalarEvolution>();
41 AU.addPreserved<ScalarEvolution>();
42 AU.addRequiredID(LCSSAID);
43 AU.addPreservedID(LCSSAID);
44 AU.addPreserved<LoopInfo>();
45 AU.addRequiredID(LoopSimplifyID);
46 AU.addPreservedID(LoopSimplifyID);
Devang Patel0aaeb172007-08-08 22:25:28 +000047 AU.addRequired<DominatorTree>();
Devang Patel95fd7172007-08-08 21:39:47 +000048 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000050 }
51
52 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000053
54 class SplitInfo {
55 public:
Devang Patel61571ca2007-08-10 00:33:50 +000056 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000057
Devang Patelc8dadbf2007-08-08 21:02:17 +000058 // Induction variable's range is split at this value.
59 Value *SplitValue;
60
Devang Patelc8dadbf2007-08-08 21:02:17 +000061 // This compare instruction compares IndVar against SplitValue.
62 ICmpInst *SplitCondition;
63
Devang Patel31696332007-08-08 21:18:27 +000064 // Clear split info.
65 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000066 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000067 SplitCondition = NULL;
Devang Patel31696332007-08-08 21:18:27 +000068 }
Devang Patel2545f7b2007-08-09 01:39:01 +000069
Devang Patelc8dadbf2007-08-08 21:02:17 +000070 };
Devang Patel61571ca2007-08-10 00:33:50 +000071
Devang Patelc8dadbf2007-08-08 21:02:17 +000072 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000073 /// Find condition inside a loop that is suitable candidate for index split.
74 void findSplitCondition();
75
Devang Patel61571ca2007-08-10 00:33:50 +000076 /// Find loop's exit condition.
77 void findLoopConditionals();
78
79 /// Return induction variable associated with value V.
80 void findIndVar(Value *V, Loop *L);
81
Devang Patelbc5fe632007-08-07 00:25:56 +000082 /// processOneIterationLoop - Current loop L contains compare instruction
83 /// that compares induction variable, IndVar, agains loop invariant. If
84 /// entire (i.e. meaningful) loop body is dominated by this compare
85 /// instruction then loop body is executed only for one iteration. In
86 /// such case eliminate loop structure surrounding this loop body. For
Devang Patelc8dadbf2007-08-08 21:02:17 +000087 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
Devang Patelbc5fe632007-08-07 00:25:56 +000088
Devang Patel0aaeb172007-08-08 22:25:28 +000089 /// If loop header includes loop variant instruction operands then
90 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000091 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000092
Devang Patel0aaeb172007-08-08 22:25:28 +000093 /// If Exit block includes loop variant instructions then this
94 /// loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +000095 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +000096
Devang Patel0aaeb172007-08-08 22:25:28 +000097 /// Find cost of spliting loop L.
98 unsigned findSplitCost(Loop *L, SplitInfo &SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +000099 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000100
Devang Patel61571ca2007-08-10 00:33:50 +0000101 void initialize() {
102 IndVar = NULL;
103 IndVarIncrement = NULL;
104 ExitCondition = NULL;
105 StartValue = ExitValue = NULL;
106 }
107
Devang Patelbc5fe632007-08-07 00:25:56 +0000108 private:
109
110 // Current Loop.
111 Loop *L;
112 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000113 DominatorTree *DT;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000114 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000115
116 // Induction variable whose range is being split by this transformation.
117 PHINode *IndVar;
118 Instruction *IndVarIncrement;
119
120 // Loop exit condition.
121 ICmpInst *ExitCondition;
122
123 // Induction variable's initial value.
124 Value *StartValue;
125
126 // Induction variable's final loop exit value.
127 Value *ExitValue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000128 };
129
130 char LoopIndexSplit::ID = 0;
131 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
132}
133
134LoopPass *llvm::createLoopIndexSplitPass() {
135 return new LoopIndexSplit();
136}
137
138// Index split Loop L. Return true if loop is split.
139bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
140 bool Changed = false;
141 L = IncomingLoop;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000142
Devang Patelbc5fe632007-08-07 00:25:56 +0000143 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000144 DT = &getAnalysis<DominatorTree>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000145
Devang Patel61571ca2007-08-10 00:33:50 +0000146 initialize();
147
148 findLoopConditionals();
149
150 if (!ExitCondition)
151 return false;
152
Devang Patelbc5fe632007-08-07 00:25:56 +0000153 findSplitCondition();
154
Devang Patelc8dadbf2007-08-08 21:02:17 +0000155 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000156 return false;
157
Devang Patelc8dadbf2007-08-08 21:02:17 +0000158 // First see if it is possible to eliminate loop itself or not.
159 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
160 E = SplitData.end(); SI != E; ++SI) {
161 SplitInfo &SD = *SI;
162 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
163 Changed = processOneIterationLoop(SD,LPM);
164 if (Changed) {
165 ++NumIndexSplit;
166 // If is loop is eliminated then nothing else to do here.
167 return Changed;
168 }
169 }
170 }
171
Devang Patel0aaeb172007-08-08 22:25:28 +0000172 unsigned MaxCost = 99;
173 unsigned Index = 0;
174 unsigned MostProfitableSDIndex = 0;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000175 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel0aaeb172007-08-08 22:25:28 +0000176 E = SplitData.end(); SI != E; ++SI, ++Index) {
177 SplitInfo SD = *SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000178
179 // ICM_EQs are already handled above.
Devang Patel0aaeb172007-08-08 22:25:28 +0000180 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
Devang Patelc8dadbf2007-08-08 21:02:17 +0000181 continue;
Devang Patel0aaeb172007-08-08 22:25:28 +0000182
183 unsigned Cost = findSplitCost(L, SD);
184 if (Cost < MaxCost)
185 MostProfitableSDIndex = Index;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000186 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000187
Devang Patel0aaeb172007-08-08 22:25:28 +0000188 // Split most profitiable condition.
189 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
190
Devang Patelbc5fe632007-08-07 00:25:56 +0000191 if (Changed)
192 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000193
Devang Patelbc5fe632007-08-07 00:25:56 +0000194 return Changed;
195}
196
Devang Patel2545f7b2007-08-09 01:39:01 +0000197/// Return true if V is a induction variable or induction variable's
198/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000199void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000200
201 Instruction *I = dyn_cast<Instruction>(V);
202 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000203 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000204
205 // Check if I is a phi node from loop header or not.
206 if (PHINode *PN = dyn_cast<PHINode>(V)) {
207 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000208 IndVar = PN;
209 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000210 }
211 }
212
213 // Check if I is a add instruction whose one operand is
214 // phi node from loop header and second operand is constant.
215 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000216 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000217
218 Value *Op0 = I->getOperand(0);
219 Value *Op1 = I->getOperand(1);
220
221 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
222 if (PN->getParent() == L->getHeader()
223 && isa<ConstantInt>(Op1)) {
224 IndVar = PN;
225 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000226 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000227 }
228 }
229
230 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
231 if (PN->getParent() == L->getHeader()
232 && isa<ConstantInt>(Op0)) {
233 IndVar = PN;
234 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000235 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000236 }
237 }
238
Devang Patel61571ca2007-08-10 00:33:50 +0000239 return;
240}
241
242// Find loop's exit condition and associated induction variable.
243void LoopIndexSplit::findLoopConditionals() {
244
245 BasicBlock *ExitBlock = NULL;
246
247 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
248 I != E; ++I) {
249 BasicBlock *BB = *I;
250 if (!L->isLoopExit(BB))
251 continue;
252 if (ExitBlock)
253 return;
254 ExitBlock = BB;
255 }
256
257 if (!ExitBlock)
258 return;
259
260 // If exit block's terminator is conditional branch inst then we have found
261 // exit condition.
262 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
263 if (!BR || BR->isUnconditional())
264 return;
265
266 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
267 if (!CI)
268 return;
269
270 ExitCondition = CI;
271
272 // Exit condition's one operand is loop invariant exit value and second
273 // operand is SCEVAddRecExpr based on induction variable.
274 Value *V0 = CI->getOperand(0);
275 Value *V1 = CI->getOperand(1);
276
277 SCEVHandle SH0 = SE->getSCEV(V0);
278 SCEVHandle SH1 = SE->getSCEV(V1);
279
280 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
281 ExitValue = V0;
282 findIndVar(V1, L);
283 }
284 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
285 ExitValue = V1;
286 findIndVar(V0, L);
287 }
288
289 if (!ExitValue || !IndVar)
290 ExitCondition = NULL;
291 else if (IndVar) {
292 BasicBlock *Preheader = L->getLoopPreheader();
293 StartValue = IndVar->getIncomingValueForBlock(Preheader);
294 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000295}
296
Devang Patelbc5fe632007-08-07 00:25:56 +0000297/// Find condition inside a loop that is suitable candidate for index split.
298void LoopIndexSplit::findSplitCondition() {
299
Devang Patelc8dadbf2007-08-08 21:02:17 +0000300 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000301 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000302
Devang Patel2545f7b2007-08-09 01:39:01 +0000303 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
304 I != E; ++I) {
305 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000306
Devang Patel2545f7b2007-08-09 01:39:01 +0000307 // If this basic block does not terminate in a conditional branch
308 // then terminator is not a suitable split condition.
309 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
310 if (!BR)
311 continue;
312
313 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000314 continue;
315
Devang Patel2545f7b2007-08-09 01:39:01 +0000316 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000317 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000318 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000319
Devang Patel2545f7b2007-08-09 01:39:01 +0000320 // If one operand is loop invariant and second operand is SCEVAddRecExpr
321 // based on induction variable then CI is a candidate split condition.
322 Value *V0 = CI->getOperand(0);
323 Value *V1 = CI->getOperand(1);
324
325 SCEVHandle SH0 = SE->getSCEV(V0);
326 SCEVHandle SH1 = SE->getSCEV(V1);
327
328 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
329 SD.SplitValue = V0;
330 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000331 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
332 if (PN == IndVar)
333 SplitData.push_back(SD);
334 }
335 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
336 if (IndVarIncrement && IndVarIncrement == Insn)
337 SplitData.push_back(SD);
338 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000339 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000340 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
341 SD.SplitValue = V1;
342 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000343 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
344 if (PN == IndVar)
345 SplitData.push_back(SD);
346 }
347 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
348 if (IndVarIncrement && IndVarIncrement == Insn)
349 SplitData.push_back(SD);
350 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000351 }
352 }
353}
354
355/// processOneIterationLoop - Current loop L contains compare instruction
356/// that compares induction variable, IndVar, against loop invariant. If
357/// entire (i.e. meaningful) loop body is dominated by this compare
358/// instruction then loop body is executed only once. In such case eliminate
359/// loop structure surrounding this loop body. For example,
360/// for (int i = start; i < end; ++i) {
361/// if ( i == somevalue) {
362/// loop_body
363/// }
364/// }
365/// can be transformed into
366/// if (somevalue >= start && somevalue < end) {
367/// i = somevalue;
368/// loop_body
369/// }
Devang Patelc8dadbf2007-08-08 21:02:17 +0000370bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000371
372 BasicBlock *Header = L->getHeader();
373
374 // First of all, check if SplitCondition dominates entire loop body
375 // or not.
376
377 // If SplitCondition is not in loop header then this loop is not suitable
378 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000379 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000380 return false;
381
Devang Patelbc5fe632007-08-07 00:25:56 +0000382 // If loop header includes loop variant instruction operands then
383 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000384 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000385 return false;
386
387 // If Exit block includes loop variant instructions then this
388 // loop may not be eliminated.
Devang Patelbfa5eba2007-08-10 00:59:03 +0000389 if (!safeExitBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000390 return false;
391
Devang Patel2bcb5012007-08-08 01:51:27 +0000392 // Update CFG.
393
394 // As a first step to break this loop, remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000395 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000396 BasicBlock *LatchSucc = NULL;
397 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
398 if (!BR)
399 return false;
400 Header->removePredecessor(Latch);
401 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
402 SI != E; ++SI) {
403 if (Header != *SI)
404 LatchSucc = *SI;
405 }
406 BR->setUnconditionalDest(LatchSucc);
407
Devang Patelbc5fe632007-08-07 00:25:56 +0000408 BasicBlock *Preheader = L->getLoopPreheader();
409 Instruction *Terminator = Header->getTerminator();
Devang Patel61571ca2007-08-10 00:33:50 +0000410 StartValue = IndVar->getIncomingValueForBlock(Preheader);
Devang Patelbc5fe632007-08-07 00:25:56 +0000411
Devang Patelbc5fe632007-08-07 00:25:56 +0000412 // Replace split condition in header.
413 // Transform
414 // SplitCondition : icmp eq i32 IndVar, SplitValue
415 // into
416 // c1 = icmp uge i32 SplitValue, StartValue
417 // c2 = icmp ult i32 vSplitValue, ExitValue
418 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000419 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000420 Instruction *C1 = new ICmpInst(SignedPredicate ?
421 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000422 SD.SplitValue, StartValue, "lisplit",
423 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000424 Instruction *C2 = new ICmpInst(SignedPredicate ?
425 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel61571ca2007-08-10 00:33:50 +0000426 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000427 Terminator);
428 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
429 Terminator);
430 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
431 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000432
Devang Patelbc5fe632007-08-07 00:25:56 +0000433 // Now, clear latch block. Remove instructions that are responsible
434 // to increment induction variable.
435 Instruction *LTerminator = Latch->getTerminator();
436 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
437 LB != LE; ) {
438 Instruction *I = LB;
439 ++LB;
440 if (isa<PHINode>(I) || I == LTerminator)
441 continue;
442
443 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000444 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000445 }
446
447 LPM.deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000448
449 // Update Dominator Info.
450 // Only CFG change done is to remove Latch to Header edge. This
451 // does not change dominator tree because Latch did not dominate
452 // Header.
453 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
454 DominanceFrontier::iterator HeaderDF = DF->find(Header);
455 if (HeaderDF != DF->end())
456 DF->removeFromFrontier(HeaderDF, Header);
457
458 DominanceFrontier::iterator LatchDF = DF->find(Latch);
459 if (LatchDF != DF->end())
460 DF->removeFromFrontier(LatchDF, Header);
461 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000462 return true;
463}
464
465// If loop header includes loop variant instruction operands then
466// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000467bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000468
469 Instruction *Terminator = Header->getTerminator();
470 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
471 BI != BE; ++BI) {
472 Instruction *I = BI;
473
Devang Patel2bcb5012007-08-08 01:51:27 +0000474 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000475 if (isa<PHINode>(I))
476 continue;
477
478 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000479 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000480 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000481
Devang Patel2545f7b2007-08-09 01:39:01 +0000482 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000483 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000484 continue;
485
486 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000487 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000488 continue;
489
Devang Patelbc5fe632007-08-07 00:25:56 +0000490 // Terminator is also harmless.
491 if (I == Terminator)
492 continue;
493
494 // Otherwise we have a instruction that may not be safe.
495 return false;
496 }
497
498 return true;
499}
500
501// If Exit block includes loop variant instructions then this
502// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000503bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000504
Devang Patelbc5fe632007-08-07 00:25:56 +0000505 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
506 BI != BE; ++BI) {
507 Instruction *I = BI;
508
Devang Patel2bcb5012007-08-08 01:51:27 +0000509 // PHI Nodes are OK. FIXME : Handle last value assignments.
Devang Patelbc5fe632007-08-07 00:25:56 +0000510 if (isa<PHINode>(I))
511 continue;
512
Devang Patel2545f7b2007-08-09 01:39:01 +0000513 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000514 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000515 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000516
Devang Patel2545f7b2007-08-09 01:39:01 +0000517 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000518 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000519
520 Value *Op0 = I->getOperand(0);
521 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000522 PHINode *PN = NULL;
523 ConstantInt *CI = NULL;
524
525 if ((PN = dyn_cast<PHINode>(Op0))) {
526 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000527 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000528 } else
529 if ((PN = dyn_cast<PHINode>(Op1))) {
530 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000531 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000532 }
533
Devang Patel61571ca2007-08-10 00:33:50 +0000534 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000535 continue;
536 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000537
Devang Patelbc5fe632007-08-07 00:25:56 +0000538 // I is an Exit condition if next instruction is block terminator.
539 // Exit condition is OK if it compares loop invariant exit value,
540 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000541 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000542 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000543 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000544 }
545
Devang Patel61571ca2007-08-10 00:33:50 +0000546 if (I == ExitBlock->getTerminator())
547 continue;
548
Devang Patelbc5fe632007-08-07 00:25:56 +0000549 // Otherwise we have instruction that may not be safe.
550 return false;
551 }
552
Devang Patelbc5fe632007-08-07 00:25:56 +0000553 // We could not find any reason to consider ExitBlock unsafe.
554 return true;
555}
556
Devang Patel0aaeb172007-08-08 22:25:28 +0000557/// Find cost of spliting loop L. Cost is measured in terms of size growth.
558/// Size is growth is calculated based on amount of code duplicated in second
559/// loop.
560unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
561
562 unsigned Cost = 0;
563 BasicBlock *SDBlock = SD.SplitCondition->getParent();
564 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
565 I != E; ++I) {
566 BasicBlock *BB = *I;
567 // If a block is not dominated by split condition block then
568 // it must be duplicated in both loops.
569 if (!DT->dominates(SDBlock, BB))
570 Cost += BB->size();
571 }
572
573 return Cost;
574}
575
Devang Patelc8dadbf2007-08-08 21:02:17 +0000576bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000577
578 BasicBlock *Preheader = L->getLoopPreheader();
579
Devang Patel61571ca2007-08-10 00:33:50 +0000580 // True loop is original loop. False loop is cloned loop.
Devang Patelf824fb42007-08-10 00:53:35 +0000581
582 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patel61571ca2007-08-10 00:33:50 +0000583 //[*] Calculate True loop's new Exit Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000584 // TLExitValue = min(SplitValue, ExitValue)
Devang Patel61571ca2007-08-10 00:33:50 +0000585 //[*] Calculate False loop's new Start Value in loop preheader.
Devang Patelf824fb42007-08-10 00:53:35 +0000586 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
587 Value *TLExitValue = NULL;
588 Value *FLStartValue = NULL;
589 if (isa<ConstantInt>(SD.SplitValue)) {
590 TLExitValue = SD.SplitValue;
591 FLStartValue = SD.SplitValue;
592 }
593 else {
594 Value *C1 = new ICmpInst(SignedPredicate ?
595 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
596 SD.SplitValue, ExitValue, "lsplit.ev",
597 Preheader->getTerminator());
598 TLExitValue = new SelectInst(C1, SD.SplitValue, ExitValue,
599 "lsplit.ev", Preheader->getTerminator());
600
601 Value *C2 = new ICmpInst(SignedPredicate ?
602 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
603 SD.SplitValue, StartValue, "lsplit.sv",
604 Preheader->getTerminator());
605 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
606 "lsplit.sv", Preheader->getTerminator());
607 }
Devang Patel61571ca2007-08-10 00:33:50 +0000608 //[*] Split Exit Edge.
609 //[*] Clone loop. Avoid true destination of split condition and
610 // the blocks dominated by true destination.
611 //[*] True loops exit edge enters False loop.
612 //[*] Eliminate split condition's false branch from True loop.
613 // Update true loop dom info.
614 //[*] Update True loop's exit value using NewExitValue.
615 //[*] Update False loop's start value using NewStartValue.
616 //[*] Fix lack of true branch in False loop CFG.
617 // Update false loop dom info.
618 //[*] Update dom info in general.
Devang Patelbc5fe632007-08-07 00:25:56 +0000619 return false;
620}