blob: 861e97ce586d582d5c2916e8c3a9a8bac4de078b [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"
Reid Spencera94d3942007-01-19 21:13:56 +000032#include "llvm/DerivedTypes.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000033#include "llvm/Function.h"
34#include "llvm/Instructions.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000036#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Transforms/Utils/Cloning.h"
38#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
Devang Patel97517ff2007-02-26 20:22:50 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000042#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000043#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/Debug.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000046#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000047#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000048using namespace llvm;
49
Chris Lattner79a42ac2006-12-19 21:40:18 +000050STATISTIC(NumBranches, "Number of branches unswitched");
51STATISTIC(NumSwitches, "Number of switches unswitched");
52STATISTIC(NumSelects , "Number of selects unswitched");
53STATISTIC(NumTrivial , "Number of unswitches that are trivial");
54STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
55
Chris Lattnerf48f7772004-04-19 18:07:02 +000056namespace {
Chris Lattner89762192006-02-09 20:15:48 +000057 cl::opt<unsigned>
58 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
60
Reid Spencer557ab152007-02-05 23:32:05 +000061 class VISIBILITY_HIDDEN LoopUnswitch : public FunctionPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +000062 LoopInfo *LI; // Loop information
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000063
64 // LoopProcessWorklist - List of loops we need to process.
65 std::vector<Loop*> LoopProcessWorklist;
Devang Patel97517ff2007-02-26 20:22:50 +000066 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel967b84c2007-02-26 19:31:58 +000067
Chris Lattnerf48f7772004-04-19 18:07:02 +000068 public:
69 virtual bool runOnFunction(Function &F);
70 bool visitLoop(Loop *L);
71
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
74 ///
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000077 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000078 AU.addRequired<LoopInfo>();
79 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000080 AU.addRequiredID(LCSSAID);
81 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000082 }
83
84 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000085 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
86 /// remove it.
87 void RemoveLoopFromWorklist(Loop *L) {
88 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
89 LoopProcessWorklist.end(), L);
90 if (I != LoopProcessWorklist.end())
91 LoopProcessWorklist.erase(I);
92 }
93
Chris Lattnerfbadd7e2006-02-11 00:43:37 +000094 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +000095 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +000096 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +000097 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000098 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +000099 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000100 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000101
102 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
103 Constant *Val, bool isEqual);
104
105 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000106 void RemoveBlockIfDead(BasicBlock *BB,
107 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000108 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000109 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000110 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000111}
112
Jeff Coheneca0d0f2005-01-06 05:47:18 +0000113FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000114
115bool LoopUnswitch::runOnFunction(Function &F) {
116 bool Changed = false;
117 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000118
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000119 // Populate the worklist of loops to process in post-order.
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
122 LoopProcessWorklist.push_back(*LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000123
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000124 // Process the loops in worklist order, this is a post-order visitation of
125 // the loops. We use a worklist of loops so that loops can be removed at any
126 // time if they are deleted (e.g. the backedge of a loop is removed).
127 while (!LoopProcessWorklist.empty()) {
128 Loop *L = LoopProcessWorklist.back();
129 LoopProcessWorklist.pop_back();
130 Changed |= visitLoop(L);
131 }
132
Devang Patel97517ff2007-02-26 20:22:50 +0000133 UnswitchedVals.clear();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000134 return Changed;
135}
136
137/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
138/// invariant in the loop, or has an invariant piece, return the invariant.
139/// Otherwise, return null.
140static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
141 // Constants should be folded, not unswitched on!
142 if (isa<Constant>(Cond)) return false;
143
144 // TODO: Handle: br (VARIANT|INVARIANT).
145 // TODO: Hoist simple expressions out of loops.
146 if (L->isLoopInvariant(Cond)) return Cond;
147
148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
149 if (BO->getOpcode() == Instruction::And ||
150 BO->getOpcode() == Instruction::Or) {
151 // If either the left or right side is invariant, we can unswitch on this,
152 // which will cause the branch to go away in one loop and the condition to
153 // simplify in the other one.
154 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
155 return LHS;
156 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
157 return RHS;
158 }
159
160 return 0;
161}
162
163bool LoopUnswitch::visitLoop(Loop *L) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000164 assert(L->isLCSSAForm());
165
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000166 bool Changed = false;
167
168 // Loop over all of the basic blocks in the loop. If we find an interior
169 // block that is branching on a loop-invariant condition, we can unswitch this
170 // loop.
171 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
172 I != E; ++I) {
173 TerminatorInst *TI = (*I)->getTerminator();
174 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
175 // If this isn't branching on an invariant condition, we can't unswitch
176 // it.
177 if (BI->isConditional()) {
178 // See if this, or some part of it, is loop invariant. If so, we can
179 // unswitch on it if we desire.
180 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000181 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000182 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000183 ++NumBranches;
184 return true;
185 }
186 }
187 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
188 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
189 if (LoopCond && SI->getNumCases() > 1) {
190 // Find a value to unswitch on:
191 // FIXME: this should chose the most expensive case!
192 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000193 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000194 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000195 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000196
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000197 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
198 ++NumSwitches;
199 return true;
200 }
201 }
202 }
203
204 // Scan the instructions to check for unswitchable values.
205 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
206 BBI != E; ++BBI)
207 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
208 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000209 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000210 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000211 ++NumSelects;
212 return true;
213 }
214 }
215 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000216
217 assert(L->isLCSSAForm());
218
Chris Lattnerf48f7772004-04-19 18:07:02 +0000219 return Changed;
220}
221
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000222/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
223/// 1. Exit the loop with no side effects.
224/// 2. Branch to the latch block with no side-effects.
225///
226/// If these conditions are true, we return true and set ExitBB to the block we
227/// exit through.
228///
229static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
230 BasicBlock *&ExitBB,
231 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000232 if (!Visited.insert(BB).second) {
233 // Already visited and Ok, end of recursion.
234 return true;
235 } else if (!L->contains(BB)) {
236 // Otherwise, this is a loop exit, this is fine so long as this is the
237 // first exit.
238 if (ExitBB != 0) return false;
239 ExitBB = BB;
240 return true;
241 }
242
243 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000244 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000245 // Check to see if the successor is a trivial loop exit.
246 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
247 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000248 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000249
250 // Okay, everything after this looks good, check to make sure that this block
251 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000252 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000253 if (I->mayWriteToMemory())
254 return false;
255
256 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000257}
258
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000259/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
260/// leads to an exit from the specified loop, and has no side-effects in the
261/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000262static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
263 std::set<BasicBlock*> Visited;
264 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000265 BasicBlock *ExitBB = 0;
266 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
267 return ExitBB;
268 return 0;
269}
Chris Lattner6e263152006-02-10 02:30:37 +0000270
Chris Lattnered7a67b2006-02-10 01:24:09 +0000271/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
272/// trivial: that is, that the condition controls whether or not the loop does
273/// anything at all. If this is a trivial condition, unswitching produces no
274/// code duplications (equivalently, it produces a simpler loop and a new empty
275/// loop, which gets deleted).
276///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000277/// If this is a trivial condition, return true, otherwise return false. When
278/// returning true, this sets Cond and Val to the condition that controls the
279/// trivial condition: when Cond dynamically equals Val, the loop is known to
280/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
281/// Cond == Val.
282///
283static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000284 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000285 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000286 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000287
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000288 BasicBlock *LoopExitBB = 0;
289 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
290 // If the header block doesn't end with a conditional branch on Cond, we
291 // can't handle it.
292 if (!BI->isConditional() || BI->getCondition() != Cond)
293 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000294
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000295 // Check to see if a successor of the branch is guaranteed to go to the
296 // latch block or exit through a one exit block without having any
297 // side-effects. If so, determine the value of Cond that causes it to do
298 // this.
299 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000300 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000301 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000302 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000303 }
304 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
305 // If this isn't a switch on Cond, we can't handle it.
306 if (SI->getCondition() != Cond) return false;
307
308 // Check to see if a successor of the switch is guaranteed to go to the
309 // latch block or exit through a one exit block without having any
310 // side-effects. If so, determine the value of Cond that causes it to do
311 // this. Note that we can't trivially unswitch on the default case.
312 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
313 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
314 // Okay, we found a trivial case, remember the value that is trivial.
315 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000316 break;
317 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000318 }
319
Chris Lattnere5521db2006-02-22 23:55:00 +0000320 // If we didn't find a single unique LoopExit block, or if the loop exit block
321 // contains phi nodes, this isn't trivial.
322 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000323 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000324
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000325 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000326
327 // We already know that nothing uses any scalar values defined inside of this
328 // loop. As such, we just have to check to see if this loop will execute any
329 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000330 // part of the loop that the code *would* execute. We already checked the
331 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000332 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
333 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000334 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000335 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000336}
337
338/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
339/// we choose to unswitch the specified loop on the specified value.
340///
341unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
342 // If the condition is trivial, always unswitch. There is no code growth for
343 // this case.
344 if (IsTrivialUnswitchCondition(L, LIC))
345 return 0;
346
Owen Anderson18e816f2006-06-28 17:47:50 +0000347 // FIXME: This is really overly conservative. However, more liberal
348 // estimations have thus far resulted in excessive unswitching, which is bad
349 // both in compile time and in code size. This should be replaced once
350 // someone figures out how a good estimation.
351 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000352
Chris Lattnered7a67b2006-02-10 01:24:09 +0000353 unsigned Cost = 0;
354 // FIXME: this is brain dead. It should take into consideration code
355 // shrinkage.
356 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
357 I != E; ++I) {
358 BasicBlock *BB = *I;
359 // Do not include empty blocks in the cost calculation. This happen due to
360 // loop canonicalization and will be removed.
361 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
362 continue;
363
364 // Count basic blocks.
365 ++Cost;
366 }
367
368 return Cost;
369}
370
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000371/// UnswitchIfProfitable - We have found that we can unswitch L when
372/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
373/// unswitch the loop, reprocess the pieces, then return true.
374bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
375 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000376 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
377 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000378 // FIXME: this should estimate growth by the amount of code shared by the
379 // resultant unswitched loops.
380 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000381 DOUT << "NOT unswitching loop %"
382 << L->getHeader()->getName() << ", cost too high: "
383 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000384 return false;
385 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000386
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 // If this is a trivial condition to unswitch (which results in no code
388 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000389 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000390 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000391 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
392 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000393 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000394 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000395 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000396
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000397 return true;
398}
399
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000400/// SplitBlock - Split the specified block at the specified instruction - every
401/// thing before SplitPt stays in Old and everything starting with SplitPt moves
402/// to a new block. The two blocks are joined by an unconditional branch and
403/// the loop info is updated.
404///
405BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000406 BasicBlock::iterator SplitIt = SplitPt;
407 while (isa<PHINode>(SplitIt))
408 ++SplitIt;
409 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000410
411 // The new block lives in whichever loop the old one did.
412 if (Loop *L = LI->getLoopFor(Old))
413 L->addBasicBlockToLoop(New, *LI);
414
415 return New;
416}
417
418
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000419BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
420 TerminatorInst *LatchTerm = BB->getTerminator();
421 unsigned SuccNum = 0;
422 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
423 assert(i != e && "Didn't find edge?");
424 if (LatchTerm->getSuccessor(i) == Succ) {
425 SuccNum = i;
426 break;
427 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000428 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000429
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000430 // If this is a critical edge, let SplitCriticalEdge do it.
431 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
432 return LatchTerm->getSuccessor(SuccNum);
433
434 // If the edge isn't critical, then BB has a single successor or Succ has a
435 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000436 BasicBlock::iterator SplitPoint;
437 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
438 // If the successor only has a single pred, split the top of the successor
439 // block.
440 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000441 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000442 } else {
443 // Otherwise, if BB has a single successor, split it at the bottom of the
444 // block.
445 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
446 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000447 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000448 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000449}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000450
Chris Lattnerf48f7772004-04-19 18:07:02 +0000451
452
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000454// current values into those specified by ValueMap.
455//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000456static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000457 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000458 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
459 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000460 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000461 if (It != ValueMap.end()) Op = It->second;
462 I->setOperand(op, Op);
463 }
464}
465
466/// CloneLoop - Recursively clone the specified loop and all of its children,
467/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000468static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000469 LoopInfo *LI) {
470 Loop *New = new Loop();
471
472 if (PL)
473 PL->addChildLoop(New);
474 else
475 LI->addTopLevelLoop(New);
476
477 // Add all of the blocks in L to the new loop.
478 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
479 I != E; ++I)
480 if (LI->getLoopFor(*I) == L)
481 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
482
483 // Add all of the subloops to the new loop.
484 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
485 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000486
Chris Lattnerf48f7772004-04-19 18:07:02 +0000487 return New;
488}
489
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000490/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
491/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
492/// code immediately before InsertPt.
493static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
494 BasicBlock *TrueDest,
495 BasicBlock *FalseDest,
496 Instruction *InsertPt) {
497 // Insert a conditional branch on LIC to the two preheaders. The original
498 // code is the true version and the new code is the false version.
499 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000500 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000501 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000502 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000503 // We want to enter the new loop when the condition is true.
504 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000505
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 Lattner8a5a3242006-02-22 06:37:14 +0000517 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000518 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000519 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
520 << L->getHeader()->getName() << " [" << L->getBlocks().size()
521 << " blocks] in Function " << L->getHeader()->getParent()->getName()
522 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000523
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000524 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000525 // to insert the conditional branch. We will change 'OrigPH' to have a
526 // conditional branch on Cond.
527 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000528 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000529
530 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000531 // to branch to: this is the exit block out of the loop that we should
532 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000533
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000534 // Split this block now, so that the loop maintains its exit block, and so
535 // that the jump from the preheader can execute the contents of the exit block
536 // without actually branching to it (the exit block should be dominated by the
537 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000538 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000539 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000540
Chris Lattnered7a67b2006-02-10 01:24:09 +0000541 // Okay, now we have a position to branch from and a position to branch to,
542 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000543 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
544 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000545 OrigPH->getTerminator()->eraseFromParent();
546
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000547 // We need to reprocess this loop, it could be unswitched again.
548 LoopProcessWorklist.push_back(L);
549
Chris Lattnered7a67b2006-02-10 01:24:09 +0000550 // Now that we know that the loop is never entered when this condition is a
551 // particular value, rewrite the loop with this info. We know that this will
552 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000553 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000554 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000555}
556
Chris Lattnerf48f7772004-04-19 18:07:02 +0000557
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000558/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
559/// equal Val. Split it into loop versions and test the condition outside of
560/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000561void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
562 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000563 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000564 DOUT << "loop-unswitch: Unswitching loop %"
565 << L->getHeader()->getName() << " [" << L->getBlocks().size()
566 << " blocks] in Function " << F->getName()
567 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000568
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000569 // LoopBlocks contains all of the basic blocks of the loop, including the
570 // preheader of the loop, the body of the loop, and the exit blocks of the
571 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000572 std::vector<BasicBlock*> LoopBlocks;
573
574 // First step, split the preheader and exit blocks, and add these blocks to
575 // the LoopBlocks list.
576 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000577 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000578
579 // We want the loop to come after the preheader, but before the exit blocks.
580 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
581
582 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000583 L->getUniqueExitBlocks(ExitBlocks);
584
Owen Andersonf52351e2006-06-26 07:44:36 +0000585 // Split all of the edges from inside the loop to their exit blocks. Update
586 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000587 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000588 BasicBlock *ExitBlock = ExitBlocks[i];
589 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
590
591 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
592 assert(L->contains(Preds[j]) &&
593 "All preds of loop exit blocks must be the same loop!");
Owen Andersonf52351e2006-06-26 07:44:36 +0000594 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
595 BasicBlock* StartBlock = Preds[j];
596 BasicBlock* EndBlock;
597 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
598 EndBlock = MiddleBlock;
599 MiddleBlock = EndBlock->getSinglePredecessor();;
600 } else {
601 EndBlock = ExitBlock;
602 }
603
604 std::set<PHINode*> InsertedPHIs;
605 PHINode* OldLCSSA = 0;
606 for (BasicBlock::iterator I = EndBlock->begin();
607 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
608 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
609 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
610 OldLCSSA->getName() + ".us-lcssa",
611 MiddleBlock->getTerminator());
612 NewLCSSA->addIncoming(OldValue, StartBlock);
613 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
614 NewLCSSA);
615 InsertedPHIs.insert(NewLCSSA);
616 }
617
Owen Anderson00b974c2006-07-19 03:51:48 +0000618 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000619 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
620 for (BasicBlock::iterator I = MiddleBlock->begin();
621 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
622 ++I) {
623 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
624 OldLCSSA->getName() + ".us-lcssa",
625 InsertPt);
626 OldLCSSA->replaceAllUsesWith(NewLCSSA);
627 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
628 }
629 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000630 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000631
632 // The exit blocks may have been changed due to edge splitting, recompute.
633 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000634 L->getUniqueExitBlocks(ExitBlocks);
635
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000636 // Add exit blocks to the loop blocks.
637 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000638
639 // Next step, clone all of the basic blocks that make up the loop (including
640 // the loop preheader and exit blocks), keeping track of the mapping between
641 // the instructions and blocks.
642 std::vector<BasicBlock*> NewBlocks;
643 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000644 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000645 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000646 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
647 NewBlocks.push_back(New);
648 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000649 }
650
651 // Splice the newly inserted blocks into the function right before the
652 // original preheader.
653 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
654 NewBlocks[0], F->end());
655
656 // Now we create the new Loop object for the versioned loop.
657 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000658 Loop *ParentLoop = L->getParentLoop();
659 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000660 // Make sure to add the cloned preheader and exit blocks to the parent loop
661 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000662 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
663 }
664
665 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
666 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000667 // The new exit block should be in the same loop as the old one.
668 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
669 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000670
671 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
672 "Exit block should have been split to have one successor!");
673 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
674
675 // If the successor of the exit block had PHI nodes, add an entry for
676 // NewExit.
677 PHINode *PN;
678 for (BasicBlock::iterator I = ExitSucc->begin();
679 (PN = dyn_cast<PHINode>(I)); ++I) {
680 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000681 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000682 if (It != ValueMap.end()) V = It->second;
683 PN->addIncoming(V, NewExit);
684 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000685 }
686
687 // Rewrite the code to refer to itself.
688 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
689 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
690 E = NewBlocks[i]->end(); I != E; ++I)
691 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000692
Chris Lattnerf48f7772004-04-19 18:07:02 +0000693 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000694 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
695 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000696 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000697
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000698 // Emit the new branch that selects between the two versions of this loop.
699 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
700 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000701
702 LoopProcessWorklist.push_back(L);
703 LoopProcessWorklist.push_back(NewLoop);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000704
705 // Now we rewrite the original code to know that the condition is true and the
706 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000707 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
708
709 // It's possible that simplifying one loop could cause the other to be
710 // deleted. If so, don't simplify it.
711 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
712 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000713}
714
Chris Lattner6fd13622006-02-17 00:31:07 +0000715/// RemoveFromWorklist - Remove all instances of I from the worklist vector
716/// specified.
717static void RemoveFromWorklist(Instruction *I,
718 std::vector<Instruction*> &Worklist) {
719 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
720 Worklist.end(), I);
721 while (WI != Worklist.end()) {
722 unsigned Offset = WI-Worklist.begin();
723 Worklist.erase(WI);
724 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
725 }
726}
727
728/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
729/// program, replacing all uses with V and update the worklist.
730static void ReplaceUsesOfWith(Instruction *I, Value *V,
731 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000732 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000733
734 // Add uses to the worklist, which may be dead now.
735 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
736 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
737 Worklist.push_back(Use);
738
739 // Add users to the worklist which may be simplified now.
740 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
741 UI != E; ++UI)
742 Worklist.push_back(cast<Instruction>(*UI));
743 I->replaceAllUsesWith(V);
744 I->eraseFromParent();
745 RemoveFromWorklist(I, Worklist);
746 ++NumSimplify;
747}
748
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000749/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
750/// information, and remove any dead successors it has.
751///
752void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
753 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000754 if (pred_begin(BB) != pred_end(BB)) {
755 // This block isn't dead, since an edge to BB was just removed, see if there
756 // are any easy simplifications we can do now.
757 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
758 // If it has one pred, fold phi nodes in BB.
759 while (isa<PHINode>(BB->begin()))
760 ReplaceUsesOfWith(BB->begin(),
761 cast<PHINode>(BB->begin())->getIncomingValue(0),
762 Worklist);
763
764 // If this is the header of a loop and the only pred is the latch, we now
765 // have an unreachable loop.
766 if (Loop *L = LI->getLoopFor(BB))
767 if (L->getHeader() == BB && L->contains(Pred)) {
768 // Remove the branch from the latch to the header block, this makes
769 // the header dead, which will make the latch dead (because the header
770 // dominates the latch).
771 Pred->getTerminator()->eraseFromParent();
772 new UnreachableInst(Pred);
773
774 // The loop is now broken, remove it from LI.
775 RemoveLoopFromHierarchy(L);
776
777 // Reprocess the header, which now IS dead.
778 RemoveBlockIfDead(BB, Worklist);
779 return;
780 }
781
782 // If pred ends in a uncond branch, add uncond branch to worklist so that
783 // the two blocks will get merged.
784 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
785 if (BI->isUnconditional())
786 Worklist.push_back(BI);
787 }
788 return;
789 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000790
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000791 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000792
793 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000794 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000795 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000796
797 // Anything that uses the instructions in this basic block should have their
798 // uses replaced with undefs.
799 if (!I->use_empty())
800 I->replaceAllUsesWith(UndefValue::get(I->getType()));
801 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000802
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000803 // If this is the edge to the header block for a loop, remove the loop and
804 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000805 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000806 if (BBLoop->getLoopLatch() == BB)
807 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000808 }
809
810 // Remove the block from the loop info, which removes it from any loops it
811 // was in.
812 LI->removeBlock(BB);
813
814
815 // Remove phi node entries in successors for this block.
816 TerminatorInst *TI = BB->getTerminator();
817 std::vector<BasicBlock*> Succs;
818 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
819 Succs.push_back(TI->getSuccessor(i));
820 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000821 }
822
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000823 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000824 std::sort(Succs.begin(), Succs.end());
825 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
826
827 // Remove the basic block, including all of the instructions contained in it.
828 BB->eraseFromParent();
829
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000830 // Remove successor blocks here that are not dead, so that we know we only
831 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
832 // then getting removed before we revisit them, which is badness.
833 //
834 for (unsigned i = 0; i != Succs.size(); ++i)
835 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
836 // One exception is loop headers. If this block was the preheader for a
837 // loop, then we DO want to visit the loop so the loop gets deleted.
838 // We know that if the successor is a loop header, that this loop had to
839 // be the preheader: the case where this was the latch block was handled
840 // above and headers can only have two predecessors.
841 if (!LI->isLoopHeader(Succs[i])) {
842 Succs.erase(Succs.begin()+i);
843 --i;
844 }
845 }
846
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000847 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
848 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000849}
Chris Lattner6fd13622006-02-17 00:31:07 +0000850
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000851/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
852/// become unwrapped, either because the backedge was deleted, or because the
853/// edge into the header was removed. If the edge into the header from the
854/// latch block was removed, the loop is unwrapped but subloops are still alive,
855/// so they just reparent loops. If the loops are actually dead, they will be
856/// removed later.
857void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
858 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
859 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
860 // they are now all in it.
861 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
862 I != E; ++I)
863 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
864 LI->changeLoopFor(*I, ParentLoop);
865
866 // Remove the loop from its parent loop.
867 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
868 ++I) {
869 assert(I != E && "Couldn't find loop");
870 if (*I == L) {
871 ParentLoop->removeChildLoop(I);
872 break;
873 }
874 }
875
876 // Move all subloops into the parent loop.
877 while (L->begin() != L->end())
878 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
879 } else {
880 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
881 // they no longer in a loop at all.
882
883 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
884 // Don't change blocks in subloops.
885 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
886 LI->removeBlock(L->getBlocks()[i]);
887 --i;
888 }
889 }
890
891 // Remove the loop from the top-level LoopInfo object.
892 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
893 assert(I != E && "Couldn't find loop");
894 if (*I == L) {
895 LI->removeLoop(I);
896 break;
897 }
898 }
899
900 // Move all of the subloops to the top-level.
901 while (L->begin() != L->end())
902 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
903 }
904
905 delete L;
906 RemoveLoopFromWorklist(L);
907}
908
909
910
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000911// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
912// the value specified by Val in the specified loop, or we know it does NOT have
913// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000914void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000915 Constant *Val,
916 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000917 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000918
Chris Lattnerf48f7772004-04-19 18:07:02 +0000919 // FIXME: Support correlated properties, like:
920 // for (...)
921 // if (li1 < li2)
922 // ...
923 // if (li1 > li2)
924 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000925
Chris Lattner6e263152006-02-10 02:30:37 +0000926 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
927 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000928 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000929 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000930
Chris Lattner6fd13622006-02-17 00:31:07 +0000931 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
932 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000933 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000934 Value *Replacement;
935 if (IsEqual)
936 Replacement = Val;
937 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000938 Replacement = ConstantInt::get(Type::Int1Ty,
939 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000940
941 for (unsigned i = 0, e = Users.size(); i != e; ++i)
942 if (Instruction *U = cast<Instruction>(Users[i])) {
943 if (!L->contains(U->getParent()))
944 continue;
945 U->replaceUsesOfWith(LIC, Replacement);
946 Worklist.push_back(U);
947 }
948 } else {
949 // Otherwise, we don't know the precise value of LIC, but we do know that it
950 // is certainly NOT "Val". As such, simplify any uses in the loop that we
951 // can. This case occurs when we unswitch switch statements.
952 for (unsigned i = 0, e = Users.size(); i != e; ++i)
953 if (Instruction *U = cast<Instruction>(Users[i])) {
954 if (!L->contains(U->getParent()))
955 continue;
956
957 Worklist.push_back(U);
958
Chris Lattnerfa335f62006-02-16 19:36:22 +0000959 // If we know that LIC is not Val, use this info to simplify code.
960 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
961 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
962 if (SI->getCaseValue(i) == Val) {
963 // Found a dead case value. Don't remove PHI nodes in the
964 // successor if they become single-entry, those PHI nodes may
965 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000966
967 // FIXME: This is a hack. We need to keep the successor around
968 // and hooked up so as to preserve the loop structure, because
969 // trying to update it is complicated. So instead we preserve the
970 // loop structure and put the block on an dead code path.
971
972 BasicBlock* Old = SI->getParent();
973 BasicBlock* Split = SplitBlock(Old, SI);
974
975 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000976 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000977 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000978
979 Old->getTerminator()->eraseFromParent();
980
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000981
982 PHINode *PN;
983 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
984 (PN = dyn_cast<PHINode>(II)); ++II) {
985 Value *InVal = PN->removeIncomingValue(Split, false);
986 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000987 }
988
Chris Lattnerfa335f62006-02-16 19:36:22 +0000989 SI->removeCase(i);
990 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000991 }
992 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000993 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000994
995 // TODO: We could do other simplifications, for example, turning
996 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000997 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000998 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000999
1000 SimplifyCode(Worklist);
1001}
1002
1003/// SimplifyCode - Okay, now that we have simplified some instructions in the
1004/// loop, walk over it and constant prop, dce, and fold control flow where
1005/// possible. Note that this is effectively a very simple loop-structure-aware
1006/// optimizer. During processing of this loop, L could very well be deleted, so
1007/// it must not be used.
1008///
1009/// FIXME: When the loop optimizer is more mature, separate this out to a new
1010/// pass.
1011///
1012void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001013 while (!Worklist.empty()) {
1014 Instruction *I = Worklist.back();
1015 Worklist.pop_back();
1016
1017 // Simple constant folding.
1018 if (Constant *C = ConstantFoldInstruction(I)) {
1019 ReplaceUsesOfWith(I, C, Worklist);
1020 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001021 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001022
1023 // Simple DCE.
1024 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001025 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001026
1027 // Add uses to the worklist, which may be dead now.
1028 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1029 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1030 Worklist.push_back(Use);
1031 I->eraseFromParent();
1032 RemoveFromWorklist(I, Worklist);
1033 ++NumSimplify;
1034 continue;
1035 }
1036
1037 // Special case hacks that appear commonly in unswitched code.
1038 switch (I->getOpcode()) {
1039 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001040 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001041 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001042 continue;
1043 }
1044 break;
1045 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001046 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001047 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001048 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001049 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001050 if (CB->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001051 if (CB->getZExtValue()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001052 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1053 else // X & 0 -> 0
1054 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1055 continue;
1056 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001057 break;
1058 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001059 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001060 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001061 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001062 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001063 if (CB->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001064 if (CB->getZExtValue()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001065 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1066 else // X | 0 -> X
1067 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1068 continue;
1069 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001070 break;
1071 case Instruction::Br: {
1072 BranchInst *BI = cast<BranchInst>(I);
1073 if (BI->isUnconditional()) {
1074 // If BI's parent is the only pred of the successor, fold the two blocks
1075 // together.
1076 BasicBlock *Pred = BI->getParent();
1077 BasicBlock *Succ = BI->getSuccessor(0);
1078 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1079 if (!SinglePred) continue; // Nothing to do.
1080 assert(SinglePred == Pred && "CFG broken");
1081
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001082 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1083 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001084
1085 // Resolve any single entry PHI nodes in Succ.
1086 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1087 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1088
1089 // Move all of the successor contents from Succ to Pred.
1090 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1091 Succ->end());
1092 BI->eraseFromParent();
1093 RemoveFromWorklist(BI, Worklist);
1094
1095 // If Succ has any successors with PHI nodes, update them to have
1096 // entries coming from Pred instead of Succ.
1097 Succ->replaceAllUsesWith(Pred);
1098
1099 // Remove Succ from the loop tree.
1100 LI->removeBlock(Succ);
1101 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001102 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001103 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001104 // Conditional branch. Turn it into an unconditional branch, then
1105 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001106 break; // FIXME: Enable.
1107
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001108 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001109 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1110 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001111 DeadSucc->removePredecessor(BI->getParent(), true);
1112 Worklist.push_back(new BranchInst(LiveSucc, BI));
1113 BI->eraseFromParent();
1114 RemoveFromWorklist(BI, Worklist);
1115 ++NumSimplify;
1116
1117 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001118 }
1119 break;
1120 }
1121 }
1122 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001123}