blob: 6698d67f91ec08b504417a2278779d82a241988d [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,
154 PHINode *IV, Instruction *IVIncrement);
155
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.
235 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
Devang Pateld651f652007-08-20 20:24:15 +0000236 E = SplitData.end(); SI != E;) {
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;
247 ++SI;
248 SplitData.erase(Delete_SI);
249 }
250 }
251 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
Devang Patel423c8b22007-08-10 18:07:13 +0000252 Changed = processOneIterationLoop(SD);
Devang Patel71554b82007-08-08 21:02:17 +0000253 if (Changed) {
254 ++NumIndexSplit;
255 // If is loop is eliminated then nothing else to do here.
256 return Changed;
Devang Pateld651f652007-08-20 20:24:15 +0000257 } else {
258 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
259 ++SI;
260 SplitData.erase(Delete_SI);
Devang Patel71554b82007-08-08 21:02:17 +0000261 }
Devang Pateld651f652007-08-20 20:24:15 +0000262 } else
263 ++SI;
Devang Patel71554b82007-08-08 21:02:17 +0000264 }
265
Devang Patel4259fe32007-08-24 06:17:19 +0000266 if (SplitData.empty())
267 return false;
268
Devang Patel9704fcf2007-08-08 22:25:28 +0000269 // Split most profitiable condition.
Devang Patel7237d112007-08-24 05:21:13 +0000270 // FIXME : Implement cost analysis.
271 unsigned MostProfitableSDIndex = 0;
272 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
Devang Patel9704fcf2007-08-08 22:25:28 +0000273
Devang Patelfee76bd2007-08-07 00:25:56 +0000274 if (Changed)
275 ++NumIndexSplit;
Devang Patel71554b82007-08-08 21:02:17 +0000276
Devang Patelfee76bd2007-08-07 00:25:56 +0000277 return Changed;
278}
279
Devang Patelc9d123d2007-08-09 01:39:01 +0000280/// Return true if V is a induction variable or induction variable's
281/// increment for loop L.
Devang Patelbacf5192007-08-10 00:33:50 +0000282void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000283
284 Instruction *I = dyn_cast<Instruction>(V);
285 if (!I)
Devang Patelbacf5192007-08-10 00:33:50 +0000286 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000287
288 // Check if I is a phi node from loop header or not.
289 if (PHINode *PN = dyn_cast<PHINode>(V)) {
290 if (PN->getParent() == L->getHeader()) {
Devang Patelbacf5192007-08-10 00:33:50 +0000291 IndVar = PN;
292 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000293 }
294 }
295
296 // Check if I is a add instruction whose one operand is
297 // phi node from loop header and second operand is constant.
298 if (I->getOpcode() != Instruction::Add)
Devang Patelbacf5192007-08-10 00:33:50 +0000299 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000300
301 Value *Op0 = I->getOperand(0);
302 Value *Op1 = I->getOperand(1);
303
304 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
305 if (PN->getParent() == L->getHeader()
306 && isa<ConstantInt>(Op1)) {
307 IndVar = PN;
308 IndVarIncrement = I;
Devang Patelbacf5192007-08-10 00:33:50 +0000309 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000310 }
311 }
312
313 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
314 if (PN->getParent() == L->getHeader()
315 && isa<ConstantInt>(Op0)) {
316 IndVar = PN;
317 IndVarIncrement = I;
Devang Patelbacf5192007-08-10 00:33:50 +0000318 return;
Devang Patelc9d123d2007-08-09 01:39:01 +0000319 }
320 }
321
Devang Patelbacf5192007-08-10 00:33:50 +0000322 return;
323}
324
325// Find loop's exit condition and associated induction variable.
326void LoopIndexSplit::findLoopConditionals() {
327
Devang Patel1cc2ec82007-08-20 23:51:18 +0000328 BasicBlock *ExitingBlock = NULL;
Devang Patelbacf5192007-08-10 00:33:50 +0000329
330 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
331 I != E; ++I) {
332 BasicBlock *BB = *I;
333 if (!L->isLoopExit(BB))
334 continue;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000335 if (ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000336 return;
Devang Patel1cc2ec82007-08-20 23:51:18 +0000337 ExitingBlock = BB;
Devang Patelbacf5192007-08-10 00:33:50 +0000338 }
339
Devang Patel1cc2ec82007-08-20 23:51:18 +0000340 if (!ExitingBlock)
Devang Patelbacf5192007-08-10 00:33:50 +0000341 return;
Devang Patelb88e4202007-08-24 05:36:56 +0000342
343 // If exiting block is neither loop header nor loop latch then this loop is
344 // not suitable.
345 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
346 return;
347
Devang Patelbacf5192007-08-10 00:33:50 +0000348 // If exit block's terminator is conditional branch inst then we have found
349 // exit condition.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000350 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patelbacf5192007-08-10 00:33:50 +0000351 if (!BR || BR->isUnconditional())
352 return;
353
354 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
355 if (!CI)
356 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000357
Bill Wendlingc6849102007-09-14 01:13:55 +0000358 // FIXME
Devang Patelbabbe272007-09-19 00:28:47 +0000359 if (CI->getPredicate() == ICmpInst::ICMP_EQ
Bill Wendlingc6849102007-09-14 01:13:55 +0000360 || CI->getPredicate() == ICmpInst::ICMP_NE)
361 return;
Devang Patel4a69da92007-08-25 00:56:38 +0000362
Devang Patelbacf5192007-08-10 00:33:50 +0000363 ExitCondition = CI;
364
365 // Exit condition's one operand is loop invariant exit value and second
366 // operand is SCEVAddRecExpr based on induction variable.
367 Value *V0 = CI->getOperand(0);
368 Value *V1 = CI->getOperand(1);
369
370 SCEVHandle SH0 = SE->getSCEV(V0);
371 SCEVHandle SH1 = SE->getSCEV(V1);
372
373 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
Devang Patel98147a32007-08-12 07:02:51 +0000374 ExitValueNum = 0;
Devang Patelbacf5192007-08-10 00:33:50 +0000375 findIndVar(V1, L);
376 }
377 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
Devang Patel98147a32007-08-12 07:02:51 +0000378 ExitValueNum = 1;
Devang Patelbacf5192007-08-10 00:33:50 +0000379 findIndVar(V0, L);
380 }
381
Devang Patel98147a32007-08-12 07:02:51 +0000382 if (!IndVar)
Devang Patelbacf5192007-08-10 00:33:50 +0000383 ExitCondition = NULL;
384 else if (IndVar) {
385 BasicBlock *Preheader = L->getLoopPreheader();
386 StartValue = IndVar->getIncomingValueForBlock(Preheader);
387 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000388}
389
Devang Patelfee76bd2007-08-07 00:25:56 +0000390/// Find condition inside a loop that is suitable candidate for index split.
391void LoopIndexSplit::findSplitCondition() {
392
Devang Patel71554b82007-08-08 21:02:17 +0000393 SplitInfo SD;
Devang Patelc9d123d2007-08-09 01:39:01 +0000394 // Check all basic block's terminators.
Devang Patelc9d123d2007-08-09 01:39:01 +0000395 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
396 I != E; ++I) {
Devang Patel964be452007-09-11 00:23:56 +0000397 SD.clear();
Devang Patelc9d123d2007-08-09 01:39:01 +0000398 BasicBlock *BB = *I;
Devang Patelfee76bd2007-08-07 00:25:56 +0000399
Devang Patelc9d123d2007-08-09 01:39:01 +0000400 // If this basic block does not terminate in a conditional branch
401 // then terminator is not a suitable split condition.
402 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
403 if (!BR)
404 continue;
405
406 if (BR->isUnconditional())
Devang Patelfee76bd2007-08-07 00:25:56 +0000407 continue;
408
Devang Patel5279d062007-09-17 20:39:48 +0000409 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
410 if (AndI->getOpcode() == Instruction::And) {
411 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
412 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
413
414 if (!Op0 || !Op1)
415 continue;
416
417 if (!safeICmpInst(Op0, SD))
418 continue;
419 SD.clear();
420 if (!safeICmpInst(Op1, SD))
421 continue;
422 SD.clear();
423 SD.SplitCondition = AndI;
424 SplitData.push_back(SD);
425 continue;
426 }
427 }
Devang Patelc9d123d2007-08-09 01:39:01 +0000428 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
Devang Patelbacf5192007-08-10 00:33:50 +0000429 if (!CI || CI == ExitCondition)
Devang Patelba32a5f2007-09-10 23:57:58 +0000430 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000431
Devang Patelc830aee2007-08-24 06:02:25 +0000432 if (CI->getPredicate() == ICmpInst::ICMP_NE)
Devang Patelba32a5f2007-09-10 23:57:58 +0000433 continue;
Devang Patelc830aee2007-08-24 06:02:25 +0000434
Devang Patel4259fe32007-08-24 06:17:19 +0000435 // If split condition predicate is GT or GE then first execute
436 // false branch of split condition.
Devang Patelc3957d12007-09-11 01:10:45 +0000437 if (CI->getPredicate() == ICmpInst::ICMP_UGT
438 || CI->getPredicate() == ICmpInst::ICMP_SGT
439 || CI->getPredicate() == ICmpInst::ICMP_UGE
440 || CI->getPredicate() == ICmpInst::ICMP_SGE)
Devang Patel4259fe32007-08-24 06:17:19 +0000441 SD.UseTrueBranchFirst = false;
442
Devang Patelc9d123d2007-08-09 01:39:01 +0000443 // If one operand is loop invariant and second operand is SCEVAddRecExpr
444 // based on induction variable then CI is a candidate split condition.
Devang Pateld35ed2c2007-09-11 00:42:56 +0000445 if (safeICmpInst(CI, SD))
446 SplitData.push_back(SD);
447 }
448}
Devang Patelc9d123d2007-08-09 01:39:01 +0000449
Devang Pateld35ed2c2007-09-11 00:42:56 +0000450// safeIcmpInst - CI is considered safe instruction if one of the operand
451// is SCEVAddRecExpr based on induction variable and other operand is
452// loop invariant. If CI is safe then populate SplitInfo object SD appropriately
453// and return true;
454bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000455
Devang Pateld35ed2c2007-09-11 00:42:56 +0000456 Value *V0 = CI->getOperand(0);
457 Value *V1 = CI->getOperand(1);
458
459 SCEVHandle SH0 = SE->getSCEV(V0);
460 SCEVHandle SH1 = SE->getSCEV(V1);
461
462 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
463 SD.SplitValue = V0;
464 SD.SplitCondition = CI;
465 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
466 if (PN == IndVar)
467 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000468 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000469 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
470 if (IndVarIncrement && IndVarIncrement == Insn)
471 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000472 }
473 }
Devang Pateld35ed2c2007-09-11 00:42:56 +0000474 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
475 SD.SplitValue = V1;
476 SD.SplitCondition = CI;
477 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
478 if (PN == IndVar)
479 return true;
480 }
481 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
482 if (IndVarIncrement && IndVarIncrement == Insn)
483 return true;
484 }
485 }
486
487 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000488}
489
490/// processOneIterationLoop - Current loop L contains compare instruction
491/// that compares induction variable, IndVar, against loop invariant. If
492/// entire (i.e. meaningful) loop body is dominated by this compare
493/// instruction then loop body is executed only once. In such case eliminate
494/// loop structure surrounding this loop body. For example,
495/// for (int i = start; i < end; ++i) {
496/// if ( i == somevalue) {
497/// loop_body
498/// }
499/// }
500/// can be transformed into
501/// if (somevalue >= start && somevalue < end) {
502/// i = somevalue;
503/// loop_body
504/// }
Devang Patel423c8b22007-08-10 18:07:13 +0000505bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000506
507 BasicBlock *Header = L->getHeader();
508
509 // First of all, check if SplitCondition dominates entire loop body
510 // or not.
511
512 // If SplitCondition is not in loop header then this loop is not suitable
513 // for this transformation.
Devang Patel71554b82007-08-08 21:02:17 +0000514 if (SD.SplitCondition->getParent() != Header)
Devang Patelfee76bd2007-08-07 00:25:56 +0000515 return false;
516
Devang Patelfee76bd2007-08-07 00:25:56 +0000517 // If loop header includes loop variant instruction operands then
518 // this loop may not be eliminated.
Devang Patel71554b82007-08-08 21:02:17 +0000519 if (!safeHeader(SD, Header))
Devang Patelfee76bd2007-08-07 00:25:56 +0000520 return false;
521
Devang Patel1cc2ec82007-08-20 23:51:18 +0000522 // If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000523 // loop may not be eliminated.
Devang Patel1cc2ec82007-08-20 23:51:18 +0000524 if (!safeExitingBlock(SD, ExitCondition->getParent()))
Devang Patelfee76bd2007-08-07 00:25:56 +0000525 return false;
526
Devang Patel968eee22007-09-19 00:15:16 +0000527 // Filter loops where split condition's false branch is not empty.
528 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
529 return false;
530
Devang Patel8893ca62007-09-17 21:01:05 +0000531 // If split condition is not safe then do not process this loop.
532 // For example,
533 // for(int i = 0; i < N; i++) {
534 // if ( i == XYZ) {
535 // A;
536 // else
537 // B;
538 // }
539 // C;
540 // D;
541 // }
542 if (!safeSplitCondition(SD))
543 return false;
544
Devang Patel84ef08b2007-09-19 00:11:01 +0000545 BasicBlock *Latch = L->getLoopLatch();
546 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
547 if (!BR)
548 return false;
549
Devang Patel6a2bfda2007-08-08 01:51:27 +0000550 // Update CFG.
551
Devang Patelebc5fea2007-08-20 20:49:01 +0000552 // Replace index variable with split value in loop body. Loop body is executed
553 // only when index variable is equal to split value.
554 IndVar->replaceAllUsesWith(SD.SplitValue);
555
556 // Remove Latch to Header edge.
Devang Patel6a2bfda2007-08-08 01:51:27 +0000557 BasicBlock *LatchSucc = NULL;
Devang Patel6a2bfda2007-08-08 01:51:27 +0000558 Header->removePredecessor(Latch);
559 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
560 SI != E; ++SI) {
561 if (Header != *SI)
562 LatchSucc = *SI;
563 }
564 BR->setUnconditionalDest(LatchSucc);
565
Devang Patelfee76bd2007-08-07 00:25:56 +0000566 Instruction *Terminator = Header->getTerminator();
Devang Patelada054a2007-08-14 01:30:57 +0000567 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
Devang Patelfee76bd2007-08-07 00:25:56 +0000568
Devang Patelfee76bd2007-08-07 00:25:56 +0000569 // Replace split condition in header.
570 // Transform
571 // SplitCondition : icmp eq i32 IndVar, SplitValue
572 // into
573 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000574 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000575 // and i32 c1, c2
Devang Patelbacf5192007-08-10 00:33:50 +0000576 bool SignedPredicate = ExitCondition->isSignedPredicate();
Devang Patelfee76bd2007-08-07 00:25:56 +0000577 Instruction *C1 = new ICmpInst(SignedPredicate ?
578 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel71554b82007-08-08 21:02:17 +0000579 SD.SplitValue, StartValue, "lisplit",
580 Terminator);
Devang Patelfee76bd2007-08-07 00:25:56 +0000581 Instruction *C2 = new ICmpInst(SignedPredicate ?
582 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Devang Patelada054a2007-08-14 01:30:57 +0000583 SD.SplitValue, ExitValue, "lisplit",
Devang Patel71554b82007-08-08 21:02:17 +0000584 Terminator);
585 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
586 Terminator);
587 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
588 SD.SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000589
Devang Patelfee76bd2007-08-07 00:25:56 +0000590 // Now, clear latch block. Remove instructions that are responsible
591 // to increment induction variable.
592 Instruction *LTerminator = Latch->getTerminator();
593 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
594 LB != LE; ) {
595 Instruction *I = LB;
596 ++LB;
597 if (isa<PHINode>(I) || I == LTerminator)
598 continue;
599
Devang Patelada054a2007-08-14 01:30:57 +0000600 if (I == IndVarIncrement)
601 I->replaceAllUsesWith(ExitValue);
602 else
603 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Devang Patel8431a1c2007-08-07 17:45:35 +0000604 I->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000605 }
606
Devang Patel423c8b22007-08-10 18:07:13 +0000607 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000608
609 // Update Dominator Info.
610 // Only CFG change done is to remove Latch to Header edge. This
611 // does not change dominator tree because Latch did not dominate
612 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000613 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000614 DominanceFrontier::iterator HeaderDF = DF->find(Header);
615 if (HeaderDF != DF->end())
616 DF->removeFromFrontier(HeaderDF, Header);
617
618 DominanceFrontier::iterator LatchDF = DF->find(Latch);
619 if (LatchDF != DF->end())
620 DF->removeFromFrontier(LatchDF, Header);
621 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000622 return true;
623}
624
625// If loop header includes loop variant instruction operands then
626// this loop can not be eliminated. This is used by processOneIterationLoop().
Devang Patel71554b82007-08-08 21:02:17 +0000627bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000628
629 Instruction *Terminator = Header->getTerminator();
630 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
631 BI != BE; ++BI) {
632 Instruction *I = BI;
633
Devang Patelada054a2007-08-14 01:30:57 +0000634 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000635 if (isa<PHINode>(I))
636 continue;
637
638 // SplitCondition itself is OK.
Devang Patel71554b82007-08-08 21:02:17 +0000639 if (I == SD.SplitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000640 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000641
Devang Patelc9d123d2007-08-09 01:39:01 +0000642 // Induction variable is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000643 if (I == IndVar)
Devang Patelc9d123d2007-08-09 01:39:01 +0000644 continue;
645
646 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000647 if (I == IndVarIncrement)
Devang Patelc9d123d2007-08-09 01:39:01 +0000648 continue;
649
Devang Patelfee76bd2007-08-07 00:25:56 +0000650 // Terminator is also harmless.
651 if (I == Terminator)
652 continue;
653
654 // Otherwise we have a instruction that may not be safe.
655 return false;
656 }
657
658 return true;
659}
660
Devang Patel1cc2ec82007-08-20 23:51:18 +0000661// If Exiting block includes loop variant instructions then this
Devang Patelfee76bd2007-08-07 00:25:56 +0000662// loop may not be eliminated. This is used by processOneIterationLoop().
Devang Patel1cc2ec82007-08-20 23:51:18 +0000663bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
664 BasicBlock *ExitingBlock) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000665
Devang Patel1cc2ec82007-08-20 23:51:18 +0000666 for (BasicBlock::iterator BI = ExitingBlock->begin(),
667 BE = ExitingBlock->end(); BI != BE; ++BI) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000668 Instruction *I = BI;
669
Devang Patelada054a2007-08-14 01:30:57 +0000670 // PHI Nodes are OK.
Devang Patelfee76bd2007-08-07 00:25:56 +0000671 if (isa<PHINode>(I))
672 continue;
673
Devang Patelc9d123d2007-08-09 01:39:01 +0000674 // Induction variable increment is OK.
Devang Patelbacf5192007-08-10 00:33:50 +0000675 if (IndVarIncrement && IndVarIncrement == I)
Devang Patelc9d123d2007-08-09 01:39:01 +0000676 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000677
Devang Patelc9d123d2007-08-09 01:39:01 +0000678 // Check if I is induction variable increment instruction.
Devang Patela6dff2f2007-09-25 18:24:48 +0000679 if (I->getOpcode() == Instruction::Add) {
Devang Patelc9d123d2007-08-09 01:39:01 +0000680
681 Value *Op0 = I->getOperand(0);
682 Value *Op1 = I->getOperand(1);
Devang Patelfee76bd2007-08-07 00:25:56 +0000683 PHINode *PN = NULL;
684 ConstantInt *CI = NULL;
685
686 if ((PN = dyn_cast<PHINode>(Op0))) {
687 if ((CI = dyn_cast<ConstantInt>(Op1)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000688 if (CI->isOne()) {
689 if (!IndVarIncrement && PN == IndVar)
690 IndVarIncrement = I;
691 // else this is another loop induction variable
692 continue;
693 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000694 } else
695 if ((PN = dyn_cast<PHINode>(Op1))) {
696 if ((CI = dyn_cast<ConstantInt>(Op0)))
Devang Patela6dff2f2007-09-25 18:24:48 +0000697 if (CI->isOne()) {
698 if (!IndVarIncrement && PN == IndVar)
699 IndVarIncrement = I;
700 // else this is another loop induction variable
701 continue;
702 }
Devang Patelfee76bd2007-08-07 00:25:56 +0000703 }
Devang Patela6dff2f2007-09-25 18:24:48 +0000704 }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000705
Devang Patelfee76bd2007-08-07 00:25:56 +0000706 // I is an Exit condition if next instruction is block terminator.
707 // Exit condition is OK if it compares loop invariant exit value,
708 // which is checked below.
Devang Patel002fe252007-08-07 23:17:52 +0000709 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
Devang Patelbacf5192007-08-10 00:33:50 +0000710 if (EC == ExitCondition)
Devang Patel6a2bfda2007-08-08 01:51:27 +0000711 continue;
Devang Patelfee76bd2007-08-07 00:25:56 +0000712 }
713
Devang Patel1cc2ec82007-08-20 23:51:18 +0000714 if (I == ExitingBlock->getTerminator())
Devang Patelbacf5192007-08-10 00:33:50 +0000715 continue;
716
Devang Patelfee76bd2007-08-07 00:25:56 +0000717 // Otherwise we have instruction that may not be safe.
718 return false;
719 }
720
Devang Patel1cc2ec82007-08-20 23:51:18 +0000721 // We could not find any reason to consider ExitingBlock unsafe.
Devang Patelfee76bd2007-08-07 00:25:56 +0000722 return true;
723}
724
Devang Patel5279d062007-09-17 20:39:48 +0000725void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
726
727 Value *V0 = CI->getOperand(0);
728 Value *V1 = CI->getOperand(1);
729 Value *NV = NULL;
730
731 SCEVHandle SH0 = SE->getSCEV(V0);
732
733 if (SH0->isLoopInvariant(L))
734 NV = V0;
735 else
736 NV = V1;
737
Devang Patel453a8442007-09-25 17:31:19 +0000738 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
739 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
740 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
741 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
742 ExitCondition->swapOperands();
743 if (ExitValueNum)
744 ExitValueNum = 0;
745 else
746 ExitValueNum = 1;
747 }
748
749 Value *NUB = NULL;
750 Value *NLB = NULL;
751 Value *UB = ExitCondition->getOperand(ExitValueNum);
752 const Type *Ty = NV->getType();
753 bool Sign = ExitCondition->isSignedPredicate();
754 BasicBlock *Preheader = L->getLoopPreheader();
755 Instruction *PHTerminator = Preheader->getTerminator();
756
757 assert (NV && "Unexpected value");
758
Devang Patel5279d062007-09-17 20:39:48 +0000759 switch (CI->getPredicate()) {
760 case ICmpInst::ICMP_ULE:
761 case ICmpInst::ICMP_SLE:
762 // for (i = LB; i < UB; ++i)
763 // if (i <= NV && ...)
764 // LOOP_BODY
765 //
766 // is transformed into
767 // NUB = min (NV+1, UB)
768 // for (i = LB; i < NUB ; ++i)
769 // LOOP_BODY
770 //
Devang Patel453a8442007-09-25 17:31:19 +0000771 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
772 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
773 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
774 "lsplit.add", PHTerminator);
775 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
776 A, UB,"lsplit,c", PHTerminator);
777 NUB = new SelectInst (C, A, UB, "lsplit.nub", PHTerminator);
778 }
779
Devang Patel5279d062007-09-17 20:39:48 +0000780 // for (i = LB; i <= UB; ++i)
781 // if (i <= NV && ...)
782 // LOOP_BODY
783 //
784 // is transformed into
785 // NUB = min (NV, UB)
786 // for (i = LB; i <= NUB ; ++i)
787 // LOOP_BODY
788 //
Devang Patel453a8442007-09-25 17:31:19 +0000789 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
790 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
791 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
792 NV, UB, "lsplit.c", PHTerminator);
793 NUB = new SelectInst (C, NV, UB, "lsplit.nub", PHTerminator);
794 }
Devang Patel5279d062007-09-17 20:39:48 +0000795 break;
796 case ICmpInst::ICMP_ULT:
797 case ICmpInst::ICMP_SLT:
798 // for (i = LB; i < UB; ++i)
799 // if (i < NV && ...)
800 // LOOP_BODY
801 //
802 // is transformed into
803 // NUB = min (NV, UB)
804 // for (i = LB; i < NUB ; ++i)
805 // LOOP_BODY
806 //
Devang Patel453a8442007-09-25 17:31:19 +0000807 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
808 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
809 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
810 NV, UB, "lsplit.c", PHTerminator);
811 NUB = new SelectInst (C, NV, UB, "lsplit.nub", PHTerminator);
812 }
Devang Patel5279d062007-09-17 20:39:48 +0000813
814 // for (i = LB; i <= UB; ++i)
815 // if (i < NV && ...)
816 // LOOP_BODY
817 //
818 // is transformed into
819 // NUB = min (NV -1 , UB)
820 // for (i = LB; i <= NUB ; ++i)
821 // LOOP_BODY
822 //
Devang Patel453a8442007-09-25 17:31:19 +0000823 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
824 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
825 Value *S = BinaryOperator::createSub(NV, ConstantInt::get(Ty, 1, Sign),
826 "lsplit.add", PHTerminator);
827 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
828 S, UB, "lsplit.c", PHTerminator);
829 NUB = new SelectInst (C, S, UB, "lsplit.nub", PHTerminator);
830 }
Devang Patel5279d062007-09-17 20:39:48 +0000831 break;
832 case ICmpInst::ICMP_UGE:
833 case ICmpInst::ICMP_SGE:
834 // for (i = LB; i (< or <=) UB; ++i)
835 // if (i >= NV && ...)
836 // LOOP_BODY
837 //
838 // is transformed into
839 // NLB = max (NV, LB)
840 // for (i = NLB; i (< or <=) UB ; ++i)
841 // LOOP_BODY
842 //
Devang Patel453a8442007-09-25 17:31:19 +0000843 {
844 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
845 NV, StartValue, "lsplit.c", PHTerminator);
846 NLB = new SelectInst (C, StartValue, NV, "lsplit.nlb", PHTerminator);
847 }
Devang Patel5279d062007-09-17 20:39:48 +0000848 break;
849 case ICmpInst::ICMP_UGT:
850 case ICmpInst::ICMP_SGT:
851 // for (i = LB; i (< or <=) UB; ++i)
852 // if (i > NV && ...)
853 // LOOP_BODY
854 //
855 // is transformed into
856 // NLB = max (NV+1, LB)
857 // for (i = NLB; i (< or <=) UB ; ++i)
858 // LOOP_BODY
859 //
Devang Patel453a8442007-09-25 17:31:19 +0000860 {
861 Value *A = BinaryOperator::createAdd(NV, ConstantInt::get(Ty, 1, Sign),
862 "lsplit.add", PHTerminator);
863 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
864 A, StartValue, "lsplit.c", PHTerminator);
865 NLB = new SelectInst (C, StartValue, A, "lsplit.nlb", PHTerminator);
866 }
Devang Patel5279d062007-09-17 20:39:48 +0000867 break;
868 default:
869 assert ( 0 && "Unexpected split condition predicate");
870 }
Devang Patel453a8442007-09-25 17:31:19 +0000871
872 if (NLB) {
873 unsigned i = IndVar->getBasicBlockIndex(Preheader);
874 IndVar->setIncomingValue(i, NLB);
875 }
876
877 if (NUB) {
878 ExitCondition->setOperand(ExitValueNum, NUB);
879 }
Devang Patel5279d062007-09-17 20:39:48 +0000880}
881/// updateLoopIterationSpace - Current loop body is covered by an AND
882/// instruction whose operands compares induction variables with loop
883/// invariants. If possible, hoist this check outside the loop by
884/// updating appropriate start and end values for induction variable.
885bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
886 BasicBlock *Header = L->getHeader();
Devang Patel453a8442007-09-25 17:31:19 +0000887 BasicBlock *ExitingBlock = ExitCondition->getParent();
888 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
889
Devang Patel5279d062007-09-17 20:39:48 +0000890 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
891 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
892
893 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
894 || Op0->getPredicate() == ICmpInst::ICMP_NE
895 || Op0->getPredicate() == ICmpInst::ICMP_EQ
896 || Op0->getPredicate() == ICmpInst::ICMP_NE)
897 return false;
898
899 // Check if SplitCondition dominates entire loop body
900 // or not.
901
902 // If SplitCondition is not in loop header then this loop is not suitable
903 // for this transformation.
904 if (SD.SplitCondition->getParent() != Header)
905 return false;
906
907 // If loop header includes loop variant instruction operands then
908 // this loop may not be eliminated.
909 Instruction *Terminator = Header->getTerminator();
910 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
911 BI != BE; ++BI) {
912 Instruction *I = BI;
913
914 // PHI Nodes are OK.
915 if (isa<PHINode>(I))
916 continue;
917
918 // SplitCondition itself is OK.
919 if (I == SD.SplitCondition)
920 continue;
921 if (I == Op0 || I == Op1)
922 continue;
923
924 // Induction variable is OK.
925 if (I == IndVar)
926 continue;
927
928 // Induction variable increment is OK.
929 if (I == IndVarIncrement)
930 continue;
931
932 // Terminator is also harmless.
933 if (I == Terminator)
934 continue;
935
936 // Otherwise we have a instruction that may not be safe.
937 return false;
938 }
939
940 // If Exiting block includes loop variant instructions then this
941 // loop may not be eliminated.
942 if (!safeExitingBlock(SD, ExitCondition->getParent()))
943 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000944
945 // Verify that loop exiting block has only two predecessor, where one predecessor
946 // is split condition block. The other predecessor will become exiting block's
947 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
948 // more then two predecessors. This requires extra work in updating dominator
949 // information.
950 BasicBlock *ExitingBBPred = NULL;
951 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
952 PI != PE; ++PI) {
953 BasicBlock *BB = *PI;
954 if (SplitCondBlock == BB)
955 continue;
956 if (ExitingBBPred)
957 return false;
958 else
959 ExitingBBPred = BB;
960 }
961
962 // Update loop bounds to absorb Op0 check.
Devang Patel5279d062007-09-17 20:39:48 +0000963 updateLoopBounds(Op0);
Devang Patel453a8442007-09-25 17:31:19 +0000964 // Update loop bounds to absorb Op1 check.
Devang Patel5279d062007-09-17 20:39:48 +0000965 updateLoopBounds(Op1);
Devang Patel453a8442007-09-25 17:31:19 +0000966
Devang Patel5279d062007-09-17 20:39:48 +0000967 // Update CFG
Devang Patel453a8442007-09-25 17:31:19 +0000968
969 // Unconditionally connect split block to its remaining successor.
970 BranchInst *SplitTerminator =
971 cast<BranchInst>(SplitCondBlock->getTerminator());
972 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
973 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
974 if (Succ0 == ExitCondition->getParent())
975 SplitTerminator->setUnconditionalDest(Succ1);
976 else
977 SplitTerminator->setUnconditionalDest(Succ0);
978
979 // Remove split condition.
980 SD.SplitCondition->eraseFromParent();
981 if (Op0->use_begin() == Op0->use_end())
982 Op0->eraseFromParent();
983 if (Op1->use_begin() == Op1->use_end())
984 Op1->eraseFromParent();
985
986 BranchInst *ExitInsn =
987 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
988 assert (ExitInsn && "Unable to find suitable loop exit branch");
989 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
990 if (L->contains(ExitBlock))
991 ExitBlock = ExitInsn->getSuccessor(0);
992
993 // Update domiantor info. Now, ExitingBlock has only one predecessor,
994 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
995 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
996
997 // If ExitingBlock is a member of loop BB's DF list then replace it with
998 // loop header and exit block.
999 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1000 I != E; ++I) {
1001 BasicBlock *BB = *I;
1002 if (BB == Header || BB == ExitingBlock)
1003 continue;
1004 DominanceFrontier::iterator BBDF = DF->find(BB);
1005 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1006 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1007 while (DomSetI != DomSetE) {
1008 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1009 ++DomSetI;
1010 BasicBlock *DFBB = *CurrentItr;
1011 if (DFBB == ExitingBlock) {
1012 BBDF->second.erase(DFBB);
1013 BBDF->second.insert(Header);
1014 if (Header != ExitingBlock)
1015 BBDF->second.insert(ExitBlock);
1016 }
1017 }
1018 }
1019
Devang Patel1c013502007-09-25 17:43:08 +00001020 return true;
Devang Patel5279d062007-09-17 20:39:48 +00001021}
1022
1023
Devang Patela6a86632007-08-14 18:35:57 +00001024/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1025/// This routine is used to remove split condition's dead branch, dominated by
1026/// DeadBB. LiveBB dominates split conidition's other branch.
1027void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1028 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +00001029
Devang Patel5b8ec612007-08-15 03:31:47 +00001030 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +00001031 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +00001032 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1033 if (DeadBBDF != DF->end()) {
1034 SmallVector<BasicBlock *, 8> PredBlocks;
1035
1036 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1037 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1038 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1039 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +00001040 FrontierBBs.push_back(FrontierBB);
1041
Devang Patel5b8ec612007-08-15 03:31:47 +00001042 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1043 PredBlocks.clear();
1044 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1045 PI != PE; ++PI) {
1046 BasicBlock *P = *PI;
1047 if (P == DeadBB || DT->dominates(DeadBB, P))
1048 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001049 }
Devang Patel96bf5242007-08-17 21:59:16 +00001050
Devang Patel5b8ec612007-08-15 03:31:47 +00001051 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1052 FBI != FBE; ++FBI) {
1053 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1054 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1055 PE = PredBlocks.end(); PI != PE; ++PI) {
1056 BasicBlock *P = *PI;
1057 PN->removeIncomingValue(P);
1058 }
1059 }
1060 else
1061 break;
Devang Patel96bf5242007-08-17 21:59:16 +00001062 }
Devang Patel98147a32007-08-12 07:02:51 +00001063 }
Devang Patel98147a32007-08-12 07:02:51 +00001064 }
Devang Patel5b8ec612007-08-15 03:31:47 +00001065
1066 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1067 SmallVector<BasicBlock *, 32> WorkList;
1068 DomTreeNode *DN = DT->getNode(DeadBB);
1069 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1070 E = df_end(DN); DI != E; ++DI) {
1071 BasicBlock *BB = DI->getBlock();
1072 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +00001073 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +00001074 }
1075
1076 while (!WorkList.empty()) {
1077 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1078 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +00001079 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +00001080 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +00001081 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +00001082 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1083 I->eraseFromParent();
1084 }
1085 LPM->deleteSimpleAnalysisValue(BB, LP);
1086 DT->eraseNode(BB);
1087 DF->removeBlock(BB);
1088 LI->removeBlock(BB);
1089 BB->eraseFromParent();
1090 }
Devang Patel96bf5242007-08-17 21:59:16 +00001091
1092 // Update Frontier BBs' dominator info.
1093 while (!FrontierBBs.empty()) {
1094 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1095 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1096 if (!NewDominator) {
1097 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1098 NewDominator = *PI;
1099 ++PI;
1100 if (NewDominator != LiveBB) {
1101 for(; PI != PE; ++PI) {
1102 BasicBlock *P = *PI;
1103 if (P == LiveBB) {
1104 NewDominator = LiveBB;
1105 break;
1106 }
1107 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1108 }
1109 }
1110 }
1111 assert (NewDominator && "Unable to fix dominator info.");
1112 DT->changeImmediateDominator(FBB, NewDominator);
1113 DF->changeImmediateDominator(FBB, NewDominator, DT);
1114 }
1115
Devang Patel98147a32007-08-12 07:02:51 +00001116}
1117
Devang Pateldc523952007-08-22 18:27:01 +00001118/// safeSplitCondition - Return true if it is possible to
1119/// split loop using given split condition.
1120bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
Devang Patel23a19f82007-08-10 00:53:35 +00001121
Devang Pateldc523952007-08-22 18:27:01 +00001122 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
Devang Patel8893ca62007-09-17 21:01:05 +00001123 BasicBlock *Latch = L->getLoopLatch();
Devang Pateldc523952007-08-22 18:27:01 +00001124 BranchInst *SplitTerminator =
1125 cast<BranchInst>(SplitCondBlock->getTerminator());
1126 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1127 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
Devang Patel20d260a2007-08-18 00:00:32 +00001128
Devang Patelb88e4202007-08-24 05:36:56 +00001129 // Finally this split condition is safe only if merge point for
1130 // split condition branch is loop latch. This check along with previous
1131 // check, to ensure that exit condition is in either loop latch or header,
1132 // filters all loops with non-empty loop body between merge point
1133 // and exit condition.
1134 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1135 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1136 if (Succ0DF->second.count(Latch))
1137 return true;
1138
1139 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1140 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1141 if (Succ1DF->second.count(Latch))
1142 return true;
1143
1144 return false;
Devang Pateldc523952007-08-22 18:27:01 +00001145}
1146
Devang Patel4a69da92007-08-25 00:56:38 +00001147/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1148/// based on split value.
1149void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1150
Devang Patel4f12c5f2007-09-11 00:12:56 +00001151 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1152 ICmpInst::Predicate SP = SC->getPredicate();
Devang Patel4a69da92007-08-25 00:56:38 +00001153 const Type *Ty = SD.SplitValue->getType();
1154 bool Sign = ExitCondition->isSignedPredicate();
1155 BasicBlock *Preheader = L->getLoopPreheader();
1156 Instruction *PHTerminator = Preheader->getTerminator();
1157
1158 // Initially use split value as upper loop bound for first loop and lower loop
1159 // bound for second loop.
1160 Value *AEV = SD.SplitValue;
1161 Value *BSV = SD.SplitValue;
1162
Devang Patelbabbe272007-09-19 00:28:47 +00001163 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1164 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1165 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1166 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)
1167 ExitCondition->swapOperands();
1168
Devang Patel4a69da92007-08-25 00:56:38 +00001169 switch (ExitCondition->getPredicate()) {
1170 case ICmpInst::ICMP_SGT:
1171 case ICmpInst::ICMP_UGT:
1172 case ICmpInst::ICMP_SGE:
1173 case ICmpInst::ICMP_UGE:
1174 default:
1175 assert (0 && "Unexpected exit condition predicate");
1176
1177 case ICmpInst::ICMP_SLT:
1178 case ICmpInst::ICMP_ULT:
1179 {
1180 switch (SP) {
1181 case ICmpInst::ICMP_SLT:
1182 case ICmpInst::ICMP_ULT:
1183 //
1184 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1185 //
1186 // is transformed into
1187 // AEV = BSV = SV
1188 // for (i = LB; i < min(UB, AEV); ++i)
1189 // A;
1190 // for (i = max(LB, BSV); i < UB; ++i);
1191 // B;
1192 break;
1193 case ICmpInst::ICMP_SLE:
1194 case ICmpInst::ICMP_ULE:
1195 {
1196 //
1197 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1198 //
1199 // is transformed into
1200 //
1201 // AEV = SV + 1
1202 // BSV = SV + 1
1203 // for (i = LB; i < min(UB, AEV); ++i)
1204 // A;
1205 // for (i = max(LB, BSV); i < UB; ++i)
1206 // B;
1207 BSV = BinaryOperator::createAdd(SD.SplitValue,
1208 ConstantInt::get(Ty, 1, Sign),
1209 "lsplit.add", PHTerminator);
1210 AEV = BSV;
1211 }
1212 break;
1213 case ICmpInst::ICMP_SGE:
1214 case ICmpInst::ICMP_UGE:
1215 //
1216 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1217 //
1218 // is transformed into
1219 // AEV = BSV = SV
1220 // for (i = LB; i < min(UB, AEV); ++i)
1221 // B;
1222 // for (i = max(BSV, LB); i < UB; ++i)
1223 // A;
1224 break;
1225 case ICmpInst::ICMP_SGT:
1226 case ICmpInst::ICMP_UGT:
1227 {
1228 //
1229 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1230 //
1231 // is transformed into
1232 //
1233 // BSV = AEV = SV + 1
1234 // for (i = LB; i < min(UB, AEV); ++i)
1235 // B;
1236 // for (i = max(LB, BSV); i < UB; ++i)
1237 // A;
1238 BSV = BinaryOperator::createAdd(SD.SplitValue,
1239 ConstantInt::get(Ty, 1, Sign),
1240 "lsplit.add", PHTerminator);
1241 AEV = BSV;
1242 }
1243 break;
1244 default:
1245 assert (0 && "Unexpected split condition predicate");
1246 break;
1247 } // end switch (SP)
1248 }
1249 break;
1250 case ICmpInst::ICMP_SLE:
1251 case ICmpInst::ICMP_ULE:
1252 {
1253 switch (SP) {
1254 case ICmpInst::ICMP_SLT:
1255 case ICmpInst::ICMP_ULT:
1256 //
1257 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1258 //
1259 // is transformed into
1260 // AEV = SV - 1;
1261 // BSV = SV;
1262 // for (i = LB; i <= min(UB, AEV); ++i)
1263 // A;
1264 // for (i = max(LB, BSV); i <= UB; ++i)
1265 // B;
1266 AEV = BinaryOperator::createSub(SD.SplitValue,
1267 ConstantInt::get(Ty, 1, Sign),
1268 "lsplit.sub", PHTerminator);
1269 break;
1270 case ICmpInst::ICMP_SLE:
1271 case ICmpInst::ICMP_ULE:
1272 //
1273 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1274 //
1275 // is transformed into
1276 // AEV = SV;
1277 // BSV = SV + 1;
1278 // for (i = LB; i <= min(UB, AEV); ++i)
1279 // A;
1280 // for (i = max(LB, BSV); i <= UB; ++i)
1281 // B;
1282 BSV = BinaryOperator::createAdd(SD.SplitValue,
1283 ConstantInt::get(Ty, 1, Sign),
1284 "lsplit.add", PHTerminator);
1285 break;
1286 case ICmpInst::ICMP_SGT:
1287 case ICmpInst::ICMP_UGT:
1288 //
1289 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1290 //
1291 // is transformed into
1292 // AEV = SV;
1293 // BSV = SV + 1;
1294 // for (i = LB; i <= min(AEV, UB); ++i)
1295 // B;
1296 // for (i = max(LB, BSV); i <= UB; ++i)
1297 // A;
1298 BSV = BinaryOperator::createAdd(SD.SplitValue,
1299 ConstantInt::get(Ty, 1, Sign),
1300 "lsplit.add", PHTerminator);
1301 break;
1302 case ICmpInst::ICMP_SGE:
1303 case ICmpInst::ICMP_UGE:
1304 // ** TODO **
1305 //
1306 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1307 //
1308 // is transformed into
1309 // AEV = SV - 1;
1310 // BSV = SV;
1311 // for (i = LB; i <= min(AEV, UB); ++i)
1312 // B;
1313 // for (i = max(LB, BSV); i <= UB; ++i)
1314 // A;
1315 AEV = BinaryOperator::createSub(SD.SplitValue,
1316 ConstantInt::get(Ty, 1, Sign),
1317 "lsplit.sub", PHTerminator);
1318 break;
1319 default:
1320 assert (0 && "Unexpected split condition predicate");
1321 break;
1322 } // end switch (SP)
1323 }
1324 break;
1325 }
1326
1327 // Calculate ALoop induction variable's new exiting value and
1328 // BLoop induction variable's new starting value. Calculuate these
1329 // values in original loop's preheader.
1330 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1331 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
Devang Patel3f65f022007-09-21 21:18:19 +00001332 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
Devang Patel5ffdc562007-12-03 19:17:21 +00001333
1334 // If ExitValue operand is also defined in Loop header then
1335 // insert new ExitValue after this operand definition.
1336 if (Instruction *EVN =
1337 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1338 if (!isa<PHINode>(EVN))
1339 if (InsertPt->getParent() == EVN->getParent()) {
1340 BasicBlock::iterator LHBI = L->getHeader()->begin();
1341 BasicBlock::iterator LHBE = L->getHeader()->end();
1342 for(;LHBI != LHBE; ++LHBI) {
1343 Instruction *I = LHBI;
1344 if (I == EVN)
1345 break;
1346 }
1347 InsertPt = ++LHBI;
1348 }
1349 }
Devang Patel4a69da92007-08-25 00:56:38 +00001350 Value *C1 = new ICmpInst(Sign ?
1351 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1352 AEV,
1353 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001354 "lsplit.ev", InsertPt);
1355
Devang Patel4a69da92007-08-25 00:56:38 +00001356 SD.A_ExitValue = new SelectInst(C1, AEV,
1357 ExitCondition->getOperand(ExitValueNum),
Devang Patel3f65f022007-09-21 21:18:19 +00001358 "lsplit.ev", InsertPt);
1359
Devang Patel4a69da92007-08-25 00:56:38 +00001360 Value *C2 = new ICmpInst(Sign ?
1361 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1362 BSV, StartValue, "lsplit.sv",
1363 PHTerminator);
1364 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
1365 "lsplit.sv", PHTerminator);
1366}
1367
Devang Pateldc523952007-08-22 18:27:01 +00001368/// splitLoop - Split current loop L in two loops using split information
1369/// SD. Update dominator information. Maintain LCSSA form.
1370bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1371
1372 if (!safeSplitCondition(SD))
1373 return false;
1374
Devang Patel8893ca62007-09-17 21:01:05 +00001375 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1376
1377 // Unable to handle triange loops at the moment.
1378 // In triangle loop, split condition is in header and one of the
1379 // the split destination is loop latch. If split condition is EQ
1380 // then such loops are already handle in processOneIterationLoop().
1381 BasicBlock *Latch = L->getLoopLatch();
1382 BranchInst *SplitTerminator =
1383 cast<BranchInst>(SplitCondBlock->getTerminator());
1384 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1385 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1386 if (L->getHeader() == SplitCondBlock
1387 && (Latch == Succ0 || Latch == Succ1))
1388 return false;
1389
1390 // If split condition branches heads do not have single predecessor,
1391 // SplitCondBlock, then is not possible to remove inactive branch.
1392 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1393 return false;
1394
Devang Patela8644e32007-08-22 19:33:29 +00001395 // After loop is cloned there are two loops.
1396 //
1397 // First loop, referred as ALoop, executes first part of loop's iteration
1398 // space split. Second loop, referred as BLoop, executes remaining
1399 // part of loop's iteration space.
1400 //
1401 // ALoop's exit edge enters BLoop's header through a forwarding block which
1402 // acts as a BLoop's preheader.
Devang Patel4a69da92007-08-25 00:56:38 +00001403 BasicBlock *Preheader = L->getLoopPreheader();
Devang Pateldc523952007-08-22 18:27:01 +00001404
Devang Patel4a69da92007-08-25 00:56:38 +00001405 // Calculate ALoop induction variable's new exiting value and
1406 // BLoop induction variable's new starting value.
1407 calculateLoopBounds(SD);
Devang Patel423c8b22007-08-10 18:07:13 +00001408
Devang Patela8644e32007-08-22 19:33:29 +00001409 //[*] Clone loop.
Devang Patel98147a32007-08-12 07:02:51 +00001410 DenseMap<const Value *, Value *> ValueMap;
Devang Patela8644e32007-08-22 19:33:29 +00001411 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
Devang Pateld79faee2007-08-25 02:39:24 +00001412 Loop *ALoop = L;
Devang Patela8644e32007-08-22 19:33:29 +00001413 BasicBlock *B_Header = BLoop->getHeader();
Devang Patel98147a32007-08-12 07:02:51 +00001414
Devang Patela8644e32007-08-22 19:33:29 +00001415 //[*] ALoop's exiting edge BLoop's header.
1416 // ALoop's original exit block becomes BLoop's exit block.
1417 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1418 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1419 BranchInst *A_ExitInsn =
1420 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1421 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1422 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1423 if (L->contains(B_ExitBlock)) {
1424 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1425 A_ExitInsn->setSuccessor(0, B_Header);
Devang Patelada054a2007-08-14 01:30:57 +00001426 } else
Devang Patela8644e32007-08-22 19:33:29 +00001427 A_ExitInsn->setSuccessor(1, B_Header);
1428
1429 //[*] Update ALoop's exit value using new exit value.
Devang Patel4a69da92007-08-25 00:56:38 +00001430 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001431
Devang Patela8644e32007-08-22 19:33:29 +00001432 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1433 // original loop's preheader. Add incoming PHINode values from
1434 // ALoop's exiting block. Update BLoop header's domiantor info.
1435
Devang Patelada054a2007-08-14 01:30:57 +00001436 // Collect inverse map of Header PHINodes.
1437 DenseMap<Value *, Value *> InverseMap;
1438 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1439 BE = L->getHeader()->end(); BI != BE; ++BI) {
1440 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1441 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1442 InverseMap[PNClone] = PN;
1443 } else
1444 break;
1445 }
Devang Patel4a69da92007-08-25 00:56:38 +00001446
Devang Patela8644e32007-08-22 19:33:29 +00001447 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel98147a32007-08-12 07:02:51 +00001448 BI != BE; ++BI) {
1449 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001450 // Remove incoming value from original preheader.
1451 PN->removeIncomingValue(Preheader);
1452
1453 // Add incoming value from A_ExitingBlock.
1454 if (PN == B_IndVar)
Devang Patel4a69da92007-08-25 00:56:38 +00001455 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001456 else {
1457 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
Devang Patela8644e32007-08-22 19:33:29 +00001458 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1459 PN->addIncoming(V2, A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001460 }
1461 } else
Devang Patel98147a32007-08-12 07:02:51 +00001462 break;
1463 }
Devang Patela8644e32007-08-22 19:33:29 +00001464 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1465 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
Devang Patel0b8e02b2007-08-21 21:12:02 +00001466
Devang Patela8644e32007-08-22 19:33:29 +00001467 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1468 // block. Remove incoming PHINode values from ALoop's exiting block.
1469 // Add new incoming values from BLoop's incoming exiting value.
1470 // Update BLoop exit block's dominator info..
1471 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1472 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
Devang Patelada054a2007-08-14 01:30:57 +00001473 BI != BE; ++BI) {
1474 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001475 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1476 B_ExitingBlock);
1477 PN->removeIncomingValue(A_ExitingBlock);
Devang Patelada054a2007-08-14 01:30:57 +00001478 } else
1479 break;
1480 }
Devang Patel98147a32007-08-12 07:02:51 +00001481
Devang Patela8644e32007-08-22 19:33:29 +00001482 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1483 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
Devang Patelfc4c5f82007-08-13 22:13:24 +00001484
Devang Patela8644e32007-08-22 19:33:29 +00001485 //[*] Split ALoop's exit edge. This creates a new block which
1486 // serves two purposes. First one is to hold PHINode defnitions
1487 // to ensure that ALoop's LCSSA form. Second use it to act
1488 // as a preheader for BLoop.
1489 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
Devang Patel423c8b22007-08-10 18:07:13 +00001490
Devang Patela8644e32007-08-22 19:33:29 +00001491 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1492 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1493 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
Devang Patel60cbab42007-08-21 19:47:46 +00001494 BI != BE; ++BI) {
1495 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Devang Patela8644e32007-08-22 19:33:29 +00001496 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001497 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
Devang Patela8644e32007-08-22 19:33:29 +00001498 newPHI->addIncoming(V1, A_ExitingBlock);
1499 A_ExitBlock->getInstList().push_front(newPHI);
1500 PN->removeIncomingValue(A_ExitBlock);
1501 PN->addIncoming(newPHI, A_ExitBlock);
Devang Patel60cbab42007-08-21 19:47:46 +00001502 } else
1503 break;
1504 }
1505
Devang Patela8644e32007-08-22 19:33:29 +00001506 //[*] Eliminate split condition's inactive branch from ALoop.
1507 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1508 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001509 BasicBlock *A_InactiveBranch = NULL;
1510 BasicBlock *A_ActiveBranch = NULL;
1511 if (SD.UseTrueBranchFirst) {
1512 A_ActiveBranch = A_BR->getSuccessor(0);
1513 A_InactiveBranch = A_BR->getSuccessor(1);
1514 } else {
1515 A_ActiveBranch = A_BR->getSuccessor(1);
1516 A_InactiveBranch = A_BR->getSuccessor(0);
1517 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001518 A_BR->setUnconditionalDest(A_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001519 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1520
1521 //[*] Eliminate split condition's inactive branch in from BLoop.
1522 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1523 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
Devang Patel4259fe32007-08-24 06:17:19 +00001524 BasicBlock *B_InactiveBranch = NULL;
1525 BasicBlock *B_ActiveBranch = NULL;
1526 if (SD.UseTrueBranchFirst) {
1527 B_ActiveBranch = B_BR->getSuccessor(1);
1528 B_InactiveBranch = B_BR->getSuccessor(0);
1529 } else {
1530 B_ActiveBranch = B_BR->getSuccessor(0);
1531 B_InactiveBranch = B_BR->getSuccessor(1);
1532 }
Devang Patel7097e9a2007-08-24 19:32:26 +00001533 B_BR->setUnconditionalDest(B_ActiveBranch);
Devang Patela8644e32007-08-22 19:33:29 +00001534 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1535
Devang Pateld79faee2007-08-25 02:39:24 +00001536 BasicBlock *A_Header = L->getHeader();
1537 if (A_ExitingBlock == A_Header)
1538 return true;
1539
1540 //[*] Move exit condition into split condition block to avoid
1541 // executing dead loop iteration.
1542 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1543 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1544 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1545
1546 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
Devang Patel4f12c5f2007-09-11 00:12:56 +00001547 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1548 ALoop);
Devang Pateld79faee2007-08-25 02:39:24 +00001549
1550 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1551 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1552
Devang Patel98147a32007-08-12 07:02:51 +00001553 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +00001554}
Devang Pateld79faee2007-08-25 02:39:24 +00001555
1556// moveExitCondition - Move exit condition EC into split condition block CondBB.
1557void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1558 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1559 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1560
1561 BasicBlock *ExitingBB = EC->getParent();
1562 Instruction *CurrentBR = CondBB->getTerminator();
1563
1564 // Move exit condition into split condition block.
1565 EC->moveBefore(CurrentBR);
1566 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1567
1568 // Move exiting block's branch into split condition block. Update its branch
1569 // destination.
1570 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1571 ExitingBR->moveBefore(CurrentBR);
1572 if (ExitingBR->getSuccessor(0) == ExitBB)
1573 ExitingBR->setSuccessor(1, ActiveBB);
1574 else
1575 ExitingBR->setSuccessor(0, ActiveBB);
1576
1577 // Remove split condition and current split condition branch.
1578 SC->eraseFromParent();
1579 CurrentBR->eraseFromParent();
1580
1581 // Connect exiting block to split condition block.
1582 new BranchInst(CondBB, ExitingBB);
1583
1584 // Update PHINodes
1585 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1586
1587 // Fix dominator info.
1588 // ExitBB is now dominated by CondBB
1589 DT->changeImmediateDominator(ExitBB, CondBB);
1590 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1591
1592 // Basicblocks dominated by ActiveBB may have ExitingBB or
1593 // a basic block outside the loop in their DF list. If so,
1594 // replace it with CondBB.
1595 DomTreeNode *Node = DT->getNode(ActiveBB);
1596 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1597 DI != DE; ++DI) {
1598 BasicBlock *BB = DI->getBlock();
1599 DominanceFrontier::iterator BBDF = DF->find(BB);
1600 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1601 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1602 while (DomSetI != DomSetE) {
1603 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1604 ++DomSetI;
1605 BasicBlock *DFBB = *CurrentItr;
1606 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1607 BBDF->second.erase(DFBB);
1608 BBDF->second.insert(CondBB);
1609 }
1610 }
1611 }
1612}
1613
1614/// updatePHINodes - CFG has been changed.
1615/// Before
1616/// - ExitBB's single predecessor was Latch
1617/// - Latch's second successor was Header
1618/// Now
1619/// - ExitBB's single predecessor was Header
1620/// - Latch's one and only successor was Header
1621///
1622/// Update ExitBB PHINodes' to reflect this change.
1623void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1624 BasicBlock *Header,
1625 PHINode *IV, Instruction *IVIncrement) {
1626
1627 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1628 BI != BE; ++BI) {
1629 PHINode *PN = dyn_cast<PHINode>(BI);
1630 if (!PN)
1631 break;
1632
1633 Value *V = PN->getIncomingValueForBlock(Latch);
1634 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1635 // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode
1636 // (i.e. PN :)).
1637 // The second use is in Header and it is new incoming value for PN.
1638 PHINode *U1 = NULL;
1639 PHINode *U2 = NULL;
1640 Value *NewV = NULL;
1641 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1642 UI != E; ++UI) {
1643 if (!U1)
1644 U1 = cast<PHINode>(*UI);
1645 else if (!U2)
1646 U2 = cast<PHINode>(*UI);
1647 else
1648 assert ( 0 && "Unexpected third use of this PHINode");
1649 }
1650 assert (U1 && U2 && "Unable to find two uses");
1651
1652 if (U1->getParent() == Header)
1653 NewV = U1;
1654 else
1655 NewV = U2;
1656 PN->addIncoming(NewV, Header);
1657
1658 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1659 // If this instruction is IVIncrement then IV is new incoming value
1660 // from header otherwise this instruction must be incoming value from
1661 // header because loop is in LCSSA form.
1662 if (PHI == IVIncrement)
1663 PN->addIncoming(IV, Header);
1664 else
1665 PN->addIncoming(V, Header);
1666 } else
1667 // Otherwise this is an incoming value from header because loop is in
1668 // LCSSA form.
1669 PN->addIncoming(V, Header);
1670
1671 // Remove incoming value from Latch.
1672 PN->removeIncomingValue(Latch);
1673 }
1674}