blob: da6f076a9a65775d1c4f71d411a30c824b01479d [file] [log] [blame]
Devang Patelfee76bd2007-08-07 00:25:56 +00001//===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelfee76bd2007-08-07 00:25:56 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Index Splitting Pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "loop-index-split"
15
Devang Patelfee76bd2007-08-07 00:25:56 +000016#include "llvm/Transforms/Scalar.h"
17#include "llvm/Analysis/LoopPass.h"
18#include "llvm/Analysis/ScalarEvolutionExpander.h"
Devang Patel787a7132007-08-08 21:39:47 +000019#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000022#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000023#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-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 Patel423c8b22007-08-10 18:07:13 +000046 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000047 AU.addPreserved<LoopInfo>();
48 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000050 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000051 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000052 AU.addPreserved<DominatorTree>();
53 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000054 }
55
56 private:
Devang Patel71554b82007-08-08 21:02:17 +000057
58 class SplitInfo {
59 public:
Devang Patel4259fe32007-08-24 06:17:19 +000060 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
Devang Patel4a69da92007-08-25 00:56:38 +000061 UseTrueBranchFirst(true), A_ExitValue(NULL),
62 B_StartValue(NULL) {}
Devang Patelc9d123d2007-08-09 01:39:01 +000063
Devang Patel71554b82007-08-08 21:02:17 +000064 // Induction variable's range is split at this value.
65 Value *SplitValue;
66
Devang Patel4f12c5f2007-09-11 00:12:56 +000067 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
Devang Patel71554b82007-08-08 21:02:17 +000069
Devang Patel4259fe32007-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 Patel4a69da92007-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 Patel9021c702007-08-08 21:18:27 +000080 // Clear split info.
81 void clear() {
Devang Patel9021c702007-08-08 21:18:27 +000082 SplitValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000083 SplitCondition = NULL;
Devang Patel4259fe32007-08-24 06:17:19 +000084 UseTrueBranchFirst = true;
Devang Patel4a69da92007-08-25 00:56:38 +000085 A_ExitValue = NULL;
86 B_StartValue = NULL;
Devang Patel9021c702007-08-08 21:18:27 +000087 }
Devang Patelc9d123d2007-08-09 01:39:01 +000088
Devang Patel71554b82007-08-08 21:02:17 +000089 };
Devang Patelbacf5192007-08-10 00:33:50 +000090
Devang Patel71554b82007-08-08 21:02:17 +000091 private:
Devang Pateld35ed2c2007-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 Patelfee76bd2007-08-07 00:25:56 +000099 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
101
Devang Patelbacf5192007-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 Patelfee76bd2007-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 Patel423c8b22007-08-10 18:07:13 +0000113 bool processOneIterationLoop(SplitInfo &SD);
Devang Patel5279d062007-09-17 20:39:48 +0000114
115 void updateLoopBounds(ICmpInst *CI);
116 /// updateLoopIterationSpace - Current loop body is covered by an AND
117 /// instruction whose operands compares induction variables with loop
118 /// invariants. If possible, hoist this check outside the loop by
119 /// updating appropriate start and end values for induction variable.
120 bool updateLoopIterationSpace(SplitInfo &SD);
121
Devang Patel9704fcf2007-08-08 22:25:28 +0000122 /// If loop header includes loop variant instruction operands then
123 /// this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000124 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000125
Devang Patel1cc2ec82007-08-20 23:51:18 +0000126 /// If Exiting block includes loop variant instructions then this
Devang Patel9704fcf2007-08-08 22:25:28 +0000127 /// loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000128 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000129
Devang Patela6a86632007-08-14 18:35:57 +0000130 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131 /// This routine is used to remove split condition's dead branch, dominated by
132 /// DeadBB. LiveBB dominates split conidition's other branch.
133 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel98147a32007-08-12 07:02:51 +0000134
Devang Pateldc523952007-08-22 18:27:01 +0000135 /// safeSplitCondition - Return true if it is possible to
136 /// split loop using given split condition.
137 bool safeSplitCondition(SplitInfo &SD);
138
Devang Patel4a69da92007-08-25 00:56:38 +0000139 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140 /// based on split value.
141 void calculateLoopBounds(SplitInfo &SD);
142
Devang Pateld79faee2007-08-25 02:39:24 +0000143 /// updatePHINodes - CFG has been changed.
144 /// Before
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
147 /// Now
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
150 ///
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
153 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000155
156 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159 PHINode *IV, Instruction *IVAdd, Loop *LP);
160
Devang Pateldc523952007-08-22 18:27:01 +0000161 /// splitLoop - Split current loop L in two loops using split information
162 /// SD. Update dominator information. Maintain LCSSA form.
Devang Patel71554b82007-08-08 21:02:17 +0000163 bool splitLoop(SplitInfo &SD);
Devang Patelfee76bd2007-08-07 00:25:56 +0000164
Devang Patelbacf5192007-08-10 00:33:50 +0000165 void initialize() {
166 IndVar = NULL;
167 IndVarIncrement = NULL;
168 ExitCondition = NULL;
Devang Patel98147a32007-08-12 07:02:51 +0000169 StartValue = NULL;
170 ExitValueNum = 0;
171 SplitData.clear();
Devang Patelbacf5192007-08-10 00:33:50 +0000172 }
173
Devang Patelfee76bd2007-08-07 00:25:56 +0000174 private:
175
176 // Current Loop.
177 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000178 LPPassManager *LPM;
179 LoopInfo *LI;
Devang Patelfee76bd2007-08-07 00:25:56 +0000180 ScalarEvolution *SE;
Devang Patel9704fcf2007-08-08 22:25:28 +0000181 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000182 DominanceFrontier *DF;
Devang Patel71554b82007-08-08 21:02:17 +0000183 SmallVector<SplitInfo, 4> SplitData;
Devang Patelbacf5192007-08-10 00:33:50 +0000184
185 // Induction variable whose range is being split by this transformation.
186 PHINode *IndVar;
187 Instruction *IndVarIncrement;
188
189 // Loop exit condition.
190 ICmpInst *ExitCondition;
191
192 // Induction variable's initial value.
193 Value *StartValue;
194
Devang Patel98147a32007-08-12 07:02:51 +0000195 // Induction variable's final loop exit value operand number in exit condition..
196 unsigned ExitValueNum;
Devang Patelfee76bd2007-08-07 00:25:56 +0000197 };
198
199 char LoopIndexSplit::ID = 0;
200 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
201}
202
203LoopPass *llvm::createLoopIndexSplitPass() {
204 return new LoopIndexSplit();
205}
206
207// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000208bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000209 bool Changed = false;
210 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000211 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000212
Devang Patel3fe4f212007-08-15 02:14:55 +0000213 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000214 if (!L->getSubLoops().empty())
215 return false;
216
Devang Patelfee76bd2007-08-07 00:25:56 +0000217 SE = &getAnalysis<ScalarEvolution>();
Devang Patel9704fcf2007-08-08 22:25:28 +0000218 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000219 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000220 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000221
Devang Patelbacf5192007-08-10 00:33:50 +0000222 initialize();
223
224 findLoopConditionals();
225
226 if (!ExitCondition)
227 return false;
228
Devang Patelfee76bd2007-08-07 00:25:56 +0000229 findSplitCondition();
230
Devang Patel71554b82007-08-08 21:02:17 +0000231 if (SplitData.empty())
Devang Patelfee76bd2007-08-07 00:25:56 +0000232 return false;
233
Devang Patel71554b82007-08-08 21:02:17 +0000234 // First see if it is possible to eliminate loop itself or not.
David Greenea022e3f2008-04-02 18:24:46 +0000235 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
236 SI != SplitData.end();) {
Devang Patel71554b82007-08-08 21:02:17 +0000237 SplitInfo &SD = *SI;
Devang Patel4f12c5f2007-09-11 00:12:56 +0000238 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
Devang Patel5279d062007-09-17 20:39:48 +0000239 if (SD.SplitCondition->getOpcode() == Instruction::And) {
240 Changed = updateLoopIterationSpace(SD);
241 if (Changed) {
242 ++NumIndexSplit;
243 // If is loop is eliminated then nothing else to do here.
244 return Changed;
245 } else {
246 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000247 SI = SplitData.erase(Delete_SI);
Devang Patel5279d062007-09-17 20:39:48 +0000248 }
249 }
250 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel423c8b22007-08-10 18:07:13 +0000251 Changed = processOneIterationLoop(SD);
Devang Patel71554b82007-08-08 21:02:17 +0000252 if (Changed) {
253 ++NumIndexSplit;
254 // If is loop is eliminated then nothing else to do here.
255 return Changed;
Devang Pateld651f652007-08-20 20:24:15 +0000256 } else {
257 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
David Greenea022e3f2008-04-02 18:24:46 +0000258 SI = SplitData.erase(Delete_SI);
Devang Patel71554b82007-08-08 21:02:17 +0000259 }
Devang Pateld651f652007-08-20 20:24:15 +0000260 } else
261 ++SI;
Devang Patel71554b82007-08-08 21:02:17 +0000262 }
263
Devang Patel4259fe32007-08-24 06:17:19 +0000264 if (SplitData.empty())
265 return false;
266
Devang Patel9704fcf2007-08-08 22:25:28 +0000267 // Split most profitiable condition.
Devang Patel7237d112007-08-24 05:21:13 +0000268 // FIXME : Implement cost analysis.
269 unsigned MostProfitableSDIndex = 0;
270 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel9704fcf2007-08-08 22:25:28 +0000271
Devang Patelfee76bd2007-08-07 00:25:56 +0000272 if (Changed)
273 ++NumIndexSplit;
Devang Patel71554b82007-08-08 21:02:17 +0000274
Devang Patelfee76bd2007-08-07 00:25:56 +0000275 return Changed;
276}
277
Devang Patelc9d123d2007-08-09 01:39:01 +0000278/// Return true if V is a induction variable or induction variable's
279/// increment for loop L.
Devang Patelbacf5192007-08-10 00:33:50 +0000280void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000281
282 Instruction *I = dyn_cast<Instruction>(V);
283 if (!I)
Devang Patelbacf5192007-08-10 00:33:50 +0000284 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000285
286 // Check if I is a phi node from loop header or not.
287 if (PHINode *PN = dyn_cast<PHINode>(V)) {
288 if (PN->getParent() == L->getHeader()) {
Devang Patelbacf5192007-08-10 00:33:50 +0000289 IndVar = PN;
290 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000291 }
292 }
293
294 // Check if I is a add instruction whose one operand is
295 // phi node from loop header and second operand is constant.
296 if (I->getOpcode() != Instruction::Add)
Devang Patelbacf5192007-08-10 00:33:50 +0000297 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000298
299 Value *Op0 = I->getOperand(0);
300 Value *Op1 = I->getOperand(1);
301
Devang Patelc840da12008-01-29 02:20:41 +0000302 if (PHINode *PN = dyn_cast<PHINode>(Op0))
303 if (PN->getParent() == L->getHeader())
304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
305 if (CI->isOne()) {
306 IndVar = PN;
307 IndVarIncrement = I;
308 return;
309 }
310
311 if (PHINode *PN = dyn_cast<PHINode>(Op1))
312 if (PN->getParent() == L->getHeader())
313 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
314 if (CI->isOne()) {
315 IndVar = PN;
316 IndVarIncrement = I;
317 return;
318 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000319
Devang Patelbacf5192007-08-10 00:33:50 +0000320 return;
321}
322
323// Find loop's exit condition and associated induction variable.
324void LoopIndexSplit::findLoopConditionals() {
325
Devang Patel1cc2ec82007-08-20 23:51:18 +0000326 BasicBlock *ExitingBlock = NULL;
Devang Patelbacf5192007-08-10 00:33:50 +0000327
328 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
329 I != E; ++I) {
330 BasicBlock *BB = *I;
331 if (!L->isLoopExit(BB))
332 continue;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000333 if (ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000334 return;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000335 ExitingBlock = BB;
Devang Patelbacf5192007-08-10 00:33:50 +0000336 }
337
Devang Patel1cc2ec82007-08-20 23:51:18 +0000338 if (!ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000339 return;
Devang Patelb88e4202007-08-24 05:36:56 +0000340
341 // If exiting block is neither loop header nor loop latch then this loop is
342 // not suitable.
343 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
344 return;
345
Devang Patelbacf5192007-08-10 00:33:50 +0000346 // If exit block's terminator is conditional branch inst then we have found
347 // exit condition.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000348 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patelbacf5192007-08-10 00:33:50 +0000349 if (!BR || BR->isUnconditional())
350 return;
351
352 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
353 if (!CI)
354 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000355
Bill Wendlingc6849102007-09-14 01:13:55 +0000356 // FIXME
Devang Patelbabbe272007-09-19 00:28:47 +0000357 if (CI->getPredicate() == ICmpInst::ICMP_EQ
Bill Wendlingc6849102007-09-14 01:13:55 +0000358 || CI->getPredicate() == ICmpInst::ICMP_NE)
359 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000360
Devang Patelbacf5192007-08-10 00:33:50 +0000361 ExitCondition = CI;
362
363 // Exit condition's one operand is loop invariant exit value and second
364 // operand is SCEVAddRecExpr based on induction variable.
365 Value *V0 = CI->getOperand(0);
366 Value *V1 = CI->getOperand(1);
367
368 SCEVHandle SH0 = SE->getSCEV(V0);
369 SCEVHandle SH1 = SE->getSCEV(V1);
370
371 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel98147a32007-08-12 07:02:51 +0000372 ExitValueNum = 0;
Devang Patelbacf5192007-08-10 00:33:50 +0000373 findIndVar(V1, L);
374 }
375 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel98147a32007-08-12 07:02:51 +0000376 ExitValueNum = 1;
Devang Patelbacf5192007-08-10 00:33:50 +0000377 findIndVar(V0, L);
378 }
379
Devang Patel98147a32007-08-12 07:02:51 +0000380 if (!IndVar)
Devang Patelbacf5192007-08-10 00:33:50 +0000381 ExitCondition = NULL;
382 else if (IndVar) {
383 BasicBlock *Preheader = L->getLoopPreheader();
384 StartValue = IndVar->getIncomingValueForBlock(Preheader);
385 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000386}
387
Devang Patelfee76bd2007-08-07 00:25:56 +0000388/// Find condition inside a loop that is suitable candidate for index split.
389void LoopIndexSplit::findSplitCondition() {
390
Devang Patel71554b82007-08-08 21:02:17 +0000391 SplitInfo SD;
Devang Patelc9d123d2007-08-09 01:39:01 +0000392 // Check all basic block's terminators.
Devang Patelc9d123d2007-08-09 01:39:01 +0000393 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
394 I != E; ++I) {
Devang Patel964be452007-09-11 00:23:56 +0000395 SD.clear();
Devang Patelc9d123d2007-08-09 01:39:01 +0000396 BasicBlock *BB = *I;
Devang Patelfee76bd2007-08-07 00:25:56 +0000397
Devang Patelc9d123d2007-08-09 01:39:01 +0000398 // If this basic block does not terminate in a conditional branch
399 // then terminator is not a suitable split condition.
400 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
401 if (!BR)
402 continue;
403
404 if (BR->isUnconditional())
Devang Patelfee76bd2007-08-07 00:25:56 +0000405 continue;
406
Devang Patel5279d062007-09-17 20:39:48 +0000407 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
408 if (AndI->getOpcode() == Instruction::And) {
409 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
410 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
411
412 if (!Op0 || !Op1)
413 continue;
414
415 if (!safeICmpInst(Op0, SD))
416 continue;
417 SD.clear();
418 if (!safeICmpInst(Op1, SD))
419 continue;
420 SD.clear();
421 SD.SplitCondition = AndI;
422 SplitData.push_back(SD);
423 continue;
424 }
425 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000426 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patelbacf5192007-08-10 00:33:50 +0000427 if (!CI || CI == ExitCondition)
Devang Patelba32a5f2007-09-10 23:57:58 +0000428 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000429
Devang Patelc830aee2007-08-24 06:02:25 +0000430 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patelba32a5f2007-09-10 23:57:58 +0000431 continue;
Devang Patelc830aee2007-08-24 06:02:25 +0000432
Devang Patel4259fe32007-08-24 06:17:19 +0000433 // If split condition predicate is GT or GE then first execute
434 // false branch of split condition.
Devang Patelc3957d12007-09-11 01:10:45 +0000435 if (CI->getPredicate() == ICmpInst::ICMP_UGT
436 || CI->getPredicate() == ICmpInst::ICMP_SGT
437 || CI->getPredicate() == ICmpInst::ICMP_UGE
438 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel4259fe32007-08-24 06:17:19 +0000439 SD.UseTrueBranchFirst = false;
440
Devang Patelc9d123d2007-08-09 01:39:01 +0000441 // If one operand is loop invariant and second operand is SCEVAddRecExpr
442 // based on induction variable then CI is a candidate split condition.
Devang Pateld35ed2c2007-09-11 00:42:56 +0000443 if (safeICmpInst(CI, SD))
444 SplitData.push_back(SD);
445 }
446}
Devang Patelc9d123d2007-08-09 01:39:01 +0000447
Devang Pateld35ed2c2007-09-11 00:42:56 +0000448// safeIcmpInst - CI is considered safe instruction if one of the operand
449// is SCEVAddRecExpr based on induction variable and other operand is
450// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
451// and return true;
452bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000453
Devang Pateld35ed2c2007-09-11 00:42:56 +0000454 Value *V0 = CI->getOperand(0);
455 Value *V1 = CI->getOperand(1);
456
457 SCEVHandle SH0 = SE->getSCEV(V0);
458 SCEVHandle SH1 = SE->getSCEV(V1);
459
460 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
461 SD.SplitValue = V0;
462 SD.SplitCondition = CI;
463 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
464 if (PN == IndVar)
465 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000466 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000467 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
468 if (IndVarIncrement && IndVarIncrement == Insn)
469 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000470 }
471 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000472 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
473 SD.SplitValue = V1;
474 SD.SplitCondition = CI;
475 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
476 if (PN == IndVar)
477 return true;
478 }
479 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
480 if (IndVarIncrement && IndVarIncrement == Insn)
481 return true;
482 }
483 }
484
485 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000486}
487
488/// processOneIterationLoop - Current loop L contains compare instruction
489/// that compares induction variable, IndVar, against loop invariant. If
490/// entire (i.e. meaningful) loop body is dominated by this compare
491/// instruction then loop body is executed only once. In such case eliminate
492/// loop structure surrounding this loop body. For example,
493/// for (int i = start; i < end; ++i) {
494/// if ( i == somevalue) {
495/// loop_body
496/// }
497/// }
498/// can be transformed into
499/// if (somevalue >= start && somevalue < end) {
500/// i = somevalue;
501/// loop_body
502/// }
Devang Patel423c8b22007-08-10 18:07:13 +0000503bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000504
505 BasicBlock *Header = L->getHeader();
506
507 // First of all, check if SplitCondition dominates entire loop body
508 // or not.
509
510 // If SplitCondition is not in loop header then this loop is not suitable
511 // for this transformation.
Devang Patel71554b82007-08-08 21:02:17 +0000512 if (SD.SplitCondition->getParent() != Header)
Devang Patelfee76bd2007-08-07 00:25:56 +0000513 return false;
514
Devang Patelfee76bd2007-08-07 00:25:56 +0000515 // If loop header includes loop variant instruction operands then
516 // this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000517 if (!safeHeader(SD, Header))
Devang Patelfee76bd2007-08-07 00:25:56 +0000518 return false;
519
Devang Patel1cc2ec82007-08-20 23:51:18 +0000520 // If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000521 // loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000522 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelfee76bd2007-08-07 00:25:56 +0000523 return false;
524
Devang Patel968eee22007-09-19 00:15:16 +0000525 // Filter loops where split condition's false branch is not empty.
526 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
527 return false;
528
Devang Patel8893ca62007-09-17 21:01:05 +0000529 // If split condition is not safe then do not process this loop.
530 // For example,
531 // for(int i = 0; i < N; i++) {
532 // if ( i == XYZ) {
533 // A;
534 // else
535 // B;
536 // }
537 // C;
538 // D;
539 // }
540 if (!safeSplitCondition(SD))
541 return false;
542
Devang Patel84ef08b2007-09-19 00:11:01 +0000543 BasicBlock *Latch = L->getLoopLatch();
544 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
545 if (!BR)
546 return false;
547
Devang Patel6a2bfda2007-08-08 01:51:27 +0000548 // Update CFG.
549
Devang Patelebc5fea2007-08-20 20:49:01 +0000550 // Replace index variable with split value in loop body. Loop body is executed
551 // only when index variable is equal to split value.
552 IndVar->replaceAllUsesWith(SD.SplitValue);
553
554 // Remove Latch to Header edge.
Devang Patel6a2bfda2007-08-08 01:51:27 +0000555 BasicBlock *LatchSucc = NULL;
Devang Patel6a2bfda2007-08-08 01:51:27 +0000556 Header->removePredecessor(Latch);
557 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
558 SI != E; ++SI) {
559 if (Header != *SI)
560 LatchSucc = *SI;
561 }
562 BR->setUnconditionalDest(LatchSucc);
563
Devang Patelfee76bd2007-08-07 00:25:56 +0000564 Instruction *Terminator = Header->getTerminator();
Devang Patelada054a2007-08-14 01:30:57 +0000565 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelfee76bd2007-08-07 00:25:56 +0000566
Devang Patelfee76bd2007-08-07 00:25:56 +0000567 // Replace split condition in header.
568 // Transform
569 // SplitCondition : icmp eq i32 IndVar, SplitValue
570 // into
571 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000572 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000573 // and i32 c1, c2
Devang Patelbacf5192007-08-10 00:33:50 +0000574 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelfee76bd2007-08-07 00:25:56 +0000575 Instruction *C1 = new ICmpInst(SignedPredicate ?
576 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel71554b82007-08-08 21:02:17 +0000577 SD.SplitValue, StartValue, "lisplit",
578 Terminator);
Devang Patelfee76bd2007-08-07 00:25:56 +0000579 Instruction *C2 = new ICmpInst(SignedPredicate ?
580 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelada054a2007-08-14 01:30:57 +0000581 SD.SplitValue, ExitValue, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000582 Terminator);
583 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
584 Terminator);
585 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
586 SD.SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000587
Devang Patelfee76bd2007-08-07 00:25:56 +0000588 // Now, clear latch block. Remove instructions that are responsible
589 // to increment induction variable.
590 Instruction *LTerminator = Latch->getTerminator();
591 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
592 LB != LE; ) {
593 Instruction *I = LB;
594 ++LB;
595 if (isa<PHINode>(I) || I == LTerminator)
596 continue;
597
Devang Patelada054a2007-08-14 01:30:57 +0000598 if (I == IndVarIncrement)
599 I->replaceAllUsesWith(ExitValue);
600 else
601 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel8431a1c2007-08-07 17:45:35 +0000602 I->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000603 }
604
Devang Patel423c8b22007-08-10 18:07:13 +0000605 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000606
607 // Update Dominator Info.
608 // Only CFG change done is to remove Latch to Header edge. This
609 // does not change dominator tree because Latch did not dominate
610 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000611 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000612 DominanceFrontier::iterator HeaderDF = DF->find(Header);
613 if (HeaderDF != DF->end())
614 DF->removeFromFrontier(HeaderDF, Header);
615
616 DominanceFrontier::iterator LatchDF = DF->find(Latch);
617 if (LatchDF != DF->end())
618 DF->removeFromFrontier(LatchDF, Header);
619 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000620 return true;
621}
622
623// If loop header includes loop variant instruction operands then
624// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patel71554b82007-08-08 21:02:17 +0000625bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000626
627 Instruction *Terminator = Header->getTerminator();
628 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
629 BI != BE; ++BI) {
630 Instruction *I = BI;
631
Devang Patelada054a2007-08-14 01:30:57 +0000632 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000633 if (isa<PHINode>(I))
634 continue;
635
636 // SplitCondition itself is OK.
Devang Patel71554b82007-08-08 21:02:17 +0000637 if (I == SD.SplitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000638 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000639
Devang Patelc9d123d2007-08-09 01:39:01 +0000640 // Induction variable is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000641 if (I == IndVar)
Devang Patelc9d123d2007-08-09 01:39:01 +0000642 continue;
643
644 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000645 if (I == IndVarIncrement)
Devang Patelc9d123d2007-08-09 01:39:01 +0000646 continue;
647
Devang Patelfee76bd2007-08-07 00:25:56 +0000648 // Terminator is also harmless.
649 if (I == Terminator)
650 continue;
651
652 // Otherwise we have a instruction that may not be safe.
653 return false;
654 }
655
656 return true;
657}
658
Devang Patel1cc2ec82007-08-20 23:51:18 +0000659// If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000660// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel1cc2ec82007-08-20 23:51:18 +0000661bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
662 BasicBlock *ExitingBlock) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000663
Devang Patel1cc2ec82007-08-20 23:51:18 +0000664 for (BasicBlock::iterator BI = ExitingBlock->begin(),
665 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000666 Instruction *I = BI;
667
Devang Patelada054a2007-08-14 01:30:57 +0000668 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000669 if (isa<PHINode>(I))
670 continue;
671
Devang Patelc9d123d2007-08-09 01:39:01 +0000672 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000673 if (IndVarIncrement && IndVarIncrement == I)
Devang Patelc9d123d2007-08-09 01:39:01 +0000674 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000675
Devang Patelc9d123d2007-08-09 01:39:01 +0000676 // Check if I is induction variable increment instruction.
Devang Patela6dff2f2007-09-25 18:24:48 +0000677 if (I->getOpcode() == Instruction::Add) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000678
679 Value *Op0 = I->getOperand(0);
680 Value *Op1 = I->getOperand(1);
Devang Patelfee76bd2007-08-07 00:25:56 +0000681 PHINode *PN = NULL;
682 ConstantInt *CI = NULL;
683
684 if ((PN = dyn_cast<PHINode>(Op0))) {
685 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000686 if (CI->isOne()) {
687 if (!IndVarIncrement && PN == IndVar)
688 IndVarIncrement = I;
689 // else this is another loop induction variable
690 continue;
691 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000692 } else
693 if ((PN = dyn_cast<PHINode>(Op1))) {
694 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000695 if (CI->isOne()) {
696 if (!IndVarIncrement && PN == IndVar)
697 IndVarIncrement = I;
698 // else this is another loop induction variable
699 continue;
700 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000701 }
Devang Patela6dff2f2007-09-25 18:24:48 +0000702 }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000703
Devang Patelfee76bd2007-08-07 00:25:56 +0000704 // I is an Exit condition if next instruction is block terminator.
705 // Exit condition is OK if it compares loop invariant exit value,
706 // which is checked below.
Devang Patel002fe252007-08-07 23:17:52 +0000707 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbacf5192007-08-10 00:33:50 +0000708 if (EC == ExitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000709 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000710 }
711
Devang Patel1cc2ec82007-08-20 23:51:18 +0000712 if (I == ExitingBlock->getTerminator())
Devang Patelbacf5192007-08-10 00:33:50 +0000713 continue;
714
Devang Patelfee76bd2007-08-07 00:25:56 +0000715 // Otherwise we have instruction that may not be safe.
716 return false;
717 }
718
Devang Patel1cc2ec82007-08-20 23:51:18 +0000719 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelfee76bd2007-08-07 00:25:56 +0000720 return true;
721}
722
Devang Patel5279d062007-09-17 20:39:48 +0000723void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
724
725 Value *V0 = CI->getOperand(0);
726 Value *V1 = CI->getOperand(1);
727 Value *NV = NULL;
728
729 SCEVHandle SH0 = SE->getSCEV(V0);
730
731 if (SH0->isLoopInvariant(L))
732 NV = V0;
733 else
734 NV = V1;
735
Devang Patel453a8442007-09-25 17:31:19 +0000736 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
737 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
738 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
739 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
740 ExitCondition->swapOperands();
741 if (ExitValueNum)
742 ExitValueNum = 0;
743 else
744 ExitValueNum = 1;
745 }
746
747 Value *NUB = NULL;
748 Value *NLB = NULL;
749 Value *UB = ExitCondition->getOperand(ExitValueNum);
750 const Type *Ty = NV->getType();
751 bool Sign = ExitCondition->isSignedPredicate();
752 BasicBlock *Preheader = L->getLoopPreheader();
753 Instruction *PHTerminator = Preheader->getTerminator();
754
755 assert (NV && "Unexpected value");
756
Devang Patel5279d062007-09-17 20:39:48 +0000757 switch (CI->getPredicate()) {
758 case ICmpInst::ICMP_ULE:
759 case ICmpInst::ICMP_SLE:
760 // for (i = LB; i < UB; ++i)
761 // if (i <= NV && ...)
762 // LOOP_BODY
763 //
764 // is transformed into
765 // NUB = min (NV+1, UB)
766 // for (i = LB; i < NUB ; ++i)
767 // LOOP_BODY
768 //
Devang Patel453a8442007-09-25 17:31:19 +0000769 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
770 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
771 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
772 "lsplit.add", PHTerminator);
773 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
774 A, UB,"lsplit,c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000775 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000776 }
777
Devang Patel5279d062007-09-17 20:39:48 +0000778 // for (i = LB; i <= UB; ++i)
779 // if (i <= NV && ...)
780 // LOOP_BODY
781 //
782 // is transformed into
783 // NUB = min (NV, UB)
784 // for (i = LB; i <= NUB ; ++i)
785 // LOOP_BODY
786 //
Devang Patel453a8442007-09-25 17:31:19 +0000787 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
788 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
789 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
790 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000791 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000792 }
Devang Patel5279d062007-09-17 20:39:48 +0000793 break;
794 case ICmpInst::ICMP_ULT:
795 case ICmpInst::ICMP_SLT:
796 // for (i = LB; i < UB; ++i)
797 // if (i < NV && ...)
798 // LOOP_BODY
799 //
800 // is transformed into
801 // NUB = min (NV, UB)
802 // for (i = LB; i < NUB ; ++i)
803 // LOOP_BODY
804 //
Devang Patel453a8442007-09-25 17:31:19 +0000805 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
806 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
807 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
808 NV, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000809 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000810 }
Devang Patel5279d062007-09-17 20:39:48 +0000811
812 // for (i = LB; i <= UB; ++i)
813 // if (i < NV && ...)
814 // LOOP_BODY
815 //
816 // is transformed into
817 // NUB = min (NV -1 , UB)
818 // for (i = LB; i <= NUB ; ++i)
819 // LOOP_BODY
820 //
Devang Patel453a8442007-09-25 17:31:19 +0000821 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
822 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
823 Value *S = BinaryOperator::createSub(NV, ConstantInt::get(Ty, 1, Sign),
824 "lsplit.add", PHTerminator);
825 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
826 S, UB, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000827 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000828 }
Devang Patel5279d062007-09-17 20:39:48 +0000829 break;
830 case ICmpInst::ICMP_UGE:
831 case ICmpInst::ICMP_SGE:
832 // for (i = LB; i (< or <=) UB; ++i)
833 // if (i >= NV && ...)
834 // LOOP_BODY
835 //
836 // is transformed into
837 // NLB = max (NV, LB)
838 // for (i = NLB; i (< or <=) UB ; ++i)
839 // LOOP_BODY
840 //
Devang Patel453a8442007-09-25 17:31:19 +0000841 {
842 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
843 NV, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000844 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000845 }
Devang Patel5279d062007-09-17 20:39:48 +0000846 break;
847 case ICmpInst::ICMP_UGT:
848 case ICmpInst::ICMP_SGT:
849 // for (i = LB; i (< or <=) UB; ++i)
850 // if (i > NV && ...)
851 // LOOP_BODY
852 //
853 // is transformed into
854 // NLB = max (NV+1, LB)
855 // for (i = NLB; i (< or <=) UB ; ++i)
856 // LOOP_BODY
857 //
Devang Patel453a8442007-09-25 17:31:19 +0000858 {
859 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
860 "lsplit.add", PHTerminator);
861 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
862 A, StartValue, "lsplit.c", PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +0000863 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
Devang Patel453a8442007-09-25 17:31:19 +0000864 }
Devang Patel5279d062007-09-17 20:39:48 +0000865 break;
866 default:
867 assert ( 0 && "Unexpected split condition predicate");
868 }
Devang Patel453a8442007-09-25 17:31:19 +0000869
870 if (NLB) {
871 unsigned i = IndVar->getBasicBlockIndex(Preheader);
872 IndVar->setIncomingValue(i, NLB);
873 }
874
875 if (NUB) {
876 ExitCondition->setOperand(ExitValueNum, NUB);
877 }
Devang Patel5279d062007-09-17 20:39:48 +0000878}
879/// updateLoopIterationSpace - Current loop body is covered by an AND
880/// instruction whose operands compares induction variables with loop
881/// invariants. If possible, hoist this check outside the loop by
882/// updating appropriate start and end values for induction variable.
883bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
884 BasicBlock *Header = L->getHeader();
Devang Patel453a8442007-09-25 17:31:19 +0000885 BasicBlock *ExitingBlock = ExitCondition->getParent();
886 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
887
Devang Patel5279d062007-09-17 20:39:48 +0000888 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
889 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
890
891 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
892 || Op0->getPredicate() == ICmpInst::ICMP_NE
893 || Op0->getPredicate() == ICmpInst::ICMP_EQ
894 || Op0->getPredicate() == ICmpInst::ICMP_NE)
895 return false;
896
897 // Check if SplitCondition dominates entire loop body
898 // or not.
899
900 // If SplitCondition is not in loop header then this loop is not suitable
901 // for this transformation.
902 if (SD.SplitCondition->getParent() != Header)
903 return false;
904
905 // If loop header includes loop variant instruction operands then
906 // this loop may not be eliminated.
907 Instruction *Terminator = Header->getTerminator();
908 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
909 BI != BE; ++BI) {
910 Instruction *I = BI;
911
912 // PHI Nodes are OK.
913 if (isa<PHINode>(I))
914 continue;
915
916 // SplitCondition itself is OK.
917 if (I == SD.SplitCondition)
918 continue;
919 if (I == Op0 || I == Op1)
920 continue;
921
922 // Induction variable is OK.
923 if (I == IndVar)
924 continue;
925
926 // Induction variable increment is OK.
927 if (I == IndVarIncrement)
928 continue;
929
930 // Terminator is also harmless.
931 if (I == Terminator)
932 continue;
933
934 // Otherwise we have a instruction that may not be safe.
935 return false;
936 }
937
938 // If Exiting block includes loop variant instructions then this
939 // loop may not be eliminated.
940 if (!safeExitingBlock(SD, ExitCondition->getParent()))
941 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000942
943 // Verify that loop exiting block has only two predecessor, where one predecessor
944 // is split condition block. The other predecessor will become exiting block's
945 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
946 // more then two predecessors. This requires extra work in updating dominator
947 // information.
948 BasicBlock *ExitingBBPred = NULL;
949 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
950 PI != PE; ++PI) {
951 BasicBlock *BB = *PI;
952 if (SplitCondBlock == BB)
953 continue;
954 if (ExitingBBPred)
955 return false;
956 else
957 ExitingBBPred = BB;
958 }
959
960 // Update loop bounds to absorb Op0 check.
Devang Patel5279d062007-09-17 20:39:48 +0000961 updateLoopBounds(Op0);
Devang Patel453a8442007-09-25 17:31:19 +0000962 // Update loop bounds to absorb Op1 check.
Devang Patel5279d062007-09-17 20:39:48 +0000963 updateLoopBounds(Op1);
Devang Patel453a8442007-09-25 17:31:19 +0000964
Devang Patel5279d062007-09-17 20:39:48 +0000965 // Update CFG
Devang Patel453a8442007-09-25 17:31:19 +0000966
967 // Unconditionally connect split block to its remaining successor.
968 BranchInst *SplitTerminator =
969 cast<BranchInst>(SplitCondBlock->getTerminator());
970 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
971 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
972 if (Succ0 == ExitCondition->getParent())
973 SplitTerminator->setUnconditionalDest(Succ1);
974 else
975 SplitTerminator->setUnconditionalDest(Succ0);
976
977 // Remove split condition.
978 SD.SplitCondition->eraseFromParent();
979 if (Op0->use_begin() == Op0->use_end())
980 Op0->eraseFromParent();
981 if (Op1->use_begin() == Op1->use_end())
982 Op1->eraseFromParent();
983
984 BranchInst *ExitInsn =
985 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
986 assert (ExitInsn && "Unable to find suitable loop exit branch");
987 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
988 if (L->contains(ExitBlock))
989 ExitBlock = ExitInsn->getSuccessor(0);
990
991 // Update domiantor info. Now, ExitingBlock has only one predecessor,
992 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
993 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
994
995 // If ExitingBlock is a member of loop BB's DF list then replace it with
996 // loop header and exit block.
997 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
998 I != E; ++I) {
999 BasicBlock *BB = *I;
1000 if (BB == Header || BB == ExitingBlock)
1001 continue;
1002 DominanceFrontier::iterator BBDF = DF->find(BB);
1003 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1004 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1005 while (DomSetI != DomSetE) {
1006 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1007 ++DomSetI;
1008 BasicBlock *DFBB = *CurrentItr;
1009 if (DFBB == ExitingBlock) {
1010 BBDF->second.erase(DFBB);
1011 BBDF->second.insert(Header);
1012 if (Header != ExitingBlock)
1013 BBDF->second.insert(ExitBlock);
1014 }
1015 }
1016 }
1017
Devang Patel1c013502007-09-25 17:43:08 +00001018 return true;
Devang Patel5279d062007-09-17 20:39:48 +00001019}
1020
1021
Devang Patela6a86632007-08-14 18:35:57 +00001022/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1023/// This routine is used to remove split condition's dead branch, dominated by
1024/// DeadBB. LiveBB dominates split conidition's other branch.
1025void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1026 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +00001027
Devang Patel5b8ec612007-08-15 03:31:47 +00001028 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +00001029 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +00001030 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1031 if (DeadBBDF != DF->end()) {
1032 SmallVector<BasicBlock *, 8> PredBlocks;
1033
1034 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1035 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1036 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1037 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +00001038 FrontierBBs.push_back(FrontierBB);
1039
Devang Patel5b8ec612007-08-15 03:31:47 +00001040 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1041 PredBlocks.clear();
1042 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1043 PI != PE; ++PI) {
1044 BasicBlock *P = *PI;
1045 if (P == DeadBB || DT->dominates(DeadBB, P))
1046 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001047 }
Devang Patel96bf5242007-08-17 21:59:16 +00001048
Devang Patel5b8ec612007-08-15 03:31:47 +00001049 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1050 FBI != FBE; ++FBI) {
1051 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1052 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1053 PE = PredBlocks.end(); PI != PE; ++PI) {
1054 BasicBlock *P = *PI;
1055 PN->removeIncomingValue(P);
1056 }
1057 }
1058 else
1059 break;
Devang Patel96bf5242007-08-17 21:59:16 +00001060 }
Devang Patel98147a32007-08-12 07:02:51 +00001061 }
Devang Patel98147a32007-08-12 07:02:51 +00001062 }
Devang Patel5b8ec612007-08-15 03:31:47 +00001063
1064 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1065 SmallVector<BasicBlock *, 32> WorkList;
1066 DomTreeNode *DN = DT->getNode(DeadBB);
1067 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1068 E = df_end(DN); DI != E; ++DI) {
1069 BasicBlock *BB = DI->getBlock();
1070 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +00001071 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +00001072 }
1073
1074 while (!WorkList.empty()) {
1075 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1076 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +00001077 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +00001078 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +00001079 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +00001080 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1081 I->eraseFromParent();
1082 }
1083 LPM->deleteSimpleAnalysisValue(BB, LP);
1084 DT->eraseNode(BB);
1085 DF->removeBlock(BB);
1086 LI->removeBlock(BB);
1087 BB->eraseFromParent();
1088 }
Devang Patel96bf5242007-08-17 21:59:16 +00001089
1090 // Update Frontier BBs' dominator info.
1091 while (!FrontierBBs.empty()) {
1092 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1093 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1094 if (!NewDominator) {
1095 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1096 NewDominator = *PI;
1097 ++PI;
1098 if (NewDominator != LiveBB) {
1099 for(; PI != PE; ++PI) {
1100 BasicBlock *P = *PI;
1101 if (P == LiveBB) {
1102 NewDominator = LiveBB;
1103 break;
1104 }
1105 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1106 }
1107 }
1108 }
1109 assert (NewDominator && "Unable to fix dominator info.");
1110 DT->changeImmediateDominator(FBB, NewDominator);
1111 DF->changeImmediateDominator(FBB, NewDominator, DT);
1112 }
1113
Devang Patel98147a32007-08-12 07:02:51 +00001114}
1115
Devang Pateldc523952007-08-22 18:27:01 +00001116/// safeSplitCondition - Return true if it is possible to
1117/// split loop using given split condition.
1118bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patel23a19f82007-08-10 00:53:35 +00001119
Devang Pateldc523952007-08-22 18:27:01 +00001120 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel8893ca62007-09-17 21:01:05 +00001121 BasicBlock *Latch = L->getLoopLatch();
Devang Pateldc523952007-08-22 18:27:01 +00001122 BranchInst *SplitTerminator =
1123 cast<BranchInst>(SplitCondBlock->getTerminator());
1124 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1125 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel20d260a2007-08-18 00:00:32 +00001126
Devang Patelb88e4202007-08-24 05:36:56 +00001127 // Finally this split condition is safe only if merge point for
1128 // split condition branch is loop latch. This check along with previous
1129 // check, to ensure that exit condition is in either loop latch or header,
1130 // filters all loops with non-empty loop body between merge point
1131 // and exit condition.
1132 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1133 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1134 if (Succ0DF->second.count(Latch))
1135 return true;
1136
1137 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1138 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1139 if (Succ1DF->second.count(Latch))
1140 return true;
1141
1142 return false;
Devang Pateldc523952007-08-22 18:27:01 +00001143}
1144
Devang Patel4a69da92007-08-25 00:56:38 +00001145/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1146/// based on split value.
1147void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1148
Devang Patel4f12c5f2007-09-11 00:12:56 +00001149 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1150 ICmpInst::Predicate SP = SC->getPredicate();
Devang Patel4a69da92007-08-25 00:56:38 +00001151 const Type *Ty = SD.SplitValue->getType();
1152 bool Sign = ExitCondition->isSignedPredicate();
1153 BasicBlock *Preheader = L->getLoopPreheader();
1154 Instruction *PHTerminator = Preheader->getTerminator();
1155
1156 // Initially use split value as upper loop bound for first loop and lower loop
1157 // bound for second loop.
1158 Value *AEV = SD.SplitValue;
1159 Value *BSV = SD.SplitValue;
1160
Devang Patelbabbe272007-09-19 00:28:47 +00001161 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1162 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1163 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
Devang Patel02c48362008-02-13 19:48:48 +00001164 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
Devang Patelbabbe272007-09-19 00:28:47 +00001165 ExitCondition->swapOperands();
Devang Patel02c48362008-02-13 19:48:48 +00001166 if (ExitValueNum)
1167 ExitValueNum = 0;
1168 else
1169 ExitValueNum = 1;
1170 }
Devang Patelbabbe272007-09-19 00:28:47 +00001171
Devang Patel4a69da92007-08-25 00:56:38 +00001172 switch (ExitCondition->getPredicate()) {
1173 case ICmpInst::ICMP_SGT:
1174 case ICmpInst::ICMP_UGT:
1175 case ICmpInst::ICMP_SGE:
1176 case ICmpInst::ICMP_UGE:
1177 default:
1178 assert (0 && "Unexpected exit condition predicate");
1179
1180 case ICmpInst::ICMP_SLT:
1181 case ICmpInst::ICMP_ULT:
1182 {
1183 switch (SP) {
1184 case ICmpInst::ICMP_SLT:
1185 case ICmpInst::ICMP_ULT:
1186 //
1187 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1188 //
1189 // is transformed into
1190 // AEV = BSV = SV
1191 // for (i = LB; i < min(UB, AEV); ++i)
1192 // A;
1193 // for (i = max(LB, BSV); i < UB; ++i);
1194 // B;
1195 break;
1196 case ICmpInst::ICMP_SLE:
1197 case ICmpInst::ICMP_ULE:
1198 {
1199 //
1200 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1201 //
1202 // is transformed into
1203 //
1204 // AEV = SV + 1
1205 // BSV = SV + 1
1206 // for (i = LB; i < min(UB, AEV); ++i)
1207 // A;
1208 // for (i = max(LB, BSV); i < UB; ++i)
1209 // B;
1210 BSV = BinaryOperator::createAdd(SD.SplitValue,
1211 ConstantInt::get(Ty, 1, Sign),
1212 "lsplit.add", PHTerminator);
1213 AEV = BSV;
1214 }
1215 break;
1216 case ICmpInst::ICMP_SGE:
1217 case ICmpInst::ICMP_UGE:
1218 //
1219 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1220 //
1221 // is transformed into
1222 // AEV = BSV = SV
1223 // for (i = LB; i < min(UB, AEV); ++i)
1224 // B;
1225 // for (i = max(BSV, LB); i < UB; ++i)
1226 // A;
1227 break;
1228 case ICmpInst::ICMP_SGT:
1229 case ICmpInst::ICMP_UGT:
1230 {
1231 //
1232 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1233 //
1234 // is transformed into
1235 //
1236 // BSV = AEV = SV + 1
1237 // for (i = LB; i < min(UB, AEV); ++i)
1238 // B;
1239 // for (i = max(LB, BSV); i < UB; ++i)
1240 // A;
1241 BSV = BinaryOperator::createAdd(SD.SplitValue,
1242 ConstantInt::get(Ty, 1, Sign),
1243 "lsplit.add", PHTerminator);
1244 AEV = BSV;
1245 }
1246 break;
1247 default:
1248 assert (0 && "Unexpected split condition predicate");
1249 break;
1250 } // end switch (SP)
1251 }
1252 break;
1253 case ICmpInst::ICMP_SLE:
1254 case ICmpInst::ICMP_ULE:
1255 {
1256 switch (SP) {
1257 case ICmpInst::ICMP_SLT:
1258 case ICmpInst::ICMP_ULT:
1259 //
1260 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1261 //
1262 // is transformed into
1263 // AEV = SV - 1;
1264 // BSV = SV;
1265 // for (i = LB; i <= min(UB, AEV); ++i)
1266 // A;
1267 // for (i = max(LB, BSV); i <= UB; ++i)
1268 // B;
1269 AEV = BinaryOperator::createSub(SD.SplitValue,
1270 ConstantInt::get(Ty, 1, Sign),
1271 "lsplit.sub", PHTerminator);
1272 break;
1273 case ICmpInst::ICMP_SLE:
1274 case ICmpInst::ICMP_ULE:
1275 //
1276 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1277 //
1278 // is transformed into
1279 // AEV = SV;
1280 // BSV = SV + 1;
1281 // for (i = LB; i <= min(UB, AEV); ++i)
1282 // A;
1283 // for (i = max(LB, BSV); i <= UB; ++i)
1284 // B;
1285 BSV = BinaryOperator::createAdd(SD.SplitValue,
1286 ConstantInt::get(Ty, 1, Sign),
1287 "lsplit.add", PHTerminator);
1288 break;
1289 case ICmpInst::ICMP_SGT:
1290 case ICmpInst::ICMP_UGT:
1291 //
1292 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1293 //
1294 // is transformed into
1295 // AEV = SV;
1296 // BSV = SV + 1;
1297 // for (i = LB; i <= min(AEV, UB); ++i)
1298 // B;
1299 // for (i = max(LB, BSV); i <= UB; ++i)
1300 // A;
1301 BSV = BinaryOperator::createAdd(SD.SplitValue,
1302 ConstantInt::get(Ty, 1, Sign),
1303 "lsplit.add", PHTerminator);
1304 break;
1305 case ICmpInst::ICMP_SGE:
1306 case ICmpInst::ICMP_UGE:
1307 // ** TODO **
1308 //
1309 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1310 //
1311 // is transformed into
1312 // AEV = SV - 1;
1313 // BSV = SV;
1314 // for (i = LB; i <= min(AEV, UB); ++i)
1315 // B;
1316 // for (i = max(LB, BSV); i <= UB; ++i)
1317 // A;
1318 AEV = BinaryOperator::createSub(SD.SplitValue,
1319 ConstantInt::get(Ty, 1, Sign),
1320 "lsplit.sub", PHTerminator);
1321 break;
1322 default:
1323 assert (0 && "Unexpected split condition predicate");
1324 break;
1325 } // end switch (SP)
1326 }
1327 break;
1328 }
1329
1330 // Calculate ALoop induction variable's new exiting value and
1331 // BLoop induction variable's new starting value. Calculuate these
1332 // values in original loop's preheader.
1333 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1334 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel3f65f022007-09-21 21:18:19 +00001335 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Patel5ffdc562007-12-03 19:17:21 +00001336
1337 // If ExitValue operand is also defined in Loop header then
1338 // insert new ExitValue after this operand definition.
1339 if (Instruction *EVN =
1340 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1341 if (!isa<PHINode>(EVN))
1342 if (InsertPt->getParent() == EVN->getParent()) {
1343 BasicBlock::iterator LHBI = L->getHeader()->begin();
1344 BasicBlock::iterator LHBE = L->getHeader()->end();
1345 for(;LHBI != LHBE; ++LHBI) {
1346 Instruction *I = LHBI;
1347 if (I == EVN)
1348 break;
1349 }
1350 InsertPt = ++LHBI;
1351 }
1352 }
Devang Patel4a69da92007-08-25 00:56:38 +00001353 Value *C1 = new ICmpInst(Sign ?
1354 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1355 AEV,
1356 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001357 "lsplit.ev", InsertPt);
1358
Gabor Greif051a9502008-04-06 20:25:17 +00001359 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1360 ExitCondition->getOperand(ExitValueNum),
1361 "lsplit.ev", InsertPt);
Devang Patel3f65f022007-09-21 21:18:19 +00001362
Devang Patel4a69da92007-08-25 00:56:38 +00001363 Value *C2 = new ICmpInst(Sign ?
1364 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1365 BSV, StartValue, "lsplit.sv",
1366 PHTerminator);
Gabor Greif051a9502008-04-06 20:25:17 +00001367 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1368 "lsplit.sv", PHTerminator);
Devang Patel4a69da92007-08-25 00:56:38 +00001369}
1370
Devang Pateldc523952007-08-22 18:27:01 +00001371/// splitLoop - Split current loop L in two loops using split information
1372/// SD. Update dominator information. Maintain LCSSA form.
1373bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1374
1375 if (!safeSplitCondition(SD))
1376 return false;
1377
Devang Patel8893ca62007-09-17 21:01:05 +00001378 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1379
1380 // Unable to handle triange loops at the moment.
1381 // In triangle loop, split condition is in header and one of the
1382 // the split destination is loop latch. If split condition is EQ
1383 // then such loops are already handle in processOneIterationLoop().
1384 BasicBlock *Latch = L->getLoopLatch();
1385 BranchInst *SplitTerminator =
1386 cast<BranchInst>(SplitCondBlock->getTerminator());
1387 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1388 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1389 if (L->getHeader() == SplitCondBlock
1390 && (Latch == Succ0 || Latch == Succ1))
1391 return false;
1392
1393 // If split condition branches heads do not have single predecessor,
1394 // SplitCondBlock, then is not possible to remove inactive branch.
1395 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1396 return false;
1397
Devang Patel82ada542008-02-08 22:49:13 +00001398 // If Exiting block includes loop variant instructions then this
1399 // loop may not be split safely.
1400 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1401 return false;
1402
Devang Patela8644e32007-08-22 19:33:29 +00001403 // After loop is cloned there are two loops.
1404 //
1405 // First loop, referred as ALoop, executes first part of loop's iteration
1406 // space split. Second loop, referred as BLoop, executes remaining
1407 // part of loop's iteration space.
1408 //
1409 // ALoop's exit edge enters BLoop's header through a forwarding block which
1410 // acts as a BLoop's preheader.
Devang Patel4a69da92007-08-25 00:56:38 +00001411 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateldc523952007-08-22 18:27:01 +00001412
Devang Patel4a69da92007-08-25 00:56:38 +00001413 // Calculate ALoop induction variable's new exiting value and
1414 // BLoop induction variable's new starting value.
1415 calculateLoopBounds(SD);
Devang Patel423c8b22007-08-10 18:07:13 +00001416
Devang Patela8644e32007-08-22 19:33:29 +00001417 //[*] Clone loop.
Devang Patel98147a32007-08-12 07:02:51 +00001418 DenseMap<const Value *, Value *> ValueMap;
Devang Patela8644e32007-08-22 19:33:29 +00001419 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Pateld79faee2007-08-25 02:39:24 +00001420 Loop *ALoop = L;
Devang Patela8644e32007-08-22 19:33:29 +00001421 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel98147a32007-08-12 07:02:51 +00001422
Devang Patela8644e32007-08-22 19:33:29 +00001423 //[*] ALoop's exiting edge BLoop's header.
1424 // ALoop's original exit block becomes BLoop's exit block.
1425 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1426 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1427 BranchInst *A_ExitInsn =
1428 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1429 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1430 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1431 if (L->contains(B_ExitBlock)) {
1432 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1433 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patelada054a2007-08-14 01:30:57 +00001434 } else
Devang Patela8644e32007-08-22 19:33:29 +00001435 A_ExitInsn->setSuccessor(1, B_Header);
1436
1437 //[*] Update ALoop's exit value using new exit value.
Devang Patel4a69da92007-08-25 00:56:38 +00001438 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001439
Devang Patela8644e32007-08-22 19:33:29 +00001440 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1441 // original loop's preheader. Add incoming PHINode values from
1442 // ALoop's exiting block. Update BLoop header's domiantor info.
1443
Devang Patelada054a2007-08-14 01:30:57 +00001444 // Collect inverse map of Header PHINodes.
1445 DenseMap<Value *, Value *> InverseMap;
1446 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1447 BE = L->getHeader()->end(); BI != BE; ++BI) {
1448 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1449 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1450 InverseMap[PNClone] = PN;
1451 } else
1452 break;
1453 }
Devang Patel4a69da92007-08-25 00:56:38 +00001454
Devang Patela8644e32007-08-22 19:33:29 +00001455 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel98147a32007-08-12 07:02:51 +00001456 BI != BE; ++BI) {
1457 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001458 // Remove incoming value from original preheader.
1459 PN->removeIncomingValue(Preheader);
1460
1461 // Add incoming value from A_ExitingBlock.
1462 if (PN == B_IndVar)
Devang Patel4a69da92007-08-25 00:56:38 +00001463 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001464 else {
1465 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patel9b03daa2008-02-14 23:18:47 +00001466 Value *V2 = NULL;
1467 // If loop header is also loop exiting block then
1468 // OrigPN is incoming value for B loop header.
1469 if (A_ExitingBlock == L->getHeader())
1470 V2 = OrigPN;
1471 else
1472 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
Devang Patela8644e32007-08-22 19:33:29 +00001473 PN->addIncoming(V2, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001474 }
1475 } else
Devang Patel98147a32007-08-12 07:02:51 +00001476 break;
1477 }
Devang Patela8644e32007-08-22 19:33:29 +00001478 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1479 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001480
Devang Patela8644e32007-08-22 19:33:29 +00001481 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1482 // block. Remove incoming PHINode values from ALoop's exiting block.
1483 // Add new incoming values from BLoop's incoming exiting value.
1484 // Update BLoop exit block's dominator info..
1485 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1486 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patelada054a2007-08-14 01:30:57 +00001487 BI != BE; ++BI) {
1488 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001489 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1490 B_ExitingBlock);
1491 PN->removeIncomingValue(A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001492 } else
1493 break;
1494 }
Devang Patel98147a32007-08-12 07:02:51 +00001495
Devang Patela8644e32007-08-22 19:33:29 +00001496 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1497 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001498
Devang Patela8644e32007-08-22 19:33:29 +00001499 //[*] Split ALoop's exit edge. This creates a new block which
1500 // serves two purposes. First one is to hold PHINode defnitions
1501 // to ensure that ALoop's LCSSA form. Second use it to act
1502 // as a preheader for BLoop.
1503 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel423c8b22007-08-10 18:07:13 +00001504
Devang Patela8644e32007-08-22 19:33:29 +00001505 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1506 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1507 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel60cbab42007-08-21 19:47:46 +00001508 BI != BE; ++BI) {
1509 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001510 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001511 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
Devang Patela8644e32007-08-22 19:33:29 +00001512 newPHI->addIncoming(V1, A_ExitingBlock);
1513 A_ExitBlock->getInstList().push_front(newPHI);
1514 PN->removeIncomingValue(A_ExitBlock);
1515 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001516 } else
1517 break;
1518 }
1519
Devang Patela8644e32007-08-22 19:33:29 +00001520 //[*] Eliminate split condition's inactive branch from ALoop.
1521 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1522 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001523 BasicBlock *A_InactiveBranch = NULL;
1524 BasicBlock *A_ActiveBranch = NULL;
1525 if (SD.UseTrueBranchFirst) {
1526 A_ActiveBranch = A_BR->getSuccessor(0);
1527 A_InactiveBranch = A_BR->getSuccessor(1);
1528 } else {
1529 A_ActiveBranch = A_BR->getSuccessor(1);
1530 A_InactiveBranch = A_BR->getSuccessor(0);
1531 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001532 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001533 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1534
1535 //[*] Eliminate split condition's inactive branch in from BLoop.
1536 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1537 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001538 BasicBlock *B_InactiveBranch = NULL;
1539 BasicBlock *B_ActiveBranch = NULL;
1540 if (SD.UseTrueBranchFirst) {
1541 B_ActiveBranch = B_BR->getSuccessor(1);
1542 B_InactiveBranch = B_BR->getSuccessor(0);
1543 } else {
1544 B_ActiveBranch = B_BR->getSuccessor(0);
1545 B_InactiveBranch = B_BR->getSuccessor(1);
1546 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001547 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001548 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1549
Devang Pateld79faee2007-08-25 02:39:24 +00001550 BasicBlock *A_Header = L->getHeader();
1551 if (A_ExitingBlock == A_Header)
1552 return true;
1553
1554 //[*] Move exit condition into split condition block to avoid
1555 // executing dead loop iteration.
1556 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1557 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1558 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1559
1560 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel4f12c5f2007-09-11 00:12:56 +00001561 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1562 ALoop);
Devang Pateld79faee2007-08-25 02:39:24 +00001563
1564 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1565 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1566
Devang Patel98147a32007-08-12 07:02:51 +00001567 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +00001568}
Devang Pateld79faee2007-08-25 02:39:24 +00001569
1570// moveExitCondition - Move exit condition EC into split condition block CondBB.
1571void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1572 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1573 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1574
1575 BasicBlock *ExitingBB = EC->getParent();
1576 Instruction *CurrentBR = CondBB->getTerminator();
1577
1578 // Move exit condition into split condition block.
1579 EC->moveBefore(CurrentBR);
1580 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1581
1582 // Move exiting block's branch into split condition block. Update its branch
1583 // destination.
1584 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1585 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +00001586 BasicBlock *OrigDestBB = NULL;
1587 if (ExitingBR->getSuccessor(0) == ExitBB) {
1588 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +00001589 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001590 }
1591 else {
1592 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +00001593 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +00001594 }
Devang Pateld79faee2007-08-25 02:39:24 +00001595
1596 // Remove split condition and current split condition branch.
1597 SC->eraseFromParent();
1598 CurrentBR->eraseFromParent();
1599
Devang Patel23067df2008-02-13 22:06:36 +00001600 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +00001601 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +00001602
1603 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +00001604 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +00001605
1606 // Fix dominator info.
1607 // ExitBB is now dominated by CondBB
1608 DT->changeImmediateDominator(ExitBB, CondBB);
1609 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1610
1611 // Basicblocks dominated by ActiveBB may have ExitingBB or
1612 // a basic block outside the loop in their DF list. If so,
1613 // replace it with CondBB.
1614 DomTreeNode *Node = DT->getNode(ActiveBB);
1615 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1616 DI != DE; ++DI) {
1617 BasicBlock *BB = DI->getBlock();
1618 DominanceFrontier::iterator BBDF = DF->find(BB);
1619 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1620 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1621 while (DomSetI != DomSetE) {
1622 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1623 ++DomSetI;
1624 BasicBlock *DFBB = *CurrentItr;
1625 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1626 BBDF->second.erase(DFBB);
1627 BBDF->second.insert(CondBB);
1628 }
1629 }
1630 }
1631}
1632
1633/// updatePHINodes - CFG has been changed.
1634/// Before
1635/// - ExitBB's single predecessor was Latch
1636/// - Latch's second successor was Header
1637/// Now
Devang Patel82ada542008-02-08 22:49:13 +00001638/// - ExitBB's single predecessor is Header
1639/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +00001640///
1641/// Update ExitBB PHINodes' to reflect this change.
1642void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1643 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +00001644 PHINode *IV, Instruction *IVIncrement,
1645 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +00001646
1647 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001648 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +00001649 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +00001650 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +00001651 if (!PN)
1652 break;
1653
1654 Value *V = PN->getIncomingValueForBlock(Latch);
1655 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +00001656 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1657 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +00001658 Value *NewV = NULL;
1659 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +00001660 UI != E; ++UI)
1661 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +00001662 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +00001663 NewV = U;
1664 break;
1665 }
1666
Devang Patel60a12902008-03-24 20:16:14 +00001667 // Add incoming value from header only if PN has any use inside the loop.
1668 if (NewV)
1669 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +00001670
1671 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1672 // If this instruction is IVIncrement then IV is new incoming value
1673 // from header otherwise this instruction must be incoming value from
1674 // header because loop is in LCSSA form.
1675 if (PHI == IVIncrement)
1676 PN->addIncoming(IV, Header);
1677 else
1678 PN->addIncoming(V, Header);
1679 } else
1680 // Otherwise this is an incoming value from header because loop is in
1681 // LCSSA form.
1682 PN->addIncoming(V, Header);
1683
1684 // Remove incoming value from Latch.
1685 PN->removeIncomingValue(Latch);
1686 }
1687}