blob: 222d1782bde7be364b7744c29c53a1fd258ef9f2 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-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 Lattnerf48f7772004-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 Lattnerec6b40a2006-02-10 19:08:15 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000039#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000043#include <iostream>
Chris Lattner2826e052006-02-09 19:14:52 +000044#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000045using namespace llvm;
46
47namespace {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +000048 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
49 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
50 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
51 Statistic<> NumTrivial ("loop-unswitch",
52 "Number of unswitches that are trivial");
Chris Lattner6fd13622006-02-17 00:31:07 +000053 Statistic<> NumSimplify("loop-unswitch",
54 "Number of simplifications of unswitched code");
Chris Lattner89762192006-02-09 20:15:48 +000055 cl::opt<unsigned>
56 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
57 cl::init(10), cl::Hidden);
58
Chris Lattnerf48f7772004-04-19 18:07:02 +000059 class LoopUnswitch : public FunctionPass {
60 LoopInfo *LI; // Loop information
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000061
62 // LoopProcessWorklist - List of loops we need to process.
63 std::vector<Loop*> LoopProcessWorklist;
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 public:
65 virtual bool runOnFunction(Function &F);
66 bool visitLoop(Loop *L);
67
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
70 ///
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000073 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000074 AU.addRequired<LoopInfo>();
75 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000076 AU.addRequiredID(LCSSAID);
77 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000078 }
79
80 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000081 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
82 /// remove it.
83 void RemoveLoopFromWorklist(Loop *L) {
84 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
85 LoopProcessWorklist.end(), L);
86 if (I != LoopProcessWorklist.end())
87 LoopProcessWorklist.erase(I);
88 }
89
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000090 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000091 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +000092 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +000093 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000094 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000095 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +000096 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000097
98 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
99 Constant *Val, bool isEqual);
100
101 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000102 void RemoveBlockIfDead(BasicBlock *BB,
103 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000104 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000105 };
106 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
107}
108
Jeff Coheneca0d0f2005-01-06 05:47:18 +0000109FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000110
111bool LoopUnswitch::runOnFunction(Function &F) {
112 bool Changed = false;
113 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000114
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000115 // Populate the worklist of loops to process in post-order.
116 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
117 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
118 LoopProcessWorklist.push_back(*LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000119
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000120 // Process the loops in worklist order, this is a post-order visitation of
121 // the loops. We use a worklist of loops so that loops can be removed at any
122 // time if they are deleted (e.g. the backedge of a loop is removed).
123 while (!LoopProcessWorklist.empty()) {
124 Loop *L = LoopProcessWorklist.back();
125 LoopProcessWorklist.pop_back();
126 Changed |= visitLoop(L);
127 }
128
129 return Changed;
130}
131
132/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
133/// invariant in the loop, or has an invariant piece, return the invariant.
134/// Otherwise, return null.
135static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
136 // Constants should be folded, not unswitched on!
137 if (isa<Constant>(Cond)) return false;
138
139 // TODO: Handle: br (VARIANT|INVARIANT).
140 // TODO: Hoist simple expressions out of loops.
141 if (L->isLoopInvariant(Cond)) return Cond;
142
143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
144 if (BO->getOpcode() == Instruction::And ||
145 BO->getOpcode() == Instruction::Or) {
146 // If either the left or right side is invariant, we can unswitch on this,
147 // which will cause the branch to go away in one loop and the condition to
148 // simplify in the other one.
149 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
150 return LHS;
151 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
152 return RHS;
153 }
154
155 return 0;
156}
157
158bool LoopUnswitch::visitLoop(Loop *L) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000159 assert(L->isLCSSAForm());
160
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000161 bool Changed = false;
162
163 // Loop over all of the basic blocks in the loop. If we find an interior
164 // block that is branching on a loop-invariant condition, we can unswitch this
165 // loop.
166 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
167 I != E; ++I) {
168 TerminatorInst *TI = (*I)->getTerminator();
169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
170 // If this isn't branching on an invariant condition, we can't unswitch
171 // it.
172 if (BI->isConditional()) {
173 // See if this, or some part of it, is loop invariant. If so, we can
174 // unswitch on it if we desire.
175 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
176 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
177 ++NumBranches;
178 return true;
179 }
180 }
181 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
182 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
183 if (LoopCond && SI->getNumCases() > 1) {
184 // Find a value to unswitch on:
185 // FIXME: this should chose the most expensive case!
186 Constant *UnswitchVal = SI->getCaseValue(1);
187 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
188 ++NumSwitches;
189 return true;
190 }
191 }
192 }
193
194 // Scan the instructions to check for unswitchable values.
195 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
196 BBI != E; ++BBI)
197 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
199 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
200 ++NumSelects;
201 return true;
202 }
203 }
204 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000205
206 assert(L->isLCSSAForm());
207
Chris Lattnerf48f7772004-04-19 18:07:02 +0000208 return Changed;
209}
210
Chris Lattnere5cb76d2006-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 Lattnerbaddba42006-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 Lattnere5cb76d2006-02-15 22:03:36 +0000233 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-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 Lattner6e263152006-02-10 02:30:37 +0000237 }
Chris Lattnere5cb76d2006-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 Lattnerfdff0bb2006-02-15 22:52:05 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000242 if (I->mayWriteToMemory())
243 return false;
244
245 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000246}
247
Chris Lattnerc2e3a7a2006-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 Lattnere5cb76d2006-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 Lattnere5cb76d2006-02-15 22:03:36 +0000254 BasicBlock *ExitBB = 0;
255 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
256 return ExitBB;
257 return 0;
258}
Chris Lattner6e263152006-02-10 02:30:37 +0000259
Chris Lattnered7a67b2006-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 Lattner8a5a3242006-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 Lattner49354172006-02-10 02:01:22 +0000273 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000274 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000275 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000276
Chris Lattnerfdff0bb2006-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 Lattnered7a67b2006-02-10 01:24:09 +0000283
Chris Lattnerfdff0bb2006-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 Lattnerff42e812006-02-16 01:24:41 +0000289 if (Val) *Val = ConstantBool::True;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000290 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
291 if (Val) *Val = ConstantBool::False;
Chris Lattnerfdff0bb2006-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 Lattnerfdff0bb2006-02-15 22:52:05 +0000305 break;
306 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000307 }
308
Chris Lattnere5521db2006-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 Lattnere5cb76d2006-02-15 22:03:36 +0000312 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000313
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000314 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-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 Lattnere5cb76d2006-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 Lattnered7a67b2006-02-10 01:24:09 +0000321 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
322 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000323 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000324 return true;
Chris Lattnered7a67b2006-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
336 unsigned Cost = 0;
337 // FIXME: this is brain dead. It should take into consideration code
338 // shrinkage.
339 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
340 I != E; ++I) {
341 BasicBlock *BB = *I;
342 // Do not include empty blocks in the cost calculation. This happen due to
343 // loop canonicalization and will be removed.
344 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
345 continue;
346
347 // Count basic blocks.
348 ++Cost;
349 }
350
351 return Cost;
352}
353
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000354/// UnswitchIfProfitable - We have found that we can unswitch L when
355/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
356/// unswitch the loop, reprocess the pieces, then return true.
357bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
358 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000359 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
360 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000361 // FIXME: this should estimate growth by the amount of code shared by the
362 // resultant unswitched loops.
363 //
364 DEBUG(std::cerr << "NOT unswitching loop %"
365 << L->getHeader()->getName() << ", cost too high: "
366 << L->getBlocks().size() << "\n");
367 return false;
368 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000369
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000370 // If this is a trivial condition to unswitch (which results in no code
371 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000372 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000373 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000374 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
375 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000376 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000377 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000378 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000379
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000380 return true;
381}
382
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000383/// SplitBlock - Split the specified block at the specified instruction - every
384/// thing before SplitPt stays in Old and everything starting with SplitPt moves
385/// to a new block. The two blocks are joined by an unconditional branch and
386/// the loop info is updated.
387///
388BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000389 BasicBlock::iterator SplitIt = SplitPt;
390 while (isa<PHINode>(SplitIt))
391 ++SplitIt;
392 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000393
394 // The new block lives in whichever loop the old one did.
395 if (Loop *L = LI->getLoopFor(Old))
396 L->addBasicBlockToLoop(New, *LI);
397
398 return New;
399}
400
401
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000402BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
403 TerminatorInst *LatchTerm = BB->getTerminator();
404 unsigned SuccNum = 0;
405 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
406 assert(i != e && "Didn't find edge?");
407 if (LatchTerm->getSuccessor(i) == Succ) {
408 SuccNum = i;
409 break;
410 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000411 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000412
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000413 // If this is a critical edge, let SplitCriticalEdge do it.
414 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
415 return LatchTerm->getSuccessor(SuccNum);
416
417 // If the edge isn't critical, then BB has a single successor or Succ has a
418 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000419 BasicBlock::iterator SplitPoint;
420 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
421 // If the successor only has a single pred, split the top of the successor
422 // block.
423 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000424 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000425 } else {
426 // Otherwise, if BB has a single successor, split it at the bottom of the
427 // block.
428 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
429 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000430 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000431 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000432}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000433
Chris Lattnerf48f7772004-04-19 18:07:02 +0000434
435
Misha Brukmanb1c93172005-04-21 23:48:37 +0000436// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000437// current values into those specified by ValueMap.
438//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000439static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000440 std::map<const Value *, Value*> &ValueMap) {
441 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
442 Value *Op = I->getOperand(op);
443 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
444 if (It != ValueMap.end()) Op = It->second;
445 I->setOperand(op, Op);
446 }
447}
448
449/// CloneLoop - Recursively clone the specified loop and all of its children,
450/// mapping the blocks with the specified map.
451static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
452 LoopInfo *LI) {
453 Loop *New = new Loop();
454
455 if (PL)
456 PL->addChildLoop(New);
457 else
458 LI->addTopLevelLoop(New);
459
460 // Add all of the blocks in L to the new loop.
461 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
462 I != E; ++I)
463 if (LI->getLoopFor(*I) == L)
464 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
465
466 // Add all of the subloops to the new loop.
467 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
468 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000469
Chris Lattnerf48f7772004-04-19 18:07:02 +0000470 return New;
471}
472
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000473/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
474/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
475/// code immediately before InsertPt.
476static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
477 BasicBlock *TrueDest,
478 BasicBlock *FalseDest,
479 Instruction *InsertPt) {
480 // Insert a conditional branch on LIC to the two preheaders. The original
481 // code is the true version and the new code is the false version.
482 Value *BranchVal = LIC;
Chris Lattner65152d82006-02-15 19:05:52 +0000483 if (!isa<ConstantBool>(Val)) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000484 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
485 } else if (Val != ConstantBool::True) {
486 // We want to enter the new loop when the condition is true.
487 std::swap(TrueDest, FalseDest);
488 }
489
490 // Insert the new branch.
491 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
492}
493
494
Chris Lattnered7a67b2006-02-10 01:24:09 +0000495/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
496/// condition in it (a cond branch from its header block to its latch block,
497/// where the path through the loop that doesn't execute its body has no
498/// side-effects), unswitch it. This doesn't involve any code duplication, just
499/// moving the conditional branch outside of the loop and updating loop info.
500void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000501 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000502 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000503 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
504 << L->getHeader()->getName() << " [" << L->getBlocks().size()
505 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattner8a5a3242006-02-22 06:37:14 +0000506 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner3fc31482006-02-10 01:36:35 +0000507
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000508 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000509 // to insert the conditional branch. We will change 'OrigPH' to have a
510 // conditional branch on Cond.
511 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000512 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000513
514 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000515 // to branch to: this is the exit block out of the loop that we should
516 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000517
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000518 // Split this block now, so that the loop maintains its exit block, and so
519 // that the jump from the preheader can execute the contents of the exit block
520 // without actually branching to it (the exit block should be dominated by the
521 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000522 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000523 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000524
Chris Lattnered7a67b2006-02-10 01:24:09 +0000525 // Okay, now we have a position to branch from and a position to branch to,
526 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000527 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
528 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000529 OrigPH->getTerminator()->eraseFromParent();
530
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000531 // We need to reprocess this loop, it could be unswitched again.
532 LoopProcessWorklist.push_back(L);
533
Chris Lattnered7a67b2006-02-10 01:24:09 +0000534 // Now that we know that the loop is never entered when this condition is a
535 // particular value, rewrite the loop with this info. We know that this will
536 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000537 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000538 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000539}
540
Chris Lattnerf48f7772004-04-19 18:07:02 +0000541
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000542/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
543/// equal Val. Split it into loop versions and test the condition outside of
544/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000545void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
546 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000547 Function *F = L->getHeader()->getParent();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000548 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000549 << L->getHeader()->getName() << " [" << L->getBlocks().size()
550 << " blocks] in Function " << F->getName()
551 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000552
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000553 // LoopBlocks contains all of the basic blocks of the loop, including the
554 // preheader of the loop, the body of the loop, and the exit blocks of the
555 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000556 std::vector<BasicBlock*> LoopBlocks;
557
558 // First step, split the preheader and exit blocks, and add these blocks to
559 // the LoopBlocks list.
560 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000561 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000562
563 // We want the loop to come after the preheader, but before the exit blocks.
564 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
565
566 std::vector<BasicBlock*> ExitBlocks;
567 L->getExitBlocks(ExitBlocks);
568 std::sort(ExitBlocks.begin(), ExitBlocks.end());
569 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
570 ExitBlocks.end());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000571
Owen Andersonf52351e2006-06-26 07:44:36 +0000572 // Split all of the edges from inside the loop to their exit blocks. Update
573 // the appropriate Phi nodes as we do so.
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000574 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner8e44ff52006-02-18 00:55:32 +0000575
Chris Lattnered7a67b2006-02-10 01:24:09 +0000576 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-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 Andersonf52351e2006-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
607 Instruction* InsertPt = EndBlock->begin();
608 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 Lattnered7a67b2006-02-10 01:24:09 +0000619 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000620
621 // The exit blocks may have been changed due to edge splitting, recompute.
622 ExitBlocks.clear();
623 L->getExitBlocks(ExitBlocks);
624 std::sort(ExitBlocks.begin(), ExitBlocks.end());
625 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
626 ExitBlocks.end());
627
628 // Add exit blocks to the loop blocks.
629 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000630
631 // Next step, clone all of the basic blocks that make up the loop (including
632 // the loop preheader and exit blocks), keeping track of the mapping between
633 // the instructions and blocks.
634 std::vector<BasicBlock*> NewBlocks;
635 NewBlocks.reserve(LoopBlocks.size());
636 std::map<const Value*, Value*> ValueMap;
637 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000638 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
639 NewBlocks.push_back(New);
640 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000641 }
642
643 // Splice the newly inserted blocks into the function right before the
644 // original preheader.
645 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
646 NewBlocks[0], F->end());
647
648 // Now we create the new Loop object for the versioned loop.
649 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000650 Loop *ParentLoop = L->getParentLoop();
651 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000652 // Make sure to add the cloned preheader and exit blocks to the parent loop
653 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000654 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
655 }
656
657 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
658 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000659 // The new exit block should be in the same loop as the old one.
660 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
661 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000662
663 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
664 "Exit block should have been split to have one successor!");
665 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
666
667 // If the successor of the exit block had PHI nodes, add an entry for
668 // NewExit.
669 PHINode *PN;
670 for (BasicBlock::iterator I = ExitSucc->begin();
671 (PN = dyn_cast<PHINode>(I)); ++I) {
672 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
673 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
674 if (It != ValueMap.end()) V = It->second;
675 PN->addIncoming(V, NewExit);
676 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000677 }
678
679 // Rewrite the code to refer to itself.
680 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
681 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
682 E = NewBlocks[i]->end(); I != E; ++I)
683 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000684
Chris Lattnerf48f7772004-04-19 18:07:02 +0000685 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000686 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
687 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000688 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000689
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000690 // Emit the new branch that selects between the two versions of this loop.
691 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
692 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000693
694 LoopProcessWorklist.push_back(L);
695 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000696
697 // Now we rewrite the original code to know that the condition is true and the
698 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000699 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
700
701 // It's possible that simplifying one loop could cause the other to be
702 // deleted. If so, don't simplify it.
703 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
704 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000705}
706
Chris Lattner6fd13622006-02-17 00:31:07 +0000707/// RemoveFromWorklist - Remove all instances of I from the worklist vector
708/// specified.
709static void RemoveFromWorklist(Instruction *I,
710 std::vector<Instruction*> &Worklist) {
711 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
712 Worklist.end(), I);
713 while (WI != Worklist.end()) {
714 unsigned Offset = WI-Worklist.begin();
715 Worklist.erase(WI);
716 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
717 }
718}
719
720/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
721/// program, replacing all uses with V and update the worklist.
722static void ReplaceUsesOfWith(Instruction *I, Value *V,
723 std::vector<Instruction*> &Worklist) {
724 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
725
726 // Add uses to the worklist, which may be dead now.
727 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
728 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
729 Worklist.push_back(Use);
730
731 // Add users to the worklist which may be simplified now.
732 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
733 UI != E; ++UI)
734 Worklist.push_back(cast<Instruction>(*UI));
735 I->replaceAllUsesWith(V);
736 I->eraseFromParent();
737 RemoveFromWorklist(I, Worklist);
738 ++NumSimplify;
739}
740
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000741/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
742/// information, and remove any dead successors it has.
743///
744void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
745 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000746 if (pred_begin(BB) != pred_end(BB)) {
747 // This block isn't dead, since an edge to BB was just removed, see if there
748 // are any easy simplifications we can do now.
749 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
750 // If it has one pred, fold phi nodes in BB.
751 while (isa<PHINode>(BB->begin()))
752 ReplaceUsesOfWith(BB->begin(),
753 cast<PHINode>(BB->begin())->getIncomingValue(0),
754 Worklist);
755
756 // If this is the header of a loop and the only pred is the latch, we now
757 // have an unreachable loop.
758 if (Loop *L = LI->getLoopFor(BB))
759 if (L->getHeader() == BB && L->contains(Pred)) {
760 // Remove the branch from the latch to the header block, this makes
761 // the header dead, which will make the latch dead (because the header
762 // dominates the latch).
763 Pred->getTerminator()->eraseFromParent();
764 new UnreachableInst(Pred);
765
766 // The loop is now broken, remove it from LI.
767 RemoveLoopFromHierarchy(L);
768
769 // Reprocess the header, which now IS dead.
770 RemoveBlockIfDead(BB, Worklist);
771 return;
772 }
773
774 // If pred ends in a uncond branch, add uncond branch to worklist so that
775 // the two blocks will get merged.
776 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
777 if (BI->isUnconditional())
778 Worklist.push_back(BI);
779 }
780 return;
781 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000782
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000783 DEBUG(std::cerr << "Nuking dead block: " << *BB);
784
785 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000786 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000787 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000788
789 // Anything that uses the instructions in this basic block should have their
790 // uses replaced with undefs.
791 if (!I->use_empty())
792 I->replaceAllUsesWith(UndefValue::get(I->getType()));
793 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000794
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000795 // If this is the edge to the header block for a loop, remove the loop and
796 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000797 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000798 if (BBLoop->getLoopLatch() == BB)
799 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000800 }
801
802 // Remove the block from the loop info, which removes it from any loops it
803 // was in.
804 LI->removeBlock(BB);
805
806
807 // Remove phi node entries in successors for this block.
808 TerminatorInst *TI = BB->getTerminator();
809 std::vector<BasicBlock*> Succs;
810 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
811 Succs.push_back(TI->getSuccessor(i));
812 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000813 }
814
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000815 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000816 std::sort(Succs.begin(), Succs.end());
817 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
818
819 // Remove the basic block, including all of the instructions contained in it.
820 BB->eraseFromParent();
821
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000822 // Remove successor blocks here that are not dead, so that we know we only
823 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
824 // then getting removed before we revisit them, which is badness.
825 //
826 for (unsigned i = 0; i != Succs.size(); ++i)
827 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
828 // One exception is loop headers. If this block was the preheader for a
829 // loop, then we DO want to visit the loop so the loop gets deleted.
830 // We know that if the successor is a loop header, that this loop had to
831 // be the preheader: the case where this was the latch block was handled
832 // above and headers can only have two predecessors.
833 if (!LI->isLoopHeader(Succs[i])) {
834 Succs.erase(Succs.begin()+i);
835 --i;
836 }
837 }
838
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000839 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
840 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000841}
Chris Lattner6fd13622006-02-17 00:31:07 +0000842
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000843/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
844/// become unwrapped, either because the backedge was deleted, or because the
845/// edge into the header was removed. If the edge into the header from the
846/// latch block was removed, the loop is unwrapped but subloops are still alive,
847/// so they just reparent loops. If the loops are actually dead, they will be
848/// removed later.
849void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
850 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
851 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
852 // they are now all in it.
853 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
854 I != E; ++I)
855 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
856 LI->changeLoopFor(*I, ParentLoop);
857
858 // Remove the loop from its parent loop.
859 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
860 ++I) {
861 assert(I != E && "Couldn't find loop");
862 if (*I == L) {
863 ParentLoop->removeChildLoop(I);
864 break;
865 }
866 }
867
868 // Move all subloops into the parent loop.
869 while (L->begin() != L->end())
870 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
871 } else {
872 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
873 // they no longer in a loop at all.
874
875 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
876 // Don't change blocks in subloops.
877 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
878 LI->removeBlock(L->getBlocks()[i]);
879 --i;
880 }
881 }
882
883 // Remove the loop from the top-level LoopInfo object.
884 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
885 assert(I != E && "Couldn't find loop");
886 if (*I == L) {
887 LI->removeLoop(I);
888 break;
889 }
890 }
891
892 // Move all of the subloops to the top-level.
893 while (L->begin() != L->end())
894 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
895 }
896
897 delete L;
898 RemoveLoopFromWorklist(L);
899}
900
901
902
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000903// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
904// the value specified by Val in the specified loop, or we know it does NOT have
905// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000906void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000907 Constant *Val,
908 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000909 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000910
Chris Lattnerf48f7772004-04-19 18:07:02 +0000911 // FIXME: Support correlated properties, like:
912 // for (...)
913 // if (li1 < li2)
914 // ...
915 // if (li1 > li2)
916 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000917
Chris Lattner6e263152006-02-10 02:30:37 +0000918 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
919 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000920 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000921 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000922
Chris Lattner6fd13622006-02-17 00:31:07 +0000923 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
924 // in the loop with the appropriate one directly.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000925 if (IsEqual || isa<ConstantBool>(Val)) {
926 Value *Replacement;
927 if (IsEqual)
928 Replacement = Val;
929 else
930 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000931
932 for (unsigned i = 0, e = Users.size(); i != e; ++i)
933 if (Instruction *U = cast<Instruction>(Users[i])) {
934 if (!L->contains(U->getParent()))
935 continue;
936 U->replaceUsesOfWith(LIC, Replacement);
937 Worklist.push_back(U);
938 }
939 } else {
940 // Otherwise, we don't know the precise value of LIC, but we do know that it
941 // is certainly NOT "Val". As such, simplify any uses in the loop that we
942 // can. This case occurs when we unswitch switch statements.
943 for (unsigned i = 0, e = Users.size(); i != e; ++i)
944 if (Instruction *U = cast<Instruction>(Users[i])) {
945 if (!L->contains(U->getParent()))
946 continue;
947
948 Worklist.push_back(U);
949
Chris Lattnerfa335f62006-02-16 19:36:22 +0000950 // If we know that LIC is not Val, use this info to simplify code.
951 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
952 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
953 if (SI->getCaseValue(i) == Val) {
954 // Found a dead case value. Don't remove PHI nodes in the
955 // successor if they become single-entry, those PHI nodes may
956 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000957
958 // FIXME: This is a hack. We need to keep the successor around
959 // and hooked up so as to preserve the loop structure, because
960 // trying to update it is complicated. So instead we preserve the
961 // loop structure and put the block on an dead code path.
962
963 BasicBlock* Old = SI->getParent();
964 BasicBlock* Split = SplitBlock(Old, SI);
965
966 Instruction* OldTerm = Old->getTerminator();
967 BranchInst* Branch = new BranchInst(Split,
968 SI->getSuccessor(i),
969 ConstantBool::True,
970 OldTerm);
971
972 Old->getTerminator()->eraseFromParent();
973
974 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin(),
975 IE = SI->getSuccessor(i)->end(); II != IE; ++II) {
976 if (isa<PHINode>(*II)) {
977 (*II).replaceUsesOfWith(Split, Old);
978 }
979 }
980
Chris Lattnerfa335f62006-02-16 19:36:22 +0000981 SI->removeCase(i);
982 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000983 }
984 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000985 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000986
987 // TODO: We could do other simplifications, for example, turning
988 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000989 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000990 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000991
992 SimplifyCode(Worklist);
993}
994
995/// SimplifyCode - Okay, now that we have simplified some instructions in the
996/// loop, walk over it and constant prop, dce, and fold control flow where
997/// possible. Note that this is effectively a very simple loop-structure-aware
998/// optimizer. During processing of this loop, L could very well be deleted, so
999/// it must not be used.
1000///
1001/// FIXME: When the loop optimizer is more mature, separate this out to a new
1002/// pass.
1003///
1004void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001005 while (!Worklist.empty()) {
1006 Instruction *I = Worklist.back();
1007 Worklist.pop_back();
1008
1009 // Simple constant folding.
1010 if (Constant *C = ConstantFoldInstruction(I)) {
1011 ReplaceUsesOfWith(I, C, Worklist);
1012 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001013 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001014
1015 // Simple DCE.
1016 if (isInstructionTriviallyDead(I)) {
1017 DEBUG(std::cerr << "Remove dead instruction '" << *I);
1018
1019 // Add uses to the worklist, which may be dead now.
1020 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1021 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1022 Worklist.push_back(Use);
1023 I->eraseFromParent();
1024 RemoveFromWorklist(I, Worklist);
1025 ++NumSimplify;
1026 continue;
1027 }
1028
1029 // Special case hacks that appear commonly in unswitched code.
1030 switch (I->getOpcode()) {
1031 case Instruction::Select:
1032 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1033 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1034 continue;
1035 }
1036 break;
1037 case Instruction::And:
1038 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1039 cast<BinaryOperator>(I)->swapOperands();
1040 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1041 if (CB->getValue()) // X & 1 -> X
1042 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1043 else // X & 0 -> 0
1044 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1045 continue;
1046 }
1047 break;
1048 case Instruction::Or:
1049 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1050 cast<BinaryOperator>(I)->swapOperands();
1051 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1052 if (CB->getValue()) // X | 1 -> 1
1053 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1054 else // X | 0 -> X
1055 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1056 continue;
1057 }
1058 break;
1059 case Instruction::Br: {
1060 BranchInst *BI = cast<BranchInst>(I);
1061 if (BI->isUnconditional()) {
1062 // If BI's parent is the only pred of the successor, fold the two blocks
1063 // together.
1064 BasicBlock *Pred = BI->getParent();
1065 BasicBlock *Succ = BI->getSuccessor(0);
1066 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1067 if (!SinglePred) continue; // Nothing to do.
1068 assert(SinglePred == Pred && "CFG broken");
1069
1070 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1071 << Succ->getName() << "\n");
1072
1073 // Resolve any single entry PHI nodes in Succ.
1074 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1075 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1076
1077 // Move all of the successor contents from Succ to Pred.
1078 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1079 Succ->end());
1080 BI->eraseFromParent();
1081 RemoveFromWorklist(BI, Worklist);
1082
1083 // If Succ has any successors with PHI nodes, update them to have
1084 // entries coming from Pred instead of Succ.
1085 Succ->replaceAllUsesWith(Pred);
1086
1087 // Remove Succ from the loop tree.
1088 LI->removeBlock(Succ);
1089 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001090 ++NumSimplify;
Chris Lattner29f771b2006-02-18 01:27:45 +00001091 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001092 // Conditional branch. Turn it into an unconditional branch, then
1093 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001094 break; // FIXME: Enable.
1095
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001096 DEBUG(std::cerr << "Folded branch: " << *BI);
1097 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1098 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1099 DeadSucc->removePredecessor(BI->getParent(), true);
1100 Worklist.push_back(new BranchInst(LiveSucc, BI));
1101 BI->eraseFromParent();
1102 RemoveFromWorklist(BI, Worklist);
1103 ++NumSimplify;
1104
1105 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001106 }
1107 break;
1108 }
1109 }
1110 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001111}