blob: abda03ca0a43c2c906384d66e6ded1f7830aa1a3 [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 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 Patelcd71bed2007-08-25 02:39:24 +0000129 /// updatePHINodes - CFG has been changed.
130 /// Before
131 /// - ExitBB's single predecessor was Latch
132 /// - Latch's second successor was Header
133 /// Now
134 /// - ExitBB's single predecessor was Header
135 /// - Latch's one and only successor was Header
136 ///
137 /// Update ExitBB PHINodes' to reflect this change.
138 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
139 BasicBlock *Header,
140 PHINode *IV, Instruction *IVIncrement);
141
142 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
143 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
144 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
145 PHINode *IV, Instruction *IVAdd, Loop *LP);
146
Devang Pateld662ace2007-08-22 18:27:01 +0000147 /// splitLoop - Split current loop L in two loops using split information
148 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000149 bool splitLoop(SplitInfo &SD);
Devang Patelbc5fe632007-08-07 00:25:56 +0000150
Devang Patel61571ca2007-08-10 00:33:50 +0000151 void initialize() {
152 IndVar = NULL;
153 IndVarIncrement = NULL;
154 ExitCondition = NULL;
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000155 StartValue = NULL;
156 ExitValueNum = 0;
157 SplitData.clear();
Devang Patel61571ca2007-08-10 00:33:50 +0000158 }
159
Devang Patelbc5fe632007-08-07 00:25:56 +0000160 private:
161
162 // Current Loop.
163 Loop *L;
Devang Patel901f67e2007-08-10 18:07:13 +0000164 LPPassManager *LPM;
165 LoopInfo *LI;
Devang Patelbc5fe632007-08-07 00:25:56 +0000166 ScalarEvolution *SE;
Devang Patel0aaeb172007-08-08 22:25:28 +0000167 DominatorTree *DT;
Devang Patelb7639612007-08-13 22:13:24 +0000168 DominanceFrontier *DF;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000169 SmallVector<SplitInfo, 4> SplitData;
Devang Patel61571ca2007-08-10 00:33:50 +0000170
171 // Induction variable whose range is being split by this transformation.
172 PHINode *IndVar;
173 Instruction *IndVarIncrement;
174
175 // Loop exit condition.
176 ICmpInst *ExitCondition;
177
178 // Induction variable's initial value.
179 Value *StartValue;
180
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000181 // Induction variable's final loop exit value operand number in exit condition..
182 unsigned ExitValueNum;
Devang Patelbc5fe632007-08-07 00:25:56 +0000183 };
184
185 char LoopIndexSplit::ID = 0;
186 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
187}
188
189LoopPass *llvm::createLoopIndexSplitPass() {
190 return new LoopIndexSplit();
191}
192
193// Index split Loop L. Return true if loop is split.
Devang Patel901f67e2007-08-10 18:07:13 +0000194bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000195 bool Changed = false;
196 L = IncomingLoop;
Devang Patel901f67e2007-08-10 18:07:13 +0000197 LPM = &LPM_Ref;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000198
Devang Patel81fcdfb2007-08-15 02:14:55 +0000199 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel79276b32007-08-14 23:53:57 +0000200 if (!L->getSubLoops().empty())
201 return false;
202
Devang Patelbc5fe632007-08-07 00:25:56 +0000203 SE = &getAnalysis<ScalarEvolution>();
Devang Patel0aaeb172007-08-08 22:25:28 +0000204 DT = &getAnalysis<DominatorTree>();
Devang Patel901f67e2007-08-10 18:07:13 +0000205 LI = &getAnalysis<LoopInfo>();
Devang Patel2190f172007-08-15 03:34:53 +0000206 DF = &getAnalysis<DominanceFrontier>();
Devang Patelbc5fe632007-08-07 00:25:56 +0000207
Devang Patel61571ca2007-08-10 00:33:50 +0000208 initialize();
209
210 findLoopConditionals();
211
212 if (!ExitCondition)
213 return false;
214
Devang Patelbc5fe632007-08-07 00:25:56 +0000215 findSplitCondition();
216
Devang Patelc8dadbf2007-08-08 21:02:17 +0000217 if (SplitData.empty())
Devang Patelbc5fe632007-08-07 00:25:56 +0000218 return false;
219
Devang Patelc8dadbf2007-08-08 21:02:17 +0000220 // First see if it is possible to eliminate loop itself or not.
221 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Patel49fbf5a2007-08-20 20:24:15 +0000222 E = SplitData.end(); SI != E;) {
Devang Patelc8dadbf2007-08-08 21:02:17 +0000223 SplitInfo &SD = *SI;
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000224 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
225 if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel901f67e2007-08-10 18:07:13 +0000226 Changed = processOneIterationLoop(SD);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000227 if (Changed) {
228 ++NumIndexSplit;
229 // If is loop is eliminated then nothing else to do here.
230 return Changed;
Devang Patel49fbf5a2007-08-20 20:24:15 +0000231 } else {
232 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
233 ++SI;
234 SplitData.erase(Delete_SI);
Devang Patelc8dadbf2007-08-08 21:02:17 +0000235 }
Devang Patel49fbf5a2007-08-20 20:24:15 +0000236 } else
237 ++SI;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000238 }
239
Devang Patel7f526a82007-08-24 06:17:19 +0000240 if (SplitData.empty())
241 return false;
242
Devang Patel0aaeb172007-08-08 22:25:28 +0000243 // Split most profitiable condition.
Devang Patel33085702007-08-24 05:21:13 +0000244 // FIXME : Implement cost analysis.
245 unsigned MostProfitableSDIndex = 0;
246 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel0aaeb172007-08-08 22:25:28 +0000247
Devang Patelbc5fe632007-08-07 00:25:56 +0000248 if (Changed)
249 ++NumIndexSplit;
Devang Patelc8dadbf2007-08-08 21:02:17 +0000250
Devang Patelbc5fe632007-08-07 00:25:56 +0000251 return Changed;
252}
253
Devang Patel2545f7b2007-08-09 01:39:01 +0000254/// Return true if V is a induction variable or induction variable's
255/// increment for loop L.
Devang Patel61571ca2007-08-10 00:33:50 +0000256void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000257
258 Instruction *I = dyn_cast<Instruction>(V);
259 if (!I)
Devang Patel61571ca2007-08-10 00:33:50 +0000260 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000261
262 // Check if I is a phi node from loop header or not.
263 if (PHINode *PN = dyn_cast<PHINode>(V)) {
264 if (PN->getParent() == L->getHeader()) {
Devang Patel61571ca2007-08-10 00:33:50 +0000265 IndVar = PN;
266 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000267 }
268 }
269
270 // Check if I is a add instruction whose one operand is
271 // phi node from loop header and second operand is constant.
272 if (I->getOpcode() != Instruction::Add)
Devang Patel61571ca2007-08-10 00:33:50 +0000273 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000274
275 Value *Op0 = I->getOperand(0);
276 Value *Op1 = I->getOperand(1);
277
278 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
279 if (PN->getParent() == L->getHeader()
280 && isa<ConstantInt>(Op1)) {
281 IndVar = PN;
282 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000283 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000284 }
285 }
286
287 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
288 if (PN->getParent() == L->getHeader()
289 && isa<ConstantInt>(Op0)) {
290 IndVar = PN;
291 IndVarIncrement = I;
Devang Patel61571ca2007-08-10 00:33:50 +0000292 return;
Devang Patel2545f7b2007-08-09 01:39:01 +0000293 }
294 }
295
Devang Patel61571ca2007-08-10 00:33:50 +0000296 return;
297}
298
299// Find loop's exit condition and associated induction variable.
300void LoopIndexSplit::findLoopConditionals() {
301
Devang Patel9263fc32007-08-20 23:51:18 +0000302 BasicBlock *ExitingBlock = NULL;
Devang Patel61571ca2007-08-10 00:33:50 +0000303
304 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
305 I != E; ++I) {
306 BasicBlock *BB = *I;
307 if (!L->isLoopExit(BB))
308 continue;
Devang Patel9263fc32007-08-20 23:51:18 +0000309 if (ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000310 return;
Devang Patel9263fc32007-08-20 23:51:18 +0000311 ExitingBlock = BB;
Devang Patel61571ca2007-08-10 00:33:50 +0000312 }
313
Devang Patel9263fc32007-08-20 23:51:18 +0000314 if (!ExitingBlock)
Devang Patel61571ca2007-08-10 00:33:50 +0000315 return;
Devang Patel4e2075d2007-08-24 05:36:56 +0000316
317 // If exiting block is neither loop header nor loop latch then this loop is
318 // not suitable.
319 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
320 return;
321
Devang Patel61571ca2007-08-10 00:33:50 +0000322 // If exit block's terminator is conditional branch inst then we have found
323 // exit condition.
Devang Patel9263fc32007-08-20 23:51:18 +0000324 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel61571ca2007-08-10 00:33:50 +0000325 if (!BR || BR->isUnconditional())
326 return;
327
328 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
329 if (!CI)
330 return;
Devang Pateledea5b32007-08-25 00:56:38 +0000331
Devang Patel7ea9ad22007-09-10 23:34:06 +0000332 // FIXME
333 if (CI->getPredicate() == ICmpInst::ICMP_EQ
334 || CI->getPredicate() == ICmpInst::ICMP_NE)
335 return;
336
Devang Pateledea5b32007-08-25 00:56:38 +0000337 if (CI->getPredicate() == ICmpInst::ICMP_SGT
338 || CI->getPredicate() == ICmpInst::ICMP_UGT
339 || CI->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel7ea9ad22007-09-10 23:34:06 +0000340 || CI->getPredicate() == ICmpInst::ICMP_UGE) {
341
342 BasicBlock *FirstSuccessor = BR->getSuccessor(0);
343 // splitLoop() is expecting LT/LE as exit condition predicate.
344 // Swap operands here if possible to meet this requirement.
345 if (!L->contains(FirstSuccessor))
346 CI->swapOperands();
347 else
348 return;
349 }
Devang Pateledea5b32007-08-25 00:56:38 +0000350
Devang Patel61571ca2007-08-10 00:33:50 +0000351 ExitCondition = CI;
352
353 // Exit condition's one operand is loop invariant exit value and second
354 // operand is SCEVAddRecExpr based on induction variable.
355 Value *V0 = CI->getOperand(0);
356 Value *V1 = CI->getOperand(1);
357
358 SCEVHandle SH0 = SE->getSCEV(V0);
359 SCEVHandle SH1 = SE->getSCEV(V1);
360
361 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000362 ExitValueNum = 0;
Devang Patel61571ca2007-08-10 00:33:50 +0000363 findIndVar(V1, L);
364 }
365 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000366 ExitValueNum = 1;
Devang Patel61571ca2007-08-10 00:33:50 +0000367 findIndVar(V0, L);
368 }
369
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000370 if (!IndVar)
Devang Patel61571ca2007-08-10 00:33:50 +0000371 ExitCondition = NULL;
372 else if (IndVar) {
373 BasicBlock *Preheader = L->getLoopPreheader();
374 StartValue = IndVar->getIncomingValueForBlock(Preheader);
375 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000376}
377
Devang Patelbc5fe632007-08-07 00:25:56 +0000378/// Find condition inside a loop that is suitable candidate for index split.
379void LoopIndexSplit::findSplitCondition() {
380
Devang Patelc8dadbf2007-08-08 21:02:17 +0000381 SplitInfo SD;
Devang Patel2545f7b2007-08-09 01:39:01 +0000382 // Check all basic block's terminators.
Devang Patel2545f7b2007-08-09 01:39:01 +0000383 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
384 I != E; ++I) {
Devang Pateld18971d2007-09-11 00:23:56 +0000385 SD.clear();
Devang Patel2545f7b2007-08-09 01:39:01 +0000386 BasicBlock *BB = *I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000387
Devang Patel2545f7b2007-08-09 01:39:01 +0000388 // If this basic block does not terminate in a conditional branch
389 // then terminator is not a suitable split condition.
390 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
391 if (!BR)
392 continue;
393
394 if (BR->isUnconditional())
Devang Patelbc5fe632007-08-07 00:25:56 +0000395 continue;
396
Devang Patel2545f7b2007-08-09 01:39:01 +0000397 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patel61571ca2007-08-10 00:33:50 +0000398 if (!CI || CI == ExitCondition)
Devang Patel5c859bc2007-09-10 23:57:58 +0000399 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000400
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000401 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patel5c859bc2007-09-10 23:57:58 +0000402 continue;
Devang Patelf6ccf6d2007-08-24 06:02:25 +0000403
Devang Patel7f526a82007-08-24 06:17:19 +0000404 // If split condition predicate is GT or GE then first execute
405 // false branch of split condition.
406 if (CI->getPredicate() != ICmpInst::ICMP_ULT
407 && CI->getPredicate() != ICmpInst::ICMP_SLT
408 && CI->getPredicate() != ICmpInst::ICMP_ULE
409 && CI->getPredicate() != ICmpInst::ICMP_SLE)
410 SD.UseTrueBranchFirst = false;
411
Devang Patel2545f7b2007-08-09 01:39:01 +0000412 // If one operand is loop invariant and second operand is SCEVAddRecExpr
413 // based on induction variable then CI is a candidate split condition.
414 Value *V0 = CI->getOperand(0);
415 Value *V1 = CI->getOperand(1);
416
417 SCEVHandle SH0 = SE->getSCEV(V0);
418 SCEVHandle SH1 = SE->getSCEV(V1);
419
420 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
421 SD.SplitValue = V0;
422 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000423 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
424 if (PN == IndVar)
425 SplitData.push_back(SD);
426 }
427 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
428 if (IndVarIncrement && IndVarIncrement == Insn)
429 SplitData.push_back(SD);
430 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000431 }
Devang Patel2545f7b2007-08-09 01:39:01 +0000432 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
433 SD.SplitValue = V1;
434 SD.SplitCondition = CI;
Devang Patel61571ca2007-08-10 00:33:50 +0000435 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
436 if (PN == IndVar)
437 SplitData.push_back(SD);
438 }
439 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
440 if (IndVarIncrement && IndVarIncrement == Insn)
441 SplitData.push_back(SD);
442 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000443 }
444 }
445}
446
447/// processOneIterationLoop - Current loop L contains compare instruction
448/// that compares induction variable, IndVar, against loop invariant. If
449/// entire (i.e. meaningful) loop body is dominated by this compare
450/// instruction then loop body is executed only once. In such case eliminate
451/// loop structure surrounding this loop body. For example,
452/// for (int i = start; i < end; ++i) {
453/// if ( i == somevalue) {
454/// loop_body
455/// }
456/// }
457/// can be transformed into
458/// if (somevalue >= start && somevalue < end) {
459/// i = somevalue;
460/// loop_body
461/// }
Devang Patel901f67e2007-08-10 18:07:13 +0000462bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000463
464 BasicBlock *Header = L->getHeader();
465
466 // First of all, check if SplitCondition dominates entire loop body
467 // or not.
468
469 // If SplitCondition is not in loop header then this loop is not suitable
470 // for this transformation.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000471 if (SD.SplitCondition->getParent() != Header)
Devang Patelbc5fe632007-08-07 00:25:56 +0000472 return false;
473
Devang Patelbc5fe632007-08-07 00:25:56 +0000474 // If loop header includes loop variant instruction operands then
475 // this loop may not be eliminated.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000476 if (!safeHeader(SD, Header))
Devang Patelbc5fe632007-08-07 00:25:56 +0000477 return false;
478
Devang Patel9263fc32007-08-20 23:51:18 +0000479 // If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000480 // loop may not be eliminated.
Devang Patel9263fc32007-08-20 23:51:18 +0000481 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelbc5fe632007-08-07 00:25:56 +0000482 return false;
483
Devang Patel2bcb5012007-08-08 01:51:27 +0000484 // Update CFG.
485
Devang Patelc166b952007-08-20 20:49:01 +0000486 // Replace index variable with split value in loop body. Loop body is executed
487 // only when index variable is equal to split value.
488 IndVar->replaceAllUsesWith(SD.SplitValue);
489
490 // Remove Latch to Header edge.
Devang Patelbc5fe632007-08-07 00:25:56 +0000491 BasicBlock *Latch = L->getLoopLatch();
Devang Patel2bcb5012007-08-08 01:51:27 +0000492 BasicBlock *LatchSucc = NULL;
493 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
494 if (!BR)
495 return false;
496 Header->removePredecessor(Latch);
497 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
498 SI != E; ++SI) {
499 if (Header != *SI)
500 LatchSucc = *SI;
501 }
502 BR->setUnconditionalDest(LatchSucc);
503
Devang Patelbc5fe632007-08-07 00:25:56 +0000504 Instruction *Terminator = Header->getTerminator();
Devang Patel59e0c062007-08-14 01:30:57 +0000505 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelbc5fe632007-08-07 00:25:56 +0000506
Devang Patelbc5fe632007-08-07 00:25:56 +0000507 // Replace split condition in header.
508 // Transform
509 // SplitCondition : icmp eq i32 IndVar, SplitValue
510 // into
511 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patel5c859bc2007-09-10 23:57:58 +0000512 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelbc5fe632007-08-07 00:25:56 +0000513 // and i32 c1, c2
Devang Patel61571ca2007-08-10 00:33:50 +0000514 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelbc5fe632007-08-07 00:25:56 +0000515 Instruction *C1 = new ICmpInst(SignedPredicate ?
516 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelc8dadbf2007-08-08 21:02:17 +0000517 SD.SplitValue, StartValue, "lisplit",
518 Terminator);
Devang Patelbc5fe632007-08-07 00:25:56 +0000519 Instruction *C2 = new ICmpInst(SignedPredicate ?
520 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patel59e0c062007-08-14 01:30:57 +0000521 SD.SplitValue, ExitValue, "lisplit",
Devang Patelc8dadbf2007-08-08 21:02:17 +0000522 Terminator);
523 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
524 Terminator);
525 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
526 SD.SplitCondition->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000527
Devang Patelbc5fe632007-08-07 00:25:56 +0000528 // Now, clear latch block. Remove instructions that are responsible
529 // to increment induction variable.
530 Instruction *LTerminator = Latch->getTerminator();
531 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
532 LB != LE; ) {
533 Instruction *I = LB;
534 ++LB;
535 if (isa<PHINode>(I) || I == LTerminator)
536 continue;
537
Devang Patel59e0c062007-08-14 01:30:57 +0000538 if (I == IndVarIncrement)
539 I->replaceAllUsesWith(ExitValue);
540 else
541 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel0d75c292007-08-07 17:45:35 +0000542 I->eraseFromParent();
Devang Patelbc5fe632007-08-07 00:25:56 +0000543 }
544
Devang Patel901f67e2007-08-10 18:07:13 +0000545 LPM->deleteLoopFromQueue(L);
Devang Patel95fd7172007-08-08 21:39:47 +0000546
547 // Update Dominator Info.
548 // Only CFG change done is to remove Latch to Header edge. This
549 // does not change dominator tree because Latch did not dominate
550 // Header.
Devang Patelb7639612007-08-13 22:13:24 +0000551 if (DF) {
Devang Patel95fd7172007-08-08 21:39:47 +0000552 DominanceFrontier::iterator HeaderDF = DF->find(Header);
553 if (HeaderDF != DF->end())
554 DF->removeFromFrontier(HeaderDF, Header);
555
556 DominanceFrontier::iterator LatchDF = DF->find(Latch);
557 if (LatchDF != DF->end())
558 DF->removeFromFrontier(LatchDF, Header);
559 }
Devang Patelbc5fe632007-08-07 00:25:56 +0000560 return true;
561}
562
563// If loop header includes loop variant instruction operands then
564// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patelc8dadbf2007-08-08 21:02:17 +0000565bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000566
567 Instruction *Terminator = Header->getTerminator();
568 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
569 BI != BE; ++BI) {
570 Instruction *I = BI;
571
Devang Patel59e0c062007-08-14 01:30:57 +0000572 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000573 if (isa<PHINode>(I))
574 continue;
575
576 // SplitCondition itself is OK.
Devang Patelc8dadbf2007-08-08 21:02:17 +0000577 if (I == SD.SplitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000578 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000579
Devang Patel2545f7b2007-08-09 01:39:01 +0000580 // Induction variable is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000581 if (I == IndVar)
Devang Patel2545f7b2007-08-09 01:39:01 +0000582 continue;
583
584 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000585 if (I == IndVarIncrement)
Devang Patel2545f7b2007-08-09 01:39:01 +0000586 continue;
587
Devang Patelbc5fe632007-08-07 00:25:56 +0000588 // Terminator is also harmless.
589 if (I == Terminator)
590 continue;
591
592 // Otherwise we have a instruction that may not be safe.
593 return false;
594 }
595
596 return true;
597}
598
Devang Patel9263fc32007-08-20 23:51:18 +0000599// If Exiting block includes loop variant instructions then this
Devang Patelbc5fe632007-08-07 00:25:56 +0000600// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel9263fc32007-08-20 23:51:18 +0000601bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
602 BasicBlock *ExitingBlock) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000603
Devang Patel9263fc32007-08-20 23:51:18 +0000604 for (BasicBlock::iterator BI = ExitingBlock->begin(),
605 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelbc5fe632007-08-07 00:25:56 +0000606 Instruction *I = BI;
607
Devang Patel59e0c062007-08-14 01:30:57 +0000608 // PHI Nodes are OK.
Devang Patelbc5fe632007-08-07 00:25:56 +0000609 if (isa<PHINode>(I))
610 continue;
611
Devang Patel2545f7b2007-08-09 01:39:01 +0000612 // Induction variable increment is OK.
Devang Patel61571ca2007-08-10 00:33:50 +0000613 if (IndVarIncrement && IndVarIncrement == I)
Devang Patel2545f7b2007-08-09 01:39:01 +0000614 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000615
Devang Patel2545f7b2007-08-09 01:39:01 +0000616 // Check if I is induction variable increment instruction.
Devang Patel61571ca2007-08-10 00:33:50 +0000617 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
Devang Patel2545f7b2007-08-09 01:39:01 +0000618
619 Value *Op0 = I->getOperand(0);
620 Value *Op1 = I->getOperand(1);
Devang Patelbc5fe632007-08-07 00:25:56 +0000621 PHINode *PN = NULL;
622 ConstantInt *CI = NULL;
623
624 if ((PN = dyn_cast<PHINode>(Op0))) {
625 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patel61571ca2007-08-10 00:33:50 +0000626 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000627 } else
628 if ((PN = dyn_cast<PHINode>(Op1))) {
629 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patel61571ca2007-08-10 00:33:50 +0000630 IndVarIncrement = I;
Devang Patelbc5fe632007-08-07 00:25:56 +0000631 }
632
Devang Patel61571ca2007-08-10 00:33:50 +0000633 if (IndVarIncrement && PN == IndVar && CI->isOne())
Devang Patelbc5fe632007-08-07 00:25:56 +0000634 continue;
635 }
Devang Patel2bcb5012007-08-08 01:51:27 +0000636
Devang Patelbc5fe632007-08-07 00:25:56 +0000637 // I is an Exit condition if next instruction is block terminator.
638 // Exit condition is OK if it compares loop invariant exit value,
639 // which is checked below.
Devang Patel3719d4f2007-08-07 23:17:52 +0000640 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patel61571ca2007-08-10 00:33:50 +0000641 if (EC == ExitCondition)
Devang Patel2bcb5012007-08-08 01:51:27 +0000642 continue;
Devang Patelbc5fe632007-08-07 00:25:56 +0000643 }
644
Devang Patel9263fc32007-08-20 23:51:18 +0000645 if (I == ExitingBlock->getTerminator())
Devang Patel61571ca2007-08-10 00:33:50 +0000646 continue;
647
Devang Patelbc5fe632007-08-07 00:25:56 +0000648 // Otherwise we have instruction that may not be safe.
649 return false;
650 }
651
Devang Patel9263fc32007-08-20 23:51:18 +0000652 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelbc5fe632007-08-07 00:25:56 +0000653 return true;
654}
655
Devang Patel60a94c72007-08-14 18:35:57 +0000656/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
657/// This routine is used to remove split condition's dead branch, dominated by
658/// DeadBB. LiveBB dominates split conidition's other branch.
659void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
660 BasicBlock *LiveBB) {
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000661
Devang Patelf4277122007-08-15 03:31:47 +0000662 // First update DeadBB's dominance frontier.
Devang Patel9cee7a02007-08-17 21:59:16 +0000663 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patelf4277122007-08-15 03:31:47 +0000664 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
665 if (DeadBBDF != DF->end()) {
666 SmallVector<BasicBlock *, 8> PredBlocks;
667
668 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
669 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
670 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
671 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel9cee7a02007-08-17 21:59:16 +0000672 FrontierBBs.push_back(FrontierBB);
673
Devang Patelf4277122007-08-15 03:31:47 +0000674 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
675 PredBlocks.clear();
676 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
677 PI != PE; ++PI) {
678 BasicBlock *P = *PI;
679 if (P == DeadBB || DT->dominates(DeadBB, P))
680 PredBlocks.push_back(P);
Devang Patelb7639612007-08-13 22:13:24 +0000681 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000682
Devang Patelf4277122007-08-15 03:31:47 +0000683 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
684 FBI != FBE; ++FBI) {
685 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
686 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
687 PE = PredBlocks.end(); PI != PE; ++PI) {
688 BasicBlock *P = *PI;
689 PN->removeIncomingValue(P);
690 }
691 }
692 else
693 break;
Devang Patel9cee7a02007-08-17 21:59:16 +0000694 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000695 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000696 }
Devang Patelf4277122007-08-15 03:31:47 +0000697
698 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
699 SmallVector<BasicBlock *, 32> WorkList;
700 DomTreeNode *DN = DT->getNode(DeadBB);
701 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
702 E = df_end(DN); DI != E; ++DI) {
703 BasicBlock *BB = DI->getBlock();
704 WorkList.push_back(BB);
Devang Patel9cee7a02007-08-17 21:59:16 +0000705 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patelf4277122007-08-15 03:31:47 +0000706 }
707
708 while (!WorkList.empty()) {
709 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
710 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
711 BBI != BBE; ++BBI) {
712 Instruction *I = BBI;
713 I->replaceAllUsesWith(UndefValue::get(I->getType()));
714 I->eraseFromParent();
715 }
716 LPM->deleteSimpleAnalysisValue(BB, LP);
717 DT->eraseNode(BB);
718 DF->removeBlock(BB);
719 LI->removeBlock(BB);
720 BB->eraseFromParent();
721 }
Devang Patel9cee7a02007-08-17 21:59:16 +0000722
723 // Update Frontier BBs' dominator info.
724 while (!FrontierBBs.empty()) {
725 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
726 BasicBlock *NewDominator = FBB->getSinglePredecessor();
727 if (!NewDominator) {
728 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
729 NewDominator = *PI;
730 ++PI;
731 if (NewDominator != LiveBB) {
732 for(; PI != PE; ++PI) {
733 BasicBlock *P = *PI;
734 if (P == LiveBB) {
735 NewDominator = LiveBB;
736 break;
737 }
738 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
739 }
740 }
741 }
742 assert (NewDominator && "Unable to fix dominator info.");
743 DT->changeImmediateDominator(FBB, NewDominator);
744 DF->changeImmediateDominator(FBB, NewDominator, DT);
745 }
746
Devang Patel6a2d6ef2007-08-12 07:02:51 +0000747}
748
Devang Pateld662ace2007-08-22 18:27:01 +0000749/// safeSplitCondition - Return true if it is possible to
750/// split loop using given split condition.
751bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patelf824fb42007-08-10 00:53:35 +0000752
Devang Pateld662ace2007-08-22 18:27:01 +0000753 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel2a24ff32007-08-21 21:12:02 +0000754
Devang Pateld662ace2007-08-22 18:27:01 +0000755 // Unable to handle triange loops at the moment.
Devang Patel81fcdfb2007-08-15 02:14:55 +0000756 // In triangle loop, split condition is in header and one of the
757 // the split destination is loop latch. If split condition is EQ
758 // then such loops are already handle in processOneIterationLoop().
Devang Pateld662ace2007-08-22 18:27:01 +0000759 BasicBlock *Latch = L->getLoopLatch();
760 BranchInst *SplitTerminator =
761 cast<BranchInst>(SplitCondBlock->getTerminator());
762 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
763 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
764 if (L->getHeader() == SplitCondBlock
765 && (Latch == Succ0 || Latch == Succ1))
Devang Patel81fcdfb2007-08-15 02:14:55 +0000766 return false;
Devang Patel2a24ff32007-08-21 21:12:02 +0000767
Devang Patelac7c7c22007-08-27 21:34:31 +0000768 // If split condition branches heads do not have single predecessor,
769 // SplitCondBlock, then is not possible to remove inactive branch.
770 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
Devang Patel9cee7a02007-08-17 21:59:16 +0000771 return false;
Devang Patel9cba64e2007-08-18 00:00:32 +0000772
Devang Patel4e2075d2007-08-24 05:36:56 +0000773 // Finally this split condition is safe only if merge point for
774 // split condition branch is loop latch. This check along with previous
775 // check, to ensure that exit condition is in either loop latch or header,
776 // filters all loops with non-empty loop body between merge point
777 // and exit condition.
778 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
779 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
780 if (Succ0DF->second.count(Latch))
781 return true;
782
783 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
784 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
785 if (Succ1DF->second.count(Latch))
786 return true;
787
788 return false;
Devang Pateld662ace2007-08-22 18:27:01 +0000789}
790
Devang Pateledea5b32007-08-25 00:56:38 +0000791/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
792/// based on split value.
793void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
794
Devang Patel5bc8a2c2007-09-11 00:12:56 +0000795 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
796 ICmpInst::Predicate SP = SC->getPredicate();
Devang Pateledea5b32007-08-25 00:56:38 +0000797 const Type *Ty = SD.SplitValue->getType();
798 bool Sign = ExitCondition->isSignedPredicate();
799 BasicBlock *Preheader = L->getLoopPreheader();
800 Instruction *PHTerminator = Preheader->getTerminator();
801
802 // Initially use split value as upper loop bound for first loop and lower loop
803 // bound for second loop.
804 Value *AEV = SD.SplitValue;
805 Value *BSV = SD.SplitValue;
806
807 switch (ExitCondition->getPredicate()) {
808 case ICmpInst::ICMP_SGT:
809 case ICmpInst::ICMP_UGT:
810 case ICmpInst::ICMP_SGE:
811 case ICmpInst::ICMP_UGE:
812 default:
813 assert (0 && "Unexpected exit condition predicate");
814
815 case ICmpInst::ICMP_SLT:
816 case ICmpInst::ICMP_ULT:
817 {
818 switch (SP) {
819 case ICmpInst::ICMP_SLT:
820 case ICmpInst::ICMP_ULT:
821 //
822 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
823 //
824 // is transformed into
825 // AEV = BSV = SV
826 // for (i = LB; i < min(UB, AEV); ++i)
827 // A;
828 // for (i = max(LB, BSV); i < UB; ++i);
829 // B;
830 break;
831 case ICmpInst::ICMP_SLE:
832 case ICmpInst::ICMP_ULE:
833 {
834 //
835 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
836 //
837 // is transformed into
838 //
839 // AEV = SV + 1
840 // BSV = SV + 1
841 // for (i = LB; i < min(UB, AEV); ++i)
842 // A;
843 // for (i = max(LB, BSV); i < UB; ++i)
844 // B;
845 BSV = BinaryOperator::createAdd(SD.SplitValue,
846 ConstantInt::get(Ty, 1, Sign),
847 "lsplit.add", PHTerminator);
848 AEV = BSV;
849 }
850 break;
851 case ICmpInst::ICMP_SGE:
852 case ICmpInst::ICMP_UGE:
853 //
854 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
855 //
856 // is transformed into
857 // AEV = BSV = SV
858 // for (i = LB; i < min(UB, AEV); ++i)
859 // B;
860 // for (i = max(BSV, LB); i < UB; ++i)
861 // A;
862 break;
863 case ICmpInst::ICMP_SGT:
864 case ICmpInst::ICMP_UGT:
865 {
866 //
867 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
868 //
869 // is transformed into
870 //
871 // BSV = AEV = SV + 1
872 // for (i = LB; i < min(UB, AEV); ++i)
873 // B;
874 // for (i = max(LB, BSV); i < UB; ++i)
875 // A;
876 BSV = BinaryOperator::createAdd(SD.SplitValue,
877 ConstantInt::get(Ty, 1, Sign),
878 "lsplit.add", PHTerminator);
879 AEV = BSV;
880 }
881 break;
882 default:
883 assert (0 && "Unexpected split condition predicate");
884 break;
885 } // end switch (SP)
886 }
887 break;
888 case ICmpInst::ICMP_SLE:
889 case ICmpInst::ICMP_ULE:
890 {
891 switch (SP) {
892 case ICmpInst::ICMP_SLT:
893 case ICmpInst::ICMP_ULT:
894 //
895 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
896 //
897 // is transformed into
898 // AEV = SV - 1;
899 // BSV = SV;
900 // for (i = LB; i <= min(UB, AEV); ++i)
901 // A;
902 // for (i = max(LB, BSV); i <= UB; ++i)
903 // B;
904 AEV = BinaryOperator::createSub(SD.SplitValue,
905 ConstantInt::get(Ty, 1, Sign),
906 "lsplit.sub", PHTerminator);
907 break;
908 case ICmpInst::ICMP_SLE:
909 case ICmpInst::ICMP_ULE:
910 //
911 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
912 //
913 // is transformed into
914 // AEV = SV;
915 // BSV = SV + 1;
916 // for (i = LB; i <= min(UB, AEV); ++i)
917 // A;
918 // for (i = max(LB, BSV); i <= UB; ++i)
919 // B;
920 BSV = BinaryOperator::createAdd(SD.SplitValue,
921 ConstantInt::get(Ty, 1, Sign),
922 "lsplit.add", PHTerminator);
923 break;
924 case ICmpInst::ICMP_SGT:
925 case ICmpInst::ICMP_UGT:
926 //
927 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
928 //
929 // is transformed into
930 // AEV = SV;
931 // BSV = SV + 1;
932 // for (i = LB; i <= min(AEV, UB); ++i)
933 // B;
934 // for (i = max(LB, BSV); i <= UB; ++i)
935 // A;
936 BSV = BinaryOperator::createAdd(SD.SplitValue,
937 ConstantInt::get(Ty, 1, Sign),
938 "lsplit.add", PHTerminator);
939 break;
940 case ICmpInst::ICMP_SGE:
941 case ICmpInst::ICMP_UGE:
942 // ** TODO **
943 //
944 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
945 //
946 // is transformed into
947 // AEV = SV - 1;
948 // BSV = SV;
949 // for (i = LB; i <= min(AEV, UB); ++i)
950 // B;
951 // for (i = max(LB, BSV); i <= UB; ++i)
952 // A;
953 AEV = BinaryOperator::createSub(SD.SplitValue,
954 ConstantInt::get(Ty, 1, Sign),
955 "lsplit.sub", PHTerminator);
956 break;
957 default:
958 assert (0 && "Unexpected split condition predicate");
959 break;
960 } // end switch (SP)
961 }
962 break;
963 }
964
965 // Calculate ALoop induction variable's new exiting value and
966 // BLoop induction variable's new starting value. Calculuate these
967 // values in original loop's preheader.
968 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
969 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Pateledea5b32007-08-25 00:56:38 +0000970 Value *C1 = new ICmpInst(Sign ?
971 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
972 AEV,
973 ExitCondition->getOperand(ExitValueNum),
974 "lsplit.ev", PHTerminator);
975 SD.A_ExitValue = new SelectInst(C1, AEV,
976 ExitCondition->getOperand(ExitValueNum),
977 "lsplit.ev", PHTerminator);
978
979 Value *C2 = new ICmpInst(Sign ?
980 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
981 BSV, StartValue, "lsplit.sv",
982 PHTerminator);
983 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
984 "lsplit.sv", PHTerminator);
985}
986
Devang Pateld662ace2007-08-22 18:27:01 +0000987/// splitLoop - Split current loop L in two loops using split information
988/// SD. Update dominator information. Maintain LCSSA form.
989bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
990
991 if (!safeSplitCondition(SD))
992 return false;
993
Devang Patela0ac7262007-08-22 19:33:29 +0000994 // After loop is cloned there are two loops.
995 //
996 // First loop, referred as ALoop, executes first part of loop's iteration
997 // space split. Second loop, referred as BLoop, executes remaining
998 // part of loop's iteration space.
999 //
1000 // ALoop's exit edge enters BLoop's header through a forwarding block which
1001 // acts as a BLoop's preheader.
Devang Pateledea5b32007-08-25 00:56:38 +00001002 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateld662ace2007-08-22 18:27:01 +00001003
Devang Pateledea5b32007-08-25 00:56:38 +00001004 // Calculate ALoop induction variable's new exiting value and
1005 // BLoop induction variable's new starting value.
1006 calculateLoopBounds(SD);
Devang Patel901f67e2007-08-10 18:07:13 +00001007
Devang Patela0ac7262007-08-22 19:33:29 +00001008 //[*] Clone loop.
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001009 DenseMap<const Value *, Value *> ValueMap;
Devang Patela0ac7262007-08-22 19:33:29 +00001010 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Patelcd71bed2007-08-25 02:39:24 +00001011 Loop *ALoop = L;
Devang Patela0ac7262007-08-22 19:33:29 +00001012 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001013
Devang Patela0ac7262007-08-22 19:33:29 +00001014 //[*] ALoop's exiting edge BLoop's header.
1015 // ALoop's original exit block becomes BLoop's exit block.
1016 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1017 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1018 BranchInst *A_ExitInsn =
1019 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1020 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1021 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1022 if (L->contains(B_ExitBlock)) {
1023 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1024 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patel59e0c062007-08-14 01:30:57 +00001025 } else
Devang Patela0ac7262007-08-22 19:33:29 +00001026 A_ExitInsn->setSuccessor(1, B_Header);
1027
1028 //[*] Update ALoop's exit value using new exit value.
Devang Pateledea5b32007-08-25 00:56:38 +00001029 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel2a24ff32007-08-21 21:12:02 +00001030
Devang Patela0ac7262007-08-22 19:33:29 +00001031 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1032 // original loop's preheader. Add incoming PHINode values from
1033 // ALoop's exiting block. Update BLoop header's domiantor info.
1034
Devang Patel59e0c062007-08-14 01:30:57 +00001035 // Collect inverse map of Header PHINodes.
1036 DenseMap<Value *, Value *> InverseMap;
1037 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1038 BE = L->getHeader()->end(); BI != BE; ++BI) {
1039 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1040 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1041 InverseMap[PNClone] = PN;
1042 } else
1043 break;
1044 }
Devang Pateledea5b32007-08-25 00:56:38 +00001045
Devang Patela0ac7262007-08-22 19:33:29 +00001046 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001047 BI != BE; ++BI) {
1048 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001049 // Remove incoming value from original preheader.
1050 PN->removeIncomingValue(Preheader);
1051
1052 // Add incoming value from A_ExitingBlock.
1053 if (PN == B_IndVar)
Devang Pateledea5b32007-08-25 00:56:38 +00001054 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001055 else {
1056 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela0ac7262007-08-22 19:33:29 +00001057 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1058 PN->addIncoming(V2, A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001059 }
1060 } else
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001061 break;
1062 }
Devang Patela0ac7262007-08-22 19:33:29 +00001063 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1064 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel2a24ff32007-08-21 21:12:02 +00001065
Devang Patela0ac7262007-08-22 19:33:29 +00001066 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1067 // block. Remove incoming PHINode values from ALoop's exiting block.
1068 // Add new incoming values from BLoop's incoming exiting value.
1069 // Update BLoop exit block's dominator info..
1070 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1071 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patel59e0c062007-08-14 01:30:57 +00001072 BI != BE; ++BI) {
1073 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001074 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1075 B_ExitingBlock);
1076 PN->removeIncomingValue(A_ExitingBlock);
Devang Patel59e0c062007-08-14 01:30:57 +00001077 } else
1078 break;
1079 }
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001080
Devang Patela0ac7262007-08-22 19:33:29 +00001081 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1082 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelb7639612007-08-13 22:13:24 +00001083
Devang Patela0ac7262007-08-22 19:33:29 +00001084 //[*] Split ALoop's exit edge. This creates a new block which
1085 // serves two purposes. First one is to hold PHINode defnitions
1086 // to ensure that ALoop's LCSSA form. Second use it to act
1087 // as a preheader for BLoop.
1088 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel901f67e2007-08-10 18:07:13 +00001089
Devang Patela0ac7262007-08-22 19:33:29 +00001090 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1091 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1092 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel7ef89b82007-08-21 19:47:46 +00001093 BI != BE; ++BI) {
1094 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela0ac7262007-08-22 19:33:29 +00001095 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001096 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela0ac7262007-08-22 19:33:29 +00001097 newPHI->addIncoming(V1, A_ExitingBlock);
1098 A_ExitBlock->getInstList().push_front(newPHI);
1099 PN->removeIncomingValue(A_ExitBlock);
1100 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel7ef89b82007-08-21 19:47:46 +00001101 } else
1102 break;
1103 }
1104
Devang Patela0ac7262007-08-22 19:33:29 +00001105 //[*] Eliminate split condition's inactive branch from ALoop.
1106 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1107 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001108 BasicBlock *A_InactiveBranch = NULL;
1109 BasicBlock *A_ActiveBranch = NULL;
1110 if (SD.UseTrueBranchFirst) {
1111 A_ActiveBranch = A_BR->getSuccessor(0);
1112 A_InactiveBranch = A_BR->getSuccessor(1);
1113 } else {
1114 A_ActiveBranch = A_BR->getSuccessor(1);
1115 A_InactiveBranch = A_BR->getSuccessor(0);
1116 }
Devang Patel4e585c72007-08-24 19:32:26 +00001117 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001118 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1119
1120 //[*] Eliminate split condition's inactive branch in from BLoop.
1121 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1122 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel7f526a82007-08-24 06:17:19 +00001123 BasicBlock *B_InactiveBranch = NULL;
1124 BasicBlock *B_ActiveBranch = NULL;
1125 if (SD.UseTrueBranchFirst) {
1126 B_ActiveBranch = B_BR->getSuccessor(1);
1127 B_InactiveBranch = B_BR->getSuccessor(0);
1128 } else {
1129 B_ActiveBranch = B_BR->getSuccessor(0);
1130 B_InactiveBranch = B_BR->getSuccessor(1);
1131 }
Devang Patel4e585c72007-08-24 19:32:26 +00001132 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela0ac7262007-08-22 19:33:29 +00001133 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1134
Devang Patelcd71bed2007-08-25 02:39:24 +00001135 BasicBlock *A_Header = L->getHeader();
1136 if (A_ExitingBlock == A_Header)
1137 return true;
1138
1139 //[*] Move exit condition into split condition block to avoid
1140 // executing dead loop iteration.
1141 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1142 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1143 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1144
1145 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel5bc8a2c2007-09-11 00:12:56 +00001146 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1147 ALoop);
Devang Patelcd71bed2007-08-25 02:39:24 +00001148
1149 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1150 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1151
Devang Patel6a2d6ef2007-08-12 07:02:51 +00001152 return true;
Devang Patelbc5fe632007-08-07 00:25:56 +00001153}
Devang Patelcd71bed2007-08-25 02:39:24 +00001154
1155// moveExitCondition - Move exit condition EC into split condition block CondBB.
1156void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1157 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1158 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1159
1160 BasicBlock *ExitingBB = EC->getParent();
1161 Instruction *CurrentBR = CondBB->getTerminator();
1162
1163 // Move exit condition into split condition block.
1164 EC->moveBefore(CurrentBR);
1165 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1166
1167 // Move exiting block's branch into split condition block. Update its branch
1168 // destination.
1169 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1170 ExitingBR->moveBefore(CurrentBR);
1171 if (ExitingBR->getSuccessor(0) == ExitBB)
1172 ExitingBR->setSuccessor(1, ActiveBB);
1173 else
1174 ExitingBR->setSuccessor(0, ActiveBB);
1175
1176 // Remove split condition and current split condition branch.
1177 SC->eraseFromParent();
1178 CurrentBR->eraseFromParent();
1179
1180 // Connect exiting block to split condition block.
1181 new BranchInst(CondBB, ExitingBB);
1182
1183 // Update PHINodes
1184 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1185
1186 // Fix dominator info.
1187 // ExitBB is now dominated by CondBB
1188 DT->changeImmediateDominator(ExitBB, CondBB);
1189 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1190
1191 // Basicblocks dominated by ActiveBB may have ExitingBB or
1192 // a basic block outside the loop in their DF list. If so,
1193 // replace it with CondBB.
1194 DomTreeNode *Node = DT->getNode(ActiveBB);
1195 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1196 DI != DE; ++DI) {
1197 BasicBlock *BB = DI->getBlock();
1198 DominanceFrontier::iterator BBDF = DF->find(BB);
1199 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1200 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1201 while (DomSetI != DomSetE) {
1202 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1203 ++DomSetI;
1204 BasicBlock *DFBB = *CurrentItr;
1205 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1206 BBDF->second.erase(DFBB);
1207 BBDF->second.insert(CondBB);
1208 }
1209 }
1210 }
1211}
1212
1213/// updatePHINodes - CFG has been changed.
1214/// Before
1215/// - ExitBB's single predecessor was Latch
1216/// - Latch's second successor was Header
1217/// Now
1218/// - ExitBB's single predecessor was Header
1219/// - Latch's one and only successor was Header
1220///
1221/// Update ExitBB PHINodes' to reflect this change.
1222void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1223 BasicBlock *Header,
1224 PHINode *IV, Instruction *IVIncrement) {
1225
1226 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1227 BI != BE; ++BI) {
1228 PHINode *PN = dyn_cast<PHINode>(BI);
1229 if (!PN)
1230 break;
1231
1232 Value *V = PN->getIncomingValueForBlock(Latch);
1233 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1234 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1235 // (i.e. PN :)).
1236 // The second use is in Header and it is new incoming value for PN.
1237 PHINode *U1 = NULL;
1238 PHINode *U2 = NULL;
1239 Value *NewV = NULL;
1240 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1241 UI != E; ++UI) {
1242 if (!U1)
1243 U1 = cast<PHINode>(*UI);
1244 else if (!U2)
1245 U2 = cast<PHINode>(*UI);
1246 else
1247 assert ( 0 && "Unexpected third use of this PHINode");
1248 }
1249 assert (U1 && U2 && "Unable to find two uses");
1250
1251 if (U1->getParent() == Header)
1252 NewV = U1;
1253 else
1254 NewV = U2;
1255 PN->addIncoming(NewV, Header);
1256
1257 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1258 // If this instruction is IVIncrement then IV is new incoming value
1259 // from header otherwise this instruction must be incoming value from
1260 // header because loop is in LCSSA form.
1261 if (PHI == IVIncrement)
1262 PN->addIncoming(IV, Header);
1263 else
1264 PN->addIncoming(V, Header);
1265 } else
1266 // Otherwise this is an incoming value from header because loop is in
1267 // LCSSA form.
1268 PN->addIncoming(V, Header);
1269
1270 // Remove incoming value from Latch.
1271 PN->removeIncomingValue(Latch);
1272 }
1273}