blob: 48626ac475ed633c5115e93166ce0bd1bd526298 [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 Patel5bc8a2c2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patelc8dadbf2007-08-08 21:02:17 +000069
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 Patel12564292007-09-11 00:42:56 +000092
93 // safeIcmpInst - CI is considered safe instruction if one of the operand
94 // is SCEVAddRecExpr based on induction variable and other operand is
95 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96 // and return true;
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
Devang Patelbc5fe632007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patel61571ca2007-08-10 00:33:50 +0000102 /// Find loop's exit condition.
103 void findLoopConditionals();
104
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
107
Devang Patelbc5fe632007-08-07 00:25:56 +0000108 /// processOneIterationLoop - Current loop L contains compare instruction
109 /// that compares induction variable, IndVar, agains loop invariant. If
110 /// entire (i.e. meaningful) loop body is dominated by this compare
111 /// instruction then loop body is executed only for one iteration. In
112 /// such case eliminate loop structure surrounding this loop body. For
Devang Patel901f67e2007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000114
Devang Patel0aaeb172007-08-08 22:25:28 +0000115 /// If loop header includes loop variant instruction operands then
116 /// this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000117 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000118
Devang Patel9263fc32007-08-20 23:51:18 +0000119 /// If Exiting block includes loop variant instructions then this
Devang Patel0aaeb172007-08-08 22:25:28 +0000120 /// loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000121 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelbc5fe632007-08-07 00:25:56 +0000122
Devang Patel60a94c72007-08-14 18:35:57 +0000123 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
124 /// This routine is used to remove split condition's dead branch, dominated by
125 /// DeadBB. LiveBB dominates split conidition's other branch.
126 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000127
Devang Pateld662ace2007-08-22 18:27:01 +0000128 /// safeSplitCondition - Return true if it is possible to
129 /// split loop using given split condition.
130 bool safeSplitCondition(SplitInfo &SD);
131
Devang Pateledea5b32007-08-25 00:56:38 +0000132 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
133 /// based on split value.
134 void calculateLoopBounds(SplitInfo &SD);
135
Devang Patelcd71bed2007-08-25 02:39:24 +0000136 /// updatePHINodes - CFG has been changed.
137 /// Before
138 /// - ExitBB's single predecessor was Latch
139 /// - Latch's second successor was Header
140 /// Now
141 /// - ExitBB's single predecessor was Header
142 /// - Latch's one and only successor was Header
143 ///
144 /// Update ExitBB PHINodes' to reflect this change.
145 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
146 BasicBlock *Header,
147 PHINode *IV, Instruction *IVIncrement);
148
149 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
150 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
151 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
152 PHINode *IV, Instruction *IVAdd, Loop *LP);
153
Devang Pateld662ace2007-08-22 18:27:01 +0000154 /// splitLoop - Split current loop L in two loops using split information
155 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000156 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000157
Devang Patel61571ca2007-08-10 00:33:50 +0000158 void initialize() {
159 IndVar = NULL;
160 IndVarIncrement = NULL;
161 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000162 StartValue = NULL;
163 ExitValueNum = 0;
164 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000165 }
166
Devang Patelbc5fe632007-08-07 00:25:56 +0000167 private:
168
169 // Current Loop.
170 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000171 LPPassManager *LPM;
172 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000173 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000174 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000175 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000176 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000177
178 // Induction variable whose range is being split by this transformation.
179 PHINode *IndVar;
180 Instruction *IndVarIncrement;
181
182 // Loop exit condition.
183 ICmpInst *ExitCondition;
184
185 // Induction variable's initial value.
186 Value *StartValue;
187
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000188 // Induction variable's final loop exit value operand number in exit condition..
189 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000190 };
191
192 char LoopIndexSplit::ID = 0;
193 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
194}
195
196LoopPass *llvm::createLoopIndexSplitPass() {
197 return new LoopIndexSplit();
198}
199
200// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000201bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000202 bool Changed = false;
203 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000204 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000205
Devang Patel81fcdfb2007-08-15 02:14:55 +0000206 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000207 if (!L->getSubLoops().empty())
208 return false;
209
Devang Patelbc5fe632007-08-07 00:25:56 +0000210 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000211 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000212 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000213 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000214
Devang Patel61571ca2007-08-10 00:33:50 +0000215 initialize();
216
217 findLoopConditionals();
218
219 if (!ExitCondition)
220 return false;
221
Devang Patelbc5fe632007-08-07 00:25:56 +0000222 findSplitCondition();
223
Devang Patelc8dadbf2007-08-08 21:02:17 +0000224 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000225 return false;
226
Devang Patelc8dadbf2007-08-08 21:02:17 +0000227 // First see if it is possible to eliminate loop itself or not.
228 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000229 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000230 SplitInfo &SD = *SI;
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000231 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
232 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000233 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000234 if (Changed) {
235 ++NumIndexSplit;
236 // If is loop is eliminated then nothing else to do here.
237 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000238 } else {
239 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
240 ++SI;
241 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000242 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000243 } else
244 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000245 }
246
Devang Patel7f526a82007-08-24 06:17:19 +0000247 if (SplitData.empty())
248 return false;
249
Devang Patel0aaeb172007-08-08 22:25:28 +0000250 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000251 // FIXME : Implement cost analysis.
252 unsigned MostProfitableSDIndex = 0;
253 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000254
Devang Patelbc5fe632007-08-07 00:25:56 +0000255 if (Changed)
256 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000257
Devang Patelbc5fe632007-08-07 00:25:56 +0000258 return Changed;
259}
260
Devang Patel2545f7b2007-08-09 01:39:01 +0000261/// Return true if V is a induction variable or induction variable's
262/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000263void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000264
265 Instruction *I = dyn_cast<Instruction>(V);
266 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000267 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000268
269 // Check if I is a phi node from loop header or not.
270 if (PHINode *PN = dyn_cast<PHINode>(V)) {
271 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000272 IndVar = PN;
273 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000274 }
275 }
276
277 // Check if I is a add instruction whose one operand is
278 // phi node from loop header and second operand is constant.
279 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000280 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000281
282 Value *Op0 = I->getOperand(0);
283 Value *Op1 = I->getOperand(1);
284
285 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
286 if (PN->getParent() == L->getHeader()
287 && isa<ConstantInt>(Op1)) {
288 IndVar = PN;
289 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000290 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000291 }
292 }
293
294 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
295 if (PN->getParent() == L->getHeader()
296 && isa<ConstantInt>(Op0)) {
297 IndVar = PN;
298 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000299 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000300 }
301 }
302
Devang Patel61571ca2007-08-10 00:33:50 +0000303 return;
304}
305
306// Find loop's exit condition and associated induction variable.
307void LoopIndexSplit::findLoopConditionals() {
308
Devang Patel9263fc32007-08-20 23:51:18 +0000309 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000310
311 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
312 I != E; ++I) {
313 BasicBlock *BB = *I;
314 if (!L->isLoopExit(BB))
315 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000316 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000317 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000318 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000319 }
320
Devang Patel9263fc32007-08-20 23:51:18 +0000321 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000322 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000323
324 // If exiting block is neither loop header nor loop latch then this loop is
325 // not suitable.
326 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
327 return;
328
Devang Patel61571ca2007-08-10 00:33:50 +0000329 // If exit block's terminator is conditional branch inst then we have found
330 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000331 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000332 if (!BR || BR->isUnconditional())
333 return;
334
335 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
336 if (!CI)
337 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000338
Devang Patel7ea9ad22007-09-10 23:34:06 +0000339 // FIXME
340 if (CI->getPredicate() == ICmpInst::ICMP_EQ
341 || CI->getPredicate() == ICmpInst::ICMP_NE)
342 return;
343
Devang Pateledea5b32007-08-25 00:56:38 +0000344 if (CI->getPredicate() == ICmpInst::ICMP_SGT
345 || CI->getPredicate() == ICmpInst::ICMP_UGT
346 || CI->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel7ea9ad22007-09-10 23:34:06 +0000347 || CI->getPredicate() == ICmpInst::ICMP_UGE) {
348
349 BasicBlock *FirstSuccessor = BR->getSuccessor(0);
350 // splitLoop() is expecting LT/LE as exit condition predicate.
351 // Swap operands here if possible to meet this requirement.
352 if (!L->contains(FirstSuccessor))
353 CI->swapOperands();
354 else
355 return;
356 }
Devang Pateledea5b32007-08-25 00:56:38 +0000357
Devang Patel61571ca2007-08-10 00:33:50 +0000358 ExitCondition = CI;
359
360 // Exit condition's one operand is loop invariant exit value and second
361 // operand is SCEVAddRecExpr based on induction variable.
362 Value *V0 = CI->getOperand(0);
363 Value *V1 = CI->getOperand(1);
364
365 SCEVHandle SH0 = SE->getSCEV(V0);
366 SCEVHandle SH1 = SE->getSCEV(V1);
367
368 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000369 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000370 findIndVar(V1, L);
371 }
372 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000373 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000374 findIndVar(V0, L);
375 }
376
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000377 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000378 ExitCondition = NULL;
379 else if (IndVar) {
380 BasicBlock *Preheader = L->getLoopPreheader();
381 StartValue = IndVar->getIncomingValueForBlock(Preheader);
382 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000383}
384
Devang Patelbc5fe632007-08-07 00:25:56 +0000385/// Find condition inside a loop that is suitable candidate for index split.
386void LoopIndexSplit::findSplitCondition() {
387
Devang Patelc8dadbf2007-08-08 21:02:17 +0000388 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000389 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000390 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
391 I != E; ++I) {
Devang Pateld18971d2007-09-11 00:23:56 +0000392 SD.clear();
Devang Patel2545f7b2007-08-09 01:39:01 +0000393 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000394
Devang Patel2545f7b2007-08-09 01:39:01 +0000395 // If this basic block does not terminate in a conditional branch
396 // then terminator is not a suitable split condition.
397 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
398 if (!BR)
399 continue;
400
401 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000402 continue;
403
Devang Patel2545f7b2007-08-09 01:39:01 +0000404 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000405 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000406 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000407
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000408 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000409 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000410
Devang Patel7f526a82007-08-24 06:17:19 +0000411 // If split condition predicate is GT or GE then first execute
412 // false branch of split condition.
Devang Patela3a23f62007-09-11 01:10:45 +0000413 if (CI->getPredicate() == ICmpInst::ICMP_UGT
414 || CI->getPredicate() == ICmpInst::ICMP_SGT
415 || CI->getPredicate() == ICmpInst::ICMP_UGE
416 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel7f526a82007-08-24 06:17:19 +0000417 SD.UseTrueBranchFirst = false;
418
Devang Patel2545f7b2007-08-09 01:39:01 +0000419 // If one operand is loop invariant and second operand is SCEVAddRecExpr
420 // based on induction variable then CI is a candidate split condition.
Devang Patel12564292007-09-11 00:42:56 +0000421 if (safeICmpInst(CI, SD))
422 SplitData.push_back(SD);
423 }
424}
Devang Patel2545f7b2007-08-09 01:39:01 +0000425
Devang Patel12564292007-09-11 00:42:56 +0000426// safeIcmpInst - CI is considered safe instruction if one of the operand
427// is SCEVAddRecExpr based on induction variable and other operand is
428// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
429// and return true;
430bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000431
Devang Patel12564292007-09-11 00:42:56 +0000432 Value *V0 = CI->getOperand(0);
433 Value *V1 = CI->getOperand(1);
434
435 SCEVHandle SH0 = SE->getSCEV(V0);
436 SCEVHandle SH1 = SE->getSCEV(V1);
437
438 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
439 SD.SplitValue = V0;
440 SD.SplitCondition = CI;
441 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
442 if (PN == IndVar)
443 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000444 }
Devang Patel12564292007-09-11 00:42:56 +0000445 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
446 if (IndVarIncrement && IndVarIncrement == Insn)
447 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +0000448 }
449 }
Devang Patel12564292007-09-11 00:42:56 +0000450 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
451 SD.SplitValue = V1;
452 SD.SplitCondition = CI;
453 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
454 if (PN == IndVar)
455 return true;
456 }
457 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
458 if (IndVarIncrement && IndVarIncrement == Insn)
459 return true;
460 }
461 }
462
463 return false;
Devang Patelbc5fe632007-08-07 00:25:56 +0000464}
465
466/// processOneIterationLoop - Current loop L contains compare instruction
467/// that compares induction variable, IndVar, against loop invariant. If
468/// entire (i.e. meaningful) loop body is dominated by this compare
469/// instruction then loop body is executed only once. In such case eliminate
470/// loop structure surrounding this loop body. For example,
471/// for (int i = start; i < end; ++i) {
472/// if ( i == somevalue) {
473/// loop_body
474/// }
475/// }
476/// can be transformed into
477/// if (somevalue >= start && somevalue < end) {
478/// i = somevalue;
479/// loop_body
480/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000481bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000482
483 BasicBlock *Header = L->getHeader();
484
485 // First of all, check if SplitCondition dominates entire loop body
486 // or not.
487
488 // If SplitCondition is not in loop header then this loop is not suitable
489 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000490 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000491 return false;
492
Devang Patelbc5fe632007-08-07 00:25:56 +0000493 // If loop header includes loop variant instruction operands then
494 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000495 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000496 return false;
497
Devang Patel9263fc32007-08-20 23:51:18 +0000498 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000499 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000500 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000501 return false;
502
Devang Patel2bcb5012007-08-08 01:51:27 +0000503 // Update CFG.
504
Devang Patelc166b952007-08-20 20:49:01 +0000505 // Replace index variable with split value in loop body. Loop body is executed
506 // only when index variable is equal to split value.
507 IndVar->replaceAllUsesWith(SD.SplitValue);
508
509 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000510 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000511 BasicBlock *LatchSucc = NULL;
512 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
513 if (!BR)
514 return false;
515 Header->removePredecessor(Latch);
516 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
517 SI != E; ++SI) {
518 if (Header != *SI)
519 LatchSucc = *SI;
520 }
521 BR->setUnconditionalDest(LatchSucc);
522
Devang Patelbc5fe632007-08-07 00:25:56 +0000523 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000524 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000525
Devang Patelbc5fe632007-08-07 00:25:56 +0000526 // Replace split condition in header.
527 // Transform
528 // SplitCondition : icmp eq i32 IndVar, SplitValue
529 // into
530 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000531 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000532 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000533 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000534 Instruction *C1 = new ICmpInst(SignedPredicate ?
535 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000536 SD.SplitValue, StartValue, "lisplit",
537 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000538 Instruction *C2 = new ICmpInst(SignedPredicate ?
539 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000540 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000541 Terminator);
542 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
543 Terminator);
544 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
545 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000546
Devang Patelbc5fe632007-08-07 00:25:56 +0000547 // Now, clear latch block. Remove instructions that are responsible
548 // to increment induction variable.
549 Instruction *LTerminator = Latch->getTerminator();
550 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
551 LB != LE; ) {
552 Instruction *I = LB;
553 ++LB;
554 if (isa<PHINode>(I) || I == LTerminator)
555 continue;
556
Devang Patel59e0c062007-08-14 01:30:57 +0000557 if (I == IndVarIncrement)
558 I->replaceAllUsesWith(ExitValue);
559 else
560 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000561 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000562 }
563
Devang Patel901f67e2007-08-10 18:07:13 +0000564 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000565
566 // Update Dominator Info.
567 // Only CFG change done is to remove Latch to Header edge. This
568 // does not change dominator tree because Latch did not dominate
569 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000570 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000571 DominanceFrontier::iterator HeaderDF = DF->find(Header);
572 if (HeaderDF != DF->end())
573 DF->removeFromFrontier(HeaderDF, Header);
574
575 DominanceFrontier::iterator LatchDF = DF->find(Latch);
576 if (LatchDF != DF->end())
577 DF->removeFromFrontier(LatchDF, Header);
578 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000579 return true;
580}
581
582// If loop header includes loop variant instruction operands then
583// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000584bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000585
586 Instruction *Terminator = Header->getTerminator();
587 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
588 BI != BE; ++BI) {
589 Instruction *I = BI;
590
Devang Patel59e0c062007-08-14 01:30:57 +0000591 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000592 if (isa<PHINode>(I))
593 continue;
594
595 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000596 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000597 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000598
Devang Patel2545f7b2007-08-09 01:39:01 +0000599 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000600 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000601 continue;
602
603 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000604 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000605 continue;
606
Devang Patelbc5fe632007-08-07 00:25:56 +0000607 // Terminator is also harmless.
608 if (I == Terminator)
609 continue;
610
611 // Otherwise we have a instruction that may not be safe.
612 return false;
613 }
614
615 return true;
616}
617
Devang Patel9263fc32007-08-20 23:51:18 +0000618// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000619// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000620bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
621 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000622
Devang Patel9263fc32007-08-20 23:51:18 +0000623 for (BasicBlock::iterator BI = ExitingBlock->begin(),
624 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000625 Instruction *I = BI;
626
Devang Patel59e0c062007-08-14 01:30:57 +0000627 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000628 if (isa<PHINode>(I))
629 continue;
630
Devang Patel2545f7b2007-08-09 01:39:01 +0000631 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000632 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000633 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000634
Devang Patel2545f7b2007-08-09 01:39:01 +0000635 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000636 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000637
638 Value *Op0 = I->getOperand(0);
639 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000640 PHINode *PN = NULL;
641 ConstantInt *CI = NULL;
642
643 if ((PN = dyn_cast<PHINode>(Op0))) {
644 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000645 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000646 } else
647 if ((PN = dyn_cast<PHINode>(Op1))) {
648 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000649 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000650 }
651
Devang Patel61571ca2007-08-10 00:33:50 +0000652 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000653 continue;
654 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000655
Devang Patelbc5fe632007-08-07 00:25:56 +0000656 // I is an Exit condition if next instruction is block terminator.
657 // Exit condition is OK if it compares loop invariant exit value,
658 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000659 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000660 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000661 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000662 }
663
Devang Patel9263fc32007-08-20 23:51:18 +0000664 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000665 continue;
666
Devang Patelbc5fe632007-08-07 00:25:56 +0000667 // Otherwise we have instruction that may not be safe.
668 return false;
669 }
670
Devang Patel9263fc32007-08-20 23:51:18 +0000671 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000672 return true;
673}
674
Devang Patel60a94c72007-08-14 18:35:57 +0000675/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
676/// This routine is used to remove split condition's dead branch, dominated by
677/// DeadBB. LiveBB dominates split conidition's other branch.
678void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
679 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000680
Devang Patelf4277122007-08-15 03:31:47 +0000681 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000682 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000683 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
684 if (DeadBBDF != DF->end()) {
685 SmallVector<BasicBlock *, 8> PredBlocks;
686
687 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
688 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
689 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
690 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000691 FrontierBBs.push_back(FrontierBB);
692
Devang Patelf4277122007-08-15 03:31:47 +0000693 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
694 PredBlocks.clear();
695 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
696 PI != PE; ++PI) {
697 BasicBlock *P = *PI;
698 if (P == DeadBB || DT->dominates(DeadBB, P))
699 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000700 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000701
Devang Patelf4277122007-08-15 03:31:47 +0000702 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
703 FBI != FBE; ++FBI) {
704 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
705 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
706 PE = PredBlocks.end(); PI != PE; ++PI) {
707 BasicBlock *P = *PI;
708 PN->removeIncomingValue(P);
709 }
710 }
711 else
712 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000713 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000714 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000715 }
Devang Patelf4277122007-08-15 03:31:47 +0000716
717 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
718 SmallVector<BasicBlock *, 32> WorkList;
719 DomTreeNode *DN = DT->getNode(DeadBB);
720 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
721 E = df_end(DN); DI != E; ++DI) {
722 BasicBlock *BB = DI->getBlock();
723 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000724 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000725 }
726
727 while (!WorkList.empty()) {
728 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
729 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
730 BBI != BBE; ++BBI) {
731 Instruction *I = BBI;
732 I->replaceAllUsesWith(UndefValue::get(I->getType()));
733 I->eraseFromParent();
734 }
735 LPM->deleteSimpleAnalysisValue(BB, LP);
736 DT->eraseNode(BB);
737 DF->removeBlock(BB);
738 LI->removeBlock(BB);
739 BB->eraseFromParent();
740 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000741
742 // Update Frontier BBs' dominator info.
743 while (!FrontierBBs.empty()) {
744 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
745 BasicBlock *NewDominator = FBB->getSinglePredecessor();
746 if (!NewDominator) {
747 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
748 NewDominator = *PI;
749 ++PI;
750 if (NewDominator != LiveBB) {
751 for(; PI != PE; ++PI) {
752 BasicBlock *P = *PI;
753 if (P == LiveBB) {
754 NewDominator = LiveBB;
755 break;
756 }
757 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
758 }
759 }
760 }
761 assert (NewDominator && "Unable to fix dominator info.");
762 DT->changeImmediateDominator(FBB, NewDominator);
763 DF->changeImmediateDominator(FBB, NewDominator, DT);
764 }
765
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000766}
767
Devang Pateld662ace2007-08-22 18:27:01 +0000768/// safeSplitCondition - Return true if it is possible to
769/// split loop using given split condition.
770bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000771
Devang Pateld662ace2007-08-22 18:27:01 +0000772 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000773
Devang Pateld662ace2007-08-22 18:27:01 +0000774 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000775 // In triangle loop, split condition is in header and one of the
776 // the split destination is loop latch. If split condition is EQ
777 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000778 BasicBlock *Latch = L->getLoopLatch();
779 BranchInst *SplitTerminator =
780 cast<BranchInst>(SplitCondBlock->getTerminator());
781 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
782 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
783 if (L->getHeader() == SplitCondBlock
784 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000785 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000786
Devang Patelac7c7c22007-08-27 21:34:31 +0000787 // If split condition branches heads do not have single predecessor,
788 // SplitCondBlock, then is not possible to remove inactive branch.
789 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000790 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000791
Devang Patel4e2075d2007-08-24 05:36:56 +0000792 // Finally this split condition is safe only if merge point for
793 // split condition branch is loop latch. This check along with previous
794 // check, to ensure that exit condition is in either loop latch or header,
795 // filters all loops with non-empty loop body between merge point
796 // and exit condition.
797 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
798 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
799 if (Succ0DF->second.count(Latch))
800 return true;
801
802 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
803 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
804 if (Succ1DF->second.count(Latch))
805 return true;
806
807 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000808}
809
Devang Pateledea5b32007-08-25 00:56:38 +0000810/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
811/// based on split value.
812void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
813
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000814 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
815 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +0000816 const Type *Ty = SD.SplitValue->getType();
817 bool Sign = ExitCondition->isSignedPredicate();
818 BasicBlock *Preheader = L->getLoopPreheader();
819 Instruction *PHTerminator = Preheader->getTerminator();
820
821 // Initially use split value as upper loop bound for first loop and lower loop
822 // bound for second loop.
823 Value *AEV = SD.SplitValue;
824 Value *BSV = SD.SplitValue;
825
826 switch (ExitCondition->getPredicate()) {
827 case ICmpInst::ICMP_SGT:
828 case ICmpInst::ICMP_UGT:
829 case ICmpInst::ICMP_SGE:
830 case ICmpInst::ICMP_UGE:
831 default:
832 assert (0 && "Unexpected exit condition predicate");
833
834 case ICmpInst::ICMP_SLT:
835 case ICmpInst::ICMP_ULT:
836 {
837 switch (SP) {
838 case ICmpInst::ICMP_SLT:
839 case ICmpInst::ICMP_ULT:
840 //
841 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
842 //
843 // is transformed into
844 // AEV = BSV = SV
845 // for (i = LB; i < min(UB, AEV); ++i)
846 // A;
847 // for (i = max(LB, BSV); i < UB; ++i);
848 // B;
849 break;
850 case ICmpInst::ICMP_SLE:
851 case ICmpInst::ICMP_ULE:
852 {
853 //
854 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
855 //
856 // is transformed into
857 //
858 // AEV = SV + 1
859 // BSV = SV + 1
860 // for (i = LB; i < min(UB, AEV); ++i)
861 // A;
862 // for (i = max(LB, BSV); i < UB; ++i)
863 // B;
864 BSV = BinaryOperator::createAdd(SD.SplitValue,
865 ConstantInt::get(Ty, 1, Sign),
866 "lsplit.add", PHTerminator);
867 AEV = BSV;
868 }
869 break;
870 case ICmpInst::ICMP_SGE:
871 case ICmpInst::ICMP_UGE:
872 //
873 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
874 //
875 // is transformed into
876 // AEV = BSV = SV
877 // for (i = LB; i < min(UB, AEV); ++i)
878 // B;
879 // for (i = max(BSV, LB); i < UB; ++i)
880 // A;
881 break;
882 case ICmpInst::ICMP_SGT:
883 case ICmpInst::ICMP_UGT:
884 {
885 //
886 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
887 //
888 // is transformed into
889 //
890 // BSV = AEV = SV + 1
891 // for (i = LB; i < min(UB, AEV); ++i)
892 // B;
893 // for (i = max(LB, BSV); i < UB; ++i)
894 // A;
895 BSV = BinaryOperator::createAdd(SD.SplitValue,
896 ConstantInt::get(Ty, 1, Sign),
897 "lsplit.add", PHTerminator);
898 AEV = BSV;
899 }
900 break;
901 default:
902 assert (0 && "Unexpected split condition predicate");
903 break;
904 } // end switch (SP)
905 }
906 break;
907 case ICmpInst::ICMP_SLE:
908 case ICmpInst::ICMP_ULE:
909 {
910 switch (SP) {
911 case ICmpInst::ICMP_SLT:
912 case ICmpInst::ICMP_ULT:
913 //
914 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
915 //
916 // is transformed into
917 // AEV = SV - 1;
918 // BSV = SV;
919 // for (i = LB; i <= min(UB, AEV); ++i)
920 // A;
921 // for (i = max(LB, BSV); i <= UB; ++i)
922 // B;
923 AEV = BinaryOperator::createSub(SD.SplitValue,
924 ConstantInt::get(Ty, 1, Sign),
925 "lsplit.sub", PHTerminator);
926 break;
927 case ICmpInst::ICMP_SLE:
928 case ICmpInst::ICMP_ULE:
929 //
930 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
931 //
932 // is transformed into
933 // AEV = SV;
934 // BSV = SV + 1;
935 // for (i = LB; i <= min(UB, AEV); ++i)
936 // A;
937 // for (i = max(LB, BSV); i <= UB; ++i)
938 // B;
939 BSV = BinaryOperator::createAdd(SD.SplitValue,
940 ConstantInt::get(Ty, 1, Sign),
941 "lsplit.add", PHTerminator);
942 break;
943 case ICmpInst::ICMP_SGT:
944 case ICmpInst::ICMP_UGT:
945 //
946 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
947 //
948 // is transformed into
949 // AEV = SV;
950 // BSV = SV + 1;
951 // for (i = LB; i <= min(AEV, UB); ++i)
952 // B;
953 // for (i = max(LB, BSV); i <= UB; ++i)
954 // A;
955 BSV = BinaryOperator::createAdd(SD.SplitValue,
956 ConstantInt::get(Ty, 1, Sign),
957 "lsplit.add", PHTerminator);
958 break;
959 case ICmpInst::ICMP_SGE:
960 case ICmpInst::ICMP_UGE:
961 // ** TODO **
962 //
963 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
964 //
965 // is transformed into
966 // AEV = SV - 1;
967 // BSV = SV;
968 // for (i = LB; i <= min(AEV, UB); ++i)
969 // B;
970 // for (i = max(LB, BSV); i <= UB; ++i)
971 // A;
972 AEV = BinaryOperator::createSub(SD.SplitValue,
973 ConstantInt::get(Ty, 1, Sign),
974 "lsplit.sub", PHTerminator);
975 break;
976 default:
977 assert (0 && "Unexpected split condition predicate");
978 break;
979 } // end switch (SP)
980 }
981 break;
982 }
983
984 // Calculate ALoop induction variable's new exiting value and
985 // BLoop induction variable's new starting value. Calculuate these
986 // values in original loop's preheader.
987 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
988 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000989 Value *C1 = new ICmpInst(Sign ?
990 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
991 AEV,
992 ExitCondition->getOperand(ExitValueNum),
993 "lsplit.ev", PHTerminator);
994 SD.A_ExitValue = new SelectInst(C1, AEV,
995 ExitCondition->getOperand(ExitValueNum),
996 "lsplit.ev", PHTerminator);
997
998 Value *C2 = new ICmpInst(Sign ?
999 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1000 BSV, StartValue, "lsplit.sv",
1001 PHTerminator);
1002 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1003 "lsplit.sv", PHTerminator);
1004}
1005
Devang Pateld662ace2007-08-22 18:27:01 +00001006/// splitLoop - Split current loop L in two loops using split information
1007/// SD. Update dominator information. Maintain LCSSA form.
1008bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1009
1010 if (!safeSplitCondition(SD))
1011 return false;
1012
Devang Patela0ac7262007-08-22 19:33:29 +00001013 // After loop is cloned there are two loops.
1014 //
1015 // First loop, referred as ALoop, executes first part of loop's iteration
1016 // space split. Second loop, referred as BLoop, executes remaining
1017 // part of loop's iteration space.
1018 //
1019 // ALoop's exit edge enters BLoop's header through a forwarding block which
1020 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001021 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001022
Devang Pateledea5b32007-08-25 00:56:38 +00001023 // Calculate ALoop induction variable's new exiting value and
1024 // BLoop induction variable's new starting value.
1025 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001026
Devang Patela0ac7262007-08-22 19:33:29 +00001027 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001028 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001029 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001030 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001031 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001032
Devang Patela0ac7262007-08-22 19:33:29 +00001033 //[*] ALoop's exiting edge BLoop's header.
1034 // ALoop's original exit block becomes BLoop's exit block.
1035 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1036 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1037 BranchInst *A_ExitInsn =
1038 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1039 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1040 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1041 if (L->contains(B_ExitBlock)) {
1042 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1043 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001044 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001045 A_ExitInsn->setSuccessor(1, B_Header);
1046
1047 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001048 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001049
Devang Patela0ac7262007-08-22 19:33:29 +00001050 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1051 // original loop's preheader. Add incoming PHINode values from
1052 // ALoop's exiting block. Update BLoop header's domiantor info.
1053
Devang Patel59e0c062007-08-14 01:30:57 +00001054 // Collect inverse map of Header PHINodes.
1055 DenseMap<Value *, Value *> InverseMap;
1056 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1057 BE = L->getHeader()->end(); BI != BE; ++BI) {
1058 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1059 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1060 InverseMap[PNClone] = PN;
1061 } else
1062 break;
1063 }
Devang Pateledea5b32007-08-25 00:56:38 +00001064
Devang Patela0ac7262007-08-22 19:33:29 +00001065 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001066 BI != BE; ++BI) {
1067 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001068 // Remove incoming value from original preheader.
1069 PN->removeIncomingValue(Preheader);
1070
1071 // Add incoming value from A_ExitingBlock.
1072 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001073 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001074 else {
1075 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001076 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1077 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001078 }
1079 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001080 break;
1081 }
Devang Patela0ac7262007-08-22 19:33:29 +00001082 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1083 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001084
Devang Patela0ac7262007-08-22 19:33:29 +00001085 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1086 // block. Remove incoming PHINode values from ALoop's exiting block.
1087 // Add new incoming values from BLoop's incoming exiting value.
1088 // Update BLoop exit block's dominator info..
1089 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1090 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001091 BI != BE; ++BI) {
1092 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001093 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1094 B_ExitingBlock);
1095 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001096 } else
1097 break;
1098 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001099
Devang Patela0ac7262007-08-22 19:33:29 +00001100 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1101 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001102
Devang Patela0ac7262007-08-22 19:33:29 +00001103 //[*] Split ALoop's exit edge. This creates a new block which
1104 // serves two purposes. First one is to hold PHINode defnitions
1105 // to ensure that ALoop's LCSSA form. Second use it to act
1106 // as a preheader for BLoop.
1107 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001108
Devang Patela0ac7262007-08-22 19:33:29 +00001109 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1110 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1111 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001112 BI != BE; ++BI) {
1113 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001114 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001115 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001116 newPHI->addIncoming(V1, A_ExitingBlock);
1117 A_ExitBlock->getInstList().push_front(newPHI);
1118 PN->removeIncomingValue(A_ExitBlock);
1119 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001120 } else
1121 break;
1122 }
1123
Devang Patela0ac7262007-08-22 19:33:29 +00001124 //[*] Eliminate split condition's inactive branch from ALoop.
1125 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1126 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001127 BasicBlock *A_InactiveBranch = NULL;
1128 BasicBlock *A_ActiveBranch = NULL;
1129 if (SD.UseTrueBranchFirst) {
1130 A_ActiveBranch = A_BR->getSuccessor(0);
1131 A_InactiveBranch = A_BR->getSuccessor(1);
1132 } else {
1133 A_ActiveBranch = A_BR->getSuccessor(1);
1134 A_InactiveBranch = A_BR->getSuccessor(0);
1135 }
Devang Patel4e585c72007-08-24 19:32:26 +00001136 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001137 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1138
1139 //[*] Eliminate split condition's inactive branch in from BLoop.
1140 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1141 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001142 BasicBlock *B_InactiveBranch = NULL;
1143 BasicBlock *B_ActiveBranch = NULL;
1144 if (SD.UseTrueBranchFirst) {
1145 B_ActiveBranch = B_BR->getSuccessor(1);
1146 B_InactiveBranch = B_BR->getSuccessor(0);
1147 } else {
1148 B_ActiveBranch = B_BR->getSuccessor(0);
1149 B_InactiveBranch = B_BR->getSuccessor(1);
1150 }
Devang Patel4e585c72007-08-24 19:32:26 +00001151 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001152 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1153
Devang Patelcd71bed2007-08-25 02:39:24 +00001154 BasicBlock *A_Header = L->getHeader();
1155 if (A_ExitingBlock == A_Header)
1156 return true;
1157
1158 //[*] Move exit condition into split condition block to avoid
1159 // executing dead loop iteration.
1160 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1161 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1162 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1163
1164 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001165 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1166 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001167
1168 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1169 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1170
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001171 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001172}
Devang Patelcd71bed2007-08-25 02:39:24 +00001173
1174// moveExitCondition - Move exit condition EC into split condition block CondBB.
1175void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1176 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1177 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1178
1179 BasicBlock *ExitingBB = EC->getParent();
1180 Instruction *CurrentBR = CondBB->getTerminator();
1181
1182 // Move exit condition into split condition block.
1183 EC->moveBefore(CurrentBR);
1184 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1185
1186 // Move exiting block's branch into split condition block. Update its branch
1187 // destination.
1188 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1189 ExitingBR->moveBefore(CurrentBR);
1190 if (ExitingBR->getSuccessor(0) == ExitBB)
1191 ExitingBR->setSuccessor(1, ActiveBB);
1192 else
1193 ExitingBR->setSuccessor(0, ActiveBB);
1194
1195 // Remove split condition and current split condition branch.
1196 SC->eraseFromParent();
1197 CurrentBR->eraseFromParent();
1198
1199 // Connect exiting block to split condition block.
1200 new BranchInst(CondBB, ExitingBB);
1201
1202 // Update PHINodes
1203 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1204
1205 // Fix dominator info.
1206 // ExitBB is now dominated by CondBB
1207 DT->changeImmediateDominator(ExitBB, CondBB);
1208 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1209
1210 // Basicblocks dominated by ActiveBB may have ExitingBB or
1211 // a basic block outside the loop in their DF list. If so,
1212 // replace it with CondBB.
1213 DomTreeNode *Node = DT->getNode(ActiveBB);
1214 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1215 DI != DE; ++DI) {
1216 BasicBlock *BB = DI->getBlock();
1217 DominanceFrontier::iterator BBDF = DF->find(BB);
1218 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1219 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1220 while (DomSetI != DomSetE) {
1221 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1222 ++DomSetI;
1223 BasicBlock *DFBB = *CurrentItr;
1224 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1225 BBDF->second.erase(DFBB);
1226 BBDF->second.insert(CondBB);
1227 }
1228 }
1229 }
1230}
1231
1232/// updatePHINodes - CFG has been changed.
1233/// Before
1234/// - ExitBB's single predecessor was Latch
1235/// - Latch's second successor was Header
1236/// Now
1237/// - ExitBB's single predecessor was Header
1238/// - Latch's one and only successor was Header
1239///
1240/// Update ExitBB PHINodes' to reflect this change.
1241void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1242 BasicBlock *Header,
1243 PHINode *IV, Instruction *IVIncrement) {
1244
1245 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1246 BI != BE; ++BI) {
1247 PHINode *PN = dyn_cast<PHINode>(BI);
1248 if (!PN)
1249 break;
1250
1251 Value *V = PN->getIncomingValueForBlock(Latch);
1252 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1253 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1254 // (i.e. PN :)).
1255 // The second use is in Header and it is new incoming value for PN.
1256 PHINode *U1 = NULL;
1257 PHINode *U2 = NULL;
1258 Value *NewV = NULL;
1259 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1260 UI != E; ++UI) {
1261 if (!U1)
1262 U1 = cast<PHINode>(*UI);
1263 else if (!U2)
1264 U2 = cast<PHINode>(*UI);
1265 else
1266 assert ( 0 && "Unexpected third use of this PHINode");
1267 }
1268 assert (U1 && U2 && "Unable to find two uses");
1269
1270 if (U1->getParent() == Header)
1271 NewV = U1;
1272 else
1273 NewV = U2;
1274 PN->addIncoming(NewV, Header);
1275
1276 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1277 // If this instruction is IVIncrement then IV is new incoming value
1278 // from header otherwise this instruction must be incoming value from
1279 // header because loop is in LCSSA form.
1280 if (PHI == IVIncrement)
1281 PN->addIncoming(IV, Header);
1282 else
1283 PN->addIncoming(V, Header);
1284 } else
1285 // Otherwise this is an incoming value from header because loop is in
1286 // LCSSA form.
1287 PN->addIncoming(V, Header);
1288
1289 // Remove incoming value from Latch.
1290 PN->removeIncomingValue(Latch);
1291 }
1292}