blob: eb084cbf0142d8bdb8420fe26116b7ee4cd3e24f [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 }
Chris Lattner0c4f5a62006-06-14 04:46:17 +0000404
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 Lattner0c4f5a62006-06-14 04:46:17 +0000459
460 // If this block has a single predecessor, remove any phi nodes. Unswitch
461 // expect that, after split the edges from inside the loop to the exit
462 // block, that there will be no phi nodes in the new exit block. Single
463 // entry phi nodes break this assumption.
464 BasicBlock::iterator I = Succ->begin();
465 while (PHINode *PN = dyn_cast<PHINode>(I)) {
466 PN->replaceAllUsesWith(PN->getIncomingValue(0));
467 PN->eraseFromParent();
468 I = Succ->begin();
469 }
470
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000471 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000472 } else {
473 // Otherwise, if BB has a single successor, split it at the bottom of the
474 // block.
475 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
476 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000477 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000478 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000479}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000480
Chris Lattnerf48f7772004-04-19 18:07:02 +0000481
482
Misha Brukmanb1c93172005-04-21 23:48:37 +0000483// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000484// current values into those specified by ValueMap.
485//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000486static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000487 std::map<const Value *, Value*> &ValueMap) {
488 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
489 Value *Op = I->getOperand(op);
490 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
491 if (It != ValueMap.end()) Op = It->second;
492 I->setOperand(op, Op);
493 }
494}
495
496/// CloneLoop - Recursively clone the specified loop and all of its children,
497/// mapping the blocks with the specified map.
498static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
499 LoopInfo *LI) {
500 Loop *New = new Loop();
501
502 if (PL)
503 PL->addChildLoop(New);
504 else
505 LI->addTopLevelLoop(New);
506
507 // Add all of the blocks in L to the new loop.
508 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
509 I != E; ++I)
510 if (LI->getLoopFor(*I) == L)
511 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
512
513 // Add all of the subloops to the new loop.
514 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
515 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000516
Chris Lattnerf48f7772004-04-19 18:07:02 +0000517 return New;
518}
519
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000520/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
521/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
522/// code immediately before InsertPt.
523static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
524 BasicBlock *TrueDest,
525 BasicBlock *FalseDest,
526 Instruction *InsertPt) {
527 // Insert a conditional branch on LIC to the two preheaders. The original
528 // code is the true version and the new code is the false version.
529 Value *BranchVal = LIC;
Chris Lattner65152d82006-02-15 19:05:52 +0000530 if (!isa<ConstantBool>(Val)) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000531 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
532 } else if (Val != ConstantBool::True) {
533 // We want to enter the new loop when the condition is true.
534 std::swap(TrueDest, FalseDest);
535 }
536
537 // Insert the new branch.
538 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
539}
540
541
Chris Lattnered7a67b2006-02-10 01:24:09 +0000542/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
543/// condition in it (a cond branch from its header block to its latch block,
544/// where the path through the loop that doesn't execute its body has no
545/// side-effects), unswitch it. This doesn't involve any code duplication, just
546/// moving the conditional branch outside of the loop and updating loop info.
547void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000548 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000549 BasicBlock *ExitBlock) {
Chris Lattner3fc31482006-02-10 01:36:35 +0000550 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
551 << L->getHeader()->getName() << " [" << L->getBlocks().size()
552 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattner8a5a3242006-02-22 06:37:14 +0000553 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner3fc31482006-02-10 01:36:35 +0000554
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000555 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000556 // to insert the conditional branch. We will change 'OrigPH' to have a
557 // conditional branch on Cond.
558 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000559 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000560
561 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000562 // to branch to: this is the exit block out of the loop that we should
563 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000564
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000565 // Split this block now, so that the loop maintains its exit block, and so
566 // that the jump from the preheader can execute the contents of the exit block
567 // without actually branching to it (the exit block should be dominated by the
568 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000569 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000570 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000571
Chris Lattnered7a67b2006-02-10 01:24:09 +0000572 // Okay, now we have a position to branch from and a position to branch to,
573 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000574 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
575 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000576 OrigPH->getTerminator()->eraseFromParent();
577
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000578 // We need to reprocess this loop, it could be unswitched again.
579 LoopProcessWorklist.push_back(L);
580
Chris Lattnered7a67b2006-02-10 01:24:09 +0000581 // Now that we know that the loop is never entered when this condition is a
582 // particular value, rewrite the loop with this info. We know that this will
583 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000584 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000585 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000586}
587
Chris Lattnerf48f7772004-04-19 18:07:02 +0000588
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000589/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
590/// equal Val. Split it into loop versions and test the condition outside of
591/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000592void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
593 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000594 Function *F = L->getHeader()->getParent();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000595 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000596 << L->getHeader()->getName() << " [" << L->getBlocks().size()
597 << " blocks] in Function " << F->getName()
598 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000599
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000600 // LoopBlocks contains all of the basic blocks of the loop, including the
601 // preheader of the loop, the body of the loop, and the exit blocks of the
602 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000603 std::vector<BasicBlock*> LoopBlocks;
604
605 // First step, split the preheader and exit blocks, and add these blocks to
606 // the LoopBlocks list.
607 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000608 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000609
610 // We want the loop to come after the preheader, but before the exit blocks.
611 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
612
613 std::vector<BasicBlock*> ExitBlocks;
614 L->getExitBlocks(ExitBlocks);
615 std::sort(ExitBlocks.begin(), ExitBlocks.end());
616 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
617 ExitBlocks.end());
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000618
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000619 // Split all of the edges from inside the loop to their exit blocks. This
620 // unswitching trivial: no phi nodes to update.
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000621 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner8e44ff52006-02-18 00:55:32 +0000622
Chris Lattnered7a67b2006-02-10 01:24:09 +0000623 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000624 BasicBlock *ExitBlock = ExitBlocks[i];
625 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
626
627 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
628 assert(L->contains(Preds[j]) &&
629 "All preds of loop exit blocks must be the same loop!");
630 SplitEdge(Preds[j], ExitBlock);
631 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000632 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000633
634 // The exit blocks may have been changed due to edge splitting, recompute.
635 ExitBlocks.clear();
636 L->getExitBlocks(ExitBlocks);
637 std::sort(ExitBlocks.begin(), ExitBlocks.end());
638 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
639 ExitBlocks.end());
640
641 // Add exit blocks to the loop blocks.
642 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000643
644 // Next step, clone all of the basic blocks that make up the loop (including
645 // the loop preheader and exit blocks), keeping track of the mapping between
646 // the instructions and blocks.
647 std::vector<BasicBlock*> NewBlocks;
648 NewBlocks.reserve(LoopBlocks.size());
649 std::map<const Value*, Value*> ValueMap;
650 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000651 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
652 NewBlocks.push_back(New);
653 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000654 }
655
656 // Splice the newly inserted blocks into the function right before the
657 // original preheader.
658 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
659 NewBlocks[0], F->end());
660
661 // Now we create the new Loop object for the versioned loop.
662 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000663 Loop *ParentLoop = L->getParentLoop();
664 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000665 // Make sure to add the cloned preheader and exit blocks to the parent loop
666 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000667 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
668 }
669
670 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
671 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000672 // The new exit block should be in the same loop as the old one.
673 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
674 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000675
676 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
677 "Exit block should have been split to have one successor!");
678 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
679
680 // If the successor of the exit block had PHI nodes, add an entry for
681 // NewExit.
682 PHINode *PN;
683 for (BasicBlock::iterator I = ExitSucc->begin();
684 (PN = dyn_cast<PHINode>(I)); ++I) {
685 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
686 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
687 if (It != ValueMap.end()) V = It->second;
688 PN->addIncoming(V, NewExit);
689 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000690 }
691
692 // Rewrite the code to refer to itself.
693 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
694 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
695 E = NewBlocks[i]->end(); I != E; ++I)
696 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000697
Chris Lattnerf48f7772004-04-19 18:07:02 +0000698 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000699 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
700 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000701 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000702
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000703 // Emit the new branch that selects between the two versions of this loop.
704 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
705 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000706
707 LoopProcessWorklist.push_back(L);
708 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000709
710 // Now we rewrite the original code to know that the condition is true and the
711 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000712 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
713
714 // It's possible that simplifying one loop could cause the other to be
715 // deleted. If so, don't simplify it.
716 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
717 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000718}
719
Chris Lattner6fd13622006-02-17 00:31:07 +0000720/// RemoveFromWorklist - Remove all instances of I from the worklist vector
721/// specified.
722static void RemoveFromWorklist(Instruction *I,
723 std::vector<Instruction*> &Worklist) {
724 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
725 Worklist.end(), I);
726 while (WI != Worklist.end()) {
727 unsigned Offset = WI-Worklist.begin();
728 Worklist.erase(WI);
729 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
730 }
731}
732
733/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
734/// program, replacing all uses with V and update the worklist.
735static void ReplaceUsesOfWith(Instruction *I, Value *V,
736 std::vector<Instruction*> &Worklist) {
737 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
738
739 // Add uses to the worklist, which may be dead now.
740 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
741 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
742 Worklist.push_back(Use);
743
744 // Add users to the worklist which may be simplified now.
745 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
746 UI != E; ++UI)
747 Worklist.push_back(cast<Instruction>(*UI));
748 I->replaceAllUsesWith(V);
749 I->eraseFromParent();
750 RemoveFromWorklist(I, Worklist);
751 ++NumSimplify;
752}
753
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000754/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
755/// information, and remove any dead successors it has.
756///
757void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
758 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000759 if (pred_begin(BB) != pred_end(BB)) {
760 // This block isn't dead, since an edge to BB was just removed, see if there
761 // are any easy simplifications we can do now.
762 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
763 // If it has one pred, fold phi nodes in BB.
764 while (isa<PHINode>(BB->begin()))
765 ReplaceUsesOfWith(BB->begin(),
766 cast<PHINode>(BB->begin())->getIncomingValue(0),
767 Worklist);
768
769 // If this is the header of a loop and the only pred is the latch, we now
770 // have an unreachable loop.
771 if (Loop *L = LI->getLoopFor(BB))
772 if (L->getHeader() == BB && L->contains(Pred)) {
773 // Remove the branch from the latch to the header block, this makes
774 // the header dead, which will make the latch dead (because the header
775 // dominates the latch).
776 Pred->getTerminator()->eraseFromParent();
777 new UnreachableInst(Pred);
778
779 // The loop is now broken, remove it from LI.
780 RemoveLoopFromHierarchy(L);
781
782 // Reprocess the header, which now IS dead.
783 RemoveBlockIfDead(BB, Worklist);
784 return;
785 }
786
787 // If pred ends in a uncond branch, add uncond branch to worklist so that
788 // the two blocks will get merged.
789 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
790 if (BI->isUnconditional())
791 Worklist.push_back(BI);
792 }
793 return;
794 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000795
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000796 DEBUG(std::cerr << "Nuking dead block: " << *BB);
797
798 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000799 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000800 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000801
802 // Anything that uses the instructions in this basic block should have their
803 // uses replaced with undefs.
804 if (!I->use_empty())
805 I->replaceAllUsesWith(UndefValue::get(I->getType()));
806 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000807
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000808 // If this is the edge to the header block for a loop, remove the loop and
809 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000810 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000811 if (BBLoop->getLoopLatch() == BB)
812 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000813 }
814
815 // Remove the block from the loop info, which removes it from any loops it
816 // was in.
817 LI->removeBlock(BB);
818
819
820 // Remove phi node entries in successors for this block.
821 TerminatorInst *TI = BB->getTerminator();
822 std::vector<BasicBlock*> Succs;
823 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
824 Succs.push_back(TI->getSuccessor(i));
825 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000826 }
827
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000828 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000829 std::sort(Succs.begin(), Succs.end());
830 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
831
832 // Remove the basic block, including all of the instructions contained in it.
833 BB->eraseFromParent();
834
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000835 // Remove successor blocks here that are not dead, so that we know we only
836 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
837 // then getting removed before we revisit them, which is badness.
838 //
839 for (unsigned i = 0; i != Succs.size(); ++i)
840 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
841 // One exception is loop headers. If this block was the preheader for a
842 // loop, then we DO want to visit the loop so the loop gets deleted.
843 // We know that if the successor is a loop header, that this loop had to
844 // be the preheader: the case where this was the latch block was handled
845 // above and headers can only have two predecessors.
846 if (!LI->isLoopHeader(Succs[i])) {
847 Succs.erase(Succs.begin()+i);
848 --i;
849 }
850 }
851
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000852 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
853 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000854}
Chris Lattner6fd13622006-02-17 00:31:07 +0000855
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000856/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
857/// become unwrapped, either because the backedge was deleted, or because the
858/// edge into the header was removed. If the edge into the header from the
859/// latch block was removed, the loop is unwrapped but subloops are still alive,
860/// so they just reparent loops. If the loops are actually dead, they will be
861/// removed later.
862void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
863 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
864 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
865 // they are now all in it.
866 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
867 I != E; ++I)
868 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
869 LI->changeLoopFor(*I, ParentLoop);
870
871 // Remove the loop from its parent loop.
872 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
873 ++I) {
874 assert(I != E && "Couldn't find loop");
875 if (*I == L) {
876 ParentLoop->removeChildLoop(I);
877 break;
878 }
879 }
880
881 // Move all subloops into the parent loop.
882 while (L->begin() != L->end())
883 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
884 } else {
885 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
886 // they no longer in a loop at all.
887
888 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
889 // Don't change blocks in subloops.
890 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
891 LI->removeBlock(L->getBlocks()[i]);
892 --i;
893 }
894 }
895
896 // Remove the loop from the top-level LoopInfo object.
897 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
898 assert(I != E && "Couldn't find loop");
899 if (*I == L) {
900 LI->removeLoop(I);
901 break;
902 }
903 }
904
905 // Move all of the subloops to the top-level.
906 while (L->begin() != L->end())
907 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
908 }
909
910 delete L;
911 RemoveLoopFromWorklist(L);
912}
913
914
915
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000916// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
917// the value specified by Val in the specified loop, or we know it does NOT have
918// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000919void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000920 Constant *Val,
921 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000922 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000923
Chris Lattnerf48f7772004-04-19 18:07:02 +0000924 // FIXME: Support correlated properties, like:
925 // for (...)
926 // if (li1 < li2)
927 // ...
928 // if (li1 > li2)
929 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000930
Chris Lattner6e263152006-02-10 02:30:37 +0000931 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
932 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000933 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000934 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000935
Chris Lattner6fd13622006-02-17 00:31:07 +0000936 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
937 // in the loop with the appropriate one directly.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000938 if (IsEqual || isa<ConstantBool>(Val)) {
939 Value *Replacement;
940 if (IsEqual)
941 Replacement = Val;
942 else
943 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000944
945 for (unsigned i = 0, e = Users.size(); i != e; ++i)
946 if (Instruction *U = cast<Instruction>(Users[i])) {
947 if (!L->contains(U->getParent()))
948 continue;
949 U->replaceUsesOfWith(LIC, Replacement);
950 Worklist.push_back(U);
951 }
952 } else {
953 // Otherwise, we don't know the precise value of LIC, but we do know that it
954 // is certainly NOT "Val". As such, simplify any uses in the loop that we
955 // can. This case occurs when we unswitch switch statements.
956 for (unsigned i = 0, e = Users.size(); i != e; ++i)
957 if (Instruction *U = cast<Instruction>(Users[i])) {
958 if (!L->contains(U->getParent()))
959 continue;
960
961 Worklist.push_back(U);
962
Chris Lattnerfa335f62006-02-16 19:36:22 +0000963 // If we know that LIC is not Val, use this info to simplify code.
964 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
965 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
966 if (SI->getCaseValue(i) == Val) {
967 // Found a dead case value. Don't remove PHI nodes in the
968 // successor if they become single-entry, those PHI nodes may
969 // be in the Users list.
970 SI->getSuccessor(i)->removePredecessor(SI->getParent(), true);
971 SI->removeCase(i);
972 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000973 }
974 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000975 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000976
977 // TODO: We could do other simplifications, for example, turning
978 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000979 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000980 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000981
982 SimplifyCode(Worklist);
983}
984
985/// SimplifyCode - Okay, now that we have simplified some instructions in the
986/// loop, walk over it and constant prop, dce, and fold control flow where
987/// possible. Note that this is effectively a very simple loop-structure-aware
988/// optimizer. During processing of this loop, L could very well be deleted, so
989/// it must not be used.
990///
991/// FIXME: When the loop optimizer is more mature, separate this out to a new
992/// pass.
993///
994void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000995 while (!Worklist.empty()) {
996 Instruction *I = Worklist.back();
997 Worklist.pop_back();
998
999 // Simple constant folding.
1000 if (Constant *C = ConstantFoldInstruction(I)) {
1001 ReplaceUsesOfWith(I, C, Worklist);
1002 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001003 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001004
1005 // Simple DCE.
1006 if (isInstructionTriviallyDead(I)) {
1007 DEBUG(std::cerr << "Remove dead instruction '" << *I);
1008
1009 // Add uses to the worklist, which may be dead now.
1010 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1011 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1012 Worklist.push_back(Use);
1013 I->eraseFromParent();
1014 RemoveFromWorklist(I, Worklist);
1015 ++NumSimplify;
1016 continue;
1017 }
1018
1019 // Special case hacks that appear commonly in unswitched code.
1020 switch (I->getOpcode()) {
1021 case Instruction::Select:
1022 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1023 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1024 continue;
1025 }
1026 break;
1027 case Instruction::And:
1028 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1029 cast<BinaryOperator>(I)->swapOperands();
1030 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1031 if (CB->getValue()) // X & 1 -> X
1032 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1033 else // X & 0 -> 0
1034 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1035 continue;
1036 }
1037 break;
1038 case Instruction::Or:
1039 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1040 cast<BinaryOperator>(I)->swapOperands();
1041 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1042 if (CB->getValue()) // X | 1 -> 1
1043 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1044 else // X | 0 -> X
1045 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1046 continue;
1047 }
1048 break;
1049 case Instruction::Br: {
1050 BranchInst *BI = cast<BranchInst>(I);
1051 if (BI->isUnconditional()) {
1052 // If BI's parent is the only pred of the successor, fold the two blocks
1053 // together.
1054 BasicBlock *Pred = BI->getParent();
1055 BasicBlock *Succ = BI->getSuccessor(0);
1056 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1057 if (!SinglePred) continue; // Nothing to do.
1058 assert(SinglePred == Pred && "CFG broken");
1059
1060 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1061 << Succ->getName() << "\n");
1062
1063 // Resolve any single entry PHI nodes in Succ.
1064 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1065 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1066
1067 // Move all of the successor contents from Succ to Pred.
1068 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1069 Succ->end());
1070 BI->eraseFromParent();
1071 RemoveFromWorklist(BI, Worklist);
1072
1073 // If Succ has any successors with PHI nodes, update them to have
1074 // entries coming from Pred instead of Succ.
1075 Succ->replaceAllUsesWith(Pred);
1076
1077 // Remove Succ from the loop tree.
1078 LI->removeBlock(Succ);
1079 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001080 ++NumSimplify;
Chris Lattner29f771b2006-02-18 01:27:45 +00001081 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001082 // Conditional branch. Turn it into an unconditional branch, then
1083 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001084 break; // FIXME: Enable.
1085
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001086 DEBUG(std::cerr << "Folded branch: " << *BI);
1087 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1088 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1089 DeadSucc->removePredecessor(BI->getParent(), true);
1090 Worklist.push_back(new BranchInst(LiveSucc, BI));
1091 BI->eraseFromParent();
1092 RemoveFromWorklist(BI, Worklist);
1093 ++NumSimplify;
1094
1095 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001096 }
1097 break;
1098 }
1099 }
1100 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001101}