blob: 157b00916cbf975d8c812c2e3cf51d69860c524b [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"
Devang Patel901a27d2007-03-07 00:26:10 +000037#include "llvm/Analysis/LoopPass.h"
Devang Patel3304e462007-06-28 00:49:00 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattnerf48f7772004-04-19 18:07:02 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerec6b40a2006-02-10 19:08:15 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Devang Patel97517ff2007-02-26 20:22:50 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000044#include "llvm/ADT/PostOrderIterator.h"
Chris Lattner89762192006-02-09 20:15:48 +000045#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000046#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000048#include <algorithm>
Chris Lattner2826e052006-02-09 19:14:52 +000049#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000050using namespace llvm;
51
Chris Lattner79a42ac2006-12-19 21:40:18 +000052STATISTIC(NumBranches, "Number of branches unswitched");
53STATISTIC(NumSwitches, "Number of switches unswitched");
54STATISTIC(NumSelects , "Number of selects unswitched");
55STATISTIC(NumTrivial , "Number of unswitches that are trivial");
56STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
57
Chris Lattnerf48f7772004-04-19 18:07:02 +000058namespace {
Chris Lattner89762192006-02-09 20:15:48 +000059 cl::opt<unsigned>
60 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61 cl::init(10), cl::Hidden);
62
Devang Patel901a27d2007-03-07 00:26:10 +000063 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +000064 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +000065 LPPassManager *LPM;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000066
Devang Patel901a27d2007-03-07 00:26:10 +000067 // LoopProcessWorklist - Used to check if second loop needs processing
68 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000069 std::vector<Loop*> LoopProcessWorklist;
Devang Patel97517ff2007-02-26 20:22:50 +000070 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel506310d2007-06-06 00:21:03 +000071
72 bool OptimizeForSize;
Chris Lattnerf48f7772004-04-19 18:07:02 +000073 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000074 static char ID; // Pass ID, replacement for typeid
Devang Patel506310d2007-06-06 00:21:03 +000075 LoopUnswitch(bool Os = false) :
76 LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
Devang Patel09f162c2007-05-01 21:15:47 +000077
Devang Patel901a27d2007-03-07 00:26:10 +000078 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnerf48f7772004-04-19 18:07:02 +000079
80 /// This transformation requires natural loop information & requires that
81 /// loop preheaders be inserted into the CFG...
82 ///
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000085 AU.addPreservedID(LoopSimplifyID);
Devang Patel3304e462007-06-28 00:49:00 +000086 AU.addPreserved<DominatorTree>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000087 AU.addRequired<LoopInfo>();
88 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000089 AU.addRequiredID(LCSSAID);
90 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000091 }
92
93 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000094 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
95 /// remove it.
96 void RemoveLoopFromWorklist(Loop *L) {
97 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
98 LoopProcessWorklist.end(), L);
99 if (I != LoopProcessWorklist.end())
100 LoopProcessWorklist.erase(I);
101 }
102
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000103 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000104 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000105 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000106 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000107 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000108 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000109 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000110
111 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
112 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000113
114 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
115 BasicBlock *TrueDest,
116 BasicBlock *FalseDest,
117 Instruction *InsertPt);
118
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000119 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000120 void RemoveBlockIfDead(BasicBlock *BB,
121 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000122 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000123 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000124 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000125 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000126}
127
Devang Patel506310d2007-06-06 00:21:03 +0000128LoopPass *llvm::createLoopUnswitchPass(bool Os) {
129 return new LoopUnswitch(Os);
130}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000131
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;
Devang Patel3c723c82007-06-28 00:44:10 +0000138
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000139 // 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
Devang Patel901a27d2007-03-07 00:26:10 +0000158bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000159 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000160 LI = &getAnalysis<LoopInfo>();
161 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000162 bool Changed = false;
163
164 // Loop over all of the basic blocks in the loop. If we find an interior
165 // block that is branching on a loop-invariant condition, we can unswitch this
166 // loop.
167 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
168 I != E; ++I) {
Devang Patel6ba5ad42007-06-28 02:05:46 +0000169 if (*I == L->getHeader())
170 continue;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000171 TerminatorInst *TI = (*I)->getTerminator();
172 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
173 // If this isn't branching on an invariant condition, we can't unswitch
174 // it.
175 if (BI->isConditional()) {
176 // See if this, or some part of it, is loop invariant. If so, we can
177 // unswitch on it if we desire.
178 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000179 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000180 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000181 ++NumBranches;
182 return true;
183 }
184 }
185 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
186 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
187 if (LoopCond && SI->getNumCases() > 1) {
188 // Find a value to unswitch on:
189 // FIXME: this should chose the most expensive case!
190 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000191 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000192 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000193 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000194
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000195 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
196 ++NumSwitches;
197 return true;
198 }
199 }
200 }
201
202 // Scan the instructions to check for unswitchable values.
203 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
204 BBI != E; ++BBI)
205 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
206 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000207 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000208 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000209 ++NumSelects;
210 return true;
211 }
212 }
213 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000214
215 assert(L->isLCSSAForm());
216
Chris Lattnerf48f7772004-04-19 18:07:02 +0000217 return Changed;
218}
219
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000220/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
221/// 1. Exit the loop with no side effects.
222/// 2. Branch to the latch block with no side-effects.
223///
224/// If these conditions are true, we return true and set ExitBB to the block we
225/// exit through.
226///
227static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
228 BasicBlock *&ExitBB,
229 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000230 if (!Visited.insert(BB).second) {
231 // Already visited and Ok, end of recursion.
232 return true;
233 } else if (!L->contains(BB)) {
234 // Otherwise, this is a loop exit, this is fine so long as this is the
235 // first exit.
236 if (ExitBB != 0) return false;
237 ExitBB = BB;
238 return true;
239 }
240
241 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000242 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000243 // Check to see if the successor is a trivial loop exit.
244 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
245 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000246 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000247
248 // Okay, everything after this looks good, check to make sure that this block
249 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000250 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000251 if (I->mayWriteToMemory())
252 return false;
253
254 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000255}
256
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000257/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
258/// leads to an exit from the specified loop, and has no side-effects in the
259/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000260static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
261 std::set<BasicBlock*> Visited;
262 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000263 BasicBlock *ExitBB = 0;
264 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
265 return ExitBB;
266 return 0;
267}
Chris Lattner6e263152006-02-10 02:30:37 +0000268
Chris Lattnered7a67b2006-02-10 01:24:09 +0000269/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
270/// trivial: that is, that the condition controls whether or not the loop does
271/// anything at all. If this is a trivial condition, unswitching produces no
272/// code duplications (equivalently, it produces a simpler loop and a new empty
273/// loop, which gets deleted).
274///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000275/// If this is a trivial condition, return true, otherwise return false. When
276/// returning true, this sets Cond and Val to the condition that controls the
277/// trivial condition: when Cond dynamically equals Val, the loop is known to
278/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
279/// Cond == Val.
280///
281static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000282 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000283 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000284 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000285
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000286 BasicBlock *LoopExitBB = 0;
287 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
288 // If the header block doesn't end with a conditional branch on Cond, we
289 // can't handle it.
290 if (!BI->isConditional() || BI->getCondition() != Cond)
291 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000292
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000293 // Check to see if a successor of the branch is guaranteed to go to the
294 // latch block or exit through a one exit block without having any
295 // side-effects. If so, determine the value of Cond that causes it to do
296 // this.
297 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000298 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000299 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000300 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000301 }
302 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
303 // If this isn't a switch on Cond, we can't handle it.
304 if (SI->getCondition() != Cond) return false;
305
306 // Check to see if a successor of the switch is guaranteed to go to the
307 // latch block or exit through a one exit block without having any
308 // side-effects. If so, determine the value of Cond that causes it to do
309 // this. Note that we can't trivially unswitch on the default case.
310 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
311 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
312 // Okay, we found a trivial case, remember the value that is trivial.
313 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000314 break;
315 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000316 }
317
Chris Lattnere5521db2006-02-22 23:55:00 +0000318 // If we didn't find a single unique LoopExit block, or if the loop exit block
319 // contains phi nodes, this isn't trivial.
320 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000321 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000322
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000323 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000324
325 // We already know that nothing uses any scalar values defined inside of this
326 // loop. As such, we just have to check to see if this loop will execute any
327 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000328 // part of the loop that the code *would* execute. We already checked the
329 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000330 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
331 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000332 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000333 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000334}
335
336/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
337/// we choose to unswitch the specified loop on the specified value.
338///
339unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
340 // If the condition is trivial, always unswitch. There is no code growth for
341 // this case.
342 if (IsTrivialUnswitchCondition(L, LIC))
343 return 0;
344
Owen Anderson18e816f2006-06-28 17:47:50 +0000345 // FIXME: This is really overly conservative. However, more liberal
346 // estimations have thus far resulted in excessive unswitching, which is bad
347 // both in compile time and in code size. This should be replaced once
348 // someone figures out how a good estimation.
349 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000350
Chris Lattnered7a67b2006-02-10 01:24:09 +0000351 unsigned Cost = 0;
352 // FIXME: this is brain dead. It should take into consideration code
353 // shrinkage.
354 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
355 I != E; ++I) {
356 BasicBlock *BB = *I;
357 // Do not include empty blocks in the cost calculation. This happen due to
358 // loop canonicalization and will be removed.
359 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
360 continue;
361
362 // Count basic blocks.
363 ++Cost;
364 }
365
366 return Cost;
367}
368
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000369/// UnswitchIfProfitable - We have found that we can unswitch L when
370/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
371/// unswitch the loop, reprocess the pieces, then return true.
372bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
373 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000374 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000375
376 // Do not do non-trivial unswitch while optimizing for size.
377 if (Cost && OptimizeForSize)
378 return false;
379
Chris Lattner5821a6a2006-03-24 07:14:00 +0000380 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000381 // FIXME: this should estimate growth by the amount of code shared by the
382 // resultant unswitched loops.
383 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000384 DOUT << "NOT unswitching loop %"
385 << L->getHeader()->getName() << ", cost too high: "
386 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 return false;
388 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000389
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000390 // If this is a trivial condition to unswitch (which results in no code
391 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000392 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000393 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000394 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
395 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000396 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000397 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000398 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000399
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000400 return true;
401}
402
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000403/// SplitBlock - Split the specified block at the specified instruction - every
404/// thing before SplitPt stays in Old and everything starting with SplitPt moves
405/// to a new block. The two blocks are joined by an unconditional branch and
406/// the loop info is updated.
407///
408BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattnerfa335f62006-02-16 19:36:22 +0000409 BasicBlock::iterator SplitIt = SplitPt;
410 while (isa<PHINode>(SplitIt))
411 ++SplitIt;
412 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000413
414 // The new block lives in whichever loop the old one did.
415 if (Loop *L = LI->getLoopFor(Old))
416 L->addBasicBlockToLoop(New, *LI);
Devang Patel95572472007-05-09 08:24:12 +0000417
Devang Patel3304e462007-06-28 00:49:00 +0000418 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
419 DT->addNewBlock(New, Old);
420
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000421 return New;
422}
423
424
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000425BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
426 TerminatorInst *LatchTerm = BB->getTerminator();
427 unsigned SuccNum = 0;
428 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
429 assert(i != e && "Didn't find edge?");
430 if (LatchTerm->getSuccessor(i) == Succ) {
431 SuccNum = i;
432 break;
433 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000434 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000435
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000436 // If this is a critical edge, let SplitCriticalEdge do it.
Devang Patel3304e462007-06-28 00:49:00 +0000437 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
438 return LatchTerm->getSuccessor(SuccNum);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000439
440 // If the edge isn't critical, then BB has a single successor or Succ has a
441 // single pred. Split the block.
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000442 BasicBlock::iterator SplitPoint;
443 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
444 // If the successor only has a single pred, split the top of the successor
445 // block.
446 assert(SP == BB && "CFG broken");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000447 return SplitBlock(Succ, Succ->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000448 } else {
449 // Otherwise, if BB has a single successor, split it at the bottom of the
450 // block.
451 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
452 "Should have a single succ!");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000453 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000454 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000455}
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000456
Chris Lattnerf48f7772004-04-19 18:07:02 +0000457
458
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000460// current values into those specified by ValueMap.
461//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000462static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000463 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000464 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
465 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000466 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000467 if (It != ValueMap.end()) Op = It->second;
468 I->setOperand(op, Op);
469 }
470}
471
Devang Patel3304e462007-06-28 00:49:00 +0000472// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
473// If Orig is in Loop then find and use Orig dominator's cloned block as NewBB
474// dominator.
475void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig, Loop *L,
476 DominatorTree *DT,
477 DenseMap<const Value*, Value*> &VM) {
478
479 DomTreeNode *OrigNode = DT->getNode(Orig);
480 if (!OrigNode)
481 return;
482 BasicBlock *OrigIDom = OrigNode->getBlock();
483 BasicBlock *NewIDom = OrigIDom;
484 if (L->contains(OrigIDom)) {
485 if (!DT->getNode(OrigIDom))
486 CloneDomInfo(NewIDom, OrigIDom, L, DT, VM);
487 NewIDom = cast<BasicBlock>(VM[OrigIDom]);
488 }
Devang Patel6ba5ad42007-06-28 02:05:46 +0000489 if (NewBB == NewIDom) {
490 DT->addNewBlock(NewBB, OrigIDom);
491 DT->changeImmediateDominator(NewBB, NewIDom);
492 } else
493 DT->addNewBlock(NewBB, NewIDom);
Devang Patel3304e462007-06-28 00:49:00 +0000494}
495
Chris Lattnerf48f7772004-04-19 18:07:02 +0000496/// CloneLoop - Recursively clone the specified loop and all of its children,
497/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000498static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000499 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000500 Loop *New = new Loop();
501
Devang Patel901a27d2007-03-07 00:26:10 +0000502 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000503
504 // Add all of the blocks in L to the new loop.
505 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
506 I != E; ++I)
507 if (LI->getLoopFor(*I) == L)
508 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
509
510 // Add all of the subloops to the new loop.
511 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000512 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000513
Chris Lattnerf48f7772004-04-19 18:07:02 +0000514 return New;
515}
516
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000517/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
518/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
519/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000520void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
521 BasicBlock *TrueDest,
522 BasicBlock *FalseDest,
523 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000524 // Insert a conditional branch on LIC to the two preheaders. The original
525 // code is the true version and the new code is the false version.
526 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000527 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000528 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000529 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000530 // We want to enter the new loop when the condition is true.
531 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000532
533 // Insert the new branch.
Devang Patel3304e462007-06-28 00:49:00 +0000534 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
535
536 // Update dominator info.
537 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
538 // BranchVal is a new preheader so it dominates true and false destination
539 // loop headers.
540 DT->changeImmediateDominator(TrueDest, BRI->getParent());
541 DT->changeImmediateDominator(FalseDest, BRI->getParent());
542 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000543}
544
545
Chris Lattnered7a67b2006-02-10 01:24:09 +0000546/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
547/// condition in it (a cond branch from its header block to its latch block,
548/// where the path through the loop that doesn't execute its body has no
549/// side-effects), unswitch it. This doesn't involve any code duplication, just
550/// moving the conditional branch outside of the loop and updating loop info.
551void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000552 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000553 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000554 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
555 << L->getHeader()->getName() << " [" << L->getBlocks().size()
556 << " blocks] in Function " << L->getHeader()->getParent()->getName()
557 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000558
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000559 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000560 // to insert the conditional branch. We will change 'OrigPH' to have a
561 // conditional branch on Cond.
562 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000563 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000564
565 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000566 // to branch to: this is the exit block out of the loop that we should
567 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000568
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000569 // Split this block now, so that the loop maintains its exit block, and so
570 // that the jump from the preheader can execute the contents of the exit block
571 // without actually branching to it (the exit block should be dominated by the
572 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000573 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000574 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000575
Chris Lattnered7a67b2006-02-10 01:24:09 +0000576 // Okay, now we have a position to branch from and a position to branch to,
577 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000578 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
579 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000580 OrigPH->getTerminator()->eraseFromParent();
581
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000582 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000583 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000584
Chris Lattnered7a67b2006-02-10 01:24:09 +0000585 // Now that we know that the loop is never entered when this condition is a
586 // particular value, rewrite the loop with this info. We know that this will
587 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000588 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000589 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000590}
591
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000592/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
593/// equal Val. Split it into loop versions and test the condition outside of
594/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000595void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
596 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000597 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000598 DOUT << "loop-unswitch: Unswitching loop %"
599 << L->getHeader()->getName() << " [" << L->getBlocks().size()
600 << " blocks] in Function " << F->getName()
601 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000602
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000603 // LoopBlocks contains all of the basic blocks of the loop, including the
604 // preheader of the loop, the body of the loop, and the exit blocks of the
605 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000606 std::vector<BasicBlock*> LoopBlocks;
607
608 // First step, split the preheader and exit blocks, and add these blocks to
609 // the LoopBlocks list.
610 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000611 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000612
613 // We want the loop to come after the preheader, but before the exit blocks.
614 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
615
616 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000617 L->getUniqueExitBlocks(ExitBlocks);
618
Owen Andersonf52351e2006-06-26 07:44:36 +0000619 // Split all of the edges from inside the loop to their exit blocks. Update
620 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000621 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000622 BasicBlock *ExitBlock = ExitBlocks[i];
623 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
624
625 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Owen Andersonf52351e2006-06-26 07:44:36 +0000626 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
627 BasicBlock* StartBlock = Preds[j];
628 BasicBlock* EndBlock;
629 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
630 EndBlock = MiddleBlock;
631 MiddleBlock = EndBlock->getSinglePredecessor();;
632 } else {
633 EndBlock = ExitBlock;
634 }
635
636 std::set<PHINode*> InsertedPHIs;
637 PHINode* OldLCSSA = 0;
638 for (BasicBlock::iterator I = EndBlock->begin();
639 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
640 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
641 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
642 OldLCSSA->getName() + ".us-lcssa",
643 MiddleBlock->getTerminator());
644 NewLCSSA->addIncoming(OldValue, StartBlock);
645 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
646 NewLCSSA);
647 InsertedPHIs.insert(NewLCSSA);
648 }
649
Owen Anderson00b974c2006-07-19 03:51:48 +0000650 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000651 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
652 for (BasicBlock::iterator I = MiddleBlock->begin();
653 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
654 ++I) {
655 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
656 OldLCSSA->getName() + ".us-lcssa",
657 InsertPt);
658 OldLCSSA->replaceAllUsesWith(NewLCSSA);
659 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
660 }
661 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000662 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000663
664 // The exit blocks may have been changed due to edge splitting, recompute.
665 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000666 L->getUniqueExitBlocks(ExitBlocks);
667
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000668 // Add exit blocks to the loop blocks.
669 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000670
671 // Next step, clone all of the basic blocks that make up the loop (including
672 // the loop preheader and exit blocks), keeping track of the mapping between
673 // the instructions and blocks.
674 std::vector<BasicBlock*> NewBlocks;
675 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000676 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000677 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000678 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
679 NewBlocks.push_back(New);
680 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000681 }
682
Devang Patel3304e462007-06-28 00:49:00 +0000683 // Update dominator info
684 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
685 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
686 BasicBlock *LBB = LoopBlocks[i];
687 BasicBlock *NBB = NewBlocks[i];
688 CloneDomInfo(NBB, LBB, L, DT, ValueMap);
689 }
690
Chris Lattnerf48f7772004-04-19 18:07:02 +0000691 // Splice the newly inserted blocks into the function right before the
692 // original preheader.
693 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
694 NewBlocks[0], F->end());
695
696 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000697 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000698 Loop *ParentLoop = L->getParentLoop();
699 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000700 // Make sure to add the cloned preheader and exit blocks to the parent loop
701 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000702 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
703 }
704
705 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
706 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000707 // The new exit block should be in the same loop as the old one.
708 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
709 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000710
711 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
712 "Exit block should have been split to have one successor!");
713 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
714
715 // If the successor of the exit block had PHI nodes, add an entry for
716 // NewExit.
717 PHINode *PN;
718 for (BasicBlock::iterator I = ExitSucc->begin();
719 (PN = dyn_cast<PHINode>(I)); ++I) {
720 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000721 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000722 if (It != ValueMap.end()) V = It->second;
723 PN->addIncoming(V, NewExit);
724 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000725 }
726
727 // Rewrite the code to refer to itself.
728 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
729 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
730 E = NewBlocks[i]->end(); I != E; ++I)
731 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000732
Chris Lattnerf48f7772004-04-19 18:07:02 +0000733 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000734 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
735 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000736 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000737
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000738 // Emit the new branch that selects between the two versions of this loop.
739 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
740 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000741
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000742 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000743 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000744
745 // Now we rewrite the original code to know that the condition is true and the
746 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000747 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
748
749 // It's possible that simplifying one loop could cause the other to be
750 // deleted. If so, don't simplify it.
751 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
752 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000753}
754
Chris Lattner6fd13622006-02-17 00:31:07 +0000755/// RemoveFromWorklist - Remove all instances of I from the worklist vector
756/// specified.
757static void RemoveFromWorklist(Instruction *I,
758 std::vector<Instruction*> &Worklist) {
759 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
760 Worklist.end(), I);
761 while (WI != Worklist.end()) {
762 unsigned Offset = WI-Worklist.begin();
763 Worklist.erase(WI);
764 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
765 }
766}
767
768/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
769/// program, replacing all uses with V and update the worklist.
770static void ReplaceUsesOfWith(Instruction *I, Value *V,
771 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000772 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000773
774 // Add uses to the worklist, which may be dead now.
775 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
776 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
777 Worklist.push_back(Use);
778
779 // Add users to the worklist which may be simplified now.
780 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
781 UI != E; ++UI)
782 Worklist.push_back(cast<Instruction>(*UI));
783 I->replaceAllUsesWith(V);
784 I->eraseFromParent();
785 RemoveFromWorklist(I, Worklist);
786 ++NumSimplify;
787}
788
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000789/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
790/// information, and remove any dead successors it has.
791///
792void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
793 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000794 if (pred_begin(BB) != pred_end(BB)) {
795 // This block isn't dead, since an edge to BB was just removed, see if there
796 // are any easy simplifications we can do now.
797 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
798 // If it has one pred, fold phi nodes in BB.
799 while (isa<PHINode>(BB->begin()))
800 ReplaceUsesOfWith(BB->begin(),
801 cast<PHINode>(BB->begin())->getIncomingValue(0),
802 Worklist);
803
804 // If this is the header of a loop and the only pred is the latch, we now
805 // have an unreachable loop.
806 if (Loop *L = LI->getLoopFor(BB))
807 if (L->getHeader() == BB && L->contains(Pred)) {
808 // Remove the branch from the latch to the header block, this makes
809 // the header dead, which will make the latch dead (because the header
810 // dominates the latch).
811 Pred->getTerminator()->eraseFromParent();
812 new UnreachableInst(Pred);
813
814 // The loop is now broken, remove it from LI.
815 RemoveLoopFromHierarchy(L);
816
817 // Reprocess the header, which now IS dead.
818 RemoveBlockIfDead(BB, Worklist);
819 return;
820 }
821
822 // If pred ends in a uncond branch, add uncond branch to worklist so that
823 // the two blocks will get merged.
824 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
825 if (BI->isUnconditional())
826 Worklist.push_back(BI);
827 }
828 return;
829 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000830
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000831 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000832
833 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000834 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000835 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000836
837 // Anything that uses the instructions in this basic block should have their
838 // uses replaced with undefs.
839 if (!I->use_empty())
840 I->replaceAllUsesWith(UndefValue::get(I->getType()));
841 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000842
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000843 // If this is the edge to the header block for a loop, remove the loop and
844 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000845 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000846 if (BBLoop->getLoopLatch() == BB)
847 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000848 }
849
850 // Remove the block from the loop info, which removes it from any loops it
851 // was in.
852 LI->removeBlock(BB);
853
854
855 // Remove phi node entries in successors for this block.
856 TerminatorInst *TI = BB->getTerminator();
857 std::vector<BasicBlock*> Succs;
858 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
859 Succs.push_back(TI->getSuccessor(i));
860 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000861 }
862
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000863 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000864 std::sort(Succs.begin(), Succs.end());
865 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
866
867 // Remove the basic block, including all of the instructions contained in it.
868 BB->eraseFromParent();
869
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000870 // Remove successor blocks here that are not dead, so that we know we only
871 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
872 // then getting removed before we revisit them, which is badness.
873 //
874 for (unsigned i = 0; i != Succs.size(); ++i)
875 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
876 // One exception is loop headers. If this block was the preheader for a
877 // loop, then we DO want to visit the loop so the loop gets deleted.
878 // We know that if the successor is a loop header, that this loop had to
879 // be the preheader: the case where this was the latch block was handled
880 // above and headers can only have two predecessors.
881 if (!LI->isLoopHeader(Succs[i])) {
882 Succs.erase(Succs.begin()+i);
883 --i;
884 }
885 }
886
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000887 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
888 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000889}
Chris Lattner6fd13622006-02-17 00:31:07 +0000890
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000891/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
892/// become unwrapped, either because the backedge was deleted, or because the
893/// edge into the header was removed. If the edge into the header from the
894/// latch block was removed, the loop is unwrapped but subloops are still alive,
895/// so they just reparent loops. If the loops are actually dead, they will be
896/// removed later.
897void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000898 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000899 RemoveLoopFromWorklist(L);
900}
901
902
903
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000904// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
905// the value specified by Val in the specified loop, or we know it does NOT have
906// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000907void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000908 Constant *Val,
909 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000910 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000911
Chris Lattnerf48f7772004-04-19 18:07:02 +0000912 // FIXME: Support correlated properties, like:
913 // for (...)
914 // if (li1 < li2)
915 // ...
916 // if (li1 > li2)
917 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000918
Chris Lattner6e263152006-02-10 02:30:37 +0000919 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
920 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000921 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000922 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000923
Chris Lattner6fd13622006-02-17 00:31:07 +0000924 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
925 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000926 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000927 Value *Replacement;
928 if (IsEqual)
929 Replacement = Val;
930 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000931 Replacement = ConstantInt::get(Type::Int1Ty,
932 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000933
934 for (unsigned i = 0, e = Users.size(); i != e; ++i)
935 if (Instruction *U = cast<Instruction>(Users[i])) {
936 if (!L->contains(U->getParent()))
937 continue;
938 U->replaceUsesOfWith(LIC, Replacement);
939 Worklist.push_back(U);
940 }
941 } else {
942 // Otherwise, we don't know the precise value of LIC, but we do know that it
943 // is certainly NOT "Val". As such, simplify any uses in the loop that we
944 // can. This case occurs when we unswitch switch statements.
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
950 Worklist.push_back(U);
951
Chris Lattnerfa335f62006-02-16 19:36:22 +0000952 // If we know that LIC is not Val, use this info to simplify code.
953 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
954 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
955 if (SI->getCaseValue(i) == Val) {
956 // Found a dead case value. Don't remove PHI nodes in the
957 // successor if they become single-entry, those PHI nodes may
958 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000959
960 // FIXME: This is a hack. We need to keep the successor around
961 // and hooked up so as to preserve the loop structure, because
962 // trying to update it is complicated. So instead we preserve the
963 // loop structure and put the block on an dead code path.
964
965 BasicBlock* Old = SI->getParent();
966 BasicBlock* Split = SplitBlock(Old, SI);
967
968 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000969 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000970 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000971
972 Old->getTerminator()->eraseFromParent();
973
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000974
975 PHINode *PN;
976 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
977 (PN = dyn_cast<PHINode>(II)); ++II) {
978 Value *InVal = PN->removeIncomingValue(Split, false);
979 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000980 }
981
Chris Lattnerfa335f62006-02-16 19:36:22 +0000982 SI->removeCase(i);
983 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000984 }
985 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000986 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000987
988 // TODO: We could do other simplifications, for example, turning
989 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000990 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000991 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000992
993 SimplifyCode(Worklist);
994}
995
996/// SimplifyCode - Okay, now that we have simplified some instructions in the
997/// loop, walk over it and constant prop, dce, and fold control flow where
998/// possible. Note that this is effectively a very simple loop-structure-aware
999/// optimizer. During processing of this loop, L could very well be deleted, so
1000/// it must not be used.
1001///
1002/// FIXME: When the loop optimizer is more mature, separate this out to a new
1003/// pass.
1004///
1005void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001006 while (!Worklist.empty()) {
1007 Instruction *I = Worklist.back();
1008 Worklist.pop_back();
1009
1010 // Simple constant folding.
1011 if (Constant *C = ConstantFoldInstruction(I)) {
1012 ReplaceUsesOfWith(I, C, Worklist);
1013 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001014 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001015
1016 // Simple DCE.
1017 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001018 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001019
1020 // Add uses to the worklist, which may be dead now.
1021 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1022 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1023 Worklist.push_back(Use);
1024 I->eraseFromParent();
1025 RemoveFromWorklist(I, Worklist);
1026 ++NumSimplify;
1027 continue;
1028 }
1029
1030 // Special case hacks that appear commonly in unswitched code.
1031 switch (I->getOpcode()) {
1032 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001033 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001034 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001035 continue;
1036 }
1037 break;
1038 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001039 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001040 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001041 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001042 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001043 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001044 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001045 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1046 else // X & 0 -> 0
1047 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1048 continue;
1049 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001050 break;
1051 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001052 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001053 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001054 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001055 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001056 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001057 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001058 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1059 else // X | 0 -> X
1060 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1061 continue;
1062 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001063 break;
1064 case Instruction::Br: {
1065 BranchInst *BI = cast<BranchInst>(I);
1066 if (BI->isUnconditional()) {
1067 // If BI's parent is the only pred of the successor, fold the two blocks
1068 // together.
1069 BasicBlock *Pred = BI->getParent();
1070 BasicBlock *Succ = BI->getSuccessor(0);
1071 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1072 if (!SinglePred) continue; // Nothing to do.
1073 assert(SinglePred == Pred && "CFG broken");
1074
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001075 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1076 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001077
1078 // Resolve any single entry PHI nodes in Succ.
1079 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1080 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1081
1082 // Move all of the successor contents from Succ to Pred.
1083 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1084 Succ->end());
1085 BI->eraseFromParent();
1086 RemoveFromWorklist(BI, Worklist);
1087
1088 // If Succ has any successors with PHI nodes, update them to have
1089 // entries coming from Pred instead of Succ.
1090 Succ->replaceAllUsesWith(Pred);
1091
1092 // Remove Succ from the loop tree.
1093 LI->removeBlock(Succ);
1094 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001095 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001096 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001097 // Conditional branch. Turn it into an unconditional branch, then
1098 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001099 break; // FIXME: Enable.
1100
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001101 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001102 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1103 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001104 DeadSucc->removePredecessor(BI->getParent(), true);
1105 Worklist.push_back(new BranchInst(LiveSucc, BI));
1106 BI->eraseFromParent();
1107 RemoveFromWorklist(BI, Worklist);
1108 ++NumSimplify;
1109
1110 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001111 }
1112 break;
1113 }
1114 }
1115 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001116}