blob: 9f5f2cfd39d807082f3e8130ee8071818efd5eed [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 Patelb23c2322009-03-30 22:24:10 +000051#include "llvm/Transforms/Utils/Local.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000052#include "llvm/Support/Compiler.h"
Devang Patel5b8ec612007-08-15 03:31:47 +000053#include "llvm/ADT/DepthFirstIterator.h"
Devang Patelfee76bd2007-08-07 00:25:56 +000054#include "llvm/ADT/Statistic.h"
55
56using namespace llvm;
57
Devang Patel38310052008-12-04 21:38:42 +000058STATISTIC(NumIndexSplit, "Number of loop index split");
59STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
60STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
Devang Patelfee76bd2007-08-07 00:25:56 +000061
62namespace {
63
64 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
65
66 public:
67 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000068 LoopIndexSplit() : LoopPass(&ID) {}
Devang Patelfee76bd2007-08-07 00:25:56 +000069
70 // Index split Loop L. Return true if loop is split.
71 bool runOnLoop(Loop *L, LPPassManager &LPM);
72
73 void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfee76bd2007-08-07 00:25:56 +000074 AU.addPreserved<ScalarEvolution>();
75 AU.addRequiredID(LCSSAID);
76 AU.addPreservedID(LCSSAID);
Devang Patel423c8b22007-08-10 18:07:13 +000077 AU.addRequired<LoopInfo>();
Devang Patelfee76bd2007-08-07 00:25:56 +000078 AU.addPreserved<LoopInfo>();
79 AU.addRequiredID(LoopSimplifyID);
80 AU.addPreservedID(LoopSimplifyID);
Devang Patel9704fcf2007-08-08 22:25:28 +000081 AU.addRequired<DominatorTree>();
Devang Patel5b8ec612007-08-15 03:31:47 +000082 AU.addRequired<DominanceFrontier>();
Devang Patel787a7132007-08-08 21:39:47 +000083 AU.addPreserved<DominatorTree>();
84 AU.addPreserved<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +000085 }
86
87 private:
Devang Patel38310052008-12-04 21:38:42 +000088 /// processOneIterationLoop -- Eliminate loop if loop body is executed
89 /// only once. For example,
90 /// for (i = 0; i < N; ++i) {
91 /// if ( i == X) {
92 /// ...
93 /// }
94 /// }
95 ///
96 bool processOneIterationLoop();
Devang Patel71554b82007-08-08 21:02:17 +000097
Devang Patel38310052008-12-04 21:38:42 +000098 // -- Routines used by updateLoopIterationSpace();
Devang Patelc9d123d2007-08-09 01:39:01 +000099
Devang Patel38310052008-12-04 21:38:42 +0000100 /// updateLoopIterationSpace -- Update loop's iteration space if loop
101 /// body is executed for certain IV range only. For example,
102 ///
103 /// for (i = 0; i < N; ++i) {
104 /// if ( i > A && i < B) {
105 /// ...
106 /// }
107 /// }
Devang Patel042b8772008-12-08 17:07:24 +0000108 /// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000109 ///
110 bool updateLoopIterationSpace();
Devang Patel71554b82007-08-08 21:02:17 +0000111
Devang Patel38310052008-12-04 21:38:42 +0000112 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
113 /// with a loop invariant value. Update loop's lower and upper bound based on
114 /// the loop invariant value.
115 bool restrictLoopBound(ICmpInst &Op);
Devang Patel4a69da92007-08-25 00:56:38 +0000116
Devang Patel38310052008-12-04 21:38:42 +0000117 // --- Routines used by splitLoop(). --- /
Devang Patel4a69da92007-08-25 00:56:38 +0000118
Devang Patel38310052008-12-04 21:38:42 +0000119 bool splitLoop();
Devang Patel4a69da92007-08-25 00:56:38 +0000120
Devang Patel38310052008-12-04 21:38:42 +0000121 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by
122 /// DeadBB. This routine is used to remove split condition's dead branch,
123 /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
Devang Patela6a86632007-08-14 18:35:57 +0000124 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
Devang Patel38310052008-12-04 21:38:42 +0000125
126 /// moveExitCondition - Move exit condition EC into split condition block.
127 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
128 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
129 PHINode *IV, Instruction *IVAdd, Loop *LP,
130 unsigned);
131
Devang Pateld79faee2007-08-25 02:39:24 +0000132 /// updatePHINodes - CFG has been changed.
133 /// Before
134 /// - ExitBB's single predecessor was Latch
135 /// - Latch's second successor was Header
136 /// Now
137 /// - ExitBB's single predecessor was Header
138 /// - Latch's one and only successor was Header
139 ///
140 /// Update ExitBB PHINodes' to reflect this change.
141 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
142 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000143 PHINode *IV, Instruction *IVIncrement, Loop *LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000144
Devang Patel38310052008-12-04 21:38:42 +0000145 // --- Utility routines --- /
Devang Pateld79faee2007-08-25 02:39:24 +0000146
Devang Patel38310052008-12-04 21:38:42 +0000147 /// cleanBlock - A block is considered clean if all non terminal
148 /// instructions are either PHINodes or IV based values.
149 bool cleanBlock(BasicBlock *BB);
Devang Patelfee76bd2007-08-07 00:25:56 +0000150
Devang Patel042b8772008-12-08 17:07:24 +0000151 /// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000152 /// IV based value is less than the loop invariant then return the loop
153 /// invariant. Otherwise return NULL.
154 Value * IVisLT(ICmpInst &Op);
155
Devang Patel042b8772008-12-08 17:07:24 +0000156 /// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000157 /// IV based value is less than or equal to the loop invariant then
158 /// return the loop invariant. Otherwise return NULL.
159 Value * IVisLE(ICmpInst &Op);
160
Devang Patel042b8772008-12-08 17:07:24 +0000161 /// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000162 /// IV based value is greater than the loop invariant then return the loop
163 /// invariant. Otherwise return NULL.
164 Value * IVisGT(ICmpInst &Op);
165
Devang Patel042b8772008-12-08 17:07:24 +0000166 /// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +0000167 /// IV based value is greater than or equal to the loop invariant then
168 /// return the loop invariant. Otherwise return NULL.
169 Value * IVisGE(ICmpInst &Op);
Devang Patelbacf5192007-08-10 00:33:50 +0000170
Devang Patelfee76bd2007-08-07 00:25:56 +0000171 private:
172
Devang Patel38310052008-12-04 21:38:42 +0000173 // Current Loop information.
Devang Patelfee76bd2007-08-07 00:25:56 +0000174 Loop *L;
Devang Patel423c8b22007-08-10 18:07:13 +0000175 LPPassManager *LPM;
176 LoopInfo *LI;
Devang Patel9704fcf2007-08-08 22:25:28 +0000177 DominatorTree *DT;
Devang Patelfc4c5f82007-08-13 22:13:24 +0000178 DominanceFrontier *DF;
Devang Patelbacf5192007-08-10 00:33:50 +0000179
Devang Patelbacf5192007-08-10 00:33:50 +0000180 PHINode *IndVar;
Devang Patelbacf5192007-08-10 00:33:50 +0000181 ICmpInst *ExitCondition;
Devang Patel38310052008-12-04 21:38:42 +0000182 ICmpInst *SplitCondition;
183 Value *IVStartValue;
184 Value *IVExitValue;
185 Instruction *IVIncrement;
186 SmallPtrSet<Value *, 4> IVBasedValues;
Devang Patelfee76bd2007-08-07 00:25:56 +0000187 };
Devang Patelfee76bd2007-08-07 00:25:56 +0000188}
189
Dan Gohman844731a2008-05-13 00:00:25 +0000190char LoopIndexSplit::ID = 0;
191static RegisterPass<LoopIndexSplit>
192X("loop-index-split", "Index Split Loops");
193
Daniel Dunbar394f0442008-10-22 23:32:42 +0000194Pass *llvm::createLoopIndexSplitPass() {
Devang Patelfee76bd2007-08-07 00:25:56 +0000195 return new LoopIndexSplit();
196}
197
198// Index split Loop L. Return true if loop is split.
Devang Patel423c8b22007-08-10 18:07:13 +0000199bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
Devang Patelfee76bd2007-08-07 00:25:56 +0000200 L = IncomingLoop;
Devang Patel423c8b22007-08-10 18:07:13 +0000201 LPM = &LPM_Ref;
Devang Patel71554b82007-08-08 21:02:17 +0000202
Devang Patel3fe4f212007-08-15 02:14:55 +0000203 // FIXME - Nested loops make dominator info updates tricky.
Devang Patel4e8061c2007-08-14 23:53:57 +0000204 if (!L->getSubLoops().empty())
205 return false;
206
Devang Patel9704fcf2007-08-08 22:25:28 +0000207 DT = &getAnalysis<DominatorTree>();
Devang Patel423c8b22007-08-10 18:07:13 +0000208 LI = &getAnalysis<LoopInfo>();
Devang Patel7375bb92007-08-15 03:34:53 +0000209 DF = &getAnalysis<DominanceFrontier>();
Devang Patelfee76bd2007-08-07 00:25:56 +0000210
Devang Patel38310052008-12-04 21:38:42 +0000211 // Initialize loop data.
212 IndVar = L->getCanonicalInductionVariable();
213 if (!IndVar) return false;
Devang Patelbacf5192007-08-10 00:33:50 +0000214
Devang Patel38310052008-12-04 21:38:42 +0000215 bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
216 IVStartValue = IndVar->getIncomingValue(!P1InLoop);
217 IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
218 if (!IVIncrement) return false;
Devang Patel71554b82007-08-08 21:02:17 +0000219
Devang Patel38310052008-12-04 21:38:42 +0000220 IVBasedValues.clear();
221 IVBasedValues.insert(IndVar);
222 IVBasedValues.insert(IVIncrement);
Devang Patelbacf5192007-08-10 00:33:50 +0000223 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
Devang Patel38310052008-12-04 21:38:42 +0000224 I != E; ++I)
225 for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
226 BI != BE; ++BI) {
227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI))
228 if (BO != IVIncrement
229 && (BO->getOpcode() == Instruction::Add
230 || BO->getOpcode() == Instruction::Sub))
231 if (IVBasedValues.count(BO->getOperand(0))
232 && L->isLoopInvariant(BO->getOperand(1)))
233 IVBasedValues.insert(BO);
234 }
Devang Patelbacf5192007-08-10 00:33:50 +0000235
Devang Patel38310052008-12-04 21:38:42 +0000236 // Reject loop if loop exit condition is not suitable.
Dan Gohmanc8332462009-02-12 18:08:24 +0000237 BasicBlock *ExitingBlock = L->getExitingBlock();
238 if (!ExitingBlock)
Devang Patel38310052008-12-04 21:38:42 +0000239 return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000240 BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Devang Patel38310052008-12-04 21:38:42 +0000241 if (!EBR) return false;
242 ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
243 if (!ExitCondition) return false;
Dan Gohmanc8332462009-02-12 18:08:24 +0000244 if (ExitingBlock != L->getLoopLatch()) return false;
Devang Patel38310052008-12-04 21:38:42 +0000245 IVExitValue = ExitCondition->getOperand(1);
246 if (!L->isLoopInvariant(IVExitValue))
247 IVExitValue = ExitCondition->getOperand(0);
248 if (!L->isLoopInvariant(IVExitValue))
249 return false;
Devang Patela5e27f82008-07-09 00:12:01 +0000250
251 // If start value is more then exit value where induction variable
252 // increments by 1 then we are potentially dealing with an infinite loop.
253 // Do not index split this loop.
Devang Patel38310052008-12-04 21:38:42 +0000254 if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
255 if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
256 if (SV->getSExtValue() > EV->getSExtValue())
257 return false;
Devang Patelc9d123d2007-08-09 01:39:01 +0000258
Devang Patel38310052008-12-04 21:38:42 +0000259 if (processOneIterationLoop())
260 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000261
Devang Patel38310052008-12-04 21:38:42 +0000262 if (updateLoopIterationSpace())
263 return true;
Devang Patelfee76bd2007-08-07 00:25:56 +0000264
Devang Patel38310052008-12-04 21:38:42 +0000265 if (splitLoop())
266 return true;
Devang Pateld35ed2c2007-09-11 00:42:56 +0000267
268 return false;
Devang Patelfee76bd2007-08-07 00:25:56 +0000269}
270
Devang Patel38310052008-12-04 21:38:42 +0000271// --- Helper routines ---
272// isUsedOutsideLoop - Returns true iff V is used outside the loop L.
273static bool isUsedOutsideLoop(Value *V, Loop *L) {
274 for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
275 if (!L->contains(cast<Instruction>(*UI)->getParent()))
276 return true;
277 return false;
278}
Devang Patelfee76bd2007-08-07 00:25:56 +0000279
Devang Patel38310052008-12-04 21:38:42 +0000280// Return V+1
281static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
282 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
283 return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
284}
Devang Patelfee76bd2007-08-07 00:25:56 +0000285
Devang Patel38310052008-12-04 21:38:42 +0000286// Return V-1
287static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
288 ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
289 return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
290}
Devang Patelfee76bd2007-08-07 00:25:56 +0000291
Devang Patel38310052008-12-04 21:38:42 +0000292// Return min(V1, V1)
293static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
294
295 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
296 V1, V2, "lsp", InsertPt);
297 return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
298}
Devang Patelfee76bd2007-08-07 00:25:56 +0000299
Devang Patel38310052008-12-04 21:38:42 +0000300// Return max(V1, V2)
301static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
302
303 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
304 V1, V2, "lsp", InsertPt);
305 return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
306}
Devang Patel968eee22007-09-19 00:15:16 +0000307
Devang Patel38310052008-12-04 21:38:42 +0000308/// processOneIterationLoop -- Eliminate loop if loop body is executed
309/// only once. For example,
310/// for (i = 0; i < N; ++i) {
311/// if ( i == X) {
312/// ...
313/// }
314/// }
315///
316bool LoopIndexSplit::processOneIterationLoop() {
317 SplitCondition = NULL;
Devang Patel84ef08b2007-09-19 00:11:01 +0000318 BasicBlock *Latch = L->getLoopLatch();
Devang Patel38310052008-12-04 21:38:42 +0000319 BasicBlock *Header = L->getHeader();
320 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
321 if (!BR) return false;
322 if (!isa<BranchInst>(Latch->getTerminator())) return false;
323 if (BR->isUnconditional()) return false;
324 SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
325 if (!SplitCondition) return false;
326 if (SplitCondition == ExitCondition) return false;
327 if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
328 if (BR->getOperand(1) != Latch) return false;
329 if (!IVBasedValues.count(SplitCondition->getOperand(0))
330 && !IVBasedValues.count(SplitCondition->getOperand(1)))
Devang Patel84ef08b2007-09-19 00:11:01 +0000331 return false;
332
Devang Patel38310052008-12-04 21:38:42 +0000333 // If IV is used outside the loop then this loop traversal is required.
334 // FIXME: Calculate and use last IV value.
335 if (isUsedOutsideLoop(IVIncrement, L))
336 return false;
337
338 // If BR operands are not IV or not loop invariants then skip this loop.
339 Value *OPV = SplitCondition->getOperand(0);
340 Value *SplitValue = SplitCondition->getOperand(1);
341 if (!L->isLoopInvariant(SplitValue)) {
342 Value *T = SplitValue;
343 SplitValue = OPV;
344 OPV = T;
345 }
346 if (!L->isLoopInvariant(SplitValue))
347 return false;
348 Instruction *OPI = dyn_cast<Instruction>(OPV);
Devang Patelb23c2322009-03-30 22:24:10 +0000349 if (!OPI)
350 return false;
Devang Patel38310052008-12-04 21:38:42 +0000351 if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
352 return false;
Devang Patelb23c2322009-03-30 22:24:10 +0000353 Value *StartValue = IVStartValue;
354 Value *ExitValue = IVExitValue;;
355
356 if (OPV != IndVar) {
357 // If BR operand is IV based then use this operand to calculate
358 // effective conditions for loop body.
359 BinaryOperator *BOPV = dyn_cast<BinaryOperator>(OPV);
360 if (!BOPV)
361 return false;
362 if (BOPV->getOpcode() != Instruction::Add)
363 return false;
364 StartValue = BinaryOperator::CreateAdd(OPV, StartValue, "" , BR);
365 ExitValue = BinaryOperator::CreateAdd(OPV, ExitValue, "" , BR);
366 }
367
Devang Patel38310052008-12-04 21:38:42 +0000368 if (!cleanBlock(Header))
369 return false;
370
371 if (!cleanBlock(Latch))
372 return false;
373
374 // If the merge point for BR is not loop latch then skip this loop.
375 if (BR->getSuccessor(0) != Latch) {
376 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
377 assert (DF0 != DF->end() && "Unable to find dominance frontier");
378 if (!DF0->second.count(Latch))
379 return false;
380 }
381
382 if (BR->getSuccessor(1) != Latch) {
383 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
384 assert (DF1 != DF->end() && "Unable to find dominance frontier");
385 if (!DF1->second.count(Latch))
386 return false;
387 }
388
389 // Now, Current loop L contains compare instruction
390 // that compares induction variable, IndVar, against loop invariant. And
391 // entire (i.e. meaningful) loop body is dominated by this compare
392 // instruction. In such case eliminate
393 // loop structure surrounding this loop body. For example,
394 // for (int i = start; i < end; ++i) {
395 // if ( i == somevalue) {
396 // loop_body
397 // }
398 // }
399 // can be transformed into
400 // if (somevalue >= start && somevalue < end) {
401 // i = somevalue;
402 // loop_body
403 // }
Devang Patel6a2bfda2007-08-08 01:51:27 +0000404
Devang Patelebc5fea2007-08-20 20:49:01 +0000405 // Replace index variable with split value in loop body. Loop body is executed
406 // only when index variable is equal to split value.
Devang Patel38310052008-12-04 21:38:42 +0000407 IndVar->replaceAllUsesWith(SplitValue);
Devang Patelfee76bd2007-08-07 00:25:56 +0000408
Devang Patelfee76bd2007-08-07 00:25:56 +0000409 // Replace split condition in header.
410 // Transform
411 // SplitCondition : icmp eq i32 IndVar, SplitValue
412 // into
413 // c1 = icmp uge i32 SplitValue, StartValue
Devang Patelba32a5f2007-09-10 23:57:58 +0000414 // c2 = icmp ult i32 SplitValue, ExitValue
Devang Patelfee76bd2007-08-07 00:25:56 +0000415 // and i32 c1, c2
Devang Patel38310052008-12-04 21:38:42 +0000416 Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ?
Devang Patelfee76bd2007-08-07 00:25:56 +0000417 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
Devang Patelb23c2322009-03-30 22:24:10 +0000418 SplitValue, StartValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000419
420 CmpInst::Predicate C2P = ExitCondition->getPredicate();
421 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
422 if (LatchBR->getOperand(0) != Header)
423 C2P = CmpInst::getInversePredicate(C2P);
Devang Patelb23c2322009-03-30 22:24:10 +0000424 Instruction *C2 = new ICmpInst(C2P, SplitValue, ExitValue, "lisplit", BR);
Devang Patel38310052008-12-04 21:38:42 +0000425 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
426
427 SplitCondition->replaceAllUsesWith(NSplitCond);
428 SplitCondition->eraseFromParent();
Devang Patelfee76bd2007-08-07 00:25:56 +0000429
Devang Patelfc19fbd2008-10-10 22:02:57 +0000430 // Remove Latch to Header edge.
431 BasicBlock *LatchSucc = NULL;
432 Header->removePredecessor(Latch);
433 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
434 SI != E; ++SI) {
435 if (Header != *SI)
436 LatchSucc = *SI;
437 }
Devang Patelfc19fbd2008-10-10 22:02:57 +0000438
Devang Patelb23c2322009-03-30 22:24:10 +0000439 // Clean up latch block.
440 Value *LatchBRCond = LatchBR->getCondition();
441 LatchBR->setUnconditionalDest(LatchSucc);
442 RecursivelyDeleteTriviallyDeadInstructions(LatchBRCond);
Devang Patel38310052008-12-04 21:38:42 +0000443
Devang Patel423c8b22007-08-10 18:07:13 +0000444 LPM->deleteLoopFromQueue(L);
Devang Patel787a7132007-08-08 21:39:47 +0000445
446 // Update Dominator Info.
447 // Only CFG change done is to remove Latch to Header edge. This
448 // does not change dominator tree because Latch did not dominate
449 // Header.
Devang Patelfc4c5f82007-08-13 22:13:24 +0000450 if (DF) {
Devang Patel787a7132007-08-08 21:39:47 +0000451 DominanceFrontier::iterator HeaderDF = DF->find(Header);
452 if (HeaderDF != DF->end())
453 DF->removeFromFrontier(HeaderDF, Header);
454
455 DominanceFrontier::iterator LatchDF = DF->find(Latch);
456 if (LatchDF != DF->end())
457 DF->removeFromFrontier(LatchDF, Header);
458 }
Devang Patel38310052008-12-04 21:38:42 +0000459
460 ++NumIndexSplitRemoved;
Devang Patelfee76bd2007-08-07 00:25:56 +0000461 return true;
462}
463
Devang Patel38310052008-12-04 21:38:42 +0000464/// restrictLoopBound - Op dominates loop body. Op compares an IV based value
465/// with a loop invariant value. Update loop's lower and upper bound based on
466/// the loop invariant value.
467bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
468 bool Sign = Op.isSignedPredicate();
469 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
Devang Patelfee76bd2007-08-07 00:25:56 +0000470
Devang Patel38310052008-12-04 21:38:42 +0000471 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
472 BranchInst *EBR =
473 cast<BranchInst>(ExitCondition->getParent()->getTerminator());
474 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
475 BasicBlock *T = EBR->getSuccessor(0);
476 EBR->setSuccessor(0, EBR->getSuccessor(1));
477 EBR->setSuccessor(1, T);
Devang Patelfee76bd2007-08-07 00:25:56 +0000478 }
479
Devang Patel38310052008-12-04 21:38:42 +0000480 // New upper and lower bounds.
Devang Patel453a8442007-09-25 17:31:19 +0000481 Value *NLB = NULL;
Devang Patel38310052008-12-04 21:38:42 +0000482 Value *NUB = NULL;
483 if (Value *V = IVisLT(Op)) {
484 // Restrict upper bound.
485 if (IVisLE(*ExitCondition))
486 V = getMinusOne(V, Sign, PHTerm);
487 NUB = getMin(V, IVExitValue, Sign, PHTerm);
488 } else if (Value *V = IVisLE(Op)) {
489 // Restrict upper bound.
490 if (IVisLT(*ExitCondition))
491 V = getPlusOne(V, Sign, PHTerm);
492 NUB = getMin(V, IVExitValue, Sign, PHTerm);
493 } else if (Value *V = IVisGT(Op)) {
494 // Restrict lower bound.
495 V = getPlusOne(V, Sign, PHTerm);
496 NLB = getMax(V, IVStartValue, Sign, PHTerm);
497 } else if (Value *V = IVisGE(Op))
498 // Restrict lower bound.
499 NLB = getMax(V, IVStartValue, Sign, PHTerm);
Devang Patel453a8442007-09-25 17:31:19 +0000500
Devang Patel38310052008-12-04 21:38:42 +0000501 if (!NLB && !NUB)
502 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000503
504 if (NLB) {
Devang Patel38310052008-12-04 21:38:42 +0000505 unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
Devang Patel453a8442007-09-25 17:31:19 +0000506 IndVar->setIncomingValue(i, NLB);
507 }
508
509 if (NUB) {
Devang Patel38310052008-12-04 21:38:42 +0000510 unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
511 ExitCondition->setOperand(i, NUB);
Devang Patel453a8442007-09-25 17:31:19 +0000512 }
Devang Patel38310052008-12-04 21:38:42 +0000513 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000514}
Devang Patel38310052008-12-04 21:38:42 +0000515
516/// updateLoopIterationSpace -- Update loop's iteration space if loop
517/// body is executed for certain IV range only. For example,
518///
519/// for (i = 0; i < N; ++i) {
520/// if ( i > A && i < B) {
521/// ...
522/// }
523/// }
Devang Patel042b8772008-12-08 17:07:24 +0000524/// is transformed to iterators from A to B, if A > 0 and B < N.
Devang Patel38310052008-12-04 21:38:42 +0000525///
526bool LoopIndexSplit::updateLoopIterationSpace() {
527 SplitCondition = NULL;
528 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
529 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
530 return false;
531 BasicBlock *Latch = L->getLoopLatch();
Devang Patel5279d062007-09-17 20:39:48 +0000532 BasicBlock *Header = L->getHeader();
Devang Patel38310052008-12-04 21:38:42 +0000533 BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
534 if (!BR) return false;
535 if (!isa<BranchInst>(Latch->getTerminator())) return false;
536 if (BR->isUnconditional()) return false;
537 BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
538 if (!AND) return false;
539 if (AND->getOpcode() != Instruction::And) return false;
540 ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
541 ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
542 if (!Op0 || !Op1)
543 return false;
544 IVBasedValues.insert(AND);
545 IVBasedValues.insert(Op0);
546 IVBasedValues.insert(Op1);
547 if (!cleanBlock(Header)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000548 BasicBlock *ExitingBlock = ExitCondition->getParent();
Devang Patel38310052008-12-04 21:38:42 +0000549 if (!cleanBlock(ExitingBlock)) return false;
Devang Patel453a8442007-09-25 17:31:19 +0000550
Devang Patelcf42ee42009-03-02 23:39:14 +0000551 // If the merge point for BR is not loop latch then skip this loop.
552 if (BR->getSuccessor(0) != Latch) {
553 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
554 assert (DF0 != DF->end() && "Unable to find dominance frontier");
555 if (!DF0->second.count(Latch))
556 return false;
557 }
558
559 if (BR->getSuccessor(1) != Latch) {
560 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
561 assert (DF1 != DF->end() && "Unable to find dominance frontier");
562 if (!DF1->second.count(Latch))
563 return false;
564 }
565
Devang Patel38310052008-12-04 21:38:42 +0000566 // Verify that loop exiting block has only two predecessor, where one pred
Devang Patel453a8442007-09-25 17:31:19 +0000567 // is split condition block. The other predecessor will become exiting block's
568 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
569 // more then two predecessors. This requires extra work in updating dominator
570 // information.
571 BasicBlock *ExitingBBPred = NULL;
572 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
573 PI != PE; ++PI) {
574 BasicBlock *BB = *PI;
Devang Patel38310052008-12-04 21:38:42 +0000575 if (Header == BB)
Devang Patel453a8442007-09-25 17:31:19 +0000576 continue;
577 if (ExitingBBPred)
578 return false;
579 else
580 ExitingBBPred = BB;
581 }
Devang Patel453a8442007-09-25 17:31:19 +0000582
Devang Patel38310052008-12-04 21:38:42 +0000583 if (!restrictLoopBound(*Op0))
584 return false;
Devang Patel453a8442007-09-25 17:31:19 +0000585
Devang Patel38310052008-12-04 21:38:42 +0000586 if (!restrictLoopBound(*Op1))
587 return false;
588
589 // Update CFG.
590 if (BR->getSuccessor(0) == ExitingBlock)
591 BR->setUnconditionalDest(BR->getSuccessor(1));
Devang Patel453a8442007-09-25 17:31:19 +0000592 else
Devang Patel38310052008-12-04 21:38:42 +0000593 BR->setUnconditionalDest(BR->getSuccessor(0));
Devang Patel453a8442007-09-25 17:31:19 +0000594
Devang Patel38310052008-12-04 21:38:42 +0000595 AND->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000596 if (Op0->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000597 Op0->eraseFromParent();
Dan Gohmana8c763b2008-08-14 18:13:49 +0000598 if (Op1->use_empty())
Devang Patel453a8442007-09-25 17:31:19 +0000599 Op1->eraseFromParent();
Devang Patel453a8442007-09-25 17:31:19 +0000600
601 // Update domiantor info. Now, ExitingBlock has only one predecessor,
602 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
603 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
Devang Patel38310052008-12-04 21:38:42 +0000604
605 BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
606 if (L->contains(ExitBlock))
607 ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
608
609 // If ExitingBlock is a member of the loop basic blocks' DF list then
610 // replace ExitingBlock with header and exit block in the DF list
611 DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
Devang Patel453a8442007-09-25 17:31:19 +0000612 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
613 I != E; ++I) {
614 BasicBlock *BB = *I;
615 if (BB == Header || BB == ExitingBlock)
616 continue;
617 DominanceFrontier::iterator BBDF = DF->find(BB);
618 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
619 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
620 while (DomSetI != DomSetE) {
621 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
622 ++DomSetI;
623 BasicBlock *DFBB = *CurrentItr;
624 if (DFBB == ExitingBlock) {
625 BBDF->second.erase(DFBB);
Devang Patel38310052008-12-04 21:38:42 +0000626 for (DominanceFrontier::DomSetType::iterator
627 EBI = ExitingBlockDF->second.begin(),
628 EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI)
629 BBDF->second.insert(*EBI);
Devang Patel453a8442007-09-25 17:31:19 +0000630 }
631 }
632 }
Devang Patel38310052008-12-04 21:38:42 +0000633 NumRestrictBounds++;
Devang Patel1c013502007-09-25 17:43:08 +0000634 return true;
Devang Patel5279d062007-09-17 20:39:48 +0000635}
636
Devang Patela6a86632007-08-14 18:35:57 +0000637/// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
638/// This routine is used to remove split condition's dead branch, dominated by
639/// DeadBB. LiveBB dominates split conidition's other branch.
640void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
641 BasicBlock *LiveBB) {
Devang Patel98147a32007-08-12 07:02:51 +0000642
Devang Patel5b8ec612007-08-15 03:31:47 +0000643 // First update DeadBB's dominance frontier.
Devang Patel96bf5242007-08-17 21:59:16 +0000644 SmallVector<BasicBlock *, 8> FrontierBBs;
Devang Patel5b8ec612007-08-15 03:31:47 +0000645 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
646 if (DeadBBDF != DF->end()) {
647 SmallVector<BasicBlock *, 8> PredBlocks;
648
649 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
650 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
Devang Patel38310052008-12-04 21:38:42 +0000651 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI)
652 {
Devang Patel5b8ec612007-08-15 03:31:47 +0000653 BasicBlock *FrontierBB = *DeadBBSetI;
Devang Patel96bf5242007-08-17 21:59:16 +0000654 FrontierBBs.push_back(FrontierBB);
655
Devang Patel5b8ec612007-08-15 03:31:47 +0000656 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
657 PredBlocks.clear();
658 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
659 PI != PE; ++PI) {
660 BasicBlock *P = *PI;
661 if (P == DeadBB || DT->dominates(DeadBB, P))
662 PredBlocks.push_back(P);
Devang Patelfc4c5f82007-08-13 22:13:24 +0000663 }
Devang Patel96bf5242007-08-17 21:59:16 +0000664
Devang Patel5b8ec612007-08-15 03:31:47 +0000665 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
666 FBI != FBE; ++FBI) {
667 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
668 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
669 PE = PredBlocks.end(); PI != PE; ++PI) {
670 BasicBlock *P = *PI;
671 PN->removeIncomingValue(P);
672 }
673 }
674 else
675 break;
Devang Patel96bf5242007-08-17 21:59:16 +0000676 }
Devang Patel98147a32007-08-12 07:02:51 +0000677 }
Devang Patel98147a32007-08-12 07:02:51 +0000678 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000679
680 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
681 SmallVector<BasicBlock *, 32> WorkList;
682 DomTreeNode *DN = DT->getNode(DeadBB);
683 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
684 E = df_end(DN); DI != E; ++DI) {
685 BasicBlock *BB = DI->getBlock();
686 WorkList.push_back(BB);
Devang Patel96bf5242007-08-17 21:59:16 +0000687 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
Devang Patel5b8ec612007-08-15 03:31:47 +0000688 }
689
690 while (!WorkList.empty()) {
691 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
Devang Patel575ec802009-03-25 23:57:48 +0000692 LPM->deleteSimpleAnalysisValue(BB, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000693 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
Devang Pateld15dd8c2007-09-20 23:01:50 +0000694 BBI != BBE; ) {
Devang Patel5b8ec612007-08-15 03:31:47 +0000695 Instruction *I = BBI;
Devang Pateld15dd8c2007-09-20 23:01:50 +0000696 ++BBI;
Devang Patel5b8ec612007-08-15 03:31:47 +0000697 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Owen Anderson0b2a1532009-04-14 01:04:19 +0000698 LPM->deleteSimpleAnalysisValue(I, LP);
Devang Patel5b8ec612007-08-15 03:31:47 +0000699 I->eraseFromParent();
700 }
Devang Patel5b8ec612007-08-15 03:31:47 +0000701 DT->eraseNode(BB);
702 DF->removeBlock(BB);
703 LI->removeBlock(BB);
704 BB->eraseFromParent();
705 }
Devang Patel96bf5242007-08-17 21:59:16 +0000706
707 // Update Frontier BBs' dominator info.
708 while (!FrontierBBs.empty()) {
709 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
710 BasicBlock *NewDominator = FBB->getSinglePredecessor();
711 if (!NewDominator) {
712 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
713 NewDominator = *PI;
714 ++PI;
715 if (NewDominator != LiveBB) {
716 for(; PI != PE; ++PI) {
717 BasicBlock *P = *PI;
718 if (P == LiveBB) {
719 NewDominator = LiveBB;
720 break;
721 }
722 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
723 }
724 }
725 }
726 assert (NewDominator && "Unable to fix dominator info.");
727 DT->changeImmediateDominator(FBB, NewDominator);
728 DF->changeImmediateDominator(FBB, NewDominator, DT);
729 }
730
Devang Patel98147a32007-08-12 07:02:51 +0000731}
732
Devang Pateld79faee2007-08-25 02:39:24 +0000733// moveExitCondition - Move exit condition EC into split condition block CondBB.
734void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
Devang Patel38310052008-12-04 21:38:42 +0000735 BasicBlock *ExitBB, ICmpInst *EC,
736 ICmpInst *SC, PHINode *IV,
737 Instruction *IVAdd, Loop *LP,
738 unsigned ExitValueNum) {
Devang Pateld79faee2007-08-25 02:39:24 +0000739
740 BasicBlock *ExitingBB = EC->getParent();
741 Instruction *CurrentBR = CondBB->getTerminator();
742
743 // Move exit condition into split condition block.
744 EC->moveBefore(CurrentBR);
745 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
746
747 // Move exiting block's branch into split condition block. Update its branch
748 // destination.
749 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
750 ExitingBR->moveBefore(CurrentBR);
Devang Patel23067df2008-02-13 22:06:36 +0000751 BasicBlock *OrigDestBB = NULL;
752 if (ExitingBR->getSuccessor(0) == ExitBB) {
753 OrigDestBB = ExitingBR->getSuccessor(1);
Devang Pateld79faee2007-08-25 02:39:24 +0000754 ExitingBR->setSuccessor(1, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000755 }
756 else {
757 OrigDestBB = ExitingBR->getSuccessor(0);
Devang Pateld79faee2007-08-25 02:39:24 +0000758 ExitingBR->setSuccessor(0, ActiveBB);
Devang Patel23067df2008-02-13 22:06:36 +0000759 }
Devang Pateld79faee2007-08-25 02:39:24 +0000760
761 // Remove split condition and current split condition branch.
762 SC->eraseFromParent();
763 CurrentBR->eraseFromParent();
764
Devang Patel23067df2008-02-13 22:06:36 +0000765 // Connect exiting block to original destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000766 BranchInst::Create(OrigDestBB, ExitingBB);
Devang Pateld79faee2007-08-25 02:39:24 +0000767
768 // Update PHINodes
Devang Patelea069062008-02-13 22:23:07 +0000769 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
Devang Pateld79faee2007-08-25 02:39:24 +0000770
771 // Fix dominator info.
772 // ExitBB is now dominated by CondBB
773 DT->changeImmediateDominator(ExitBB, CondBB);
774 DF->changeImmediateDominator(ExitBB, CondBB, DT);
775
776 // Basicblocks dominated by ActiveBB may have ExitingBB or
777 // a basic block outside the loop in their DF list. If so,
778 // replace it with CondBB.
779 DomTreeNode *Node = DT->getNode(ActiveBB);
780 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
781 DI != DE; ++DI) {
782 BasicBlock *BB = DI->getBlock();
783 DominanceFrontier::iterator BBDF = DF->find(BB);
784 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
785 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
786 while (DomSetI != DomSetE) {
787 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
788 ++DomSetI;
789 BasicBlock *DFBB = *CurrentItr;
790 if (DFBB == ExitingBB || !L->contains(DFBB)) {
791 BBDF->second.erase(DFBB);
792 BBDF->second.insert(CondBB);
793 }
794 }
795 }
796}
797
798/// updatePHINodes - CFG has been changed.
799/// Before
800/// - ExitBB's single predecessor was Latch
801/// - Latch's second successor was Header
802/// Now
Devang Patel82ada542008-02-08 22:49:13 +0000803/// - ExitBB's single predecessor is Header
804/// - Latch's one and only successor is Header
Devang Pateld79faee2007-08-25 02:39:24 +0000805///
806/// Update ExitBB PHINodes' to reflect this change.
807void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
808 BasicBlock *Header,
Devang Patelea069062008-02-13 22:23:07 +0000809 PHINode *IV, Instruction *IVIncrement,
810 Loop *LP) {
Devang Pateld79faee2007-08-25 02:39:24 +0000811
812 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000813 BI != BE; ) {
Devang Pateld79faee2007-08-25 02:39:24 +0000814 PHINode *PN = dyn_cast<PHINode>(BI);
Devang Patel4a3c0ac2008-03-27 17:32:46 +0000815 ++BI;
Devang Pateld79faee2007-08-25 02:39:24 +0000816 if (!PN)
817 break;
818
819 Value *V = PN->getIncomingValueForBlock(Latch);
820 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
Devang Patel82ada542008-02-08 22:49:13 +0000821 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
822 // in Header which is new incoming value for PN.
Devang Pateld79faee2007-08-25 02:39:24 +0000823 Value *NewV = NULL;
824 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
Devang Patel82ada542008-02-08 22:49:13 +0000825 UI != E; ++UI)
826 if (PHINode *U = dyn_cast<PHINode>(*UI))
Devang Patelea069062008-02-13 22:23:07 +0000827 if (LP->contains(U->getParent())) {
Devang Patel82ada542008-02-08 22:49:13 +0000828 NewV = U;
829 break;
830 }
831
Devang Patel60a12902008-03-24 20:16:14 +0000832 // Add incoming value from header only if PN has any use inside the loop.
833 if (NewV)
834 PN->addIncoming(NewV, Header);
Devang Pateld79faee2007-08-25 02:39:24 +0000835
836 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
837 // If this instruction is IVIncrement then IV is new incoming value
838 // from header otherwise this instruction must be incoming value from
839 // header because loop is in LCSSA form.
840 if (PHI == IVIncrement)
841 PN->addIncoming(IV, Header);
842 else
843 PN->addIncoming(V, Header);
844 } else
845 // Otherwise this is an incoming value from header because loop is in
846 // LCSSA form.
847 PN->addIncoming(V, Header);
848
849 // Remove incoming value from Latch.
850 PN->removeIncomingValue(Latch);
851 }
852}
Devang Patel38310052008-12-04 21:38:42 +0000853
854bool LoopIndexSplit::splitLoop() {
855 SplitCondition = NULL;
856 if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
857 || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
858 return false;
859 BasicBlock *Header = L->getHeader();
860 BasicBlock *Latch = L->getLoopLatch();
861 BranchInst *SBR = NULL; // Split Condition Branch
862 BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
863 // If Exiting block includes loop variant instructions then this
864 // loop may not be split safely.
865 BasicBlock *ExitingBlock = ExitCondition->getParent();
866 if (!cleanBlock(ExitingBlock)) return false;
867
868 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
869 I != E; ++I) {
870 BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
871 if (!BR || BR->isUnconditional()) continue;
872 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
873 if (!CI || CI == ExitCondition
874 || CI->getPredicate() == ICmpInst::ICMP_NE
875 || CI->getPredicate() == ICmpInst::ICMP_EQ)
876 continue;
877
878 // Unable to handle triangle loops at the moment.
879 // In triangle loop, split condition is in header and one of the
880 // the split destination is loop latch. If split condition is EQ
881 // then such loops are already handle in processOneIterationLoop().
882 if (Header == (*I)
883 && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
884 continue;
885
886 // If the block does not dominate the latch then this is not a diamond.
887 // Such loop may not benefit from index split.
888 if (!DT->dominates((*I), Latch))
889 continue;
890
891 // If split condition branches heads do not have single predecessor,
892 // SplitCondBlock, then is not possible to remove inactive branch.
893 if (!BR->getSuccessor(0)->getSinglePredecessor()
894 || !BR->getSuccessor(1)->getSinglePredecessor())
895 return false;
896
897 // If the merge point for BR is not loop latch then skip this condition.
898 if (BR->getSuccessor(0) != Latch) {
899 DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
900 assert (DF0 != DF->end() && "Unable to find dominance frontier");
901 if (!DF0->second.count(Latch))
902 continue;
903 }
904
905 if (BR->getSuccessor(1) != Latch) {
906 DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
907 assert (DF1 != DF->end() && "Unable to find dominance frontier");
908 if (!DF1->second.count(Latch))
909 continue;
910 }
911 SplitCondition = CI;
912 SBR = BR;
913 break;
914 }
915
916 if (!SplitCondition)
917 return false;
918
919 // If the predicate sign does not match then skip.
920 if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
921 return false;
922
923 unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
924 unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
925 Value *SplitValue = SplitCondition->getOperand(SVOpNum);
926 if (!L->isLoopInvariant(SplitValue))
927 return false;
928 if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
929 return false;
930
931 // Normalize loop conditions so that it is easier to calculate new loop
932 // bounds.
933 if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
934 ExitCondition->setPredicate(ExitCondition->getInversePredicate());
935 BasicBlock *T = EBR->getSuccessor(0);
936 EBR->setSuccessor(0, EBR->getSuccessor(1));
937 EBR->setSuccessor(1, T);
938 }
939
940 if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
941 SplitCondition->setPredicate(SplitCondition->getInversePredicate());
942 BasicBlock *T = SBR->getSuccessor(0);
943 SBR->setSuccessor(0, SBR->getSuccessor(1));
944 SBR->setSuccessor(1, T);
945 }
946
947 //[*] Calculate new loop bounds.
948 Value *AEV = SplitValue;
949 Value *BSV = SplitValue;
950 bool Sign = SplitCondition->isSignedPredicate();
951 Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
952
953 if (IVisLT(*ExitCondition)) {
954 if (IVisLT(*SplitCondition)) {
955 /* Do nothing */
956 }
957 else if (IVisLE(*SplitCondition)) {
958 AEV = getPlusOne(SplitValue, Sign, PHTerm);
959 BSV = getPlusOne(SplitValue, Sign, PHTerm);
960 } else {
961 assert (0 && "Unexpected split condition!");
962 }
963 }
964 else if (IVisLE(*ExitCondition)) {
965 if (IVisLT(*SplitCondition)) {
966 AEV = getMinusOne(SplitValue, Sign, PHTerm);
967 }
968 else if (IVisLE(*SplitCondition)) {
969 BSV = getPlusOne(SplitValue, Sign, PHTerm);
970 } else {
971 assert (0 && "Unexpected split condition!");
972 }
973 } else {
974 assert (0 && "Unexpected exit condition!");
975 }
976 AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
977 BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
978
979 // [*] Clone Loop
980 DenseMap<const Value *, Value *> ValueMap;
981 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
982 Loop *ALoop = L;
983
984 // [*] ALoop's exiting edge enters BLoop's header.
985 // ALoop's original exit block becomes BLoop's exit block.
986 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
987 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
988 BranchInst *A_ExitInsn =
989 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
990 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
991 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
992 BasicBlock *B_Header = BLoop->getHeader();
993 if (ALoop->contains(B_ExitBlock)) {
994 B_ExitBlock = A_ExitInsn->getSuccessor(0);
995 A_ExitInsn->setSuccessor(0, B_Header);
996 } else
997 A_ExitInsn->setSuccessor(1, B_Header);
998
999 // [*] Update ALoop's exit value using new exit value.
1000 ExitCondition->setOperand(EVOpNum, AEV);
1001
1002 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1003 // original loop's preheader. Add incoming PHINode values from
1004 // ALoop's exiting block. Update BLoop header's domiantor info.
1005
1006 // Collect inverse map of Header PHINodes.
1007 DenseMap<Value *, Value *> InverseMap;
1008 for (BasicBlock::iterator BI = ALoop->getHeader()->begin(),
1009 BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
1010 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1011 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1012 InverseMap[PNClone] = PN;
1013 } else
1014 break;
1015 }
1016
1017 BasicBlock *A_Preheader = ALoop->getLoopPreheader();
1018 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1019 BI != BE; ++BI) {
1020 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1021 // Remove incoming value from original preheader.
1022 PN->removeIncomingValue(A_Preheader);
1023
1024 // Add incoming value from A_ExitingBlock.
1025 if (PN == B_IndVar)
1026 PN->addIncoming(BSV, A_ExitingBlock);
1027 else {
1028 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1029 Value *V2 = NULL;
1030 // If loop header is also loop exiting block then
1031 // OrigPN is incoming value for B loop header.
1032 if (A_ExitingBlock == ALoop->getHeader())
1033 V2 = OrigPN;
1034 else
1035 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1036 PN->addIncoming(V2, A_ExitingBlock);
1037 }
1038 } else
1039 break;
1040 }
1041
1042 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1043 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1044
1045 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1046 // block. Remove incoming PHINode values from ALoop's exiting block.
1047 // Add new incoming values from BLoop's incoming exiting value.
1048 // Update BLoop exit block's dominator info..
1049 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1050 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1051 BI != BE; ++BI) {
1052 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1053 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1054 B_ExitingBlock);
1055 PN->removeIncomingValue(A_ExitingBlock);
1056 } else
1057 break;
1058 }
1059
1060 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1061 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1062
1063 //[*] Split ALoop's exit edge. This creates a new block which
1064 // serves two purposes. First one is to hold PHINode defnitions
1065 // to ensure that ALoop's LCSSA form. Second use it to act
1066 // as a preheader for BLoop.
1067 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1068
1069 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1070 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1071 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1072 BI != BE; ++BI) {
1073 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1074 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1075 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1076 newPHI->addIncoming(V1, A_ExitingBlock);
1077 A_ExitBlock->getInstList().push_front(newPHI);
1078 PN->removeIncomingValue(A_ExitBlock);
1079 PN->addIncoming(newPHI, A_ExitBlock);
1080 } else
1081 break;
1082 }
1083
1084 //[*] Eliminate split condition's inactive branch from ALoop.
1085 BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1086 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1087 BasicBlock *A_InactiveBranch = NULL;
1088 BasicBlock *A_ActiveBranch = NULL;
1089 A_ActiveBranch = A_BR->getSuccessor(0);
1090 A_InactiveBranch = A_BR->getSuccessor(1);
1091 A_BR->setUnconditionalDest(A_ActiveBranch);
1092 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1093
1094 //[*] Eliminate split condition's inactive branch in from BLoop.
1095 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1096 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1097 BasicBlock *B_InactiveBranch = NULL;
1098 BasicBlock *B_ActiveBranch = NULL;
1099 B_ActiveBranch = B_BR->getSuccessor(1);
1100 B_InactiveBranch = B_BR->getSuccessor(0);
1101 B_BR->setUnconditionalDest(B_ActiveBranch);
1102 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1103
1104 BasicBlock *A_Header = ALoop->getHeader();
1105 if (A_ExitingBlock == A_Header)
1106 return true;
1107
1108 //[*] Move exit condition into split condition block to avoid
1109 // executing dead loop iteration.
1110 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1111 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1112 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1113
1114 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1115 cast<ICmpInst>(SplitCondition), IndVar, IVIncrement,
1116 ALoop, EVOpNum);
1117
1118 moveExitCondition(B_SplitCondBlock, B_ActiveBranch,
1119 B_ExitBlock, B_ExitCondition,
1120 B_SplitCondition, B_IndVar, B_IndVarIncrement,
1121 BLoop, EVOpNum);
1122
1123 NumIndexSplit++;
1124 return true;
1125}
1126
1127/// cleanBlock - A block is considered clean if all non terminal instructions
1128/// are either, PHINodes, IV based.
1129bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1130 Instruction *Terminator = BB->getTerminator();
1131 for(BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1132 BI != BE; ++BI) {
1133 Instruction *I = BI;
1134
1135 if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
Devang Pateld96c60d2009-02-06 06:19:06 +00001136 || I == SplitCondition || IVBasedValues.count(I)
1137 || isa<DbgInfoIntrinsic>(I))
Devang Patel38310052008-12-04 21:38:42 +00001138 continue;
1139
1140 if (I->mayWriteToMemory())
1141 return false;
1142
1143 // I is used only inside this block then it is OK.
1144 bool usedOutsideBB = false;
1145 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1146 UI != UE; ++UI) {
1147 Instruction *U = cast<Instruction>(UI);
1148 if (U->getParent() != BB)
1149 usedOutsideBB = true;
1150 }
1151 if (!usedOutsideBB)
1152 continue;
1153
1154 // Otherwise we have a instruction that may not allow loop spliting.
1155 return false;
1156 }
1157 return true;
1158}
1159
Devang Patel042b8772008-12-08 17:07:24 +00001160/// IVisLT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001161/// IV based value is less than the loop invariant then return the loop
1162/// invariant. Otherwise return NULL.
1163Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1164 ICmpInst::Predicate P = Op.getPredicate();
1165 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1166 && IVBasedValues.count(Op.getOperand(0))
1167 && L->isLoopInvariant(Op.getOperand(1)))
1168 return Op.getOperand(1);
1169
1170 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1171 && IVBasedValues.count(Op.getOperand(1))
1172 && L->isLoopInvariant(Op.getOperand(0)))
1173 return Op.getOperand(0);
1174
1175 return NULL;
1176}
1177
Devang Patel042b8772008-12-08 17:07:24 +00001178/// IVisLE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001179/// IV based value is less than or equal to the loop invariant then
1180/// return the loop invariant. Otherwise return NULL.
1181Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1182 ICmpInst::Predicate P = Op.getPredicate();
1183 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1184 && IVBasedValues.count(Op.getOperand(0))
1185 && L->isLoopInvariant(Op.getOperand(1)))
1186 return Op.getOperand(1);
1187
1188 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1189 && IVBasedValues.count(Op.getOperand(1))
1190 && L->isLoopInvariant(Op.getOperand(0)))
1191 return Op.getOperand(0);
1192
1193 return NULL;
1194}
1195
Devang Patel042b8772008-12-08 17:07:24 +00001196/// IVisGT - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001197/// IV based value is greater than the loop invariant then return the loop
1198/// invariant. Otherwise return NULL.
1199Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1200 ICmpInst::Predicate P = Op.getPredicate();
1201 if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT)
1202 && IVBasedValues.count(Op.getOperand(0))
1203 && L->isLoopInvariant(Op.getOperand(1)))
1204 return Op.getOperand(1);
1205
1206 if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT)
1207 && IVBasedValues.count(Op.getOperand(1))
1208 && L->isLoopInvariant(Op.getOperand(0)))
1209 return Op.getOperand(0);
1210
1211 return NULL;
1212}
1213
Devang Patel042b8772008-12-08 17:07:24 +00001214/// IVisGE - If Op is comparing IV based value with an loop invariant and
Devang Patel38310052008-12-04 21:38:42 +00001215/// IV based value is greater than or equal to the loop invariant then
1216/// return the loop invariant. Otherwise return NULL.
1217Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1218 ICmpInst::Predicate P = Op.getPredicate();
1219 if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1220 && IVBasedValues.count(Op.getOperand(0))
1221 && L->isLoopInvariant(Op.getOperand(1)))
1222 return Op.getOperand(1);
1223
1224 if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1225 && IVBasedValues.count(Op.getOperand(1))
1226 && L->isLoopInvariant(Op.getOperand(0)))
1227 return Op.getOperand(0);
1228
1229 return NULL;
1230}
1231