blob: 79243a4385b02ad63e5fad38d5536c8e7e752157 [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 Lattner2826e052006-02-09 19:14:52 +0000211
Chris Lattnered7a67b2006-02-10 01:24:09 +0000212/// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
213/// the loop that are used by instructions outside of it.
Chris Lattner2826e052006-02-09 19:14:52 +0000214static bool LoopValuesUsedOutsideLoop(Loop *L) {
215 // We will be doing lots of "loop contains block" queries. Loop::contains is
216 // linear time, use a set to speed this up.
217 std::set<BasicBlock*> LoopBlocks;
218
219 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
220 BB != E; ++BB)
221 LoopBlocks.insert(*BB);
222
223 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
224 BB != E; ++BB) {
225 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
226 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
227 ++UI) {
228 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
229 if (!LoopBlocks.count(UserBB))
230 return true;
231 }
232 }
233 return false;
234}
235
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000236/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
237/// 1. Exit the loop with no side effects.
238/// 2. Branch to the latch block with no side-effects.
239///
240/// If these conditions are true, we return true and set ExitBB to the block we
241/// exit through.
242///
243static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
244 BasicBlock *&ExitBB,
245 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000246 if (!Visited.insert(BB).second) {
247 // Already visited and Ok, end of recursion.
248 return true;
249 } else if (!L->contains(BB)) {
250 // Otherwise, this is a loop exit, this is fine so long as this is the
251 // first exit.
252 if (ExitBB != 0) return false;
253 ExitBB = BB;
254 return true;
255 }
256
257 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000258 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000259 // Check to see if the successor is a trivial loop exit.
260 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
261 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000262 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000263
264 // Okay, everything after this looks good, check to make sure that this block
265 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000267 if (I->mayWriteToMemory())
268 return false;
269
270 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000271}
272
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000273/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
274/// leads to an exit from the specified loop, and has no side-effects in the
275/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000276static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
277 std::set<BasicBlock*> Visited;
278 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000279 BasicBlock *ExitBB = 0;
280 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
281 return ExitBB;
282 return 0;
283}
Chris Lattner6e263152006-02-10 02:30:37 +0000284
Chris Lattnered7a67b2006-02-10 01:24:09 +0000285/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
286/// trivial: that is, that the condition controls whether or not the loop does
287/// anything at all. If this is a trivial condition, unswitching produces no
288/// code duplications (equivalently, it produces a simpler loop and a new empty
289/// loop, which gets deleted).
290///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000291/// If this is a trivial condition, return true, otherwise return false. When
292/// returning true, this sets Cond and Val to the condition that controls the
293/// trivial condition: when Cond dynamically equals Val, the loop is known to
294/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
295/// Cond == Val.
296///
297static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000298 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000299 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000300 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000301
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000302 BasicBlock *LoopExitBB = 0;
303 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
304 // If the header block doesn't end with a conditional branch on Cond, we
305 // can't handle it.
306 if (!BI->isConditional() || BI->getCondition() != Cond)
307 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000308
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000309 // Check to see if a successor of the branch is guaranteed to go to the
310 // latch block or exit through a one exit block without having any
311 // side-effects. If so, determine the value of Cond that causes it to do
312 // this.
313 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Chris Lattnerff42e812006-02-16 01:24:41 +0000314 if (Val) *Val = ConstantBool::True;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000315 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
316 if (Val) *Val = ConstantBool::False;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000317 }
318 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
319 // If this isn't a switch on Cond, we can't handle it.
320 if (SI->getCondition() != Cond) return false;
321
322 // Check to see if a successor of the switch is guaranteed to go to the
323 // latch block or exit through a one exit block without having any
324 // side-effects. If so, determine the value of Cond that causes it to do
325 // this. Note that we can't trivially unswitch on the default case.
326 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
327 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
328 // Okay, we found a trivial case, remember the value that is trivial.
329 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000330 break;
331 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000332 }
333
Chris Lattnere5521db2006-02-22 23:55:00 +0000334 // If we didn't find a single unique LoopExit block, or if the loop exit block
335 // contains phi nodes, this isn't trivial.
336 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000337 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000338
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000339 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000340
341 // We already know that nothing uses any scalar values defined inside of this
342 // loop. As such, we just have to check to see if this loop will execute any
343 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000344 // part of the loop that the code *would* execute. We already checked the
345 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000346 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
347 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000348 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000349 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000350}
351
352/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
353/// we choose to unswitch the specified loop on the specified value.
354///
355unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
356 // If the condition is trivial, always unswitch. There is no code growth for
357 // this case.
358 if (IsTrivialUnswitchCondition(L, LIC))
359 return 0;
360
361 unsigned Cost = 0;
362 // FIXME: this is brain dead. It should take into consideration code
363 // shrinkage.
364 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
365 I != E; ++I) {
366 BasicBlock *BB = *I;
367 // Do not include empty blocks in the cost calculation. This happen due to
368 // loop canonicalization and will be removed.
369 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
370 continue;
371
372 // Count basic blocks.
373 ++Cost;
374 }
375
376 return Cost;
377}
378
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000379/// UnswitchIfProfitable - We have found that we can unswitch L when
380/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
381/// unswitch the loop, reprocess the pieces, then return true.
382bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
383 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000384 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
385 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000386 // FIXME: this should estimate growth by the amount of code shared by the
387 // resultant unswitched loops.
388 //
389 DEBUG(std::cerr << "NOT unswitching loop %"
390 << L->getHeader()->getName() << ", cost too high: "
391 << L->getBlocks().size() << "\n");
392 return false;
393 }
394
395 // If this loop has live-out values, we can't unswitch it. We need something
396 // like loop-closed SSA form in order to know how to insert PHI nodes for
397 // these values.
398 if (LoopValuesUsedOutsideLoop(L)) {
399 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
Chris Lattner5821a6a2006-03-24 07:14:00 +0000400 << ", a loop value is used outside loop! Cost: "
401 << Cost << "\n");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000402 return false;
403 }
404
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000405 // If this is a trivial condition to unswitch (which results in no code
406 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000407 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000408 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000409 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
410 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000411 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000412 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000413 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000414
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000415 return true;
416}
417
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000418/// SplitBlock - Split the specified block at the specified instruction - every
419/// thing before SplitPt stays in Old and everything starting with SplitPt moves
420/// to a new block. The two blocks are joined by an unconditional branch and
421/// the loop info is updated.
422///
423BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000424 BasicBlock::iterator SplitIt = SplitPt;
425 while (isa<PHINode>(SplitIt))
426 ++SplitIt;
427 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000428
429 // The new block lives in whichever loop the old one did.
430 if (Loop *L = LI->getLoopFor(Old))
431 L->addBasicBlockToLoop(New, *LI);
432
433 return New;
434}
435
436
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000437BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
438 TerminatorInst *LatchTerm = BB->getTerminator();
439 unsigned SuccNum = 0;
440 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
441 assert(i != e && "Didn't find edge?");
442 if (LatchTerm->getSuccessor(i) == Succ) {
443 SuccNum = i;
444 break;
445 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000446 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000447
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000448 // If this is a critical edge, let SplitCriticalEdge do it.
449 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
450 return LatchTerm->getSuccessor(SuccNum);
451
452 // If the edge isn't critical, then BB has a single successor or Succ has a
453 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000454 BasicBlock::iterator SplitPoint;
455 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
456 // If the successor only has a single pred, split the top of the successor
457 // block.
458 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000459 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000460 } else {
461 // Otherwise, if BB has a single successor, split it at the bottom of the
462 // block.
463 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
464 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000465 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000466 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000467}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000468
Chris Lattnerf48f7772004-04-19 18:07:02 +0000469
470
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000472// current values into those specified by ValueMap.
473//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000474static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000475 std::map<const Value *, Value*> &ValueMap) {
476 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
477 Value *Op = I->getOperand(op);
478 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
479 if (It != ValueMap.end()) Op = It->second;
480 I->setOperand(op, Op);
481 }
482}
483
484/// CloneLoop - Recursively clone the specified loop and all of its children,
485/// mapping the blocks with the specified map.
486static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
487 LoopInfo *LI) {
488 Loop *New = new Loop();
489
490 if (PL)
491 PL->addChildLoop(New);
492 else
493 LI->addTopLevelLoop(New);
494
495 // Add all of the blocks in L to the new loop.
496 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
497 I != E; ++I)
498 if (LI->getLoopFor(*I) == L)
499 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
500
501 // Add all of the subloops to the new loop.
502 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
503 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000504
Chris Lattnerf48f7772004-04-19 18:07:02 +0000505 return New;
506}
507
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000508/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
509/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
510/// code immediately before InsertPt.
511static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
512 BasicBlock *TrueDest,
513 BasicBlock *FalseDest,
514 Instruction *InsertPt) {
515 // Insert a conditional branch on LIC to the two preheaders. The original
516 // code is the true version and the new code is the false version.
517 Value *BranchVal = LIC;
Chris Lattner65152d82006-02-15 19:05:52 +0000518 if (!isa<ConstantBool>(Val)) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000519 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
520 } else if (Val != ConstantBool::True) {
521 // We want to enter the new loop when the condition is true.
522 std::swap(TrueDest, FalseDest);
523 }
524
525 // Insert the new branch.
526 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
527}
528
529
Chris Lattnered7a67b2006-02-10 01:24:09 +0000530/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
531/// condition in it (a cond branch from its header block to its latch block,
532/// where the path through the loop that doesn't execute its body has no
533/// side-effects), unswitch it. This doesn't involve any code duplication, just
534/// moving the conditional branch outside of the loop and updating loop info.
535void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000536 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000537 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000538 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
539 << L->getHeader()->getName() << " [" << L->getBlocks().size()
540 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattner8a5a3242006-02-22 06:37:14 +0000541 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner3fc31482006-02-10 01:36:35 +0000542
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000543 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000544 // to insert the conditional branch. We will change 'OrigPH' to have a
545 // conditional branch on Cond.
546 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000547 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000548
549 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000550 // to branch to: this is the exit block out of the loop that we should
551 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000552
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000553 // Split this block now, so that the loop maintains its exit block, and so
554 // that the jump from the preheader can execute the contents of the exit block
555 // without actually branching to it (the exit block should be dominated by the
556 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000557 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000558 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000559
Chris Lattnered7a67b2006-02-10 01:24:09 +0000560 // Okay, now we have a position to branch from and a position to branch to,
561 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000562 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
563 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000564 OrigPH->getTerminator()->eraseFromParent();
565
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000566 // We need to reprocess this loop, it could be unswitched again.
567 LoopProcessWorklist.push_back(L);
568
Chris Lattnered7a67b2006-02-10 01:24:09 +0000569 // Now that we know that the loop is never entered when this condition is a
570 // particular value, rewrite the loop with this info. We know that this will
571 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000572 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000573 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000574}
575
Chris Lattnerf48f7772004-04-19 18:07:02 +0000576
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000577/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
578/// equal Val. Split it into loop versions and test the condition outside of
579/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000580void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
581 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000582 Function *F = L->getHeader()->getParent();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000583 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000584 << L->getHeader()->getName() << " [" << L->getBlocks().size()
585 << " blocks] in Function " << F->getName()
586 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000587
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000588 // LoopBlocks contains all of the basic blocks of the loop, including the
589 // preheader of the loop, the body of the loop, and the exit blocks of the
590 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000591 std::vector<BasicBlock*> LoopBlocks;
592
593 // First step, split the preheader and exit blocks, and add these blocks to
594 // the LoopBlocks list.
595 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000596 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000597
598 // We want the loop to come after the preheader, but before the exit blocks.
599 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
600
601 std::vector<BasicBlock*> ExitBlocks;
602 L->getExitBlocks(ExitBlocks);
603 std::sort(ExitBlocks.begin(), ExitBlocks.end());
604 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
605 ExitBlocks.end());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000606
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000607 // Split all of the edges from inside the loop to their exit blocks. This
608 // unswitching trivial: no phi nodes to update.
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000609 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner8e44ff52006-02-18 00:55:32 +0000610
Chris Lattnered7a67b2006-02-10 01:24:09 +0000611 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000612 BasicBlock *ExitBlock = ExitBlocks[i];
613 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
614
615 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
616 assert(L->contains(Preds[j]) &&
617 "All preds of loop exit blocks must be the same loop!");
618 SplitEdge(Preds[j], ExitBlock);
619 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000620 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000621
622 // The exit blocks may have been changed due to edge splitting, recompute.
623 ExitBlocks.clear();
624 L->getExitBlocks(ExitBlocks);
625 std::sort(ExitBlocks.begin(), ExitBlocks.end());
626 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
627 ExitBlocks.end());
628
629 // Add exit blocks to the loop blocks.
630 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000631
632 // Next step, clone all of the basic blocks that make up the loop (including
633 // the loop preheader and exit blocks), keeping track of the mapping between
634 // the instructions and blocks.
635 std::vector<BasicBlock*> NewBlocks;
636 NewBlocks.reserve(LoopBlocks.size());
637 std::map<const Value*, Value*> ValueMap;
638 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000639 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
640 NewBlocks.push_back(New);
641 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000642 }
643
644 // Splice the newly inserted blocks into the function right before the
645 // original preheader.
646 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
647 NewBlocks[0], F->end());
648
649 // Now we create the new Loop object for the versioned loop.
650 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000651 Loop *ParentLoop = L->getParentLoop();
652 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000653 // Make sure to add the cloned preheader and exit blocks to the parent loop
654 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000655 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
656 }
657
658 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
659 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000660 // The new exit block should be in the same loop as the old one.
661 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
662 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000663
664 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
665 "Exit block should have been split to have one successor!");
666 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
667
668 // If the successor of the exit block had PHI nodes, add an entry for
669 // NewExit.
670 PHINode *PN;
671 for (BasicBlock::iterator I = ExitSucc->begin();
672 (PN = dyn_cast<PHINode>(I)); ++I) {
673 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
674 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
675 if (It != ValueMap.end()) V = It->second;
676 PN->addIncoming(V, NewExit);
677 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000678 }
679
680 // Rewrite the code to refer to itself.
681 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
682 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
683 E = NewBlocks[i]->end(); I != E; ++I)
684 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000685
Chris Lattnerf48f7772004-04-19 18:07:02 +0000686 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000687 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
688 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000689 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000690
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000691 // Emit the new branch that selects between the two versions of this loop.
692 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
693 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000694
695 LoopProcessWorklist.push_back(L);
696 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000697
698 // Now we rewrite the original code to know that the condition is true and the
699 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000700 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
701
702 // It's possible that simplifying one loop could cause the other to be
703 // deleted. If so, don't simplify it.
704 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
705 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000706}
707
Chris Lattner6fd13622006-02-17 00:31:07 +0000708/// RemoveFromWorklist - Remove all instances of I from the worklist vector
709/// specified.
710static void RemoveFromWorklist(Instruction *I,
711 std::vector<Instruction*> &Worklist) {
712 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
713 Worklist.end(), I);
714 while (WI != Worklist.end()) {
715 unsigned Offset = WI-Worklist.begin();
716 Worklist.erase(WI);
717 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
718 }
719}
720
721/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
722/// program, replacing all uses with V and update the worklist.
723static void ReplaceUsesOfWith(Instruction *I, Value *V,
724 std::vector<Instruction*> &Worklist) {
725 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
726
727 // Add uses to the worklist, which may be dead now.
728 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
729 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
730 Worklist.push_back(Use);
731
732 // Add users to the worklist which may be simplified now.
733 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
734 UI != E; ++UI)
735 Worklist.push_back(cast<Instruction>(*UI));
736 I->replaceAllUsesWith(V);
737 I->eraseFromParent();
738 RemoveFromWorklist(I, Worklist);
739 ++NumSimplify;
740}
741
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000742/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
743/// information, and remove any dead successors it has.
744///
745void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
746 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000747 if (pred_begin(BB) != pred_end(BB)) {
748 // This block isn't dead, since an edge to BB was just removed, see if there
749 // are any easy simplifications we can do now.
750 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
751 // If it has one pred, fold phi nodes in BB.
752 while (isa<PHINode>(BB->begin()))
753 ReplaceUsesOfWith(BB->begin(),
754 cast<PHINode>(BB->begin())->getIncomingValue(0),
755 Worklist);
756
757 // If this is the header of a loop and the only pred is the latch, we now
758 // have an unreachable loop.
759 if (Loop *L = LI->getLoopFor(BB))
760 if (L->getHeader() == BB && L->contains(Pred)) {
761 // Remove the branch from the latch to the header block, this makes
762 // the header dead, which will make the latch dead (because the header
763 // dominates the latch).
764 Pred->getTerminator()->eraseFromParent();
765 new UnreachableInst(Pred);
766
767 // The loop is now broken, remove it from LI.
768 RemoveLoopFromHierarchy(L);
769
770 // Reprocess the header, which now IS dead.
771 RemoveBlockIfDead(BB, Worklist);
772 return;
773 }
774
775 // If pred ends in a uncond branch, add uncond branch to worklist so that
776 // the two blocks will get merged.
777 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
778 if (BI->isUnconditional())
779 Worklist.push_back(BI);
780 }
781 return;
782 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000783
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000784 DEBUG(std::cerr << "Nuking dead block: " << *BB);
785
786 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000787 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000788 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000789
790 // Anything that uses the instructions in this basic block should have their
791 // uses replaced with undefs.
792 if (!I->use_empty())
793 I->replaceAllUsesWith(UndefValue::get(I->getType()));
794 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000795
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000796 // If this is the edge to the header block for a loop, remove the loop and
797 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000798 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000799 if (BBLoop->getLoopLatch() == BB)
800 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000801 }
802
803 // Remove the block from the loop info, which removes it from any loops it
804 // was in.
805 LI->removeBlock(BB);
806
807
808 // Remove phi node entries in successors for this block.
809 TerminatorInst *TI = BB->getTerminator();
810 std::vector<BasicBlock*> Succs;
811 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
812 Succs.push_back(TI->getSuccessor(i));
813 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000814 }
815
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000816 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000817 std::sort(Succs.begin(), Succs.end());
818 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
819
820 // Remove the basic block, including all of the instructions contained in it.
821 BB->eraseFromParent();
822
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000823 // Remove successor blocks here that are not dead, so that we know we only
824 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
825 // then getting removed before we revisit them, which is badness.
826 //
827 for (unsigned i = 0; i != Succs.size(); ++i)
828 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
829 // One exception is loop headers. If this block was the preheader for a
830 // loop, then we DO want to visit the loop so the loop gets deleted.
831 // We know that if the successor is a loop header, that this loop had to
832 // be the preheader: the case where this was the latch block was handled
833 // above and headers can only have two predecessors.
834 if (!LI->isLoopHeader(Succs[i])) {
835 Succs.erase(Succs.begin()+i);
836 --i;
837 }
838 }
839
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000840 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
841 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000842}
Chris Lattner6fd13622006-02-17 00:31:07 +0000843
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000844/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
845/// become unwrapped, either because the backedge was deleted, or because the
846/// edge into the header was removed. If the edge into the header from the
847/// latch block was removed, the loop is unwrapped but subloops are still alive,
848/// so they just reparent loops. If the loops are actually dead, they will be
849/// removed later.
850void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
851 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
852 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
853 // they are now all in it.
854 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
855 I != E; ++I)
856 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
857 LI->changeLoopFor(*I, ParentLoop);
858
859 // Remove the loop from its parent loop.
860 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
861 ++I) {
862 assert(I != E && "Couldn't find loop");
863 if (*I == L) {
864 ParentLoop->removeChildLoop(I);
865 break;
866 }
867 }
868
869 // Move all subloops into the parent loop.
870 while (L->begin() != L->end())
871 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
872 } else {
873 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
874 // they no longer in a loop at all.
875
876 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
877 // Don't change blocks in subloops.
878 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
879 LI->removeBlock(L->getBlocks()[i]);
880 --i;
881 }
882 }
883
884 // Remove the loop from the top-level LoopInfo object.
885 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
886 assert(I != E && "Couldn't find loop");
887 if (*I == L) {
888 LI->removeLoop(I);
889 break;
890 }
891 }
892
893 // Move all of the subloops to the top-level.
894 while (L->begin() != L->end())
895 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
896 }
897
898 delete L;
899 RemoveLoopFromWorklist(L);
900}
901
902
903
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000904// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
905// the value specified by Val in the specified loop, or we know it does NOT have
906// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000907void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000908 Constant *Val,
909 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000910 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000911
Chris Lattnerf48f7772004-04-19 18:07:02 +0000912 // FIXME: Support correlated properties, like:
913 // for (...)
914 // if (li1 < li2)
915 // ...
916 // if (li1 > li2)
917 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000918
Chris Lattner6e263152006-02-10 02:30:37 +0000919 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
920 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000921 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000922 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000923
Chris Lattner6fd13622006-02-17 00:31:07 +0000924 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
925 // in the loop with the appropriate one directly.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000926 if (IsEqual || isa<ConstantBool>(Val)) {
927 Value *Replacement;
928 if (IsEqual)
929 Replacement = Val;
930 else
931 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000932
933 for (unsigned i = 0, e = Users.size(); i != e; ++i)
934 if (Instruction *U = cast<Instruction>(Users[i])) {
935 if (!L->contains(U->getParent()))
936 continue;
937 U->replaceUsesOfWith(LIC, Replacement);
938 Worklist.push_back(U);
939 }
940 } else {
941 // Otherwise, we don't know the precise value of LIC, but we do know that it
942 // is certainly NOT "Val". As such, simplify any uses in the loop that we
943 // can. This case occurs when we unswitch switch statements.
944 for (unsigned i = 0, e = Users.size(); i != e; ++i)
945 if (Instruction *U = cast<Instruction>(Users[i])) {
946 if (!L->contains(U->getParent()))
947 continue;
948
949 Worklist.push_back(U);
950
Chris Lattnerfa335f62006-02-16 19:36:22 +0000951 // If we know that LIC is not Val, use this info to simplify code.
952 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
953 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
954 if (SI->getCaseValue(i) == Val) {
955 // Found a dead case value. Don't remove PHI nodes in the
956 // successor if they become single-entry, those PHI nodes may
957 // be in the Users list.
958 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
959 SI->removeCase(i);
960 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000961 }
962 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000963 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000964
965 // TODO: We could do other simplifications, for example, turning
966 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000967 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000968 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000969
970 SimplifyCode(Worklist);
971}
972
973/// SimplifyCode - Okay, now that we have simplified some instructions in the
974/// loop, walk over it and constant prop, dce, and fold control flow where
975/// possible. Note that this is effectively a very simple loop-structure-aware
976/// optimizer. During processing of this loop, L could very well be deleted, so
977/// it must not be used.
978///
979/// FIXME: When the loop optimizer is more mature, separate this out to a new
980/// pass.
981///
982void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000983 while (!Worklist.empty()) {
984 Instruction *I = Worklist.back();
985 Worklist.pop_back();
986
987 // Simple constant folding.
988 if (Constant *C = ConstantFoldInstruction(I)) {
989 ReplaceUsesOfWith(I, C, Worklist);
990 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000991 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000992
993 // Simple DCE.
994 if (isInstructionTriviallyDead(I)) {
995 DEBUG(std::cerr << "Remove dead instruction '" << *I);
996
997 // Add uses to the worklist, which may be dead now.
998 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
999 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1000 Worklist.push_back(Use);
1001 I->eraseFromParent();
1002 RemoveFromWorklist(I, Worklist);
1003 ++NumSimplify;
1004 continue;
1005 }
1006
1007 // Special case hacks that appear commonly in unswitched code.
1008 switch (I->getOpcode()) {
1009 case Instruction::Select:
1010 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1011 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1012 continue;
1013 }
1014 break;
1015 case Instruction::And:
1016 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1017 cast<BinaryOperator>(I)->swapOperands();
1018 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1019 if (CB->getValue()) // X & 1 -> X
1020 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1021 else // X & 0 -> 0
1022 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1023 continue;
1024 }
1025 break;
1026 case Instruction::Or:
1027 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1028 cast<BinaryOperator>(I)->swapOperands();
1029 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1030 if (CB->getValue()) // X | 1 -> 1
1031 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1032 else // X | 0 -> X
1033 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1034 continue;
1035 }
1036 break;
1037 case Instruction::Br: {
1038 BranchInst *BI = cast<BranchInst>(I);
1039 if (BI->isUnconditional()) {
1040 // If BI's parent is the only pred of the successor, fold the two blocks
1041 // together.
1042 BasicBlock *Pred = BI->getParent();
1043 BasicBlock *Succ = BI->getSuccessor(0);
1044 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1045 if (!SinglePred) continue; // Nothing to do.
1046 assert(SinglePred == Pred && "CFG broken");
1047
1048 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1049 << Succ->getName() << "\n");
1050
1051 // Resolve any single entry PHI nodes in Succ.
1052 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1053 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1054
1055 // Move all of the successor contents from Succ to Pred.
1056 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1057 Succ->end());
1058 BI->eraseFromParent();
1059 RemoveFromWorklist(BI, Worklist);
1060
1061 // If Succ has any successors with PHI nodes, update them to have
1062 // entries coming from Pred instead of Succ.
1063 Succ->replaceAllUsesWith(Pred);
1064
1065 // Remove Succ from the loop tree.
1066 LI->removeBlock(Succ);
1067 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001068 ++NumSimplify;
Chris Lattner29f771b2006-02-18 01:27:45 +00001069 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001070 // Conditional branch. Turn it into an unconditional branch, then
1071 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001072 break; // FIXME: Enable.
1073
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001074 DEBUG(std::cerr << "Folded branch: " << *BI);
1075 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1076 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1077 DeadSucc->removePredecessor(BI->getParent(), true);
1078 Worklist.push_back(new BranchInst(LiveSucc, BI));
1079 BI->eraseFromParent();
1080 RemoveFromWorklist(BI, Worklist);
1081 ++NumSimplify;
1082
1083 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001084 }
1085 break;
1086 }
1087 }
1088 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001089}