blob: f6cb4293f6ec9fdbb5834abb98dc38392f37b0e4 [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"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel95fd7172007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel901f67e2007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
Devang Patelf4277122007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelbc5fe632007-08-07 00:25:56 +000024#include "llvm/ADT/Statistic.h"
25
26using namespace llvm;
27
28STATISTIC(NumIndexSplit, "Number of loops index split");
29
30namespace {
31
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34 public:
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
40
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<ScalarEvolution>();
43 AU.addPreserved<ScalarEvolution>();
44 AU.addRequiredID(LCSSAID);
45 AU.addPreservedID(LCSSAID);
Devang Patel901f67e2007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelbc5fe632007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel0aaeb172007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patelf4277122007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel95fd7172007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patelc8dadbf2007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel7f526a82007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Pateledea5b32007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patel2545f7b2007-08-09 01:39:01 +000063
Devang Patelc8dadbf2007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patelc8dadbf2007-08-08 21:02:17 +000067 // This compare instruction compares IndVar against SplitValue.
68 ICmpInst *SplitCondition;
69
Devang Patel7f526a82007-08-24 06:17:19 +000070 // True if after loop index split, first loop will execute split condition's
71 // true branch.
72 bool UseTrueBranchFirst;
Devang Pateledea5b32007-08-25 00:56:38 +000073
74 // Exit value for first loop after loop split.
75 Value *A_ExitValue;
76
77 // Start value for second loop after loop split.
78 Value *B_StartValue;
79
Devang Patel31696332007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel31696332007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel7f526a82007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Pateledea5b32007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel31696332007-08-08 21:18:27 +000087 }
Devang Patel2545f7b2007-08-09 01:39:01 +000088
Devang Patelc8dadbf2007-08-08 21:02:17 +000089 };
Devang Patel61571ca2007-08-10 00:33:50 +000090
Devang Patelc8dadbf2007-08-08 21:02:17 +000091 private:
Devang Patelbc5fe632007-08-07 00:25:56 +000092 /// Find condition inside a loop that is suitable candidate for index split.
93 void findSplitCondition();
94
Devang Patel61571ca2007-08-10 00:33:50 +000095 /// Find loop's exit condition.
96 void findLoopConditionals();
97
98 /// Return induction variable associated with value V.
99 void findIndVar(Value *V, Loop *L);
100
Devang Patelbc5fe632007-08-07 00:25:56 +0000101 /// processOneIterationLoop - Current loop L contains compare instruction
102 /// that compares induction variable, IndVar, agains loop invariant. If
103 /// entire (i.e. meaningful) loop body is dominated by this compare
104 /// instruction then loop body is executed only for one iteration. In
105 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +0000106 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000107
Devang Patel0aaeb172007-08-08 22:25:28 +0000108 /// If loop header includes loop variant instruction operands then
109 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000110 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000111
Devang Patel9263fc32007-08-20 23:51:18 +0000112 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +0000113 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000114 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000115
Devang Patel60a94c72007-08-14 18:35:57 +0000116 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117 /// This routine is used to remove split condition's dead branch, dominated by
118 /// DeadBB. LiveBB dominates split conidition's other branch.
119 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000120
Devang Pateld662ace2007-08-22 18:27:01 +0000121 /// safeSplitCondition - Return true if it is possible to
122 /// split loop using given split condition.
123 bool safeSplitCondition(SplitInfo &SD);
124
Devang Pateledea5b32007-08-25 00:56:38 +0000125 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126 /// based on split value.
127 void calculateLoopBounds(SplitInfo &SD);
128
Devang Pateld662ace2007-08-22 18:27:01 +0000129 /// splitLoop - Split current loop L in two loops using split information
130 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000131 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000132
Devang Patel61571ca2007-08-10 00:33:50 +0000133 void initialize() {
134 IndVar = NULL;
135 IndVarIncrement = NULL;
136 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000137 StartValue = NULL;
138 ExitValueNum = 0;
139 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000140 }
141
Devang Patelbc5fe632007-08-07 00:25:56 +0000142 private:
143
144 // Current Loop.
145 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000146 LPPassManager *LPM;
147 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000148 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000149 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000150 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000151 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000152
153 // Induction variable whose range is being split by this transformation.
154 PHINode *IndVar;
155 Instruction *IndVarIncrement;
156
157 // Loop exit condition.
158 ICmpInst *ExitCondition;
159
160 // Induction variable's initial value.
161 Value *StartValue;
162
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000163 // Induction variable's final loop exit value operand number in exit condition..
164 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000165 };
166
167 char LoopIndexSplit::ID = 0;
168 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
169}
170
171LoopPass *llvm::createLoopIndexSplitPass() {
172 return new LoopIndexSplit();
173}
174
175// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000176bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000177 bool Changed = false;
178 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000179 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000180
Devang Patel81fcdfb2007-08-15 02:14:55 +0000181 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000182 if (!L->getSubLoops().empty())
183 return false;
184
Devang Patelbc5fe632007-08-07 00:25:56 +0000185 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000186 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000187 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000188 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000189
Devang Patel61571ca2007-08-10 00:33:50 +0000190 initialize();
191
192 findLoopConditionals();
193
194 if (!ExitCondition)
195 return false;
196
Devang Patelbc5fe632007-08-07 00:25:56 +0000197 findSplitCondition();
198
Devang Patelc8dadbf2007-08-08 21:02:17 +0000199 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000200 return false;
201
Devang Patelc8dadbf2007-08-08 21:02:17 +0000202 // First see if it is possible to eliminate loop itself or not.
203 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000204 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000205 SplitInfo &SD = *SI;
206 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000207 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000208 if (Changed) {
209 ++NumIndexSplit;
210 // If is loop is eliminated then nothing else to do here.
211 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000212 } else {
213 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
214 ++SI;
215 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000216 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000217 } else
218 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000219 }
220
Devang Patel7f526a82007-08-24 06:17:19 +0000221 if (SplitData.empty())
222 return false;
223
Devang Patel0aaeb172007-08-08 22:25:28 +0000224 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000225 // FIXME : Implement cost analysis.
226 unsigned MostProfitableSDIndex = 0;
227 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000228
Devang Patelbc5fe632007-08-07 00:25:56 +0000229 if (Changed)
230 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000231
Devang Patelbc5fe632007-08-07 00:25:56 +0000232 return Changed;
233}
234
Devang Patel2545f7b2007-08-09 01:39:01 +0000235/// Return true if V is a induction variable or induction variable's
236/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000237void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000238
239 Instruction *I = dyn_cast<Instruction>(V);
240 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000241 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000242
243 // Check if I is a phi node from loop header or not.
244 if (PHINode *PN = dyn_cast<PHINode>(V)) {
245 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000246 IndVar = PN;
247 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000248 }
249 }
250
251 // Check if I is a add instruction whose one operand is
252 // phi node from loop header and second operand is constant.
253 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000254 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000255
256 Value *Op0 = I->getOperand(0);
257 Value *Op1 = I->getOperand(1);
258
259 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
260 if (PN->getParent() == L->getHeader()
261 && isa<ConstantInt>(Op1)) {
262 IndVar = PN;
263 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000264 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000265 }
266 }
267
268 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
269 if (PN->getParent() == L->getHeader()
270 && isa<ConstantInt>(Op0)) {
271 IndVar = PN;
272 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000273 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000274 }
275 }
276
Devang Patel61571ca2007-08-10 00:33:50 +0000277 return;
278}
279
280// Find loop's exit condition and associated induction variable.
281void LoopIndexSplit::findLoopConditionals() {
282
Devang Patel9263fc32007-08-20 23:51:18 +0000283 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000284
285 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
286 I != E; ++I) {
287 BasicBlock *BB = *I;
288 if (!L->isLoopExit(BB))
289 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000290 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000291 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000292 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000293 }
294
Devang Patel9263fc32007-08-20 23:51:18 +0000295 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000296 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000297
298 // If exiting block is neither loop header nor loop latch then this loop is
299 // not suitable.
300 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
301 return;
302
Devang Patel61571ca2007-08-10 00:33:50 +0000303 // If exit block's terminator is conditional branch inst then we have found
304 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000305 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000306 if (!BR || BR->isUnconditional())
307 return;
308
309 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
310 if (!CI)
311 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000312
313 // FIXME
314 if (CI->getPredicate() == ICmpInst::ICMP_SGT
315 || CI->getPredicate() == ICmpInst::ICMP_UGT
316 || CI->getPredicate() == ICmpInst::ICMP_SGE
317 || CI->getPredicate() == ICmpInst::ICMP_UGE)
318 return;
319
Devang Patel61571ca2007-08-10 00:33:50 +0000320 ExitCondition = CI;
321
322 // Exit condition's one operand is loop invariant exit value and second
323 // operand is SCEVAddRecExpr based on induction variable.
324 Value *V0 = CI->getOperand(0);
325 Value *V1 = CI->getOperand(1);
326
327 SCEVHandle SH0 = SE->getSCEV(V0);
328 SCEVHandle SH1 = SE->getSCEV(V1);
329
330 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000331 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000332 findIndVar(V1, L);
333 }
334 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000335 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000336 findIndVar(V0, L);
337 }
338
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000339 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000340 ExitCondition = NULL;
341 else if (IndVar) {
342 BasicBlock *Preheader = L->getLoopPreheader();
343 StartValue = IndVar->getIncomingValueForBlock(Preheader);
344 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000345}
346
Devang Patelbc5fe632007-08-07 00:25:56 +0000347/// Find condition inside a loop that is suitable candidate for index split.
348void LoopIndexSplit::findSplitCondition() {
349
Devang Patelc8dadbf2007-08-08 21:02:17 +0000350 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000351 // Check all basic block's terminators.
Devang Patelbc5fe632007-08-07 00:25:56 +0000352
Devang Patel2545f7b2007-08-09 01:39:01 +0000353 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
354 I != E; ++I) {
355 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000356
Devang Patel2545f7b2007-08-09 01:39:01 +0000357 // If this basic block does not terminate in a conditional branch
358 // then terminator is not a suitable split condition.
359 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
360 if (!BR)
361 continue;
362
363 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000364 continue;
365
Devang Patel2545f7b2007-08-09 01:39:01 +0000366 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000367 if (!CI || CI == ExitCondition)
Devang Patel2545f7b2007-08-09 01:39:01 +0000368 return;
Devang Patelbc5fe632007-08-07 00:25:56 +0000369
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000370 if (CI->getPredicate() == ICmpInst::ICMP_NE)
371 return;
372
Devang Patel7f526a82007-08-24 06:17:19 +0000373 // If split condition predicate is GT or GE then first execute
374 // false branch of split condition.
375 if (CI->getPredicate() != ICmpInst::ICMP_ULT
376 && CI->getPredicate() != ICmpInst::ICMP_SLT
377 && CI->getPredicate() != ICmpInst::ICMP_ULE
378 && CI->getPredicate() != ICmpInst::ICMP_SLE)
379 SD.UseTrueBranchFirst = false;
380
Devang Patel2545f7b2007-08-09 01:39:01 +0000381 // If one operand is loop invariant and second operand is SCEVAddRecExpr
382 // based on induction variable then CI is a candidate split condition.
383 Value *V0 = CI->getOperand(0);
384 Value *V1 = CI->getOperand(1);
385
386 SCEVHandle SH0 = SE->getSCEV(V0);
387 SCEVHandle SH1 = SE->getSCEV(V1);
388
389 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
390 SD.SplitValue = V0;
391 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000392 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
393 if (PN == IndVar)
394 SplitData.push_back(SD);
395 }
396 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
397 if (IndVarIncrement && IndVarIncrement == Insn)
398 SplitData.push_back(SD);
399 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000400 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000401 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
402 SD.SplitValue = V1;
403 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000404 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
405 if (PN == IndVar)
406 SplitData.push_back(SD);
407 }
408 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
409 if (IndVarIncrement && IndVarIncrement == Insn)
410 SplitData.push_back(SD);
411 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000412 }
413 }
414}
415
416/// processOneIterationLoop - Current loop L contains compare instruction
417/// that compares induction variable, IndVar, against loop invariant. If
418/// entire (i.e. meaningful) loop body is dominated by this compare
419/// instruction then loop body is executed only once. In such case eliminate
420/// loop structure surrounding this loop body. For example,
421/// for (int i = start; i < end; ++i) {
422/// if ( i == somevalue) {
423/// loop_body
424/// }
425/// }
426/// can be transformed into
427/// if (somevalue >= start && somevalue < end) {
428/// i = somevalue;
429/// loop_body
430/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000431bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000432
433 BasicBlock *Header = L->getHeader();
434
435 // First of all, check if SplitCondition dominates entire loop body
436 // or not.
437
438 // If SplitCondition is not in loop header then this loop is not suitable
439 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000440 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000441 return false;
442
Devang Patelbc5fe632007-08-07 00:25:56 +0000443 // If loop header includes loop variant instruction operands then
444 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000445 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000446 return false;
447
Devang Patel9263fc32007-08-20 23:51:18 +0000448 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000449 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000450 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000451 return false;
452
Devang Patel2bcb5012007-08-08 01:51:27 +0000453 // Update CFG.
454
Devang Patelc166b952007-08-20 20:49:01 +0000455 // Replace index variable with split value in loop body. Loop body is executed
456 // only when index variable is equal to split value.
457 IndVar->replaceAllUsesWith(SD.SplitValue);
458
459 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000460 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000461 BasicBlock *LatchSucc = NULL;
462 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
463 if (!BR)
464 return false;
465 Header->removePredecessor(Latch);
466 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
467 SI != E; ++SI) {
468 if (Header != *SI)
469 LatchSucc = *SI;
470 }
471 BR->setUnconditionalDest(LatchSucc);
472
Devang Patelbc5fe632007-08-07 00:25:56 +0000473 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000474 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000475
Devang Patelbc5fe632007-08-07 00:25:56 +0000476 // Replace split condition in header.
477 // Transform
478 // SplitCondition : icmp eq i32 IndVar, SplitValue
479 // into
480 // c1 = icmp uge i32 SplitValue, StartValue
481 // c2 = icmp ult i32 vSplitValue, ExitValue
482 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000483 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000484 Instruction *C1 = new ICmpInst(SignedPredicate ?
485 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000486 SD.SplitValue, StartValue, "lisplit",
487 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000488 Instruction *C2 = new ICmpInst(SignedPredicate ?
489 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000490 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000491 Terminator);
492 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
493 Terminator);
494 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
495 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000496
Devang Patelbc5fe632007-08-07 00:25:56 +0000497 // Now, clear latch block. Remove instructions that are responsible
498 // to increment induction variable.
499 Instruction *LTerminator = Latch->getTerminator();
500 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
501 LB != LE; ) {
502 Instruction *I = LB;
503 ++LB;
504 if (isa<PHINode>(I) || I == LTerminator)
505 continue;
506
Devang Patel59e0c062007-08-14 01:30:57 +0000507 if (I == IndVarIncrement)
508 I->replaceAllUsesWith(ExitValue);
509 else
510 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000511 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000512 }
513
Devang Patel901f67e2007-08-10 18:07:13 +0000514 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000515
516 // Update Dominator Info.
517 // Only CFG change done is to remove Latch to Header edge. This
518 // does not change dominator tree because Latch did not dominate
519 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000520 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000521 DominanceFrontier::iterator HeaderDF = DF->find(Header);
522 if (HeaderDF != DF->end())
523 DF->removeFromFrontier(HeaderDF, Header);
524
525 DominanceFrontier::iterator LatchDF = DF->find(Latch);
526 if (LatchDF != DF->end())
527 DF->removeFromFrontier(LatchDF, Header);
528 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000529 return true;
530}
531
532// If loop header includes loop variant instruction operands then
533// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000534bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000535
536 Instruction *Terminator = Header->getTerminator();
537 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
538 BI != BE; ++BI) {
539 Instruction *I = BI;
540
Devang Patel59e0c062007-08-14 01:30:57 +0000541 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000542 if (isa<PHINode>(I))
543 continue;
544
545 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000546 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000547 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000548
Devang Patel2545f7b2007-08-09 01:39:01 +0000549 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000550 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000551 continue;
552
553 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000554 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000555 continue;
556
Devang Patelbc5fe632007-08-07 00:25:56 +0000557 // Terminator is also harmless.
558 if (I == Terminator)
559 continue;
560
561 // Otherwise we have a instruction that may not be safe.
562 return false;
563 }
564
565 return true;
566}
567
Devang Patel9263fc32007-08-20 23:51:18 +0000568// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000569// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000570bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
571 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000572
Devang Patel9263fc32007-08-20 23:51:18 +0000573 for (BasicBlock::iterator BI = ExitingBlock->begin(),
574 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000575 Instruction *I = BI;
576
Devang Patel59e0c062007-08-14 01:30:57 +0000577 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000578 if (isa<PHINode>(I))
579 continue;
580
Devang Patel2545f7b2007-08-09 01:39:01 +0000581 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000582 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000583 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000584
Devang Patel2545f7b2007-08-09 01:39:01 +0000585 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000586 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000587
588 Value *Op0 = I->getOperand(0);
589 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000590 PHINode *PN = NULL;
591 ConstantInt *CI = NULL;
592
593 if ((PN = dyn_cast<PHINode>(Op0))) {
594 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000595 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000596 } else
597 if ((PN = dyn_cast<PHINode>(Op1))) {
598 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000599 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000600 }
601
Devang Patel61571ca2007-08-10 00:33:50 +0000602 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000603 continue;
604 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000605
Devang Patelbc5fe632007-08-07 00:25:56 +0000606 // I is an Exit condition if next instruction is block terminator.
607 // Exit condition is OK if it compares loop invariant exit value,
608 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000609 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000610 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000611 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000612 }
613
Devang Patel9263fc32007-08-20 23:51:18 +0000614 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000615 continue;
616
Devang Patelbc5fe632007-08-07 00:25:56 +0000617 // Otherwise we have instruction that may not be safe.
618 return false;
619 }
620
Devang Patel9263fc32007-08-20 23:51:18 +0000621 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000622 return true;
623}
624
Devang Patel60a94c72007-08-14 18:35:57 +0000625/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
626/// This routine is used to remove split condition's dead branch, dominated by
627/// DeadBB. LiveBB dominates split conidition's other branch.
628void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
629 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000630
Devang Patelf4277122007-08-15 03:31:47 +0000631 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000632 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000633 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
634 if (DeadBBDF != DF->end()) {
635 SmallVector<BasicBlock *, 8> PredBlocks;
636
637 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
638 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
639 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
640 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000641 FrontierBBs.push_back(FrontierBB);
642
Devang Patelf4277122007-08-15 03:31:47 +0000643 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
644 PredBlocks.clear();
645 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
646 PI != PE; ++PI) {
647 BasicBlock *P = *PI;
648 if (P == DeadBB || DT->dominates(DeadBB, P))
649 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000650 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000651
Devang Patelf4277122007-08-15 03:31:47 +0000652 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
653 FBI != FBE; ++FBI) {
654 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
655 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
656 PE = PredBlocks.end(); PI != PE; ++PI) {
657 BasicBlock *P = *PI;
658 PN->removeIncomingValue(P);
659 }
660 }
661 else
662 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000663 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000664 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000665 }
Devang Patelf4277122007-08-15 03:31:47 +0000666
667 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
668 SmallVector<BasicBlock *, 32> WorkList;
669 DomTreeNode *DN = DT->getNode(DeadBB);
670 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
671 E = df_end(DN); DI != E; ++DI) {
672 BasicBlock *BB = DI->getBlock();
673 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000674 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000675 }
676
677 while (!WorkList.empty()) {
678 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
679 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
680 BBI != BBE; ++BBI) {
681 Instruction *I = BBI;
682 I->replaceAllUsesWith(UndefValue::get(I->getType()));
683 I->eraseFromParent();
684 }
685 LPM->deleteSimpleAnalysisValue(BB, LP);
686 DT->eraseNode(BB);
687 DF->removeBlock(BB);
688 LI->removeBlock(BB);
689 BB->eraseFromParent();
690 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000691
692 // Update Frontier BBs' dominator info.
693 while (!FrontierBBs.empty()) {
694 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
695 BasicBlock *NewDominator = FBB->getSinglePredecessor();
696 if (!NewDominator) {
697 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
698 NewDominator = *PI;
699 ++PI;
700 if (NewDominator != LiveBB) {
701 for(; PI != PE; ++PI) {
702 BasicBlock *P = *PI;
703 if (P == LiveBB) {
704 NewDominator = LiveBB;
705 break;
706 }
707 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
708 }
709 }
710 }
711 assert (NewDominator && "Unable to fix dominator info.");
712 DT->changeImmediateDominator(FBB, NewDominator);
713 DF->changeImmediateDominator(FBB, NewDominator, DT);
714 }
715
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000716}
717
Devang Pateld662ace2007-08-22 18:27:01 +0000718/// safeSplitCondition - Return true if it is possible to
719/// split loop using given split condition.
720bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000721
Devang Pateld662ace2007-08-22 18:27:01 +0000722 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000723
Devang Pateld662ace2007-08-22 18:27:01 +0000724 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000725 // In triangle loop, split condition is in header and one of the
726 // the split destination is loop latch. If split condition is EQ
727 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000728 BasicBlock *Latch = L->getLoopLatch();
729 BranchInst *SplitTerminator =
730 cast<BranchInst>(SplitCondBlock->getTerminator());
731 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
732 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
733 if (L->getHeader() == SplitCondBlock
734 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000735 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000736
Devang Patel9cba64e2007-08-18 00:00:32 +0000737 // If one of the split condition branch is post dominating other then loop
738 // index split is not appropriate.
Devang Pateld662ace2007-08-22 18:27:01 +0000739 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
Devang Patel9cee7a02007-08-17 21:59:16 +0000740 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000741
Devang Patel9cba64e2007-08-18 00:00:32 +0000742 // If one of the split condition branch is a predecessor of the other
743 // split condition branch head then do not split loop on this condition.
Devang Patel2a24ff32007-08-21 21:12:02 +0000744 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
745 PI != PE; ++PI)
Devang Patel9cba64e2007-08-18 00:00:32 +0000746 if (Succ1 == *PI)
747 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000748 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
749 PI != PE; ++PI)
Devang Patel9cba64e2007-08-18 00:00:32 +0000750 if (Succ0 == *PI)
751 return false;
752
Devang Patel4e2075d2007-08-24 05:36:56 +0000753 // Finally this split condition is safe only if merge point for
754 // split condition branch is loop latch. This check along with previous
755 // check, to ensure that exit condition is in either loop latch or header,
756 // filters all loops with non-empty loop body between merge point
757 // and exit condition.
758 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
759 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
760 if (Succ0DF->second.count(Latch))
761 return true;
762
763 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
764 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
765 if (Succ1DF->second.count(Latch))
766 return true;
767
768 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000769}
770
Devang Pateledea5b32007-08-25 00:56:38 +0000771/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
772/// based on split value.
773void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
774
775 ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
776 const Type *Ty = SD.SplitValue->getType();
777 bool Sign = ExitCondition->isSignedPredicate();
778 BasicBlock *Preheader = L->getLoopPreheader();
779 Instruction *PHTerminator = Preheader->getTerminator();
780
781 // Initially use split value as upper loop bound for first loop and lower loop
782 // bound for second loop.
783 Value *AEV = SD.SplitValue;
784 Value *BSV = SD.SplitValue;
785
786 switch (ExitCondition->getPredicate()) {
787 case ICmpInst::ICMP_SGT:
788 case ICmpInst::ICMP_UGT:
789 case ICmpInst::ICMP_SGE:
790 case ICmpInst::ICMP_UGE:
791 default:
792 assert (0 && "Unexpected exit condition predicate");
793
794 case ICmpInst::ICMP_SLT:
795 case ICmpInst::ICMP_ULT:
796 {
797 switch (SP) {
798 case ICmpInst::ICMP_SLT:
799 case ICmpInst::ICMP_ULT:
800 //
801 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
802 //
803 // is transformed into
804 // AEV = BSV = SV
805 // for (i = LB; i < min(UB, AEV); ++i)
806 // A;
807 // for (i = max(LB, BSV); i < UB; ++i);
808 // B;
809 break;
810 case ICmpInst::ICMP_SLE:
811 case ICmpInst::ICMP_ULE:
812 {
813 //
814 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
815 //
816 // is transformed into
817 //
818 // AEV = SV + 1
819 // BSV = SV + 1
820 // for (i = LB; i < min(UB, AEV); ++i)
821 // A;
822 // for (i = max(LB, BSV); i < UB; ++i)
823 // B;
824 BSV = BinaryOperator::createAdd(SD.SplitValue,
825 ConstantInt::get(Ty, 1, Sign),
826 "lsplit.add", PHTerminator);
827 AEV = BSV;
828 }
829 break;
830 case ICmpInst::ICMP_SGE:
831 case ICmpInst::ICMP_UGE:
832 //
833 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
834 //
835 // is transformed into
836 // AEV = BSV = SV
837 // for (i = LB; i < min(UB, AEV); ++i)
838 // B;
839 // for (i = max(BSV, LB); i < UB; ++i)
840 // A;
841 break;
842 case ICmpInst::ICMP_SGT:
843 case ICmpInst::ICMP_UGT:
844 {
845 //
846 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
847 //
848 // is transformed into
849 //
850 // BSV = AEV = SV + 1
851 // for (i = LB; i < min(UB, AEV); ++i)
852 // B;
853 // for (i = max(LB, BSV); i < UB; ++i)
854 // A;
855 BSV = BinaryOperator::createAdd(SD.SplitValue,
856 ConstantInt::get(Ty, 1, Sign),
857 "lsplit.add", PHTerminator);
858 AEV = BSV;
859 }
860 break;
861 default:
862 assert (0 && "Unexpected split condition predicate");
863 break;
864 } // end switch (SP)
865 }
866 break;
867 case ICmpInst::ICMP_SLE:
868 case ICmpInst::ICMP_ULE:
869 {
870 switch (SP) {
871 case ICmpInst::ICMP_SLT:
872 case ICmpInst::ICMP_ULT:
873 //
874 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
875 //
876 // is transformed into
877 // AEV = SV - 1;
878 // BSV = SV;
879 // for (i = LB; i <= min(UB, AEV); ++i)
880 // A;
881 // for (i = max(LB, BSV); i <= UB; ++i)
882 // B;
883 AEV = BinaryOperator::createSub(SD.SplitValue,
884 ConstantInt::get(Ty, 1, Sign),
885 "lsplit.sub", PHTerminator);
886 break;
887 case ICmpInst::ICMP_SLE:
888 case ICmpInst::ICMP_ULE:
889 //
890 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
891 //
892 // is transformed into
893 // AEV = SV;
894 // BSV = SV + 1;
895 // for (i = LB; i <= min(UB, AEV); ++i)
896 // A;
897 // for (i = max(LB, BSV); i <= UB; ++i)
898 // B;
899 BSV = BinaryOperator::createAdd(SD.SplitValue,
900 ConstantInt::get(Ty, 1, Sign),
901 "lsplit.add", PHTerminator);
902 break;
903 case ICmpInst::ICMP_SGT:
904 case ICmpInst::ICMP_UGT:
905 //
906 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
907 //
908 // is transformed into
909 // AEV = SV;
910 // BSV = SV + 1;
911 // for (i = LB; i <= min(AEV, UB); ++i)
912 // B;
913 // for (i = max(LB, BSV); i <= UB; ++i)
914 // A;
915 BSV = BinaryOperator::createAdd(SD.SplitValue,
916 ConstantInt::get(Ty, 1, Sign),
917 "lsplit.add", PHTerminator);
918 break;
919 case ICmpInst::ICMP_SGE:
920 case ICmpInst::ICMP_UGE:
921 // ** TODO **
922 //
923 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
924 //
925 // is transformed into
926 // AEV = SV - 1;
927 // BSV = SV;
928 // for (i = LB; i <= min(AEV, UB); ++i)
929 // B;
930 // for (i = max(LB, BSV); i <= UB; ++i)
931 // A;
932 AEV = BinaryOperator::createSub(SD.SplitValue,
933 ConstantInt::get(Ty, 1, Sign),
934 "lsplit.sub", PHTerminator);
935 break;
936 default:
937 assert (0 && "Unexpected split condition predicate");
938 break;
939 } // end switch (SP)
940 }
941 break;
942 }
943
944 // Calculate ALoop induction variable's new exiting value and
945 // BLoop induction variable's new starting value. Calculuate these
946 // values in original loop's preheader.
947 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
948 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
949 if (isa<ConstantInt>(SD.SplitValue)) {
950 SD.A_ExitValue = AEV;
951 SD.B_StartValue = BSV;
952 return;
953 }
954
955 Value *C1 = new ICmpInst(Sign ?
956 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
957 AEV,
958 ExitCondition->getOperand(ExitValueNum),
959 "lsplit.ev", PHTerminator);
960 SD.A_ExitValue = new SelectInst(C1, AEV,
961 ExitCondition->getOperand(ExitValueNum),
962 "lsplit.ev", PHTerminator);
963
964 Value *C2 = new ICmpInst(Sign ?
965 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
966 BSV, StartValue, "lsplit.sv",
967 PHTerminator);
968 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
969 "lsplit.sv", PHTerminator);
970}
971
Devang Pateld662ace2007-08-22 18:27:01 +0000972/// splitLoop - Split current loop L in two loops using split information
973/// SD. Update dominator information. Maintain LCSSA form.
974bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
975
976 if (!safeSplitCondition(SD))
977 return false;
978
Devang Patela0ac7262007-08-22 19:33:29 +0000979 // After loop is cloned there are two loops.
980 //
981 // First loop, referred as ALoop, executes first part of loop's iteration
982 // space split. Second loop, referred as BLoop, executes remaining
983 // part of loop's iteration space.
984 //
985 // ALoop's exit edge enters BLoop's header through a forwarding block which
986 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +0000987 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +0000988
Devang Pateledea5b32007-08-25 00:56:38 +0000989 // Calculate ALoop induction variable's new exiting value and
990 // BLoop induction variable's new starting value.
991 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +0000992
Devang Patela0ac7262007-08-22 19:33:29 +0000993 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000994 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +0000995 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
996 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000997
Devang Patela0ac7262007-08-22 19:33:29 +0000998 //[*] ALoop's exiting edge BLoop's header.
999 // ALoop's original exit block becomes BLoop's exit block.
1000 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1001 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1002 BranchInst *A_ExitInsn =
1003 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1004 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1005 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1006 if (L->contains(B_ExitBlock)) {
1007 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1008 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001009 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001010 A_ExitInsn->setSuccessor(1, B_Header);
1011
1012 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001013 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001014
Devang Patela0ac7262007-08-22 19:33:29 +00001015 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1016 // original loop's preheader. Add incoming PHINode values from
1017 // ALoop's exiting block. Update BLoop header's domiantor info.
1018
Devang Patel59e0c062007-08-14 01:30:57 +00001019 // Collect inverse map of Header PHINodes.
1020 DenseMap<Value *, Value *> InverseMap;
1021 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1022 BE = L->getHeader()->end(); BI != BE; ++BI) {
1023 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1024 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1025 InverseMap[PNClone] = PN;
1026 } else
1027 break;
1028 }
Devang Pateledea5b32007-08-25 00:56:38 +00001029
Devang Patela0ac7262007-08-22 19:33:29 +00001030 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001031 BI != BE; ++BI) {
1032 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001033 // Remove incoming value from original preheader.
1034 PN->removeIncomingValue(Preheader);
1035
1036 // Add incoming value from A_ExitingBlock.
1037 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001038 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001039 else {
1040 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001041 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1042 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001043 }
1044 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001045 break;
1046 }
Devang Patela0ac7262007-08-22 19:33:29 +00001047 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1048 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001049
Devang Patela0ac7262007-08-22 19:33:29 +00001050 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1051 // block. Remove incoming PHINode values from ALoop's exiting block.
1052 // Add new incoming values from BLoop's incoming exiting value.
1053 // Update BLoop exit block's dominator info..
1054 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1055 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001056 BI != BE; ++BI) {
1057 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001058 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1059 B_ExitingBlock);
1060 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001061 } else
1062 break;
1063 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001064
Devang Patela0ac7262007-08-22 19:33:29 +00001065 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1066 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001067
Devang Patela0ac7262007-08-22 19:33:29 +00001068 //[*] Split ALoop's exit edge. This creates a new block which
1069 // serves two purposes. First one is to hold PHINode defnitions
1070 // to ensure that ALoop's LCSSA form. Second use it to act
1071 // as a preheader for BLoop.
1072 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001073
Devang Patela0ac7262007-08-22 19:33:29 +00001074 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1075 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1076 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001077 BI != BE; ++BI) {
1078 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001079 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001080 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001081 newPHI->addIncoming(V1, A_ExitingBlock);
1082 A_ExitBlock->getInstList().push_front(newPHI);
1083 PN->removeIncomingValue(A_ExitBlock);
1084 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001085 } else
1086 break;
1087 }
1088
Devang Patela0ac7262007-08-22 19:33:29 +00001089 //[*] Eliminate split condition's inactive branch from ALoop.
1090 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1091 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001092 BasicBlock *A_InactiveBranch = NULL;
1093 BasicBlock *A_ActiveBranch = NULL;
1094 if (SD.UseTrueBranchFirst) {
1095 A_ActiveBranch = A_BR->getSuccessor(0);
1096 A_InactiveBranch = A_BR->getSuccessor(1);
1097 } else {
1098 A_ActiveBranch = A_BR->getSuccessor(1);
1099 A_InactiveBranch = A_BR->getSuccessor(0);
1100 }
Devang Patel4e585c72007-08-24 19:32:26 +00001101 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001102 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1103
1104 //[*] Eliminate split condition's inactive branch in from BLoop.
1105 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1106 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001107 BasicBlock *B_InactiveBranch = NULL;
1108 BasicBlock *B_ActiveBranch = NULL;
1109 if (SD.UseTrueBranchFirst) {
1110 B_ActiveBranch = B_BR->getSuccessor(1);
1111 B_InactiveBranch = B_BR->getSuccessor(0);
1112 } else {
1113 B_ActiveBranch = B_BR->getSuccessor(0);
1114 B_InactiveBranch = B_BR->getSuccessor(1);
1115 }
Devang Patel4e585c72007-08-24 19:32:26 +00001116 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001117 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1118
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001119 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001120}