blob: 3ef6376899a51e1678bb40563650e867eddb18bb [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);
Chris Lattnerf48f7772004-04-19 18:07:02 +000086 AU.addRequired<LoopInfo>();
87 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000088 AU.addRequiredID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000089 }
90
91 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000092 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
93 /// remove it.
94 void RemoveLoopFromWorklist(Loop *L) {
95 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
96 LoopProcessWorklist.end(), L);
97 if (I != LoopProcessWorklist.end())
98 LoopProcessWorklist.erase(I);
99 }
100
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000101 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000102 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000103 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000104 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000105 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000106
107 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
108 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000109
110 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
111 BasicBlock *TrueDest,
112 BasicBlock *FalseDest,
113 Instruction *InsertPt);
114
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000115 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000116 void RemoveBlockIfDead(BasicBlock *BB,
117 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000118 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000119 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000120 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000121 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000122}
123
Devang Patel506310d2007-06-06 00:21:03 +0000124LoopPass *llvm::createLoopUnswitchPass(bool Os) {
125 return new LoopUnswitch(Os);
126}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000127
128/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
129/// invariant in the loop, or has an invariant piece, return the invariant.
130/// Otherwise, return null.
131static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
132 // Constants should be folded, not unswitched on!
133 if (isa<Constant>(Cond)) return false;
Devang Patel3c723c82007-06-28 00:44:10 +0000134
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000135 // TODO: Handle: br (VARIANT|INVARIANT).
136 // TODO: Hoist simple expressions out of loops.
137 if (L->isLoopInvariant(Cond)) return Cond;
138
139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
140 if (BO->getOpcode() == Instruction::And ||
141 BO->getOpcode() == Instruction::Or) {
142 // If either the left or right side is invariant, we can unswitch on this,
143 // which will cause the branch to go away in one loop and the condition to
144 // simplify in the other one.
145 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
146 return LHS;
147 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
148 return RHS;
149 }
150
151 return 0;
152}
153
Devang Patel901a27d2007-03-07 00:26:10 +0000154bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000155 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000156 LI = &getAnalysis<LoopInfo>();
157 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000158 bool Changed = false;
159
160 // Loop over all of the basic blocks in the loop. If we find an interior
161 // block that is branching on a loop-invariant condition, we can unswitch this
162 // loop.
163 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
164 I != E; ++I) {
165 TerminatorInst *TI = (*I)->getTerminator();
166 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
167 // If this isn't branching on an invariant condition, we can't unswitch
168 // it.
169 if (BI->isConditional()) {
170 // See if this, or some part of it, is loop invariant. If so, we can
171 // unswitch on it if we desire.
172 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000173 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000174 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000175 ++NumBranches;
176 return true;
177 }
178 }
179 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
180 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
181 if (LoopCond && SI->getNumCases() > 1) {
182 // Find a value to unswitch on:
183 // FIXME: this should chose the most expensive case!
184 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000185 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000186 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000187 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000188
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000189 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
190 ++NumSwitches;
191 return true;
192 }
193 }
194 }
195
196 // Scan the instructions to check for unswitchable values.
197 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
198 BBI != E; ++BBI)
199 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
200 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000201 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000202 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000203 ++NumSelects;
204 return true;
205 }
206 }
207 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000208
209 assert(L->isLCSSAForm());
210
Chris Lattnerf48f7772004-04-19 18:07:02 +0000211 return Changed;
212}
213
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000214/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
215/// 1. Exit the loop with no side effects.
216/// 2. Branch to the latch block with no side-effects.
217///
218/// If these conditions are true, we return true and set ExitBB to the block we
219/// exit through.
220///
221static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
222 BasicBlock *&ExitBB,
223 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000224 if (!Visited.insert(BB).second) {
225 // Already visited and Ok, end of recursion.
226 return true;
227 } else if (!L->contains(BB)) {
228 // Otherwise, this is a loop exit, this is fine so long as this is the
229 // first exit.
230 if (ExitBB != 0) return false;
231 ExitBB = BB;
232 return true;
233 }
234
235 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000236 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000237 // Check to see if the successor is a trivial loop exit.
238 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
239 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000240 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000241
242 // Okay, everything after this looks good, check to make sure that this block
243 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000245 if (I->mayWriteToMemory())
246 return false;
247
248 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000249}
250
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000251/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
252/// leads to an exit from the specified loop, and has no side-effects in the
253/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000254static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
255 std::set<BasicBlock*> Visited;
256 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000257 BasicBlock *ExitBB = 0;
258 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
259 return ExitBB;
260 return 0;
261}
Chris Lattner6e263152006-02-10 02:30:37 +0000262
Chris Lattnered7a67b2006-02-10 01:24:09 +0000263/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
264/// trivial: that is, that the condition controls whether or not the loop does
265/// anything at all. If this is a trivial condition, unswitching produces no
266/// code duplications (equivalently, it produces a simpler loop and a new empty
267/// loop, which gets deleted).
268///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000269/// If this is a trivial condition, return true, otherwise return false. When
270/// returning true, this sets Cond and Val to the condition that controls the
271/// trivial condition: when Cond dynamically equals Val, the loop is known to
272/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
273/// Cond == Val.
274///
275static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000276 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000277 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000278 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000279
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000280 BasicBlock *LoopExitBB = 0;
281 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
282 // If the header block doesn't end with a conditional branch on Cond, we
283 // can't handle it.
284 if (!BI->isConditional() || BI->getCondition() != Cond)
285 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000286
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000287 // Check to see if a successor of the branch is guaranteed to go to the
288 // latch block or exit through a one exit block without having any
289 // side-effects. If so, determine the value of Cond that causes it to do
290 // this.
291 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000292 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000293 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000294 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000295 }
296 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
297 // If this isn't a switch on Cond, we can't handle it.
298 if (SI->getCondition() != Cond) return false;
299
300 // Check to see if a successor of the switch is guaranteed to go to the
301 // latch block or exit through a one exit block without having any
302 // side-effects. If so, determine the value of Cond that causes it to do
303 // this. Note that we can't trivially unswitch on the default case.
304 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
305 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
306 // Okay, we found a trivial case, remember the value that is trivial.
307 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000308 break;
309 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000310 }
311
Chris Lattnere5521db2006-02-22 23:55:00 +0000312 // If we didn't find a single unique LoopExit block, or if the loop exit block
313 // contains phi nodes, this isn't trivial.
314 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000315 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000316
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000317 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000318
319 // We already know that nothing uses any scalar values defined inside of this
320 // loop. As such, we just have to check to see if this loop will execute any
321 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000322 // part of the loop that the code *would* execute. We already checked the
323 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000324 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
325 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000326 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000327 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000328}
329
330/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
331/// we choose to unswitch the specified loop on the specified value.
332///
333unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
334 // If the condition is trivial, always unswitch. There is no code growth for
335 // this case.
336 if (IsTrivialUnswitchCondition(L, LIC))
337 return 0;
338
Owen Anderson18e816f2006-06-28 17:47:50 +0000339 // FIXME: This is really overly conservative. However, more liberal
340 // estimations have thus far resulted in excessive unswitching, which is bad
341 // both in compile time and in code size. This should be replaced once
342 // someone figures out how a good estimation.
343 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000344
Chris Lattnered7a67b2006-02-10 01:24:09 +0000345 unsigned Cost = 0;
346 // FIXME: this is brain dead. It should take into consideration code
347 // shrinkage.
348 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
349 I != E; ++I) {
350 BasicBlock *BB = *I;
351 // Do not include empty blocks in the cost calculation. This happen due to
352 // loop canonicalization and will be removed.
353 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
354 continue;
355
356 // Count basic blocks.
357 ++Cost;
358 }
359
360 return Cost;
361}
362
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000363/// UnswitchIfProfitable - We have found that we can unswitch L when
364/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
365/// unswitch the loop, reprocess the pieces, then return true.
366bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
367 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000368 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000369
370 // Do not do non-trivial unswitch while optimizing for size.
371 if (Cost && OptimizeForSize)
372 return false;
373
Chris Lattner5821a6a2006-03-24 07:14:00 +0000374 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000375 // FIXME: this should estimate growth by the amount of code shared by the
376 // resultant unswitched loops.
377 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000378 DOUT << "NOT unswitching loop %"
379 << L->getHeader()->getName() << ", cost too high: "
380 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000381 return false;
382 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000383
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000384 // If this is a trivial condition to unswitch (which results in no code
385 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000386 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000388 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
389 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000390 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000391 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000392 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000393
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000394 return true;
395}
396
Misha Brukmanb1c93172005-04-21 23:48:37 +0000397// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000398// current values into those specified by ValueMap.
399//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000400static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000401 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000402 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
403 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000404 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000405 if (It != ValueMap.end()) Op = It->second;
406 I->setOperand(op, Op);
407 }
408}
409
Devang Patel3304e462007-06-28 00:49:00 +0000410// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000411//
412// If Orig block's immediate dominator is mapped in VM then use corresponding
413// immediate dominator from the map. Otherwise Orig block's dominator is also
414// NewBB's dominator.
415//
Devang Patel8a1d1ac2007-07-18 23:50:19 +0000416// OrigPreheader is loop pre-header before this pass started
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000417// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel8a1d1ac2007-07-18 23:50:19 +0000418// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000419void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
420 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
421 BasicBlock *OrigHeader,
Devang Patel0975c6d2007-06-29 23:11:49 +0000422 DominatorTree *DT, DominanceFrontier *DF,
Devang Patel3304e462007-06-28 00:49:00 +0000423 DenseMap<const Value*, Value*> &VM) {
424
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000425 // If NewBB alreay has found its place in domiantor tree then no need to do
426 // anything.
427 if (DT->getNode(NewBB))
428 return;
429
430 // If Orig does not have any immediate domiantor then its clone, NewBB, does
431 // not need any immediate dominator.
Devang Patel3304e462007-06-28 00:49:00 +0000432 DomTreeNode *OrigNode = DT->getNode(Orig);
433 if (!OrigNode)
434 return;
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000435 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
436 if (!OrigIDomNode)
437 return;
438
439 BasicBlock *OrigIDom = NULL;
440
441 // If Orig is original loop header then its immediate dominator is
442 // NewPreheader.
443 if (Orig == OrigHeader)
444 OrigIDom = NewPreheader;
445
446 // If Orig is new pre-header then its immediate dominator is
447 // original pre-header.
448 else if (Orig == NewPreheader)
449 OrigIDom = OrigPreheader;
450
451 // Other as DT to find Orig's immediate dominator.
452 else
453 OrigIDom = OrigIDomNode->getBlock();
454
455 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
456 BasicBlock *NewIDom = OrigIDom;
457 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
458 if (I != VM.end()) {
459 // if (!DT->getNode(OrigIDom))
460 // CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
461 // OrigHeader, DT, DF, VM);
462
463 NewIDom = cast<BasicBlock>(I->second);
464
465 // If NewIDom does not have corresponding dominatore tree node then
466 // get one.
467 if (!DT->getNode(NewIDom))
468 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
469 OrigHeader, DT, DF, VM);
Devang Patel3304e462007-06-28 00:49:00 +0000470 }
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000471 // if (NewBB == NewIDom) {
472 // DT->addNewBlock(NewBB, OrigIDom);
473 // DT->changeImmediateDominator(NewBB, NewIDom);
474 //} else
Devang Patel6ba5ad42007-06-28 02:05:46 +0000475 DT->addNewBlock(NewBB, NewIDom);
Devang Patel0975c6d2007-06-29 23:11:49 +0000476
477 DominanceFrontier::DomSetType NewDFSet;
478 if (DF) {
479 DominanceFrontier::iterator DFI = DF->find(Orig);
480 if ( DFI != DF->end()) {
481 DominanceFrontier::DomSetType S = DFI->second;
482 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
483 I != E; ++I) {
484 BasicBlock *BB = *I;
Chuck Rose III1a39a2d12007-07-27 18:26:35 +0000485 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
486 if (IDM != VM.end())
487 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patel0975c6d2007-06-29 23:11:49 +0000488 else
489 NewDFSet.insert(BB);
490 }
491 }
492 DF->addBasicBlock(NewBB, NewDFSet);
493 }
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.
Devang Patel0975c6d2007-06-29 23:11:49 +0000537 // BranchVal is a new preheader so it dominates true and false destination
538 // loop headers.
Devang Patel3304e462007-06-28 00:49:00 +0000539 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Devang Patel3304e462007-06-28 00:49:00 +0000540 DT->changeImmediateDominator(TrueDest, BRI->getParent());
541 DT->changeImmediateDominator(FalseDest, BRI->getParent());
542 }
Devang Patel0975c6d2007-06-29 23:11:49 +0000543 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
544 // and FalseDest anyway. Now it immediately dominates them.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000545}
546
547
Chris Lattnered7a67b2006-02-10 01:24:09 +0000548/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
549/// condition in it (a cond branch from its header block to its latch block,
550/// where the path through the loop that doesn't execute its body has no
551/// side-effects), unswitch it. This doesn't involve any code duplication, just
552/// moving the conditional branch outside of the loop and updating loop info.
553void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000554 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000555 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000556 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
557 << L->getHeader()->getName() << " [" << L->getBlocks().size()
558 << " blocks] in Function " << L->getHeader()->getParent()->getName()
559 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000560
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000561 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000562 // to insert the conditional branch. We will change 'OrigPH' to have a
563 // conditional branch on Cond.
564 BasicBlock *OrigPH = L->getLoopPreheader();
Devang Patel12358b42007-07-06 22:03:47 +0000565 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000566
567 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000568 // to branch to: this is the exit block out of the loop that we should
569 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000570
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000571 // Split this block now, so that the loop maintains its exit block, and so
572 // that the jump from the preheader can execute the contents of the exit block
573 // without actually branching to it (the exit block should be dominated by the
574 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000575 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel12358b42007-07-06 22:03:47 +0000576 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000577
Chris Lattnered7a67b2006-02-10 01:24:09 +0000578 // Okay, now we have a position to branch from and a position to branch to,
579 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000580 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
581 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000582 OrigPH->getTerminator()->eraseFromParent();
583
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000584 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000585 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000586
Chris Lattnered7a67b2006-02-10 01:24:09 +0000587 // Now that we know that the loop is never entered when this condition is a
588 // particular value, rewrite the loop with this info. We know that this will
589 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000590 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000591 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000592}
593
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000594/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
595/// equal Val. Split it into loop versions and test the condition outside of
596/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000597void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
598 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000599 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000600 DOUT << "loop-unswitch: Unswitching loop %"
601 << L->getHeader()->getName() << " [" << L->getBlocks().size()
602 << " blocks] in Function " << F->getName()
603 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000604
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000605 // LoopBlocks contains all of the basic blocks of the loop, including the
606 // preheader of the loop, the body of the loop, and the exit blocks of the
607 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000608 std::vector<BasicBlock*> LoopBlocks;
609
610 // First step, split the preheader and exit blocks, and add these blocks to
611 // the LoopBlocks list.
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000612 BasicBlock *OrigHeader = L->getHeader();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000613 BasicBlock *OrigPreheader = L->getLoopPreheader();
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000614 BasicBlock *NewPreheader = SplitEdge(OrigPreheader, L->getHeader(), this);
615 LoopBlocks.push_back(NewPreheader);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000616
617 // We want the loop to come after the preheader, but before the exit blocks.
618 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
619
620 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000621 L->getUniqueExitBlocks(ExitBlocks);
622
Owen Andersonf52351e2006-06-26 07:44:36 +0000623 // Split all of the edges from inside the loop to their exit blocks. Update
624 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000625 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000626 BasicBlock *ExitBlock = ExitBlocks[i];
627 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
628
629 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel12358b42007-07-06 22:03:47 +0000630 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Owen Andersonf52351e2006-06-26 07:44:36 +0000631 BasicBlock* StartBlock = Preds[j];
632 BasicBlock* EndBlock;
633 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
634 EndBlock = MiddleBlock;
635 MiddleBlock = EndBlock->getSinglePredecessor();;
636 } else {
637 EndBlock = ExitBlock;
638 }
639
640 std::set<PHINode*> InsertedPHIs;
641 PHINode* OldLCSSA = 0;
642 for (BasicBlock::iterator I = EndBlock->begin();
643 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
644 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
645 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
646 OldLCSSA->getName() + ".us-lcssa",
647 MiddleBlock->getTerminator());
648 NewLCSSA->addIncoming(OldValue, StartBlock);
649 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
650 NewLCSSA);
651 InsertedPHIs.insert(NewLCSSA);
652 }
653
Owen Anderson00b974c2006-07-19 03:51:48 +0000654 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000655 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
656 for (BasicBlock::iterator I = MiddleBlock->begin();
657 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
658 ++I) {
659 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
660 OldLCSSA->getName() + ".us-lcssa",
661 InsertPt);
662 OldLCSSA->replaceAllUsesWith(NewLCSSA);
663 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
664 }
665 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000666 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000667
668 // The exit blocks may have been changed due to edge splitting, recompute.
669 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000670 L->getUniqueExitBlocks(ExitBlocks);
671
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000672 // Add exit blocks to the loop blocks.
673 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000674
675 // Next step, clone all of the basic blocks that make up the loop (including
676 // the loop preheader and exit blocks), keeping track of the mapping between
677 // the instructions and blocks.
678 std::vector<BasicBlock*> NewBlocks;
679 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000680 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000681 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000682 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
683 NewBlocks.push_back(New);
684 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000685 }
686
Devang Patel3304e462007-06-28 00:49:00 +0000687 // Update dominator info
Devang Patel0975c6d2007-06-29 23:11:49 +0000688 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patel3304e462007-06-28 00:49:00 +0000689 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
690 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
691 BasicBlock *LBB = LoopBlocks[i];
692 BasicBlock *NBB = NewBlocks[i];
Devang Patelbb8ea8c2007-07-18 23:48:20 +0000693 CloneDomInfo(NBB, LBB, NewPreheader, OrigPreheader,
694 OrigHeader, DT, DF, ValueMap);
Devang Patel3304e462007-06-28 00:49:00 +0000695 }
696
Chris Lattnerf48f7772004-04-19 18:07:02 +0000697 // Splice the newly inserted blocks into the function right before the
698 // original preheader.
699 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
700 NewBlocks[0], F->end());
701
702 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000703 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000704 Loop *ParentLoop = L->getParentLoop();
705 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000706 // Make sure to add the cloned preheader and exit blocks to the parent loop
707 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000708 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
709 }
710
711 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
712 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000713 // The new exit block should be in the same loop as the old one.
714 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
715 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000716
717 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
718 "Exit block should have been split to have one successor!");
719 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
720
721 // If the successor of the exit block had PHI nodes, add an entry for
722 // NewExit.
723 PHINode *PN;
724 for (BasicBlock::iterator I = ExitSucc->begin();
725 (PN = dyn_cast<PHINode>(I)); ++I) {
726 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000727 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000728 if (It != ValueMap.end()) V = It->second;
729 PN->addIncoming(V, NewExit);
730 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000731 }
732
733 // Rewrite the code to refer to itself.
734 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
735 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
736 E = NewBlocks[i]->end(); I != E; ++I)
737 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000738
Chris Lattnerf48f7772004-04-19 18:07:02 +0000739 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000740 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
741 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000742 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000743
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000744 // Emit the new branch that selects between the two versions of this loop.
745 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
746 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000747
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000748 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000749 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000750
751 // Now we rewrite the original code to know that the condition is true and the
752 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000753 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
754
755 // It's possible that simplifying one loop could cause the other to be
756 // deleted. If so, don't simplify it.
757 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
758 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000759}
760
Chris Lattner6fd13622006-02-17 00:31:07 +0000761/// RemoveFromWorklist - Remove all instances of I from the worklist vector
762/// specified.
763static void RemoveFromWorklist(Instruction *I,
764 std::vector<Instruction*> &Worklist) {
765 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
766 Worklist.end(), I);
767 while (WI != Worklist.end()) {
768 unsigned Offset = WI-Worklist.begin();
769 Worklist.erase(WI);
770 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
771 }
772}
773
774/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
775/// program, replacing all uses with V and update the worklist.
776static void ReplaceUsesOfWith(Instruction *I, Value *V,
777 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000778 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000779
780 // Add uses to the worklist, which may be dead now.
781 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
782 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
783 Worklist.push_back(Use);
784
785 // Add users to the worklist which may be simplified now.
786 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
787 UI != E; ++UI)
788 Worklist.push_back(cast<Instruction>(*UI));
789 I->replaceAllUsesWith(V);
790 I->eraseFromParent();
791 RemoveFromWorklist(I, Worklist);
792 ++NumSimplify;
793}
794
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000795/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
796/// information, and remove any dead successors it has.
797///
798void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
799 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000800 if (pred_begin(BB) != pred_end(BB)) {
801 // This block isn't dead, since an edge to BB was just removed, see if there
802 // are any easy simplifications we can do now.
803 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
804 // If it has one pred, fold phi nodes in BB.
805 while (isa<PHINode>(BB->begin()))
806 ReplaceUsesOfWith(BB->begin(),
807 cast<PHINode>(BB->begin())->getIncomingValue(0),
808 Worklist);
809
810 // If this is the header of a loop and the only pred is the latch, we now
811 // have an unreachable loop.
812 if (Loop *L = LI->getLoopFor(BB))
813 if (L->getHeader() == BB && L->contains(Pred)) {
814 // Remove the branch from the latch to the header block, this makes
815 // the header dead, which will make the latch dead (because the header
816 // dominates the latch).
817 Pred->getTerminator()->eraseFromParent();
818 new UnreachableInst(Pred);
819
820 // The loop is now broken, remove it from LI.
821 RemoveLoopFromHierarchy(L);
822
823 // Reprocess the header, which now IS dead.
824 RemoveBlockIfDead(BB, Worklist);
825 return;
826 }
827
828 // If pred ends in a uncond branch, add uncond branch to worklist so that
829 // the two blocks will get merged.
830 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
831 if (BI->isUnconditional())
832 Worklist.push_back(BI);
833 }
834 return;
835 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000836
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000837 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000838
839 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000840 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000841 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000842
843 // Anything that uses the instructions in this basic block should have their
844 // uses replaced with undefs.
845 if (!I->use_empty())
846 I->replaceAllUsesWith(UndefValue::get(I->getType()));
847 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000848
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000849 // If this is the edge to the header block for a loop, remove the loop and
850 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000851 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000852 if (BBLoop->getLoopLatch() == BB)
853 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000854 }
855
856 // Remove the block from the loop info, which removes it from any loops it
857 // was in.
858 LI->removeBlock(BB);
859
860
861 // Remove phi node entries in successors for this block.
862 TerminatorInst *TI = BB->getTerminator();
863 std::vector<BasicBlock*> Succs;
864 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
865 Succs.push_back(TI->getSuccessor(i));
866 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000867 }
868
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000869 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000870 std::sort(Succs.begin(), Succs.end());
871 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
872
873 // Remove the basic block, including all of the instructions contained in it.
874 BB->eraseFromParent();
875
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000876 // Remove successor blocks here that are not dead, so that we know we only
877 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
878 // then getting removed before we revisit them, which is badness.
879 //
880 for (unsigned i = 0; i != Succs.size(); ++i)
881 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
882 // One exception is loop headers. If this block was the preheader for a
883 // loop, then we DO want to visit the loop so the loop gets deleted.
884 // We know that if the successor is a loop header, that this loop had to
885 // be the preheader: the case where this was the latch block was handled
886 // above and headers can only have two predecessors.
887 if (!LI->isLoopHeader(Succs[i])) {
888 Succs.erase(Succs.begin()+i);
889 --i;
890 }
891 }
892
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000893 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
894 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000895}
Chris Lattner6fd13622006-02-17 00:31:07 +0000896
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000897/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
898/// become unwrapped, either because the backedge was deleted, or because the
899/// edge into the header was removed. If the edge into the header from the
900/// latch block was removed, the loop is unwrapped but subloops are still alive,
901/// so they just reparent loops. If the loops are actually dead, they will be
902/// removed later.
903void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000904 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000905 RemoveLoopFromWorklist(L);
906}
907
908
909
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000910// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
911// the value specified by Val in the specified loop, or we know it does NOT have
912// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000913void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000914 Constant *Val,
915 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000916 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000917
Chris Lattnerf48f7772004-04-19 18:07:02 +0000918 // FIXME: Support correlated properties, like:
919 // for (...)
920 // if (li1 < li2)
921 // ...
922 // if (li1 > li2)
923 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000924
Chris Lattner6e263152006-02-10 02:30:37 +0000925 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
926 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000927 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000928 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000929
Chris Lattner6fd13622006-02-17 00:31:07 +0000930 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
931 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000932 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000933 Value *Replacement;
934 if (IsEqual)
935 Replacement = Val;
936 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000937 Replacement = ConstantInt::get(Type::Int1Ty,
938 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000939
940 for (unsigned i = 0, e = Users.size(); i != e; ++i)
941 if (Instruction *U = cast<Instruction>(Users[i])) {
942 if (!L->contains(U->getParent()))
943 continue;
944 U->replaceUsesOfWith(LIC, Replacement);
945 Worklist.push_back(U);
946 }
947 } else {
948 // Otherwise, we don't know the precise value of LIC, but we do know that it
949 // is certainly NOT "Val". As such, simplify any uses in the loop that we
950 // can. This case occurs when we unswitch switch statements.
951 for (unsigned i = 0, e = Users.size(); i != e; ++i)
952 if (Instruction *U = cast<Instruction>(Users[i])) {
953 if (!L->contains(U->getParent()))
954 continue;
955
956 Worklist.push_back(U);
957
Chris Lattnerfa335f62006-02-16 19:36:22 +0000958 // If we know that LIC is not Val, use this info to simplify code.
959 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
960 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
961 if (SI->getCaseValue(i) == Val) {
962 // Found a dead case value. Don't remove PHI nodes in the
963 // successor if they become single-entry, those PHI nodes may
964 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000965
966 // FIXME: This is a hack. We need to keep the successor around
967 // and hooked up so as to preserve the loop structure, because
968 // trying to update it is complicated. So instead we preserve the
969 // loop structure and put the block on an dead code path.
970
971 BasicBlock* Old = SI->getParent();
Devang Patel12358b42007-07-06 22:03:47 +0000972 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Andersonf52351e2006-06-26 07:44:36 +0000973
974 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000975 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000976 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000977
978 Old->getTerminator()->eraseFromParent();
979
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000980
981 PHINode *PN;
982 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
983 (PN = dyn_cast<PHINode>(II)); ++II) {
984 Value *InVal = PN->removeIncomingValue(Split, false);
985 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000986 }
987
Chris Lattnerfa335f62006-02-16 19:36:22 +0000988 SI->removeCase(i);
989 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000990 }
991 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000992 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000993
994 // TODO: We could do other simplifications, for example, turning
995 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000996 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000997 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000998
999 SimplifyCode(Worklist);
1000}
1001
1002/// SimplifyCode - Okay, now that we have simplified some instructions in the
1003/// loop, walk over it and constant prop, dce, and fold control flow where
1004/// possible. Note that this is effectively a very simple loop-structure-aware
1005/// optimizer. During processing of this loop, L could very well be deleted, so
1006/// it must not be used.
1007///
1008/// FIXME: When the loop optimizer is more mature, separate this out to a new
1009/// pass.
1010///
1011void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001012 while (!Worklist.empty()) {
1013 Instruction *I = Worklist.back();
1014 Worklist.pop_back();
1015
1016 // Simple constant folding.
1017 if (Constant *C = ConstantFoldInstruction(I)) {
1018 ReplaceUsesOfWith(I, C, Worklist);
1019 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +00001020 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001021
1022 // Simple DCE.
1023 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001024 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +00001025
1026 // Add uses to the worklist, which may be dead now.
1027 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1028 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1029 Worklist.push_back(Use);
1030 I->eraseFromParent();
1031 RemoveFromWorklist(I, Worklist);
1032 ++NumSimplify;
1033 continue;
1034 }
1035
1036 // Special case hacks that appear commonly in unswitched code.
1037 switch (I->getOpcode()) {
1038 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001039 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001040 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001041 continue;
1042 }
1043 break;
1044 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001045 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001046 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001047 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001048 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001049 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001050 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001051 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1052 else // X & 0 -> 0
1053 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1054 continue;
1055 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001056 break;
1057 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001058 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001059 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001060 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001061 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001062 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001063 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001064 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1065 else // X | 0 -> X
1066 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1067 continue;
1068 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001069 break;
1070 case Instruction::Br: {
1071 BranchInst *BI = cast<BranchInst>(I);
1072 if (BI->isUnconditional()) {
1073 // If BI's parent is the only pred of the successor, fold the two blocks
1074 // together.
1075 BasicBlock *Pred = BI->getParent();
1076 BasicBlock *Succ = BI->getSuccessor(0);
1077 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1078 if (!SinglePred) continue; // Nothing to do.
1079 assert(SinglePred == Pred && "CFG broken");
1080
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001081 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1082 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001083
1084 // Resolve any single entry PHI nodes in Succ.
1085 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1086 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1087
1088 // Move all of the successor contents from Succ to Pred.
1089 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1090 Succ->end());
1091 BI->eraseFromParent();
1092 RemoveFromWorklist(BI, Worklist);
1093
1094 // If Succ has any successors with PHI nodes, update them to have
1095 // entries coming from Pred instead of Succ.
1096 Succ->replaceAllUsesWith(Pred);
1097
1098 // Remove Succ from the loop tree.
1099 LI->removeBlock(Succ);
1100 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001101 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001102 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001103 // Conditional branch. Turn it into an unconditional branch, then
1104 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001105 break; // FIXME: Enable.
1106
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001107 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001108 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1109 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001110 DeadSucc->removePredecessor(BI->getParent(), true);
1111 Worklist.push_back(new BranchInst(LiveSucc, BI));
1112 BI->eraseFromParent();
1113 RemoveFromWorklist(BI, Worklist);
1114 ++NumSimplify;
1115
1116 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001117 }
1118 break;
1119 }
1120 }
1121 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001122}