blob: e93d448cc1be826f5f71310d89aacfd3b56a8880 [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//
Devang Patel38310052008-12-04 21:38:42 +000010// This file implements Loop Index Splitting Pass. This pass handles three
11// kinds of loops.
Devang Patelfee76bd2007-08-07 00:25:56 +000012//
Devang Patel38310052008-12-04 21:38:42 +000013// [1] Loop is eliminated when loop body is executed only once. For example,
14// for (i = 0; i < N; ++i) {
15// if ( i == X) {
16// ...
17// }
18// }
19//
20// [2] Loop's iteration space is shrunk if loop body is executed for certain
21// range only. For example,
22//
23// for (i = 0; i < N; ++i) {
24// if ( i > A && i < B) {
25// ...
26// }
27// }
28// is trnasformed to iterators from A to B, if A > 0 and B < N.
29//
30// [3] Loop is split if the loop body is dominated by an branch. For example,
31//
32// for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
33//
34// is transformed into
35// AEV = BSV = SV
36// for (i = LB; i < min(UB, AEV); ++i)
37// A;
38// for (i = max(LB, BSV); i < UB; ++i);
39// B;
Devang Patelfee76bd2007-08-07 00:25:56 +000040//===----------------------------------------------------------------------===//
41
42#define DEBUG_TYPE "loop-index-split"
43
Devang Patelfee76bd2007-08-07 00:25:56 +000044#include "llvm/Transforms/Scalar.h"
Devang Pateld96c60d2009-02-06 06:19:06 +000045#include "llvm/IntrinsicInst.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000046#include "llvm/Analysis/LoopPass.h"
Dan Gohman97b6e2c2009-02-17 20:50:11 +000047#include "llvm/Analysis/ScalarEvolution.h"
Devang Patel787a7132007-08-08 21:39:47 +000048#include "llvm/Analysis/Dominators.h"
Devang Patel423c8b22007-08-10 18:07:13 +000049#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Cloning.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000051#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000052#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000053#include "llvm/ADT/Statistic.h"
54
55using namespace llvm;
56
Devang Patel38310052008-12-04 21:38:42 +000057STATISTIC(NumIndexSplit, "Number of loop index split");
58STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
59STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
Devang Patelfee76bd2007-08-07 00:25:56 +000060
61namespace {
62
63 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
64
65 public:
66 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000068
69 // Index split Loop L. Return true if loop is split.
70 bool runOnLoop(Loop *L, LPPassManager &LPM);
71
72 void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfee76bd2007-08-07 00:25:56 +000073 AU.addPreserved<ScalarEvolution>();
74 AU.addRequiredID(LCSSAID);
75 AU.addPreservedID(LCSSAID);
Devang Patel423c8b22007-08-10 18:07:13 +000076 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000077 AU.addPreserved<LoopInfo>();
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000080 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000081 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000082 AU.addPreserved<DominatorTree>();
83 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000084 }
85
86 private:
Devang Patel38310052008-12-04 21:38:42 +000087 /// processOneIterationLoop -- Eliminate loop if loop body is executed
88 /// only once. For example,
89 /// for (i = 0; i < N; ++i) {
90 /// if ( i == X) {
91 /// ...
92 /// }
93 /// }
94 ///
95 bool processOneIterationLoop();
Devang Patel71554b82007-08-08 21:02:17 +000096
Devang Patel38310052008-12-04 21:38:42 +000097 // -- Routines used by updateLoopIterationSpace();
Devang Patelc9d123d2007-08-09 01:39:01 +000098
Devang Patel38310052008-12-04 21:38:42 +000099 /// updateLoopIterationSpace -- Update loop's iteration space if loop
100 /// body is executed for certain IV range only. For example,
101 ///
102 /// for (i = 0; i < N; ++i) {
103 /// if ( i > A && i < B) {
104 /// ...
105 /// }
106 /// }
Devang Patel042b8772008-12-08 17:07:24 +0000107 /// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000108 ///
109 bool updateLoopIterationSpace();
Devang Patel71554b82007-08-08 21:02:17 +0000110
Devang Patel38310052008-12-04 21:38:42 +0000111 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
112 /// with a loop invariant value. Update loop's lower and upper bound based on
113 /// the loop invariant value.
114 bool restrictLoopBound(ICmpInst &Op);
Devang Patel4a69da92007-08-25 00:56:38 +0000115
Devang Patel38310052008-12-04 21:38:42 +0000116 // --- Routines used by splitLoop(). --- /
Devang Patel4a69da92007-08-25 00:56:38 +0000117
Devang Patel38310052008-12-04 21:38:42 +0000118 bool splitLoop();
Devang Patel4a69da92007-08-25 00:56:38 +0000119
Devang Patel38310052008-12-04 21:38:42 +0000120 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
121 /// DeadBB. This routine is used to remove split condition's dead branch,
122 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
Devang Patela6a86632007-08-14 18:35:57 +0000123 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel38310052008-12-04 21:38:42 +0000124
125 /// moveExitCondition - Move exit condition EC into split condition block.
126 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
127 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
128 PHINode *IV, Instruction *IVAdd, Loop *LP,
129 unsigned);
130
Devang Pateld79faee2007-08-25 02:39:24 +0000131 /// updatePHINodes - CFG has been changed.
132 /// Before
133 /// - ExitBB's single predecessor was Latch
134 /// - Latch's second successor was Header
135 /// Now
136 /// - ExitBB's single predecessor was Header
137 /// - Latch's one and only successor was Header
138 ///
139 /// Update ExitBB PHINodes' to reflect this change.
140 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
141 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000142 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000143
Devang Patel38310052008-12-04 21:38:42 +0000144 // --- Utility routines --- /
Devang Pateld79faee2007-08-25 02:39:24 +0000145
Devang Patel38310052008-12-04 21:38:42 +0000146 /// cleanBlock - A block is considered clean if all non terminal
147 /// instructions are either PHINodes or IV based values.
148 bool cleanBlock(BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000149
Devang Patel042b8772008-12-08 17:07:24 +0000150 /// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000151 /// IV based value is less than the loop invariant then return the loop
152 /// invariant. Otherwise return NULL.
153 Value * IVisLT(ICmpInst &Op);
154
Devang Patel042b8772008-12-08 17:07:24 +0000155 /// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000156 /// IV based value is less than or equal to the loop invariant then
157 /// return the loop invariant. Otherwise return NULL.
158 Value * IVisLE(ICmpInst &Op);
159
Devang Patel042b8772008-12-08 17:07:24 +0000160 /// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000161 /// IV based value is greater than the loop invariant then return the loop
162 /// invariant. Otherwise return NULL.
163 Value * IVisGT(ICmpInst &Op);
164
Devang Patel042b8772008-12-08 17:07:24 +0000165 /// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000166 /// IV based value is greater than or equal to the loop invariant then
167 /// return the loop invariant. Otherwise return NULL.
168 Value * IVisGE(ICmpInst &Op);
Devang Patelbacf5192007-08-10 00:33:50 +0000169
Devang Patelfee76bd2007-08-07 00:25:56 +0000170 private:
171
Devang Patel38310052008-12-04 21:38:42 +0000172 // Current Loop information.
Devang Patelfee76bd2007-08-07 00:25:56 +0000173 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000174 LPPassManager *LPM;
175 LoopInfo *LI;
Devang Patel9704fcf2007-08-08 22:25:28 +0000176 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000177 DominanceFrontier *DF;
Devang Patelbacf5192007-08-10 00:33:50 +0000178
Devang Patelbacf5192007-08-10 00:33:50 +0000179 PHINode *IndVar;
Devang Patelbacf5192007-08-10 00:33:50 +0000180 ICmpInst *ExitCondition;
Devang Patel38310052008-12-04 21:38:42 +0000181 ICmpInst *SplitCondition;
182 Value *IVStartValue;
183 Value *IVExitValue;
184 Instruction *IVIncrement;
185 SmallPtrSet<Value *, 4> IVBasedValues;
Devang Patelfee76bd2007-08-07 00:25:56 +0000186 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000187}
188
Dan Gohman844731a2008-05-13 00:00:25 +0000189char LoopIndexSplit::ID = 0;
190static RegisterPass<LoopIndexSplit>
191X("loop-index-split", "Index Split Loops");
192
Daniel Dunbar394f0442008-10-22 23:32:42 +0000193Pass *llvm::createLoopIndexSplitPass() {
Devang Patelfee76bd2007-08-07 00:25:56 +0000194 return new LoopIndexSplit();
195}
196
197// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000198bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000199 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000200 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000201
Devang Patel3fe4f212007-08-15 02:14:55 +0000202 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000203 if (!L->getSubLoops().empty())
204 return false;
205
Devang Patel9704fcf2007-08-08 22:25:28 +0000206 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000207 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000208 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000209
Devang Patel38310052008-12-04 21:38:42 +0000210 // Initialize loop data.
211 IndVar = L->getCanonicalInductionVariable();
212 if (!IndVar) return false;
Devang Patelbacf5192007-08-10 00:33:50 +0000213
Devang Patel38310052008-12-04 21:38:42 +0000214 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
215 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
216 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
217 if (!IVIncrement) return false;
Devang Patel71554b82007-08-08 21:02:17 +0000218
Devang Patel38310052008-12-04 21:38:42 +0000219 IVBasedValues.clear();
220 IVBasedValues.insert(IndVar);
221 IVBasedValues.insert(IVIncrement);
Devang Patelbacf5192007-08-10 00:33:50 +0000222 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Devang Patel38310052008-12-04 21:38:42 +0000223 I != E; ++I)
224 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
225 BI != BE; ++BI) {
226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
227 if (BO != IVIncrement
228 && (BO->getOpcode() == Instruction::Add
229 || BO->getOpcode() == Instruction::Sub))
230 if (IVBasedValues.count(BO->getOperand(0))
231 && L->isLoopInvariant(BO->getOperand(1)))
232 IVBasedValues.insert(BO);
233 }
Devang Patelbacf5192007-08-10 00:33:50 +0000234
Devang Patel38310052008-12-04 21:38:42 +0000235 // Reject loop if loop exit condition is not suitable.
Dan Gohmanc8332462009-02-12 18:08:24 +0000236 BasicBlock *ExitingBlock = L->getExitingBlock();
237 if (!ExitingBlock)
Devang Patel38310052008-12-04 21:38:42 +0000238 return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000239 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel38310052008-12-04 21:38:42 +0000240 if (!EBR) return false;
241 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
242 if (!ExitCondition) return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000243 if (ExitingBlock != L->getLoopLatch()) return false;
Devang Patel38310052008-12-04 21:38:42 +0000244 IVExitValue = ExitCondition->getOperand(1);
245 if (!L->isLoopInvariant(IVExitValue))
246 IVExitValue = ExitCondition->getOperand(0);
247 if (!L->isLoopInvariant(IVExitValue))
248 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000249
250 // If start value is more then exit value where induction variable
251 // increments by 1 then we are potentially dealing with an infinite loop.
252 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000253 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
254 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
255 if (SV->getSExtValue() > EV->getSExtValue())
256 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000257
Devang Patel38310052008-12-04 21:38:42 +0000258 if (processOneIterationLoop())
259 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000260
Devang Patel38310052008-12-04 21:38:42 +0000261 if (updateLoopIterationSpace())
262 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000263
Devang Patel38310052008-12-04 21:38:42 +0000264 if (splitLoop())
265 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000266
267 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000268}
269
Devang Patel38310052008-12-04 21:38:42 +0000270// --- Helper routines ---
271// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
272static bool isUsedOutsideLoop(Value *V, Loop *L) {
273 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
274 if (!L->contains(cast<Instruction>(*UI)->getParent()))
275 return true;
276 return false;
277}
Devang Patelfee76bd2007-08-07 00:25:56 +0000278
Devang Patel38310052008-12-04 21:38:42 +0000279// Return V+1
280static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
281 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
282 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
283}
Devang Patelfee76bd2007-08-07 00:25:56 +0000284
Devang Patel38310052008-12-04 21:38:42 +0000285// Return V-1
286static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
287 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
288 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
289}
Devang Patelfee76bd2007-08-07 00:25:56 +0000290
Devang Patel38310052008-12-04 21:38:42 +0000291// Return min(V1, V1)
292static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
293
294 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
295 V1, V2, "lsp", InsertPt);
296 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
297}
Devang Patelfee76bd2007-08-07 00:25:56 +0000298
Devang Patel38310052008-12-04 21:38:42 +0000299// Return max(V1, V2)
300static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
301
302 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
303 V1, V2, "lsp", InsertPt);
304 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
305}
Devang Patel968eee22007-09-19 00:15:16 +0000306
Devang Patel38310052008-12-04 21:38:42 +0000307/// processOneIterationLoop -- Eliminate loop if loop body is executed
308/// only once. For example,
309/// for (i = 0; i < N; ++i) {
310/// if ( i == X) {
311/// ...
312/// }
313/// }
314///
315bool LoopIndexSplit::processOneIterationLoop() {
316 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000317 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000318 BasicBlock *Header = L->getHeader();
319 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
320 if (!BR) return false;
321 if (!isa<BranchInst>(Latch->getTerminator())) return false;
322 if (BR->isUnconditional()) return false;
323 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
324 if (!SplitCondition) return false;
325 if (SplitCondition == ExitCondition) return false;
326 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
327 if (BR->getOperand(1) != Latch) return false;
328 if (!IVBasedValues.count(SplitCondition->getOperand(0))
329 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000330 return false;
331
Devang Patel38310052008-12-04 21:38:42 +0000332 // If IV is used outside the loop then this loop traversal is required.
333 // FIXME: Calculate and use last IV value.
334 if (isUsedOutsideLoop(IVIncrement, L))
335 return false;
336
337 // If BR operands are not IV or not loop invariants then skip this loop.
338 Value *OPV = SplitCondition->getOperand(0);
339 Value *SplitValue = SplitCondition->getOperand(1);
340 if (!L->isLoopInvariant(SplitValue)) {
341 Value *T = SplitValue;
342 SplitValue = OPV;
343 OPV = T;
344 }
345 if (!L->isLoopInvariant(SplitValue))
346 return false;
347 Instruction *OPI = dyn_cast<Instruction>(OPV);
348 if (!OPI) return false;
349 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
350 return false;
351
352 if (!cleanBlock(Header))
353 return false;
354
355 if (!cleanBlock(Latch))
356 return false;
357
358 // If the merge point for BR is not loop latch then skip this loop.
359 if (BR->getSuccessor(0) != Latch) {
360 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
361 assert (DF0 != DF->end() && "Unable to find dominance frontier");
362 if (!DF0->second.count(Latch))
363 return false;
364 }
365
366 if (BR->getSuccessor(1) != Latch) {
367 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
368 assert (DF1 != DF->end() && "Unable to find dominance frontier");
369 if (!DF1->second.count(Latch))
370 return false;
371 }
372
373 // Now, Current loop L contains compare instruction
374 // that compares induction variable, IndVar, against loop invariant. And
375 // entire (i.e. meaningful) loop body is dominated by this compare
376 // instruction. In such case eliminate
377 // loop structure surrounding this loop body. For example,
378 // for (int i = start; i < end; ++i) {
379 // if ( i == somevalue) {
380 // loop_body
381 // }
382 // }
383 // can be transformed into
384 // if (somevalue >= start && somevalue < end) {
385 // i = somevalue;
386 // loop_body
387 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000388
Devang Patelebc5fea2007-08-20 20:49:01 +0000389 // Replace index variable with split value in loop body. Loop body is executed
390 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000391 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000392
Devang Patelfee76bd2007-08-07 00:25:56 +0000393 // Replace split condition in header.
394 // Transform
395 // SplitCondition : icmp eq i32 IndVar, SplitValue
396 // into
397 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000398 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000399 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000400 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000401 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patel38310052008-12-04 21:38:42 +0000402 SplitValue, IVStartValue, "lisplit", BR);
403
404 CmpInst::Predicate C2P = ExitCondition->getPredicate();
405 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
406 if (LatchBR->getOperand(0) != Header)
407 C2P = CmpInst::getInversePredicate(C2P);
408 Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
409 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
410
411 SplitCondition->replaceAllUsesWith(NSplitCond);
412 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000413
Devang Patelfc19fbd2008-10-10 22:02:57 +0000414 // Remove Latch to Header edge.
415 BasicBlock *LatchSucc = NULL;
416 Header->removePredecessor(Latch);
417 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
418 SI != E; ++SI) {
419 if (Header != *SI)
420 LatchSucc = *SI;
421 }
Devang Patel38310052008-12-04 21:38:42 +0000422 LatchBR->setUnconditionalDest(LatchSucc);
Devang Patelfc19fbd2008-10-10 22:02:57 +0000423
Devang Patel38310052008-12-04 21:38:42 +0000424 // Remove IVIncrement
425 IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
426 IVIncrement->eraseFromParent();
427
Devang Patel423c8b22007-08-10 18:07:13 +0000428 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000429
430 // Update Dominator Info.
431 // Only CFG change done is to remove Latch to Header edge. This
432 // does not change dominator tree because Latch did not dominate
433 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000434 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000435 DominanceFrontier::iterator HeaderDF = DF->find(Header);
436 if (HeaderDF != DF->end())
437 DF->removeFromFrontier(HeaderDF, Header);
438
439 DominanceFrontier::iterator LatchDF = DF->find(Latch);
440 if (LatchDF != DF->end())
441 DF->removeFromFrontier(LatchDF, Header);
442 }
Devang Patel38310052008-12-04 21:38:42 +0000443
444 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000445 return true;
446}
447
Devang Patel38310052008-12-04 21:38:42 +0000448/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
449/// with a loop invariant value. Update loop's lower and upper bound based on
450/// the loop invariant value.
451bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
452 bool Sign = Op.isSignedPredicate();
453 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000454
Devang Patel38310052008-12-04 21:38:42 +0000455 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
456 BranchInst *EBR =
457 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
458 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
459 BasicBlock *T = EBR->getSuccessor(0);
460 EBR->setSuccessor(0, EBR->getSuccessor(1));
461 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000462 }
463
Devang Patel38310052008-12-04 21:38:42 +0000464 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000465 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000466 Value *NUB = NULL;
467 if (Value *V = IVisLT(Op)) {
468 // Restrict upper bound.
469 if (IVisLE(*ExitCondition))
470 V = getMinusOne(V, Sign, PHTerm);
471 NUB = getMin(V, IVExitValue, Sign, PHTerm);
472 } else if (Value *V = IVisLE(Op)) {
473 // Restrict upper bound.
474 if (IVisLT(*ExitCondition))
475 V = getPlusOne(V, Sign, PHTerm);
476 NUB = getMin(V, IVExitValue, Sign, PHTerm);
477 } else if (Value *V = IVisGT(Op)) {
478 // Restrict lower bound.
479 V = getPlusOne(V, Sign, PHTerm);
480 NLB = getMax(V, IVStartValue, Sign, PHTerm);
481 } else if (Value *V = IVisGE(Op))
482 // Restrict lower bound.
483 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000484
Devang Patel38310052008-12-04 21:38:42 +0000485 if (!NLB && !NUB)
486 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000487
488 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000489 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000490 IndVar->setIncomingValue(i, NLB);
491 }
492
493 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000494 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
495 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000496 }
Devang Patel38310052008-12-04 21:38:42 +0000497 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000498}
Devang Patel38310052008-12-04 21:38:42 +0000499
500/// updateLoopIterationSpace -- Update loop's iteration space if loop
501/// body is executed for certain IV range only. For example,
502///
503/// for (i = 0; i < N; ++i) {
504/// if ( i > A && i < B) {
505/// ...
506/// }
507/// }
Devang Patel042b8772008-12-08 17:07:24 +0000508/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000509///
510bool LoopIndexSplit::updateLoopIterationSpace() {
511 SplitCondition = NULL;
512 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
513 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
514 return false;
515 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000516 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000517 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
518 if (!BR) return false;
519 if (!isa<BranchInst>(Latch->getTerminator())) return false;
520 if (BR->isUnconditional()) return false;
521 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
522 if (!AND) return false;
523 if (AND->getOpcode() != Instruction::And) return false;
524 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
525 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
526 if (!Op0 || !Op1)
527 return false;
528 IVBasedValues.insert(AND);
529 IVBasedValues.insert(Op0);
530 IVBasedValues.insert(Op1);
531 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000532 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000533 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000534
Devang Patelcf42ee42009-03-02 23:39:14 +0000535 // If the merge point for BR is not loop latch then skip this loop.
536 if (BR->getSuccessor(0) != Latch) {
537 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
538 assert (DF0 != DF->end() && "Unable to find dominance frontier");
539 if (!DF0->second.count(Latch))
540 return false;
541 }
542
543 if (BR->getSuccessor(1) != Latch) {
544 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
545 assert (DF1 != DF->end() && "Unable to find dominance frontier");
546 if (!DF1->second.count(Latch))
547 return false;
548 }
549
Devang Patel38310052008-12-04 21:38:42 +0000550 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000551 // is split condition block. The other predecessor will become exiting block's
552 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
553 // more then two predecessors. This requires extra work in updating dominator
554 // information.
555 BasicBlock *ExitingBBPred = NULL;
556 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
557 PI != PE; ++PI) {
558 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000559 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000560 continue;
561 if (ExitingBBPred)
562 return false;
563 else
564 ExitingBBPred = BB;
565 }
Devang Patel453a8442007-09-25 17:31:19 +0000566
Devang Patel38310052008-12-04 21:38:42 +0000567 if (!restrictLoopBound(*Op0))
568 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000569
Devang Patel38310052008-12-04 21:38:42 +0000570 if (!restrictLoopBound(*Op1))
571 return false;
572
573 // Update CFG.
574 if (BR->getSuccessor(0) == ExitingBlock)
575 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000576 else
Devang Patel38310052008-12-04 21:38:42 +0000577 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000578
Devang Patel38310052008-12-04 21:38:42 +0000579 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000580 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000581 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000582 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000583 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000584
585 // Update domiantor info. Now, ExitingBlock has only one predecessor,
586 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
587 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000588
589 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
590 if (L->contains(ExitBlock))
591 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
592
593 // If ExitingBlock is a member of the loop basic blocks' DF list then
594 // replace ExitingBlock with header and exit block in the DF list
595 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000596 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
597 I != E; ++I) {
598 BasicBlock *BB = *I;
599 if (BB == Header || BB == ExitingBlock)
600 continue;
601 DominanceFrontier::iterator BBDF = DF->find(BB);
602 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
603 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
604 while (DomSetI != DomSetE) {
605 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
606 ++DomSetI;
607 BasicBlock *DFBB = *CurrentItr;
608 if (DFBB == ExitingBlock) {
609 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000610 for (DominanceFrontier::DomSetType::iterator
611 EBI = ExitingBlockDF->second.begin(),
612 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
613 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000614 }
615 }
616 }
Devang Patel38310052008-12-04 21:38:42 +0000617 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000618 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000619}
620
Devang Patela6a86632007-08-14 18:35:57 +0000621/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
622/// This routine is used to remove split condition's dead branch, dominated by
623/// DeadBB. LiveBB dominates split conidition's other branch.
624void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
625 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000626
Devang Patel5b8ec612007-08-15 03:31:47 +0000627 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000628 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000629 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
630 if (DeadBBDF != DF->end()) {
631 SmallVector<BasicBlock *, 8> PredBlocks;
632
633 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
634 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000635 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
636 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000637 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000638 FrontierBBs.push_back(FrontierBB);
639
Devang Patel5b8ec612007-08-15 03:31:47 +0000640 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
641 PredBlocks.clear();
642 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
643 PI != PE; ++PI) {
644 BasicBlock *P = *PI;
645 if (P == DeadBB || DT->dominates(DeadBB, P))
646 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000647 }
Devang Patel96bf5242007-08-17 21:59:16 +0000648
Devang Patel5b8ec612007-08-15 03:31:47 +0000649 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
650 FBI != FBE; ++FBI) {
651 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
652 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
653 PE = PredBlocks.end(); PI != PE; ++PI) {
654 BasicBlock *P = *PI;
655 PN->removeIncomingValue(P);
656 }
657 }
658 else
659 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000660 }
Devang Patel98147a32007-08-12 07:02:51 +0000661 }
Devang Patel98147a32007-08-12 07:02:51 +0000662 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000663
664 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
665 SmallVector<BasicBlock *, 32> WorkList;
666 DomTreeNode *DN = DT->getNode(DeadBB);
667 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
668 E = df_end(DN); DI != E; ++DI) {
669 BasicBlock *BB = DI->getBlock();
670 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000671 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000672 }
673
674 while (!WorkList.empty()) {
675 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
676 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000677 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000678 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000679 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000680 I->replaceAllUsesWith(UndefValue::get(I->getType()));
681 I->eraseFromParent();
682 }
683 LPM->deleteSimpleAnalysisValue(BB, LP);
684 DT->eraseNode(BB);
685 DF->removeBlock(BB);
686 LI->removeBlock(BB);
687 BB->eraseFromParent();
688 }
Devang Patel96bf5242007-08-17 21:59:16 +0000689
690 // Update Frontier BBs' dominator info.
691 while (!FrontierBBs.empty()) {
692 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
693 BasicBlock *NewDominator = FBB->getSinglePredecessor();
694 if (!NewDominator) {
695 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
696 NewDominator = *PI;
697 ++PI;
698 if (NewDominator != LiveBB) {
699 for(; PI != PE; ++PI) {
700 BasicBlock *P = *PI;
701 if (P == LiveBB) {
702 NewDominator = LiveBB;
703 break;
704 }
705 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
706 }
707 }
708 }
709 assert (NewDominator && "Unable to fix dominator info.");
710 DT->changeImmediateDominator(FBB, NewDominator);
711 DF->changeImmediateDominator(FBB, NewDominator, DT);
712 }
713
Devang Patel98147a32007-08-12 07:02:51 +0000714}
715
Devang Pateld79faee2007-08-25 02:39:24 +0000716// moveExitCondition - Move exit condition EC into split condition block CondBB.
717void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000718 BasicBlock *ExitBB, ICmpInst *EC,
719 ICmpInst *SC, PHINode *IV,
720 Instruction *IVAdd, Loop *LP,
721 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000722
723 BasicBlock *ExitingBB = EC->getParent();
724 Instruction *CurrentBR = CondBB->getTerminator();
725
726 // Move exit condition into split condition block.
727 EC->moveBefore(CurrentBR);
728 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
729
730 // Move exiting block's branch into split condition block. Update its branch
731 // destination.
732 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
733 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000734 BasicBlock *OrigDestBB = NULL;
735 if (ExitingBR->getSuccessor(0) == ExitBB) {
736 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000737 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000738 }
739 else {
740 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000741 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000742 }
Devang Pateld79faee2007-08-25 02:39:24 +0000743
744 // Remove split condition and current split condition branch.
745 SC->eraseFromParent();
746 CurrentBR->eraseFromParent();
747
Devang Patel23067df2008-02-13 22:06:36 +0000748 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000749 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000750
751 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000752 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000753
754 // Fix dominator info.
755 // ExitBB is now dominated by CondBB
756 DT->changeImmediateDominator(ExitBB, CondBB);
757 DF->changeImmediateDominator(ExitBB, CondBB, DT);
758
759 // Basicblocks dominated by ActiveBB may have ExitingBB or
760 // a basic block outside the loop in their DF list. If so,
761 // replace it with CondBB.
762 DomTreeNode *Node = DT->getNode(ActiveBB);
763 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
764 DI != DE; ++DI) {
765 BasicBlock *BB = DI->getBlock();
766 DominanceFrontier::iterator BBDF = DF->find(BB);
767 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
768 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
769 while (DomSetI != DomSetE) {
770 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
771 ++DomSetI;
772 BasicBlock *DFBB = *CurrentItr;
773 if (DFBB == ExitingBB || !L->contains(DFBB)) {
774 BBDF->second.erase(DFBB);
775 BBDF->second.insert(CondBB);
776 }
777 }
778 }
779}
780
781/// updatePHINodes - CFG has been changed.
782/// Before
783/// - ExitBB's single predecessor was Latch
784/// - Latch's second successor was Header
785/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000786/// - ExitBB's single predecessor is Header
787/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000788///
789/// Update ExitBB PHINodes' to reflect this change.
790void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
791 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000792 PHINode *IV, Instruction *IVIncrement,
793 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000794
795 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000796 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000797 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000798 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000799 if (!PN)
800 break;
801
802 Value *V = PN->getIncomingValueForBlock(Latch);
803 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000804 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
805 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000806 Value *NewV = NULL;
807 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000808 UI != E; ++UI)
809 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000810 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000811 NewV = U;
812 break;
813 }
814
Devang Patel60a12902008-03-24 20:16:14 +0000815 // Add incoming value from header only if PN has any use inside the loop.
816 if (NewV)
817 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000818
819 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
820 // If this instruction is IVIncrement then IV is new incoming value
821 // from header otherwise this instruction must be incoming value from
822 // header because loop is in LCSSA form.
823 if (PHI == IVIncrement)
824 PN->addIncoming(IV, Header);
825 else
826 PN->addIncoming(V, Header);
827 } else
828 // Otherwise this is an incoming value from header because loop is in
829 // LCSSA form.
830 PN->addIncoming(V, Header);
831
832 // Remove incoming value from Latch.
833 PN->removeIncomingValue(Latch);
834 }
835}
Devang Patel38310052008-12-04 21:38:42 +0000836
837bool LoopIndexSplit::splitLoop() {
838 SplitCondition = NULL;
839 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
840 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
841 return false;
842 BasicBlock *Header = L->getHeader();
843 BasicBlock *Latch = L->getLoopLatch();
844 BranchInst *SBR = NULL; // Split Condition Branch
845 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
846 // If Exiting block includes loop variant instructions then this
847 // loop may not be split safely.
848 BasicBlock *ExitingBlock = ExitCondition->getParent();
849 if (!cleanBlock(ExitingBlock)) return false;
850
851 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
852 I != E; ++I) {
853 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
854 if (!BR || BR->isUnconditional()) continue;
855 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
856 if (!CI || CI == ExitCondition
857 || CI->getPredicate() == ICmpInst::ICMP_NE
858 || CI->getPredicate() == ICmpInst::ICMP_EQ)
859 continue;
860
861 // Unable to handle triangle loops at the moment.
862 // In triangle loop, split condition is in header and one of the
863 // the split destination is loop latch. If split condition is EQ
864 // then such loops are already handle in processOneIterationLoop().
865 if (Header == (*I)
866 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
867 continue;
868
869 // If the block does not dominate the latch then this is not a diamond.
870 // Such loop may not benefit from index split.
871 if (!DT->dominates((*I), Latch))
872 continue;
873
874 // If split condition branches heads do not have single predecessor,
875 // SplitCondBlock, then is not possible to remove inactive branch.
876 if (!BR->getSuccessor(0)->getSinglePredecessor()
877 || !BR->getSuccessor(1)->getSinglePredecessor())
878 return false;
879
880 // If the merge point for BR is not loop latch then skip this condition.
881 if (BR->getSuccessor(0) != Latch) {
882 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
883 assert (DF0 != DF->end() && "Unable to find dominance frontier");
884 if (!DF0->second.count(Latch))
885 continue;
886 }
887
888 if (BR->getSuccessor(1) != Latch) {
889 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
890 assert (DF1 != DF->end() && "Unable to find dominance frontier");
891 if (!DF1->second.count(Latch))
892 continue;
893 }
894 SplitCondition = CI;
895 SBR = BR;
896 break;
897 }
898
899 if (!SplitCondition)
900 return false;
901
902 // If the predicate sign does not match then skip.
903 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
904 return false;
905
906 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
907 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
908 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
909 if (!L->isLoopInvariant(SplitValue))
910 return false;
911 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
912 return false;
913
914 // Normalize loop conditions so that it is easier to calculate new loop
915 // bounds.
916 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
917 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
918 BasicBlock *T = EBR->getSuccessor(0);
919 EBR->setSuccessor(0, EBR->getSuccessor(1));
920 EBR->setSuccessor(1, T);
921 }
922
923 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
924 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
925 BasicBlock *T = SBR->getSuccessor(0);
926 SBR->setSuccessor(0, SBR->getSuccessor(1));
927 SBR->setSuccessor(1, T);
928 }
929
930 //[*] Calculate new loop bounds.
931 Value *AEV = SplitValue;
932 Value *BSV = SplitValue;
933 bool Sign = SplitCondition->isSignedPredicate();
934 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
935
936 if (IVisLT(*ExitCondition)) {
937 if (IVisLT(*SplitCondition)) {
938 /* Do nothing */
939 }
940 else if (IVisLE(*SplitCondition)) {
941 AEV = getPlusOne(SplitValue, Sign, PHTerm);
942 BSV = getPlusOne(SplitValue, Sign, PHTerm);
943 } else {
944 assert (0 && "Unexpected split condition!");
945 }
946 }
947 else if (IVisLE(*ExitCondition)) {
948 if (IVisLT(*SplitCondition)) {
949 AEV = getMinusOne(SplitValue, Sign, PHTerm);
950 }
951 else if (IVisLE(*SplitCondition)) {
952 BSV = getPlusOne(SplitValue, Sign, PHTerm);
953 } else {
954 assert (0 && "Unexpected split condition!");
955 }
956 } else {
957 assert (0 && "Unexpected exit condition!");
958 }
959 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
960 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
961
962 // [*] Clone Loop
963 DenseMap<const Value *, Value *> ValueMap;
964 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
965 Loop *ALoop = L;
966
967 // [*] ALoop's exiting edge enters BLoop's header.
968 // ALoop's original exit block becomes BLoop's exit block.
969 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
970 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
971 BranchInst *A_ExitInsn =
972 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
973 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
974 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
975 BasicBlock *B_Header = BLoop->getHeader();
976 if (ALoop->contains(B_ExitBlock)) {
977 B_ExitBlock = A_ExitInsn->getSuccessor(0);
978 A_ExitInsn->setSuccessor(0, B_Header);
979 } else
980 A_ExitInsn->setSuccessor(1, B_Header);
981
982 // [*] Update ALoop's exit value using new exit value.
983 ExitCondition->setOperand(EVOpNum, AEV);
984
985 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
986 // original loop's preheader. Add incoming PHINode values from
987 // ALoop's exiting block. Update BLoop header's domiantor info.
988
989 // Collect inverse map of Header PHINodes.
990 DenseMap<Value *, Value *> InverseMap;
991 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
992 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
993 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
994 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
995 InverseMap[PNClone] = PN;
996 } else
997 break;
998 }
999
1000 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
1001 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1002 BI != BE; ++BI) {
1003 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1004 // Remove incoming value from original preheader.
1005 PN->removeIncomingValue(A_Preheader);
1006
1007 // Add incoming value from A_ExitingBlock.
1008 if (PN == B_IndVar)
1009 PN->addIncoming(BSV, A_ExitingBlock);
1010 else {
1011 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1012 Value *V2 = NULL;
1013 // If loop header is also loop exiting block then
1014 // OrigPN is incoming value for B loop header.
1015 if (A_ExitingBlock == ALoop->getHeader())
1016 V2 = OrigPN;
1017 else
1018 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1019 PN->addIncoming(V2, A_ExitingBlock);
1020 }
1021 } else
1022 break;
1023 }
1024
1025 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1026 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1027
1028 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1029 // block. Remove incoming PHINode values from ALoop's exiting block.
1030 // Add new incoming values from BLoop's incoming exiting value.
1031 // Update BLoop exit block's dominator info..
1032 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1033 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1034 BI != BE; ++BI) {
1035 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1036 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1037 B_ExitingBlock);
1038 PN->removeIncomingValue(A_ExitingBlock);
1039 } else
1040 break;
1041 }
1042
1043 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1044 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1045
1046 //[*] Split ALoop's exit edge. This creates a new block which
1047 // serves two purposes. First one is to hold PHINode defnitions
1048 // to ensure that ALoop's LCSSA form. Second use it to act
1049 // as a preheader for BLoop.
1050 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1051
1052 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1053 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1054 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1055 BI != BE; ++BI) {
1056 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1057 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1058 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1059 newPHI->addIncoming(V1, A_ExitingBlock);
1060 A_ExitBlock->getInstList().push_front(newPHI);
1061 PN->removeIncomingValue(A_ExitBlock);
1062 PN->addIncoming(newPHI, A_ExitBlock);
1063 } else
1064 break;
1065 }
1066
1067 //[*] Eliminate split condition's inactive branch from ALoop.
1068 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1069 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1070 BasicBlock *A_InactiveBranch = NULL;
1071 BasicBlock *A_ActiveBranch = NULL;
1072 A_ActiveBranch = A_BR->getSuccessor(0);
1073 A_InactiveBranch = A_BR->getSuccessor(1);
1074 A_BR->setUnconditionalDest(A_ActiveBranch);
1075 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1076
1077 //[*] Eliminate split condition's inactive branch in from BLoop.
1078 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1079 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1080 BasicBlock *B_InactiveBranch = NULL;
1081 BasicBlock *B_ActiveBranch = NULL;
1082 B_ActiveBranch = B_BR->getSuccessor(1);
1083 B_InactiveBranch = B_BR->getSuccessor(0);
1084 B_BR->setUnconditionalDest(B_ActiveBranch);
1085 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1086
1087 BasicBlock *A_Header = ALoop->getHeader();
1088 if (A_ExitingBlock == A_Header)
1089 return true;
1090
1091 //[*] Move exit condition into split condition block to avoid
1092 // executing dead loop iteration.
1093 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1094 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1095 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1096
1097 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1098 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1099 ALoop, EVOpNum);
1100
1101 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1102 B_ExitBlock, B_ExitCondition,
1103 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1104 BLoop, EVOpNum);
1105
1106 NumIndexSplit++;
1107 return true;
1108}
1109
1110/// cleanBlock - A block is considered clean if all non terminal instructions
1111/// are either, PHINodes, IV based.
1112bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1113 Instruction *Terminator = BB->getTerminator();
1114 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1115 BI != BE; ++BI) {
1116 Instruction *I = BI;
1117
1118 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001119 || I == SplitCondition || IVBasedValues.count(I)
1120 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001121 continue;
1122
1123 if (I->mayWriteToMemory())
1124 return false;
1125
1126 // I is used only inside this block then it is OK.
1127 bool usedOutsideBB = false;
1128 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1129 UI != UE; ++UI) {
1130 Instruction *U = cast<Instruction>(UI);
1131 if (U->getParent() != BB)
1132 usedOutsideBB = true;
1133 }
1134 if (!usedOutsideBB)
1135 continue;
1136
1137 // Otherwise we have a instruction that may not allow loop spliting.
1138 return false;
1139 }
1140 return true;
1141}
1142
Devang Patel042b8772008-12-08 17:07:24 +00001143/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001144/// IV based value is less than the loop invariant then return the loop
1145/// invariant. Otherwise return NULL.
1146Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1147 ICmpInst::Predicate P = Op.getPredicate();
1148 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1149 && IVBasedValues.count(Op.getOperand(0))
1150 && L->isLoopInvariant(Op.getOperand(1)))
1151 return Op.getOperand(1);
1152
1153 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1154 && IVBasedValues.count(Op.getOperand(1))
1155 && L->isLoopInvariant(Op.getOperand(0)))
1156 return Op.getOperand(0);
1157
1158 return NULL;
1159}
1160
Devang Patel042b8772008-12-08 17:07:24 +00001161/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001162/// IV based value is less than or equal to the loop invariant then
1163/// return the loop invariant. Otherwise return NULL.
1164Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1165 ICmpInst::Predicate P = Op.getPredicate();
1166 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1167 && IVBasedValues.count(Op.getOperand(0))
1168 && L->isLoopInvariant(Op.getOperand(1)))
1169 return Op.getOperand(1);
1170
1171 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1172 && IVBasedValues.count(Op.getOperand(1))
1173 && L->isLoopInvariant(Op.getOperand(0)))
1174 return Op.getOperand(0);
1175
1176 return NULL;
1177}
1178
Devang Patel042b8772008-12-08 17:07:24 +00001179/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001180/// IV based value is greater than the loop invariant then return the loop
1181/// invariant. Otherwise return NULL.
1182Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1183 ICmpInst::Predicate P = Op.getPredicate();
1184 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1185 && IVBasedValues.count(Op.getOperand(0))
1186 && L->isLoopInvariant(Op.getOperand(1)))
1187 return Op.getOperand(1);
1188
1189 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1190 && IVBasedValues.count(Op.getOperand(1))
1191 && L->isLoopInvariant(Op.getOperand(0)))
1192 return Op.getOperand(0);
1193
1194 return NULL;
1195}
1196
Devang Patel042b8772008-12-08 17:07:24 +00001197/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001198/// IV based value is greater than or equal to the loop invariant then
1199/// return the loop invariant. Otherwise return NULL.
1200Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1201 ICmpInst::Predicate P = Op.getPredicate();
1202 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1203 && IVBasedValues.count(Op.getOperand(0))
1204 && L->isLoopInvariant(Op.getOperand(1)))
1205 return Op.getOperand(1);
1206
1207 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1208 && IVBasedValues.count(Op.getOperand(1))
1209 && L->isLoopInvariant(Op.getOperand(0)))
1210 return Op.getOperand(0);
1211
1212 return NULL;
1213}
1214