blob: d0b97e0d7f252616e62c1990ef38d0df8a190e27 [file] [log] [blame]
Chris Lattner18f16092004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner18f16092004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner18f16092004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
29#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Constants.h"
32#include "llvm/Function.h"
33#include "llvm/Instructions.h"
Chris Lattner18f16092004-04-19 18:07:02 +000034#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/Transforms/Utils/Cloning.h"
36#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattnera6fc94b2006-02-18 07:57:38 +000039#include "llvm/ADT/PostOrderIterator.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/CommandLine.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattner2f4b8982006-02-09 19:14:52 +000043#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000044using namespace llvm;
45
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumBranches, "Number of branches unswitched");
47STATISTIC(NumSwitches, "Number of switches unswitched");
48STATISTIC(NumSelects , "Number of selects unswitched");
49STATISTIC(NumTrivial , "Number of unswitches that are trivial");
50STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
51
Chris Lattner18f16092004-04-19 18:07:02 +000052namespace {
Chris Lattnere487abb2006-02-09 20:15:48 +000053 cl::opt<unsigned>
54 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
55 cl::init(10), cl::Hidden);
56
Chris Lattner18f16092004-04-19 18:07:02 +000057 class LoopUnswitch : public FunctionPass {
58 LoopInfo *LI; // Loop information
Chris Lattnera6fc94b2006-02-18 07:57:38 +000059
60 // LoopProcessWorklist - List of loops we need to process.
61 std::vector<Loop*> LoopProcessWorklist;
Chris Lattner18f16092004-04-19 18:07:02 +000062 public:
63 virtual bool runOnFunction(Function &F);
64 bool visitLoop(Loop *L);
65
66 /// This transformation requires natural loop information & requires that
67 /// loop preheaders be inserted into the CFG...
68 ///
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +000071 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +000072 AU.addRequired<LoopInfo>();
73 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +000074 AU.addRequiredID(LCSSAID);
75 AU.addPreservedID(LCSSAID);
Chris Lattner18f16092004-04-19 18:07:02 +000076 }
77
78 private:
Chris Lattnera6fc94b2006-02-18 07:57:38 +000079 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
80 /// remove it.
81 void RemoveLoopFromWorklist(Loop *L) {
82 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
83 LoopProcessWorklist.end(), L);
84 if (I != LoopProcessWorklist.end())
85 LoopProcessWorklist.erase(I);
86 }
87
Chris Lattnerc2358092006-02-11 00:43:37 +000088 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattner4c41d492006-02-10 01:24:09 +000089 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +000090 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +000091 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +000092 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerb2bc3152006-02-10 23:16:39 +000093 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattner4e132392006-02-15 22:03:36 +000094 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnera6fc94b2006-02-18 07:57:38 +000095
96 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
97 Constant *Val, bool isEqual);
98
99 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattnerdb410242006-02-18 02:42:34 +0000100 void RemoveBlockIfDead(BasicBlock *BB,
101 std::vector<Instruction*> &Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000102 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattner18f16092004-04-19 18:07:02 +0000103 };
Chris Lattner7f8897f2006-08-27 22:42:52 +0000104 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000105}
106
Jeff Cohenf5e58f82005-01-06 05:47:18 +0000107FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattner18f16092004-04-19 18:07:02 +0000108
109bool LoopUnswitch::runOnFunction(Function &F) {
110 bool Changed = false;
111 LI = &getAnalysis<LoopInfo>();
Chris Lattner18f16092004-04-19 18:07:02 +0000112
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000113 // Populate the worklist of loops to process in post-order.
114 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
115 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
116 LoopProcessWorklist.push_back(*LI);
Chris Lattner18f16092004-04-19 18:07:02 +0000117
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000118 // Process the loops in worklist order, this is a post-order visitation of
119 // the loops. We use a worklist of loops so that loops can be removed at any
120 // time if they are deleted (e.g. the backedge of a loop is removed).
121 while (!LoopProcessWorklist.empty()) {
122 Loop *L = LoopProcessWorklist.back();
123 LoopProcessWorklist.pop_back();
124 Changed |= visitLoop(L);
125 }
126
127 return Changed;
128}
129
130/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
131/// invariant in the loop, or has an invariant piece, return the invariant.
132/// Otherwise, return null.
133static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
134 // Constants should be folded, not unswitched on!
135 if (isa<Constant>(Cond)) return false;
136
137 // TODO: Handle: br (VARIANT|INVARIANT).
138 // TODO: Hoist simple expressions out of loops.
139 if (L->isLoopInvariant(Cond)) return Cond;
140
141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
142 if (BO->getOpcode() == Instruction::And ||
143 BO->getOpcode() == Instruction::Or) {
144 // If either the left or right side is invariant, we can unswitch on this,
145 // which will cause the branch to go away in one loop and the condition to
146 // simplify in the other one.
147 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
148 return LHS;
149 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
150 return RHS;
151 }
152
153 return 0;
154}
155
156bool LoopUnswitch::visitLoop(Loop *L) {
Owen Anderson6edf3992006-06-12 21:49:21 +0000157 assert(L->isLCSSAForm());
158
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000159 bool Changed = false;
160
161 // Loop over all of the basic blocks in the loop. If we find an interior
162 // block that is branching on a loop-invariant condition, we can unswitch this
163 // loop.
164 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
165 I != E; ++I) {
166 TerminatorInst *TI = (*I)->getTerminator();
167 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
168 // If this isn't branching on an invariant condition, we can't unswitch
169 // it.
170 if (BI->isConditional()) {
171 // See if this, or some part of it, is loop invariant. If so, we can
172 // unswitch on it if we desire.
173 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Chris Lattner47811b72006-09-28 23:35:22 +0000174 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(),
175 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000176 ++NumBranches;
177 return true;
178 }
179 }
180 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
181 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
182 if (LoopCond && SI->getNumCases() > 1) {
183 // Find a value to unswitch on:
184 // FIXME: this should chose the most expensive case!
185 Constant *UnswitchVal = SI->getCaseValue(1);
186 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
187 ++NumSwitches;
188 return true;
189 }
190 }
191 }
192
193 // Scan the instructions to check for unswitchable values.
194 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
195 BBI != E; ++BBI)
196 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
197 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Chris Lattner47811b72006-09-28 23:35:22 +0000198 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(),
199 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000200 ++NumSelects;
201 return true;
202 }
203 }
204 }
Owen Anderson6edf3992006-06-12 21:49:21 +0000205
206 assert(L->isLCSSAForm());
207
Chris Lattner18f16092004-04-19 18:07:02 +0000208 return Changed;
209}
210
Chris Lattner4e132392006-02-15 22:03:36 +0000211/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
212/// 1. Exit the loop with no side effects.
213/// 2. Branch to the latch block with no side-effects.
214///
215/// If these conditions are true, we return true and set ExitBB to the block we
216/// exit through.
217///
218static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
219 BasicBlock *&ExitBB,
220 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000221 if (!Visited.insert(BB).second) {
222 // Already visited and Ok, end of recursion.
223 return true;
224 } else if (!L->contains(BB)) {
225 // Otherwise, this is a loop exit, this is fine so long as this is the
226 // first exit.
227 if (ExitBB != 0) return false;
228 ExitBB = BB;
229 return true;
230 }
231
232 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000233 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000234 // Check to see if the successor is a trivial loop exit.
235 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
236 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000237 }
Chris Lattner4e132392006-02-15 22:03:36 +0000238
239 // Okay, everything after this looks good, check to make sure that this block
240 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000242 if (I->mayWriteToMemory())
243 return false;
244
245 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000246}
247
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000248/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
249/// leads to an exit from the specified loop, and has no side-effects in the
250/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000251static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
252 std::set<BasicBlock*> Visited;
253 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000254 BasicBlock *ExitBB = 0;
255 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
256 return ExitBB;
257 return 0;
258}
Chris Lattner708e1a52006-02-10 02:30:37 +0000259
Chris Lattner4c41d492006-02-10 01:24:09 +0000260/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
261/// trivial: that is, that the condition controls whether or not the loop does
262/// anything at all. If this is a trivial condition, unswitching produces no
263/// code duplications (equivalently, it produces a simpler loop and a new empty
264/// loop, which gets deleted).
265///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000266/// If this is a trivial condition, return true, otherwise return false. When
267/// returning true, this sets Cond and Val to the condition that controls the
268/// trivial condition: when Cond dynamically equals Val, the loop is known to
269/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
270/// Cond == Val.
271///
272static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000273 BasicBlock **LoopExit = 0) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000274 BasicBlock *Header = L->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000275 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000276
Chris Lattnera48654e2006-02-15 22:52:05 +0000277 BasicBlock *LoopExitBB = 0;
278 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
279 // If the header block doesn't end with a conditional branch on Cond, we
280 // can't handle it.
281 if (!BI->isConditional() || BI->getCondition() != Cond)
282 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000283
Chris Lattnera48654e2006-02-15 22:52:05 +0000284 // Check to see if a successor of the branch is guaranteed to go to the
285 // latch block or exit through a one exit block without having any
286 // side-effects. If so, determine the value of Cond that causes it to do
287 // this.
288 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Chris Lattner47811b72006-09-28 23:35:22 +0000289 if (Val) *Val = ConstantBool::getTrue();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000290 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Chris Lattner47811b72006-09-28 23:35:22 +0000291 if (Val) *Val = ConstantBool::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000292 }
293 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
294 // If this isn't a switch on Cond, we can't handle it.
295 if (SI->getCondition() != Cond) return false;
296
297 // Check to see if a successor of the switch is guaranteed to go to the
298 // latch block or exit through a one exit block without having any
299 // side-effects. If so, determine the value of Cond that causes it to do
300 // this. Note that we can't trivially unswitch on the default case.
301 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
302 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
303 // Okay, we found a trivial case, remember the value that is trivial.
304 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000305 break;
306 }
Chris Lattner4e132392006-02-15 22:03:36 +0000307 }
308
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000309 // If we didn't find a single unique LoopExit block, or if the loop exit block
310 // contains phi nodes, this isn't trivial.
311 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000312 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000313
Chris Lattnera48654e2006-02-15 22:52:05 +0000314 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000315
316 // We already know that nothing uses any scalar values defined inside of this
317 // loop. As such, we just have to check to see if this loop will execute any
318 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000319 // part of the loop that the code *would* execute. We already checked the
320 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000321 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
322 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000323 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000324 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000325}
326
327/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
328/// we choose to unswitch the specified loop on the specified value.
329///
330unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
331 // If the condition is trivial, always unswitch. There is no code growth for
332 // this case.
333 if (IsTrivialUnswitchCondition(L, LIC))
334 return 0;
335
Owen Anderson372994b2006-06-28 17:47:50 +0000336 // FIXME: This is really overly conservative. However, more liberal
337 // estimations have thus far resulted in excessive unswitching, which is bad
338 // both in compile time and in code size. This should be replaced once
339 // someone figures out how a good estimation.
340 return L->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000341
Chris Lattner4c41d492006-02-10 01:24:09 +0000342 unsigned Cost = 0;
343 // FIXME: this is brain dead. It should take into consideration code
344 // shrinkage.
345 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
346 I != E; ++I) {
347 BasicBlock *BB = *I;
348 // Do not include empty blocks in the cost calculation. This happen due to
349 // loop canonicalization and will be removed.
350 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
351 continue;
352
353 // Count basic blocks.
354 ++Cost;
355 }
356
357 return Cost;
358}
359
Chris Lattnerc2358092006-02-11 00:43:37 +0000360/// UnswitchIfProfitable - We have found that we can unswitch L when
361/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
362/// unswitch the loop, reprocess the pieces, then return true.
363bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
364 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner0f862e52006-03-24 07:14:00 +0000365 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
366 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000367 // FIXME: this should estimate growth by the amount of code shared by the
368 // resultant unswitched loops.
369 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000370 DOUT << "NOT unswitching loop %"
371 << L->getHeader()->getName() << ", cost too high: "
372 << L->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000373 return false;
374 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000375
Chris Lattnerc2358092006-02-11 00:43:37 +0000376 // If this is a trivial condition to unswitch (which results in no code
377 // duplication), do it now.
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000378 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000379 BasicBlock *ExitBlock;
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000380 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
381 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000382 } else {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000383 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerc2358092006-02-11 00:43:37 +0000384 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000385
Chris Lattnerc2358092006-02-11 00:43:37 +0000386 return true;
387}
388
Chris Lattner4e132392006-02-15 22:03:36 +0000389/// SplitBlock - Split the specified block at the specified instruction - every
390/// thing before SplitPt stays in Old and everything starting with SplitPt moves
391/// to a new block. The two blocks are joined by an unconditional branch and
392/// the loop info is updated.
393///
394BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000395 BasicBlock::iterator SplitIt = SplitPt;
396 while (isa<PHINode>(SplitIt))
397 ++SplitIt;
398 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattner4e132392006-02-15 22:03:36 +0000399
400 // The new block lives in whichever loop the old one did.
401 if (Loop *L = LI->getLoopFor(Old))
402 L->addBasicBlockToLoop(New, *LI);
403
404 return New;
405}
406
407
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000408BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
409 TerminatorInst *LatchTerm = BB->getTerminator();
410 unsigned SuccNum = 0;
411 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
412 assert(i != e && "Didn't find edge?");
413 if (LatchTerm->getSuccessor(i) == Succ) {
414 SuccNum = i;
415 break;
416 }
Chris Lattner18f16092004-04-19 18:07:02 +0000417 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000418
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000419 // If this is a critical edge, let SplitCriticalEdge do it.
420 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
421 return LatchTerm->getSuccessor(SuccNum);
422
423 // If the edge isn't critical, then BB has a single successor or Succ has a
424 // single pred. Split the block.
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000425 BasicBlock::iterator SplitPoint;
426 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
427 // If the successor only has a single pred, split the top of the successor
428 // block.
429 assert(SP == BB && "CFG broken");
Chris Lattner4e132392006-02-15 22:03:36 +0000430 return SplitBlock(Succ, Succ->begin());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000431 } else {
432 // Otherwise, if BB has a single successor, split it at the bottom of the
433 // block.
434 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
435 "Should have a single succ!");
Chris Lattner4e132392006-02-15 22:03:36 +0000436 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000437 }
Chris Lattner18f16092004-04-19 18:07:02 +0000438}
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000439
Chris Lattner18f16092004-04-19 18:07:02 +0000440
441
Misha Brukmanfd939082005-04-21 23:48:37 +0000442// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000443// current values into those specified by ValueMap.
444//
Misha Brukmanfd939082005-04-21 23:48:37 +0000445static inline void RemapInstruction(Instruction *I,
Chris Lattner18f16092004-04-19 18:07:02 +0000446 std::map<const Value *, Value*> &ValueMap) {
447 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
448 Value *Op = I->getOperand(op);
449 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
450 if (It != ValueMap.end()) Op = It->second;
451 I->setOperand(op, Op);
452 }
453}
454
455/// CloneLoop - Recursively clone the specified loop and all of its children,
456/// mapping the blocks with the specified map.
457static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
458 LoopInfo *LI) {
459 Loop *New = new Loop();
460
461 if (PL)
462 PL->addChildLoop(New);
463 else
464 LI->addTopLevelLoop(New);
465
466 // Add all of the blocks in L to the new loop.
467 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
468 I != E; ++I)
469 if (LI->getLoopFor(*I) == L)
470 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
471
472 // Add all of the subloops to the new loop.
473 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
474 CloneLoop(*I, New, VM, LI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000475
Chris Lattner18f16092004-04-19 18:07:02 +0000476 return New;
477}
478
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000479/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
480/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
481/// code immediately before InsertPt.
482static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
483 BasicBlock *TrueDest,
484 BasicBlock *FalseDest,
485 Instruction *InsertPt) {
486 // Insert a conditional branch on LIC to the two preheaders. The original
487 // code is the true version and the new code is the false version.
488 Value *BranchVal = LIC;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 if (!isa<ConstantBool>(Val))
490 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
491 else if (Val != ConstantBool::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000492 // We want to enter the new loop when the condition is true.
493 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000494
495 // Insert the new branch.
496 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
497}
498
499
Chris Lattner4c41d492006-02-10 01:24:09 +0000500/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
501/// condition in it (a cond branch from its header block to its latch block,
502/// where the path through the loop that doesn't execute its body has no
503/// side-effects), unswitch it. This doesn't involve any code duplication, just
504/// moving the conditional branch outside of the loop and updating loop info.
505void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000506 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000507 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000508 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
509 << L->getHeader()->getName() << " [" << L->getBlocks().size()
510 << " blocks] in Function " << L->getHeader()->getParent()->getName()
511 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000512
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000513 // First step, split the preheader, so that we know that there is a safe place
Chris Lattner4c41d492006-02-10 01:24:09 +0000514 // to insert the conditional branch. We will change 'OrigPH' to have a
515 // conditional branch on Cond.
516 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000517 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattner4c41d492006-02-10 01:24:09 +0000518
519 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000520 // to branch to: this is the exit block out of the loop that we should
521 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000522
Chris Lattner4e132392006-02-15 22:03:36 +0000523 // Split this block now, so that the loop maintains its exit block, and so
524 // that the jump from the preheader can execute the contents of the exit block
525 // without actually branching to it (the exit block should be dominated by the
526 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000527 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattner4e132392006-02-15 22:03:36 +0000528 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000529
Chris Lattner4c41d492006-02-10 01:24:09 +0000530 // Okay, now we have a position to branch from and a position to branch to,
531 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000532 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
533 OrigPH->getTerminator());
Chris Lattner4c41d492006-02-10 01:24:09 +0000534 OrigPH->getTerminator()->eraseFromParent();
535
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000536 // We need to reprocess this loop, it could be unswitched again.
537 LoopProcessWorklist.push_back(L);
538
Chris Lattner4c41d492006-02-10 01:24:09 +0000539 // Now that we know that the loop is never entered when this condition is a
540 // particular value, rewrite the loop with this info. We know that this will
541 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000542 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000543 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000544}
545
Chris Lattner18f16092004-04-19 18:07:02 +0000546
Chris Lattnerc2358092006-02-11 00:43:37 +0000547/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
548/// equal Val. Split it into loop versions and test the condition outside of
549/// either loop. Return the loops created as Out1/Out2.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000550void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
551 Loop *L) {
Chris Lattner18f16092004-04-19 18:07:02 +0000552 Function *F = L->getHeader()->getParent();
Bill Wendlingb7427032006-11-26 09:46:52 +0000553 DOUT << "loop-unswitch: Unswitching loop %"
554 << L->getHeader()->getName() << " [" << L->getBlocks().size()
555 << " blocks] in Function " << F->getName()
556 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattner18f16092004-04-19 18:07:02 +0000557
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000558 // LoopBlocks contains all of the basic blocks of the loop, including the
559 // preheader of the loop, the body of the loop, and the exit blocks of the
560 // loop, in that order.
Chris Lattner18f16092004-04-19 18:07:02 +0000561 std::vector<BasicBlock*> LoopBlocks;
562
563 // First step, split the preheader and exit blocks, and add these blocks to
564 // the LoopBlocks list.
565 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000566 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattner18f16092004-04-19 18:07:02 +0000567
568 // We want the loop to come after the preheader, but before the exit blocks.
569 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
570
571 std::vector<BasicBlock*> ExitBlocks;
Devang Patel4b8f36f2006-08-29 22:29:16 +0000572 L->getUniqueExitBlocks(ExitBlocks);
573
Owen Anderson2b67f072006-06-26 07:44:36 +0000574 // Split all of the edges from inside the loop to their exit blocks. Update
575 // the appropriate Phi nodes as we do so.
Chris Lattner4c41d492006-02-10 01:24:09 +0000576 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000577 BasicBlock *ExitBlock = ExitBlocks[i];
578 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
579
580 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
581 assert(L->contains(Preds[j]) &&
582 "All preds of loop exit blocks must be the same loop!");
Owen Anderson2b67f072006-06-26 07:44:36 +0000583 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
584 BasicBlock* StartBlock = Preds[j];
585 BasicBlock* EndBlock;
586 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
587 EndBlock = MiddleBlock;
588 MiddleBlock = EndBlock->getSinglePredecessor();;
589 } else {
590 EndBlock = ExitBlock;
591 }
592
593 std::set<PHINode*> InsertedPHIs;
594 PHINode* OldLCSSA = 0;
595 for (BasicBlock::iterator I = EndBlock->begin();
596 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
597 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
598 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
599 OldLCSSA->getName() + ".us-lcssa",
600 MiddleBlock->getTerminator());
601 NewLCSSA->addIncoming(OldValue, StartBlock);
602 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
603 NewLCSSA);
604 InsertedPHIs.insert(NewLCSSA);
605 }
606
Owen Andersondb5b9cf2006-07-19 03:51:48 +0000607 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Anderson2b67f072006-06-26 07:44:36 +0000608 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
609 for (BasicBlock::iterator I = MiddleBlock->begin();
610 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
611 ++I) {
612 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
613 OldLCSSA->getName() + ".us-lcssa",
614 InsertPt);
615 OldLCSSA->replaceAllUsesWith(NewLCSSA);
616 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
617 }
618 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000619 }
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000620
621 // The exit blocks may have been changed due to edge splitting, recompute.
622 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000623 L->getUniqueExitBlocks(ExitBlocks);
624
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000625 // Add exit blocks to the loop blocks.
626 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000627
628 // Next step, clone all of the basic blocks that make up the loop (including
629 // the loop preheader and exit blocks), keeping track of the mapping between
630 // the instructions and blocks.
631 std::vector<BasicBlock*> NewBlocks;
632 NewBlocks.reserve(LoopBlocks.size());
633 std::map<const Value*, Value*> ValueMap;
634 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000635 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
636 NewBlocks.push_back(New);
637 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattner18f16092004-04-19 18:07:02 +0000638 }
639
640 // Splice the newly inserted blocks into the function right before the
641 // original preheader.
642 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
643 NewBlocks[0], F->end());
644
645 // Now we create the new Loop object for the versioned loop.
646 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnere8255932006-02-10 23:26:14 +0000647 Loop *ParentLoop = L->getParentLoop();
648 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000649 // Make sure to add the cloned preheader and exit blocks to the parent loop
650 // as well.
Chris Lattnere8255932006-02-10 23:26:14 +0000651 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
652 }
653
654 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
655 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000656 // The new exit block should be in the same loop as the old one.
657 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
658 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnere8255932006-02-10 23:26:14 +0000659
660 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
661 "Exit block should have been split to have one successor!");
662 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
663
664 // If the successor of the exit block had PHI nodes, add an entry for
665 // NewExit.
666 PHINode *PN;
667 for (BasicBlock::iterator I = ExitSucc->begin();
668 (PN = dyn_cast<PHINode>(I)); ++I) {
669 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
670 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
671 if (It != ValueMap.end()) V = It->second;
672 PN->addIncoming(V, NewExit);
673 }
Chris Lattner18f16092004-04-19 18:07:02 +0000674 }
675
676 // Rewrite the code to refer to itself.
677 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
678 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
679 E = NewBlocks[i]->end(); I != E; ++I)
680 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000681
Chris Lattner18f16092004-04-19 18:07:02 +0000682 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000683 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
684 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000685 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000686
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000687 // Emit the new branch that selects between the two versions of this loop.
688 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
689 OldBR->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000690
691 LoopProcessWorklist.push_back(L);
692 LoopProcessWorklist.push_back(NewLoop);
Chris Lattner18f16092004-04-19 18:07:02 +0000693
694 // Now we rewrite the original code to know that the condition is true and the
695 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000696 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
697
698 // It's possible that simplifying one loop could cause the other to be
699 // deleted. If so, don't simplify it.
700 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
701 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000702}
703
Chris Lattner52221f72006-02-17 00:31:07 +0000704/// RemoveFromWorklist - Remove all instances of I from the worklist vector
705/// specified.
706static void RemoveFromWorklist(Instruction *I,
707 std::vector<Instruction*> &Worklist) {
708 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
709 Worklist.end(), I);
710 while (WI != Worklist.end()) {
711 unsigned Offset = WI-Worklist.begin();
712 Worklist.erase(WI);
713 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
714 }
715}
716
717/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
718/// program, replacing all uses with V and update the worklist.
719static void ReplaceUsesOfWith(Instruction *I, Value *V,
720 std::vector<Instruction*> &Worklist) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000721 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +0000722
723 // Add uses to the worklist, which may be dead now.
724 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
725 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
726 Worklist.push_back(Use);
727
728 // Add users to the worklist which may be simplified now.
729 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
730 UI != E; ++UI)
731 Worklist.push_back(cast<Instruction>(*UI));
732 I->replaceAllUsesWith(V);
733 I->eraseFromParent();
734 RemoveFromWorklist(I, Worklist);
735 ++NumSimplify;
736}
737
Chris Lattnerdb410242006-02-18 02:42:34 +0000738/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
739/// information, and remove any dead successors it has.
740///
741void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
742 std::vector<Instruction*> &Worklist) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000743 if (pred_begin(BB) != pred_end(BB)) {
744 // This block isn't dead, since an edge to BB was just removed, see if there
745 // are any easy simplifications we can do now.
746 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
747 // If it has one pred, fold phi nodes in BB.
748 while (isa<PHINode>(BB->begin()))
749 ReplaceUsesOfWith(BB->begin(),
750 cast<PHINode>(BB->begin())->getIncomingValue(0),
751 Worklist);
752
753 // If this is the header of a loop and the only pred is the latch, we now
754 // have an unreachable loop.
755 if (Loop *L = LI->getLoopFor(BB))
756 if (L->getHeader() == BB && L->contains(Pred)) {
757 // Remove the branch from the latch to the header block, this makes
758 // the header dead, which will make the latch dead (because the header
759 // dominates the latch).
760 Pred->getTerminator()->eraseFromParent();
761 new UnreachableInst(Pred);
762
763 // The loop is now broken, remove it from LI.
764 RemoveLoopFromHierarchy(L);
765
766 // Reprocess the header, which now IS dead.
767 RemoveBlockIfDead(BB, Worklist);
768 return;
769 }
770
771 // If pred ends in a uncond branch, add uncond branch to worklist so that
772 // the two blocks will get merged.
773 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
774 if (BI->isUnconditional())
775 Worklist.push_back(BI);
776 }
777 return;
778 }
Chris Lattner52221f72006-02-17 00:31:07 +0000779
Bill Wendlingb7427032006-11-26 09:46:52 +0000780 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +0000781
782 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000783 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +0000784 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000785
786 // Anything that uses the instructions in this basic block should have their
787 // uses replaced with undefs.
788 if (!I->use_empty())
789 I->replaceAllUsesWith(UndefValue::get(I->getType()));
790 }
Chris Lattnerdb410242006-02-18 02:42:34 +0000791
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000792 // If this is the edge to the header block for a loop, remove the loop and
793 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +0000794 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000795 if (BBLoop->getLoopLatch() == BB)
796 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +0000797 }
798
799 // Remove the block from the loop info, which removes it from any loops it
800 // was in.
801 LI->removeBlock(BB);
802
803
804 // Remove phi node entries in successors for this block.
805 TerminatorInst *TI = BB->getTerminator();
806 std::vector<BasicBlock*> Succs;
807 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
808 Succs.push_back(TI->getSuccessor(i));
809 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000810 }
811
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000812 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +0000813 std::sort(Succs.begin(), Succs.end());
814 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
815
816 // Remove the basic block, including all of the instructions contained in it.
817 BB->eraseFromParent();
818
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000819 // Remove successor blocks here that are not dead, so that we know we only
820 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
821 // then getting removed before we revisit them, which is badness.
822 //
823 for (unsigned i = 0; i != Succs.size(); ++i)
824 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
825 // One exception is loop headers. If this block was the preheader for a
826 // loop, then we DO want to visit the loop so the loop gets deleted.
827 // We know that if the successor is a loop header, that this loop had to
828 // be the preheader: the case where this was the latch block was handled
829 // above and headers can only have two predecessors.
830 if (!LI->isLoopHeader(Succs[i])) {
831 Succs.erase(Succs.begin()+i);
832 --i;
833 }
834 }
835
Chris Lattnerdb410242006-02-18 02:42:34 +0000836 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
837 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000838}
Chris Lattner52221f72006-02-17 00:31:07 +0000839
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000840/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
841/// become unwrapped, either because the backedge was deleted, or because the
842/// edge into the header was removed. If the edge into the header from the
843/// latch block was removed, the loop is unwrapped but subloops are still alive,
844/// so they just reparent loops. If the loops are actually dead, they will be
845/// removed later.
846void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
847 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
848 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
849 // they are now all in it.
850 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
851 I != E; ++I)
852 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
853 LI->changeLoopFor(*I, ParentLoop);
854
855 // Remove the loop from its parent loop.
856 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
857 ++I) {
858 assert(I != E && "Couldn't find loop");
859 if (*I == L) {
860 ParentLoop->removeChildLoop(I);
861 break;
862 }
863 }
864
865 // Move all subloops into the parent loop.
866 while (L->begin() != L->end())
867 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
868 } else {
869 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
870 // they no longer in a loop at all.
871
872 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
873 // Don't change blocks in subloops.
874 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
875 LI->removeBlock(L->getBlocks()[i]);
876 --i;
877 }
878 }
879
880 // Remove the loop from the top-level LoopInfo object.
881 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
882 assert(I != E && "Couldn't find loop");
883 if (*I == L) {
884 LI->removeLoop(I);
885 break;
886 }
887 }
888
889 // Move all of the subloops to the top-level.
890 while (L->begin() != L->end())
891 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
892 }
893
894 delete L;
895 RemoveLoopFromWorklist(L);
896}
897
898
899
Chris Lattnerc2358092006-02-11 00:43:37 +0000900// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
901// the value specified by Val in the specified loop, or we know it does NOT have
902// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000903void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000904 Constant *Val,
905 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000906 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +0000907
Chris Lattner18f16092004-04-19 18:07:02 +0000908 // FIXME: Support correlated properties, like:
909 // for (...)
910 // if (li1 < li2)
911 // ...
912 // if (li1 > li2)
913 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +0000914
Chris Lattner708e1a52006-02-10 02:30:37 +0000915 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
916 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +0000917 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +0000918 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000919
Chris Lattner52221f72006-02-17 00:31:07 +0000920 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
921 // in the loop with the appropriate one directly.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000922 if (IsEqual || isa<ConstantBool>(Val)) {
923 Value *Replacement;
924 if (IsEqual)
925 Replacement = Val;
926 else
927 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner52221f72006-02-17 00:31:07 +0000928
929 for (unsigned i = 0, e = Users.size(); i != e; ++i)
930 if (Instruction *U = cast<Instruction>(Users[i])) {
931 if (!L->contains(U->getParent()))
932 continue;
933 U->replaceUsesOfWith(LIC, Replacement);
934 Worklist.push_back(U);
935 }
936 } else {
937 // Otherwise, we don't know the precise value of LIC, but we do know that it
938 // is certainly NOT "Val". As such, simplify any uses in the loop that we
939 // can. This case occurs when we unswitch switch statements.
940 for (unsigned i = 0, e = Users.size(); i != e; ++i)
941 if (Instruction *U = cast<Instruction>(Users[i])) {
942 if (!L->contains(U->getParent()))
943 continue;
944
945 Worklist.push_back(U);
946
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000947 // If we know that LIC is not Val, use this info to simplify code.
948 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
949 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
950 if (SI->getCaseValue(i) == Val) {
951 // Found a dead case value. Don't remove PHI nodes in the
952 // successor if they become single-entry, those PHI nodes may
953 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +0000954
955 // FIXME: This is a hack. We need to keep the successor around
956 // and hooked up so as to preserve the loop structure, because
957 // trying to update it is complicated. So instead we preserve the
958 // loop structure and put the block on an dead code path.
959
960 BasicBlock* Old = SI->getParent();
961 BasicBlock* Split = SplitBlock(Old, SI);
962
963 Instruction* OldTerm = Old->getTerminator();
Reid Spencer3ed469c2006-11-02 20:25:50 +0000964 new BranchInst(Split, SI->getSuccessor(i),
965 ConstantBool::getTrue(), OldTerm);
Owen Anderson2b67f072006-06-26 07:44:36 +0000966
967 Old->getTerminator()->eraseFromParent();
968
Owen Andersonbef85082006-06-27 22:26:09 +0000969
970 PHINode *PN;
971 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
972 (PN = dyn_cast<PHINode>(II)); ++II) {
973 Value *InVal = PN->removeIncomingValue(Split, false);
974 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +0000975 }
976
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000977 SI->removeCase(i);
978 break;
Chris Lattnerc2358092006-02-11 00:43:37 +0000979 }
980 }
Chris Lattnerc2358092006-02-11 00:43:37 +0000981 }
Chris Lattner52221f72006-02-17 00:31:07 +0000982
983 // TODO: We could do other simplifications, for example, turning
984 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000985 }
Chris Lattner52221f72006-02-17 00:31:07 +0000986 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000987
988 SimplifyCode(Worklist);
989}
990
991/// SimplifyCode - Okay, now that we have simplified some instructions in the
992/// loop, walk over it and constant prop, dce, and fold control flow where
993/// possible. Note that this is effectively a very simple loop-structure-aware
994/// optimizer. During processing of this loop, L could very well be deleted, so
995/// it must not be used.
996///
997/// FIXME: When the loop optimizer is more mature, separate this out to a new
998/// pass.
999///
1000void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner52221f72006-02-17 00:31:07 +00001001 while (!Worklist.empty()) {
1002 Instruction *I = Worklist.back();
1003 Worklist.pop_back();
1004
1005 // Simple constant folding.
1006 if (Constant *C = ConstantFoldInstruction(I)) {
1007 ReplaceUsesOfWith(I, C, Worklist);
1008 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001009 }
Chris Lattner52221f72006-02-17 00:31:07 +00001010
1011 // Simple DCE.
1012 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001013 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001014
1015 // Add uses to the worklist, which may be dead now.
1016 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1017 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1018 Worklist.push_back(Use);
1019 I->eraseFromParent();
1020 RemoveFromWorklist(I, Worklist);
1021 ++NumSimplify;
1022 continue;
1023 }
1024
1025 // Special case hacks that appear commonly in unswitched code.
1026 switch (I->getOpcode()) {
1027 case Instruction::Select:
1028 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1029 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1030 continue;
1031 }
1032 break;
1033 case Instruction::And:
1034 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1035 cast<BinaryOperator>(I)->swapOperands();
1036 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1037 if (CB->getValue()) // X & 1 -> X
1038 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1039 else // X & 0 -> 0
1040 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1041 continue;
1042 }
1043 break;
1044 case Instruction::Or:
1045 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1046 cast<BinaryOperator>(I)->swapOperands();
1047 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1048 if (CB->getValue()) // X | 1 -> 1
1049 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1050 else // X | 0 -> X
1051 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1052 continue;
1053 }
1054 break;
1055 case Instruction::Br: {
1056 BranchInst *BI = cast<BranchInst>(I);
1057 if (BI->isUnconditional()) {
1058 // If BI's parent is the only pred of the successor, fold the two blocks
1059 // together.
1060 BasicBlock *Pred = BI->getParent();
1061 BasicBlock *Succ = BI->getSuccessor(0);
1062 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1063 if (!SinglePred) continue; // Nothing to do.
1064 assert(SinglePred == Pred && "CFG broken");
1065
Bill Wendlingb7427032006-11-26 09:46:52 +00001066 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1067 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001068
1069 // Resolve any single entry PHI nodes in Succ.
1070 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1071 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1072
1073 // Move all of the successor contents from Succ to Pred.
1074 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1075 Succ->end());
1076 BI->eraseFromParent();
1077 RemoveFromWorklist(BI, Worklist);
1078
1079 // If Succ has any successors with PHI nodes, update them to have
1080 // entries coming from Pred instead of Succ.
1081 Succ->replaceAllUsesWith(Pred);
1082
1083 // Remove Succ from the loop tree.
1084 LI->removeBlock(Succ);
1085 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001086 ++NumSimplify;
Chris Lattnerf4412d82006-02-18 01:27:45 +00001087 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001088 // Conditional branch. Turn it into an unconditional branch, then
1089 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001090 break; // FIXME: Enable.
1091
Bill Wendlingb7427032006-11-26 09:46:52 +00001092 DOUT << "Folded branch: " << *BI;
Chris Lattnerdb410242006-02-18 02:42:34 +00001093 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1094 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1095 DeadSucc->removePredecessor(BI->getParent(), true);
1096 Worklist.push_back(new BranchInst(LiveSucc, BI));
1097 BI->eraseFromParent();
1098 RemoveFromWorklist(BI, Worklist);
1099 ++NumSimplify;
1100
1101 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner52221f72006-02-17 00:31:07 +00001102 }
1103 break;
1104 }
1105 }
1106 }
Chris Lattner18f16092004-04-19 18:07:02 +00001107}