blob: 6b5a71cbdf32bf75b38af5c023039ff400d2f768 [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 Lattner89762192006-02-09 20:15:48 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000041#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000042#include <iostream>
Chris Lattner2826e052006-02-09 19:14:52 +000043#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000044using namespace llvm;
45
46namespace {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +000047 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
48 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
49 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
50 Statistic<> NumTrivial ("loop-unswitch",
51 "Number of unswitches that are trivial");
Chris Lattner6fd13622006-02-17 00:31:07 +000052 Statistic<> NumSimplify("loop-unswitch",
53 "Number of simplifications of unswitched code");
Chris Lattner89762192006-02-09 20:15:48 +000054 cl::opt<unsigned>
55 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
56 cl::init(10), cl::Hidden);
57
Chris Lattnerf48f7772004-04-19 18:07:02 +000058 class LoopUnswitch : public FunctionPass {
59 LoopInfo *LI; // Loop information
Chris Lattnerf48f7772004-04-19 18:07:02 +000060 public:
61 virtual bool runOnFunction(Function &F);
62 bool visitLoop(Loop *L);
63
64 /// This transformation requires natural loop information & requires that
65 /// loop preheaders be inserted into the CFG...
66 ///
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000069 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000070 AU.addRequired<LoopInfo>();
71 AU.addPreserved<LoopInfo>();
72 }
73
74 private:
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000075 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000076 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000077 void VersionLoop(Value *LIC, Constant *OnVal,
78 Loop *L, Loop *&Out1, Loop *&Out2);
Chris Lattner29f771b2006-02-18 01:27:45 +000079 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
80 bool EntersWhenTrue, BasicBlock *ExitBlock);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000081 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +000082 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000083 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,Constant *Val,
84 bool isEqual);
Chris Lattner19fa8ac2006-02-18 02:42:34 +000085 void RemoveBlockIfDead(BasicBlock *BB,
86 std::vector<Instruction*> &Worklist);
Chris Lattnerf48f7772004-04-19 18:07:02 +000087 };
88 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
89}
90
Jeff Coheneca0d0f2005-01-06 05:47:18 +000091FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +000092
93bool LoopUnswitch::runOnFunction(Function &F) {
94 bool Changed = false;
95 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000096
97 // Transform all the top-level loops. Copy the loop list so that the child
98 // can update the loop tree if it needs to delete the loop.
99 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
100 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
101 Changed |= visitLoop(SubLoops[i]);
102
103 return Changed;
104}
105
Chris Lattner2826e052006-02-09 19:14:52 +0000106
Chris Lattnered7a67b2006-02-10 01:24:09 +0000107/// LoopValuesUsedOutsideLoop - Return true if there are any values defined in
108/// the loop that are used by instructions outside of it.
Chris Lattner2826e052006-02-09 19:14:52 +0000109static bool LoopValuesUsedOutsideLoop(Loop *L) {
110 // We will be doing lots of "loop contains block" queries. Loop::contains is
111 // linear time, use a set to speed this up.
112 std::set<BasicBlock*> LoopBlocks;
113
114 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
115 BB != E; ++BB)
116 LoopBlocks.insert(*BB);
117
118 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
119 BB != E; ++BB) {
120 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
121 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
122 ++UI) {
123 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
124 if (!LoopBlocks.count(UserBB))
125 return true;
126 }
127 }
128 return false;
129}
130
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000131/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
132/// 1. Exit the loop with no side effects.
133/// 2. Branch to the latch block with no side-effects.
134///
135/// If these conditions are true, we return true and set ExitBB to the block we
136/// exit through.
137///
138static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
139 BasicBlock *&ExitBB,
140 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000141 if (!Visited.insert(BB).second) {
142 // Already visited and Ok, end of recursion.
143 return true;
144 } else if (!L->contains(BB)) {
145 // Otherwise, this is a loop exit, this is fine so long as this is the
146 // first exit.
147 if (ExitBB != 0) return false;
148 ExitBB = BB;
149 return true;
150 }
151
152 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000153 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000154 // Check to see if the successor is a trivial loop exit.
155 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
156 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000157 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000158
159 // Okay, everything after this looks good, check to make sure that this block
160 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000161 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000162 if (I->mayWriteToMemory())
163 return false;
164
165 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000166}
167
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000168static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
169 std::set<BasicBlock*> Visited;
170 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000171 BasicBlock *ExitBB = 0;
172 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
173 return ExitBB;
174 return 0;
175}
Chris Lattner6e263152006-02-10 02:30:37 +0000176
Chris Lattnered7a67b2006-02-10 01:24:09 +0000177/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
178/// trivial: that is, that the condition controls whether or not the loop does
179/// anything at all. If this is a trivial condition, unswitching produces no
180/// code duplications (equivalently, it produces a simpler loop and a new empty
181/// loop, which gets deleted).
182///
183/// If this is a trivial condition, return ConstantBool::True if the loop body
184/// runs when the condition is true, False if the loop body executes when the
185/// condition is false. Otherwise, return null to indicate a complex condition.
Chris Lattner49354172006-02-10 02:01:22 +0000186static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond,
Chris Lattner01db04e2006-02-15 01:44:42 +0000187 Constant **Val = 0,
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000188 bool *EntersWhenTrue = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000189 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000190 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000191 TerminatorInst *HeaderTerm = Header->getTerminator();
192
193 BasicBlock *LoopExitBB = 0;
194 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
195 // If the header block doesn't end with a conditional branch on Cond, we
196 // can't handle it.
197 if (!BI->isConditional() || BI->getCondition() != Cond)
198 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000199
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000200 // Check to see if a successor of the branch is guaranteed to go to the
201 // latch block or exit through a one exit block without having any
202 // side-effects. If so, determine the value of Cond that causes it to do
203 // this.
204 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000205 if (Val) *Val = ConstantBool::False;
Chris Lattnerff42e812006-02-16 01:24:41 +0000206 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
207 if (Val) *Val = ConstantBool::True;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000208 }
209 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
210 // If this isn't a switch on Cond, we can't handle it.
211 if (SI->getCondition() != Cond) return false;
212
213 // Check to see if a successor of the switch is guaranteed to go to the
214 // latch block or exit through a one exit block without having any
215 // side-effects. If so, determine the value of Cond that causes it to do
216 // this. Note that we can't trivially unswitch on the default case.
217 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
218 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
219 // Okay, we found a trivial case, remember the value that is trivial.
220 if (Val) *Val = SI->getCaseValue(i);
221 if (EntersWhenTrue) *EntersWhenTrue = false;
222 break;
223 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000224 }
225
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000226 if (!LoopExitBB)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000227 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000228
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000229 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000230
231 // We already know that nothing uses any scalar values defined inside of this
232 // loop. As such, we just have to check to see if this loop will execute any
233 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000234 // part of the loop that the code *would* execute. We already checked the
235 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000236 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
237 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000238 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000239 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000240}
241
242/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
243/// we choose to unswitch the specified loop on the specified value.
244///
245unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
246 // If the condition is trivial, always unswitch. There is no code growth for
247 // this case.
248 if (IsTrivialUnswitchCondition(L, LIC))
249 return 0;
250
251 unsigned Cost = 0;
252 // FIXME: this is brain dead. It should take into consideration code
253 // shrinkage.
254 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
255 I != E; ++I) {
256 BasicBlock *BB = *I;
257 // Do not include empty blocks in the cost calculation. This happen due to
258 // loop canonicalization and will be removed.
259 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
260 continue;
261
262 // Count basic blocks.
263 ++Cost;
264 }
265
266 return Cost;
267}
268
Chris Lattner6e263152006-02-10 02:30:37 +0000269/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
270/// invariant in the loop, or has an invariant piece, return the invariant.
271/// Otherwise, return null.
272static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
273 // Constants should be folded, not unswitched on!
274 if (isa<Constant>(Cond)) return false;
275
276 // TODO: Handle: br (VARIANT|INVARIANT).
277 // TODO: Hoist simple expressions out of loops.
278 if (L->isLoopInvariant(Cond)) return Cond;
279
280 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
281 if (BO->getOpcode() == Instruction::And ||
282 BO->getOpcode() == Instruction::Or) {
283 // If either the left or right side is invariant, we can unswitch on this,
284 // which will cause the branch to go away in one loop and the condition to
285 // simplify in the other one.
286 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
287 return LHS;
288 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
289 return RHS;
290 }
291
292 return 0;
293}
294
Chris Lattnerf48f7772004-04-19 18:07:02 +0000295bool LoopUnswitch::visitLoop(Loop *L) {
296 bool Changed = false;
297
298 // Recurse through all subloops before we process this loop. Copy the loop
299 // list so that the child can update the loop tree if it needs to delete the
300 // loop.
301 std::vector<Loop*> SubLoops(L->begin(), L->end());
302 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
303 Changed |= visitLoop(SubLoops[i]);
304
305 // Loop over all of the basic blocks in the loop. If we find an interior
306 // block that is branching on a loop-invariant condition, we can unswitch this
307 // loop.
308 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
309 I != E; ++I) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000310 TerminatorInst *TI = (*I)->getTerminator();
311 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
312 // If this isn't branching on an invariant condition, we can't unswitch
313 // it.
314 if (BI->isConditional()) {
315 // See if this, or some part of it, is loop invariant. If so, we can
316 // unswitch on it if we desire.
317 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000318 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
319 ++NumBranches;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000320 return true;
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000321 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000322 }
323 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
324 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
325 if (LoopCond && SI->getNumCases() > 1) {
326 // Find a value to unswitch on:
327 // FIXME: this should chose the most expensive case!
328 Constant *UnswitchVal = SI->getCaseValue(1);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000329 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
330 ++NumSwitches;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000331 return true;
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000332 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000333 }
334 }
335
336 // Scan the instructions to check for unswitchable values.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000337 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
338 BBI != E; ++BBI)
339 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
340 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000341 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
342 ++NumSelects;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000343 return true;
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000344 }
Chris Lattnerf1b15162006-02-10 23:26:14 +0000345 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000346 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000347
Chris Lattnerf48f7772004-04-19 18:07:02 +0000348 return Changed;
349}
350
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000351/// UnswitchIfProfitable - We have found that we can unswitch L when
352/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
353/// unswitch the loop, reprocess the pieces, then return true.
354bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
355 // Check to see if it would be profitable to unswitch this loop.
356 if (getLoopUnswitchCost(L, LoopCond) > Threshold) {
357 // FIXME: this should estimate growth by the amount of code shared by the
358 // resultant unswitched loops.
359 //
360 DEBUG(std::cerr << "NOT unswitching loop %"
361 << L->getHeader()->getName() << ", cost too high: "
362 << L->getBlocks().size() << "\n");
363 return false;
364 }
365
366 // If this loop has live-out values, we can't unswitch it. We need something
367 // like loop-closed SSA form in order to know how to insert PHI nodes for
368 // these values.
369 if (LoopValuesUsedOutsideLoop(L)) {
370 DEBUG(std::cerr << "NOT unswitching loop %" << L->getHeader()->getName()
371 << ", a loop value is used outside loop!\n");
372 return false;
373 }
374
375 //std::cerr << "BEFORE:\n"; LI->dump();
376 Loop *NewLoop1 = 0, *NewLoop2 = 0;
377
378 // If this is a trivial condition to unswitch (which results in no code
379 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000380 Constant *CondVal;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000381 bool EntersWhenTrue = true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000382 BasicBlock *ExitBlock;
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000383 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal,
384 &EntersWhenTrue, &ExitBlock)) {
385 UnswitchTrivialCondition(L, LoopCond, CondVal, EntersWhenTrue, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000386 NewLoop1 = L;
387 } else {
388 VersionLoop(LoopCond, Val, L, NewLoop1, NewLoop2);
389 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000390
391 //std::cerr << "AFTER:\n"; LI->dump();
392
393 // Try to unswitch each of our new loops now!
394 if (NewLoop1) visitLoop(NewLoop1);
395 if (NewLoop2) visitLoop(NewLoop2);
396 return true;
397}
398
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000399/// SplitBlock - Split the specified block at the specified instruction - every
400/// thing before SplitPt stays in Old and everything starting with SplitPt moves
401/// to a new block. The two blocks are joined by an unconditional branch and
402/// the loop info is updated.
403///
404BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000405 BasicBlock::iterator SplitIt = SplitPt;
406 while (isa<PHINode>(SplitIt))
407 ++SplitIt;
408 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000409
410 // The new block lives in whichever loop the old one did.
411 if (Loop *L = LI->getLoopFor(Old))
412 L->addBasicBlockToLoop(New, *LI);
413
414 return New;
415}
416
417
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000418BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
419 TerminatorInst *LatchTerm = BB->getTerminator();
420 unsigned SuccNum = 0;
421 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
422 assert(i != e && "Didn't find edge?");
423 if (LatchTerm->getSuccessor(i) == Succ) {
424 SuccNum = i;
425 break;
426 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000427 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000428
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000429 // If this is a critical edge, let SplitCriticalEdge do it.
430 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
431 return LatchTerm->getSuccessor(SuccNum);
432
433 // If the edge isn't critical, then BB has a single successor or Succ has a
434 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000435 BasicBlock::iterator SplitPoint;
436 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
437 // If the successor only has a single pred, split the top of the successor
438 // block.
439 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000440 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000441 } else {
442 // Otherwise, if BB has a single successor, split it at the bottom of the
443 // block.
444 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
445 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000446 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000447 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000448}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000449
Chris Lattnerf48f7772004-04-19 18:07:02 +0000450
451
Misha Brukmanb1c93172005-04-21 23:48:37 +0000452// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000453// current values into those specified by ValueMap.
454//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000455static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000456 std::map<const Value *, Value*> &ValueMap) {
457 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
458 Value *Op = I->getOperand(op);
459 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
460 if (It != ValueMap.end()) Op = It->second;
461 I->setOperand(op, Op);
462 }
463}
464
465/// CloneLoop - Recursively clone the specified loop and all of its children,
466/// mapping the blocks with the specified map.
467static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
468 LoopInfo *LI) {
469 Loop *New = new Loop();
470
471 if (PL)
472 PL->addChildLoop(New);
473 else
474 LI->addTopLevelLoop(New);
475
476 // Add all of the blocks in L to the new loop.
477 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
478 I != E; ++I)
479 if (LI->getLoopFor(*I) == L)
480 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
481
482 // Add all of the subloops to the new loop.
483 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
484 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000485
Chris Lattnerf48f7772004-04-19 18:07:02 +0000486 return New;
487}
488
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000489/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
490/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
491/// code immediately before InsertPt.
492static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
493 BasicBlock *TrueDest,
494 BasicBlock *FalseDest,
495 Instruction *InsertPt) {
496 // Insert a conditional branch on LIC to the two preheaders. The original
497 // code is the true version and the new code is the false version.
498 Value *BranchVal = LIC;
Chris Lattner65152d82006-02-15 19:05:52 +0000499 if (!isa<ConstantBool>(Val)) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000500 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
501 } else if (Val != ConstantBool::True) {
502 // We want to enter the new loop when the condition is true.
503 std::swap(TrueDest, FalseDest);
504 }
505
506 // Insert the new branch.
507 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
508}
509
510
Chris Lattnered7a67b2006-02-10 01:24:09 +0000511/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
512/// condition in it (a cond branch from its header block to its latch block,
513/// where the path through the loop that doesn't execute its body has no
514/// side-effects), unswitch it. This doesn't involve any code duplication, just
515/// moving the conditional branch outside of the loop and updating loop info.
516void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000517 Constant *Val, bool EntersWhenTrue,
Chris Lattner49354172006-02-10 02:01:22 +0000518 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000519 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
520 << L->getHeader()->getName() << " [" << L->getBlocks().size()
521 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000522 << " on cond: " << *Val << (EntersWhenTrue ? " == " : " != ") <<
523 *Cond << "\n");
Chris Lattner3fc31482006-02-10 01:36:35 +0000524
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000525 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000526 // to insert the conditional branch. We will change 'OrigPH' to have a
527 // conditional branch on Cond.
528 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000529 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000530
531 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000532 // to branch to: this is the exit block out of the loop that we should
533 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000534
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000535 // Split this block now, so that the loop maintains its exit block, and so
536 // that the jump from the preheader can execute the contents of the exit block
537 // without actually branching to it (the exit block should be dominated by the
538 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000539 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000540 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000541
Chris Lattnered7a67b2006-02-10 01:24:09 +0000542 // Okay, now we have a position to branch from and a position to branch to,
543 // insert the new conditional branch.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000544 {
545 BasicBlock *TrueDest = NewPH, *FalseDest = NewExit;
546 if (!EntersWhenTrue) std::swap(TrueDest, FalseDest);
547 EmitPreheaderBranchOnCondition(Cond, Val, TrueDest, FalseDest,
548 OrigPH->getTerminator());
549 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000550 OrigPH->getTerminator()->eraseFromParent();
551
552 // Now that we know that the loop is never entered when this condition is a
553 // particular value, rewrite the loop with this info. We know that this will
554 // at least eliminate the old branch.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000555 RewriteLoopBodyWithConditionConstant(L, Cond, Val, EntersWhenTrue);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000556 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000557}
558
Chris Lattnerf48f7772004-04-19 18:07:02 +0000559
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000560/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
561/// equal Val. Split it into loop versions and test the condition outside of
562/// either loop. Return the loops created as Out1/Out2.
563void LoopUnswitch::VersionLoop(Value *LIC, Constant *Val, Loop *L,
564 Loop *&Out1, Loop *&Out2) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000565 Function *F = L->getHeader()->getParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000566
Chris Lattnerf48f7772004-04-19 18:07:02 +0000567 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000568 << L->getHeader()->getName() << " [" << L->getBlocks().size()
569 << " blocks] in Function " << F->getName()
570 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000571
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000572 // LoopBlocks contains all of the basic blocks of the loop, including the
573 // preheader of the loop, the body of the loop, and the exit blocks of the
574 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000575 std::vector<BasicBlock*> LoopBlocks;
576
577 // First step, split the preheader and exit blocks, and add these blocks to
578 // the LoopBlocks list.
579 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000580 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000581
582 // We want the loop to come after the preheader, but before the exit blocks.
583 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
584
585 std::vector<BasicBlock*> ExitBlocks;
586 L->getExitBlocks(ExitBlocks);
587 std::sort(ExitBlocks.begin(), ExitBlocks.end());
588 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
589 ExitBlocks.end());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000590
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000591 // Split all of the edges from inside the loop to their exit blocks. This
592 // unswitching trivial: no phi nodes to update.
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000593 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner8e44ff52006-02-18 00:55:32 +0000594
Chris Lattnered7a67b2006-02-10 01:24:09 +0000595 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000596 BasicBlock *ExitBlock = ExitBlocks[i];
597 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
598
599 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
600 assert(L->contains(Preds[j]) &&
601 "All preds of loop exit blocks must be the same loop!");
602 SplitEdge(Preds[j], ExitBlock);
603 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000604 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000605
606 // The exit blocks may have been changed due to edge splitting, recompute.
607 ExitBlocks.clear();
608 L->getExitBlocks(ExitBlocks);
609 std::sort(ExitBlocks.begin(), ExitBlocks.end());
610 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
611 ExitBlocks.end());
612
613 // Add exit blocks to the loop blocks.
614 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000615
616 // Next step, clone all of the basic blocks that make up the loop (including
617 // the loop preheader and exit blocks), keeping track of the mapping between
618 // the instructions and blocks.
619 std::vector<BasicBlock*> NewBlocks;
620 NewBlocks.reserve(LoopBlocks.size());
621 std::map<const Value*, Value*> ValueMap;
622 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000623 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
624 NewBlocks.push_back(New);
625 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000626 }
627
628 // Splice the newly inserted blocks into the function right before the
629 // original preheader.
630 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
631 NewBlocks[0], F->end());
632
633 // Now we create the new Loop object for the versioned loop.
634 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000635 Loop *ParentLoop = L->getParentLoop();
636 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000637 // Make sure to add the cloned preheader and exit blocks to the parent loop
638 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000639 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
640 }
641
642 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
643 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000644 // The new exit block should be in the same loop as the old one.
645 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
646 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000647
648 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
649 "Exit block should have been split to have one successor!");
650 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
651
652 // If the successor of the exit block had PHI nodes, add an entry for
653 // NewExit.
654 PHINode *PN;
655 for (BasicBlock::iterator I = ExitSucc->begin();
656 (PN = dyn_cast<PHINode>(I)); ++I) {
657 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
658 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
659 if (It != ValueMap.end()) V = It->second;
660 PN->addIncoming(V, NewExit);
661 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000662 }
663
664 // Rewrite the code to refer to itself.
665 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
666 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
667 E = NewBlocks[i]->end(); I != E; ++I)
668 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000669
Chris Lattnerf48f7772004-04-19 18:07:02 +0000670 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000671 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
672 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000673 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000674
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000675 // Emit the new branch that selects between the two versions of this loop.
676 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
677 OldBR->eraseFromParent();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000678
679 // Now we rewrite the original code to know that the condition is true and the
680 // new code to know that the condition is false.
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000681 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
682 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000683 Out1 = L;
684 Out2 = NewLoop;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000685}
686
Chris Lattner6fd13622006-02-17 00:31:07 +0000687/// RemoveFromWorklist - Remove all instances of I from the worklist vector
688/// specified.
689static void RemoveFromWorklist(Instruction *I,
690 std::vector<Instruction*> &Worklist) {
691 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
692 Worklist.end(), I);
693 while (WI != Worklist.end()) {
694 unsigned Offset = WI-Worklist.begin();
695 Worklist.erase(WI);
696 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
697 }
698}
699
700/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
701/// program, replacing all uses with V and update the worklist.
702static void ReplaceUsesOfWith(Instruction *I, Value *V,
703 std::vector<Instruction*> &Worklist) {
704 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
705
706 // Add uses to the worklist, which may be dead now.
707 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
708 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
709 Worklist.push_back(Use);
710
711 // Add users to the worklist which may be simplified now.
712 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
713 UI != E; ++UI)
714 Worklist.push_back(cast<Instruction>(*UI));
715 I->replaceAllUsesWith(V);
716 I->eraseFromParent();
717 RemoveFromWorklist(I, Worklist);
718 ++NumSimplify;
719}
720
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000721/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
722/// information, and remove any dead successors it has.
723///
724void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
725 std::vector<Instruction*> &Worklist) {
726 if (pred_begin(BB) != pred_end(BB)) return; // not dead.
Chris Lattner6fd13622006-02-17 00:31:07 +0000727
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000728 DEBUG(std::cerr << "Nuking dead block: " << *BB);
729
730 // Remove the instructions in the basic block from the worklist.
731 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
732 RemoveFromWorklist(I, Worklist);
733
734 // If this is the header block for a loop, remove the loop and all subloops.
735 // We leave all of the blocks that used to be part of this loop in the parent
736 // loop if any.
737 if (Loop *BBLoop = LI->getLoopFor(BB)) {
738 if (BBLoop->getHeader() == BB) {
739 if (Loop *ParentLoop = BBLoop->getParentLoop()) { // not a top-level loop.
740 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
741 ++I) {
742 assert(I != E && "Couldn't find loop");
743 if (*I == BBLoop) {
744 ParentLoop->removeChildLoop(I);
745 break;
746 }
747 }
748 } else {
749 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
750 assert(I != E && "Couldn't find loop");
751 if (*I == BBLoop) {
752 LI->removeLoop(I);
753 break;
754 }
755 }
756 }
757 delete BBLoop;
758 }
759 }
760
761 // Remove the block from the loop info, which removes it from any loops it
762 // was in.
763 LI->removeBlock(BB);
764
765
766 // Remove phi node entries in successors for this block.
767 TerminatorInst *TI = BB->getTerminator();
768 std::vector<BasicBlock*> Succs;
769 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
770 Succs.push_back(TI->getSuccessor(i));
771 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000772 }
773
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000774 // Unique the successors.
775 std::sort(Succs.begin(), Succs.end());
776 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
777
778 // Remove the basic block, including all of the instructions contained in it.
779 BB->eraseFromParent();
780
781 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
782 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000783}
Chris Lattner6fd13622006-02-17 00:31:07 +0000784
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000785// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
786// the value specified by Val in the specified loop, or we know it does NOT have
787// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000788void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000789 Constant *Val,
790 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000791 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000792
Chris Lattnerf48f7772004-04-19 18:07:02 +0000793 // FIXME: Support correlated properties, like:
794 // for (...)
795 // if (li1 < li2)
796 // ...
797 // if (li1 > li2)
798 // ...
Chris Lattnerf48f7772004-04-19 18:07:02 +0000799
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000800 // NotVal - If Val is a bool, this contains its inverse.
801 Constant *NotVal = 0;
802 if (ConstantBool *CB = dyn_cast<ConstantBool>(Val))
803 NotVal = ConstantBool::get(!CB->getValue());
804
Chris Lattner6e263152006-02-10 02:30:37 +0000805 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
806 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000807 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000808
809 std::vector<Instruction*> Worklist;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000810
Chris Lattner6fd13622006-02-17 00:31:07 +0000811 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
812 // in the loop with the appropriate one directly.
813 if (IsEqual || NotVal) {
814 Value *Replacement = NotVal ? NotVal : Val;
815
816 for (unsigned i = 0, e = Users.size(); i != e; ++i)
817 if (Instruction *U = cast<Instruction>(Users[i])) {
818 if (!L->contains(U->getParent()))
819 continue;
820 U->replaceUsesOfWith(LIC, Replacement);
821 Worklist.push_back(U);
822 }
823 } else {
824 // Otherwise, we don't know the precise value of LIC, but we do know that it
825 // is certainly NOT "Val". As such, simplify any uses in the loop that we
826 // can. This case occurs when we unswitch switch statements.
827 for (unsigned i = 0, e = Users.size(); i != e; ++i)
828 if (Instruction *U = cast<Instruction>(Users[i])) {
829 if (!L->contains(U->getParent()))
830 continue;
831
832 Worklist.push_back(U);
833
Chris Lattnerfa335f62006-02-16 19:36:22 +0000834 // If we know that LIC is not Val, use this info to simplify code.
835 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
836 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
837 if (SI->getCaseValue(i) == Val) {
838 // Found a dead case value. Don't remove PHI nodes in the
839 // successor if they become single-entry, those PHI nodes may
840 // be in the Users list.
841 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
842 SI->removeCase(i);
843 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000844 }
845 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000846 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000847
848 // TODO: We could do other simplifications, for example, turning
849 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000850 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000851 }
852
853 // Okay, now that we have simplified some instructions in the loop, walk over
854 // it and constant prop, dce, and fold control flow where possible. Note that
855 // this is effectively a very simple loop-structure-aware optimizer.
856 while (!Worklist.empty()) {
857 Instruction *I = Worklist.back();
858 Worklist.pop_back();
859
860 // Simple constant folding.
861 if (Constant *C = ConstantFoldInstruction(I)) {
862 ReplaceUsesOfWith(I, C, Worklist);
863 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000864 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000865
866 // Simple DCE.
867 if (isInstructionTriviallyDead(I)) {
868 DEBUG(std::cerr << "Remove dead instruction '" << *I);
869
870 // Add uses to the worklist, which may be dead now.
871 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
872 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
873 Worklist.push_back(Use);
874 I->eraseFromParent();
875 RemoveFromWorklist(I, Worklist);
876 ++NumSimplify;
877 continue;
878 }
879
880 // Special case hacks that appear commonly in unswitched code.
881 switch (I->getOpcode()) {
882 case Instruction::Select:
883 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
884 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
885 continue;
886 }
887 break;
888 case Instruction::And:
889 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
890 cast<BinaryOperator>(I)->swapOperands();
891 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
892 if (CB->getValue()) // X & 1 -> X
893 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
894 else // X & 0 -> 0
895 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
896 continue;
897 }
898 break;
899 case Instruction::Or:
900 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
901 cast<BinaryOperator>(I)->swapOperands();
902 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
903 if (CB->getValue()) // X | 1 -> 1
904 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
905 else // X | 0 -> X
906 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
907 continue;
908 }
909 break;
910 case Instruction::Br: {
911 BranchInst *BI = cast<BranchInst>(I);
912 if (BI->isUnconditional()) {
913 // If BI's parent is the only pred of the successor, fold the two blocks
914 // together.
915 BasicBlock *Pred = BI->getParent();
916 BasicBlock *Succ = BI->getSuccessor(0);
917 BasicBlock *SinglePred = Succ->getSinglePredecessor();
918 if (!SinglePred) continue; // Nothing to do.
919 assert(SinglePred == Pred && "CFG broken");
920
921 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
922 << Succ->getName() << "\n");
923
924 // Resolve any single entry PHI nodes in Succ.
925 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
926 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
927
928 // Move all of the successor contents from Succ to Pred.
929 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
930 Succ->end());
931 BI->eraseFromParent();
932 RemoveFromWorklist(BI, Worklist);
933
934 // If Succ has any successors with PHI nodes, update them to have
935 // entries coming from Pred instead of Succ.
936 Succ->replaceAllUsesWith(Pred);
937
938 // Remove Succ from the loop tree.
939 LI->removeBlock(Succ);
940 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +0000941 ++NumSimplify;
Chris Lattner29f771b2006-02-18 01:27:45 +0000942 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000943 break; // FIXME: disabled
944 // Conditional branch. Turn it into an unconditional branch, then
945 // remove dead blocks.
946 DEBUG(std::cerr << "Folded branch: " << *BI);
947 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
948 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
949 DeadSucc->removePredecessor(BI->getParent(), true);
950 Worklist.push_back(new BranchInst(LiveSucc, BI));
951 BI->eraseFromParent();
952 RemoveFromWorklist(BI, Worklist);
953 ++NumSimplify;
954
955 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +0000956 }
957 break;
958 }
959 }
960 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000961}