blob: f57c0450083d31cb4f843b4aafefcad36ad19f90 [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>();
Devang Patel0975c6d2007-06-29 23:11:49 +000087 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000088 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +000090 AU.addRequiredID(LCSSAID);
91 AU.addPreservedID(LCSSAID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000092 }
93
94 private:
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +000095 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
96 /// remove it.
97 void RemoveLoopFromWorklist(Loop *L) {
98 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
99 LoopProcessWorklist.end(), L);
100 if (I != LoopProcessWorklist.end())
101 LoopProcessWorklist.erase(I);
102 }
103
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000104 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000105 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattner29f771b2006-02-18 01:27:45 +0000106 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000107 BasicBlock *ExitBlock);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000108 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000109
110 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
111 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000112
113 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
114 BasicBlock *TrueDest,
115 BasicBlock *FalseDest,
116 Instruction *InsertPt);
117
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000118 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000119 void RemoveBlockIfDead(BasicBlock *BB,
120 std::vector<Instruction*> &Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000121 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000122 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000123 char LoopUnswitch::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000124 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000125}
126
Devang Patel506310d2007-06-06 00:21:03 +0000127LoopPass *llvm::createLoopUnswitchPass(bool Os) {
128 return new LoopUnswitch(Os);
129}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000130
131/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
132/// invariant in the loop, or has an invariant piece, return the invariant.
133/// Otherwise, return null.
134static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
135 // Constants should be folded, not unswitched on!
136 if (isa<Constant>(Cond)) return false;
Devang Patel3c723c82007-06-28 00:44:10 +0000137
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000138 // TODO: Handle: br (VARIANT|INVARIANT).
139 // TODO: Hoist simple expressions out of loops.
140 if (L->isLoopInvariant(Cond)) return Cond;
141
142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
143 if (BO->getOpcode() == Instruction::And ||
144 BO->getOpcode() == Instruction::Or) {
145 // If either the left or right side is invariant, we can unswitch on this,
146 // which will cause the branch to go away in one loop and the condition to
147 // simplify in the other one.
148 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
149 return LHS;
150 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
151 return RHS;
152 }
153
154 return 0;
155}
156
Devang Patel901a27d2007-03-07 00:26:10 +0000157bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000158 assert(L->isLCSSAForm());
Devang Patel901a27d2007-03-07 00:26:10 +0000159 LI = &getAnalysis<LoopInfo>();
160 LPM = &LPM_Ref;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000161 bool Changed = false;
162
163 // Loop over all of the basic blocks in the loop. If we find an interior
164 // block that is branching on a loop-invariant condition, we can unswitch this
165 // loop.
166 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
167 I != E; ++I) {
168 TerminatorInst *TI = (*I)->getTerminator();
169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
170 // If this isn't branching on an invariant condition, we can't unswitch
171 // it.
172 if (BI->isConditional()) {
173 // See if this, or some part of it, is loop invariant. If so, we can
174 // unswitch on it if we desire.
175 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000176 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000177 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000178 ++NumBranches;
179 return true;
180 }
181 }
182 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
183 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
184 if (LoopCond && SI->getNumCases() > 1) {
185 // Find a value to unswitch on:
186 // FIXME: this should chose the most expensive case!
187 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel967b84c2007-02-26 19:31:58 +0000188 // Do not process same value again and again.
Devang Patel97517ff2007-02-26 20:22:50 +0000189 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel967b84c2007-02-26 19:31:58 +0000190 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000191
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000192 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
193 ++NumSwitches;
194 return true;
195 }
196 }
197 }
198
199 // Scan the instructions to check for unswitchable values.
200 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
201 BBI != E; ++BBI)
202 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
203 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000204 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
Chris Lattner6ab03f62006-09-28 23:35:22 +0000205 L)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000206 ++NumSelects;
207 return true;
208 }
209 }
210 }
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000211
212 assert(L->isLCSSAForm());
213
Chris Lattnerf48f7772004-04-19 18:07:02 +0000214 return Changed;
215}
216
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000217/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
218/// 1. Exit the loop with no side effects.
219/// 2. Branch to the latch block with no side-effects.
220///
221/// If these conditions are true, we return true and set ExitBB to the block we
222/// exit through.
223///
224static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
225 BasicBlock *&ExitBB,
226 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000227 if (!Visited.insert(BB).second) {
228 // Already visited and Ok, end of recursion.
229 return true;
230 } else if (!L->contains(BB)) {
231 // Otherwise, this is a loop exit, this is fine so long as this is the
232 // first exit.
233 if (ExitBB != 0) return false;
234 ExitBB = BB;
235 return true;
236 }
237
238 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000239 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000240 // Check to see if the successor is a trivial loop exit.
241 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
242 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000243 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000244
245 // Okay, everything after this looks good, check to make sure that this block
246 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000248 if (I->mayWriteToMemory())
249 return false;
250
251 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000252}
253
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000254/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
255/// leads to an exit from the specified loop, and has no side-effects in the
256/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000257static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
258 std::set<BasicBlock*> Visited;
259 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000260 BasicBlock *ExitBB = 0;
261 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
262 return ExitBB;
263 return 0;
264}
Chris Lattner6e263152006-02-10 02:30:37 +0000265
Chris Lattnered7a67b2006-02-10 01:24:09 +0000266/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
267/// trivial: that is, that the condition controls whether or not the loop does
268/// anything at all. If this is a trivial condition, unswitching produces no
269/// code duplications (equivalently, it produces a simpler loop and a new empty
270/// loop, which gets deleted).
271///
Chris Lattner8a5a3242006-02-22 06:37:14 +0000272/// If this is a trivial condition, return true, otherwise return false. When
273/// returning true, this sets Cond and Val to the condition that controls the
274/// trivial condition: when Cond dynamically equals Val, the loop is known to
275/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
276/// Cond == Val.
277///
278static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattner49354172006-02-10 02:01:22 +0000279 BasicBlock **LoopExit = 0) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000280 BasicBlock *Header = L->getHeader();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000281 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000282
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000283 BasicBlock *LoopExitBB = 0;
284 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
285 // If the header block doesn't end with a conditional branch on Cond, we
286 // can't handle it.
287 if (!BI->isConditional() || BI->getCondition() != Cond)
288 return false;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000289
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000290 // Check to see if a successor of the branch is guaranteed to go to the
291 // latch block or exit through a one exit block without having any
292 // side-effects. If so, determine the value of Cond that causes it to do
293 // this.
294 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000295 if (Val) *Val = ConstantInt::getTrue();
Chris Lattner8a5a3242006-02-22 06:37:14 +0000296 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000297 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000298 }
299 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
300 // If this isn't a switch on Cond, we can't handle it.
301 if (SI->getCondition() != Cond) return false;
302
303 // Check to see if a successor of the switch is guaranteed to go to the
304 // latch block or exit through a one exit block without having any
305 // side-effects. If so, determine the value of Cond that causes it to do
306 // this. Note that we can't trivially unswitch on the default case.
307 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
308 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
309 // Okay, we found a trivial case, remember the value that is trivial.
310 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000311 break;
312 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000313 }
314
Chris Lattnere5521db2006-02-22 23:55:00 +0000315 // If we didn't find a single unique LoopExit block, or if the loop exit block
316 // contains phi nodes, this isn't trivial.
317 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000318 return false; // Can't handle this.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000319
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000320 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000321
322 // We already know that nothing uses any scalar values defined inside of this
323 // loop. As such, we just have to check to see if this loop will execute any
324 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000325 // part of the loop that the code *would* execute. We already checked the
326 // tail, check the header now.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000327 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
328 if (I->mayWriteToMemory())
Chris Lattner49354172006-02-10 02:01:22 +0000329 return false;
Chris Lattner49354172006-02-10 02:01:22 +0000330 return true;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000331}
332
333/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
334/// we choose to unswitch the specified loop on the specified value.
335///
336unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
337 // If the condition is trivial, always unswitch. There is no code growth for
338 // this case.
339 if (IsTrivialUnswitchCondition(L, LIC))
340 return 0;
341
Owen Anderson18e816f2006-06-28 17:47:50 +0000342 // FIXME: This is really overly conservative. However, more liberal
343 // estimations have thus far resulted in excessive unswitching, which is bad
344 // both in compile time and in code size. This should be replaced once
345 // someone figures out how a good estimation.
346 return L->getBlocks().size();
Chris Lattner0a2e1122006-06-28 16:38:55 +0000347
Chris Lattnered7a67b2006-02-10 01:24:09 +0000348 unsigned Cost = 0;
349 // FIXME: this is brain dead. It should take into consideration code
350 // shrinkage.
351 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
352 I != E; ++I) {
353 BasicBlock *BB = *I;
354 // Do not include empty blocks in the cost calculation. This happen due to
355 // loop canonicalization and will be removed.
356 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
357 continue;
358
359 // Count basic blocks.
360 ++Cost;
361 }
362
363 return Cost;
364}
365
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000366/// UnswitchIfProfitable - We have found that we can unswitch L when
367/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
368/// unswitch the loop, reprocess the pieces, then return true.
369bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
370 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner5821a6a2006-03-24 07:14:00 +0000371 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
Devang Patel506310d2007-06-06 00:21:03 +0000372
373 // Do not do non-trivial unswitch while optimizing for size.
374 if (Cost && OptimizeForSize)
375 return false;
376
Chris Lattner5821a6a2006-03-24 07:14:00 +0000377 if (Cost > Threshold) {
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000378 // FIXME: this should estimate growth by the amount of code shared by the
379 // resultant unswitched loops.
380 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000381 DOUT << "NOT unswitching loop %"
382 << L->getHeader()->getName() << ", cost too high: "
383 << L->getBlocks().size() << "\n";
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000384 return false;
385 }
Owen Andersonf52351e2006-06-26 07:44:36 +0000386
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000387 // If this is a trivial condition to unswitch (which results in no code
388 // duplication), do it now.
Chris Lattner01db04e2006-02-15 01:44:42 +0000389 Constant *CondVal;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000390 BasicBlock *ExitBlock;
Chris Lattner8a5a3242006-02-22 06:37:14 +0000391 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
392 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000393 } else {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000394 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000395 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000396
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000397 return true;
398}
399
Misha Brukmanb1c93172005-04-21 23:48:37 +0000400// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000401// current values into those specified by ValueMap.
402//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000403static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000404 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000405 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
406 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000407 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000408 if (It != ValueMap.end()) Op = It->second;
409 I->setOperand(op, Op);
410 }
411}
412
Devang Patel3304e462007-06-28 00:49:00 +0000413// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator Info.
414// If Orig is in Loop then find and use Orig dominator's cloned block as NewBB
415// dominator.
416void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig, Loop *L,
Devang Patel0975c6d2007-06-29 23:11:49 +0000417 DominatorTree *DT, DominanceFrontier *DF,
Devang Patel3304e462007-06-28 00:49:00 +0000418 DenseMap<const Value*, Value*> &VM) {
419
420 DomTreeNode *OrigNode = DT->getNode(Orig);
421 if (!OrigNode)
422 return;
423 BasicBlock *OrigIDom = OrigNode->getBlock();
424 BasicBlock *NewIDom = OrigIDom;
425 if (L->contains(OrigIDom)) {
426 if (!DT->getNode(OrigIDom))
Devang Patel0975c6d2007-06-29 23:11:49 +0000427 CloneDomInfo(NewIDom, OrigIDom, L, DT, DF, VM);
Devang Patel3304e462007-06-28 00:49:00 +0000428 NewIDom = cast<BasicBlock>(VM[OrigIDom]);
429 }
Devang Patel6ba5ad42007-06-28 02:05:46 +0000430 if (NewBB == NewIDom) {
431 DT->addNewBlock(NewBB, OrigIDom);
432 DT->changeImmediateDominator(NewBB, NewIDom);
433 } else
434 DT->addNewBlock(NewBB, NewIDom);
Devang Patel0975c6d2007-06-29 23:11:49 +0000435
436 DominanceFrontier::DomSetType NewDFSet;
437 if (DF) {
438 DominanceFrontier::iterator DFI = DF->find(Orig);
439 if ( DFI != DF->end()) {
440 DominanceFrontier::DomSetType S = DFI->second;
441 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
442 I != E; ++I) {
443 BasicBlock *BB = *I;
444 if (L->contains(BB))
445 NewDFSet.insert(cast<BasicBlock>(VM[Orig]));
446 else
447 NewDFSet.insert(BB);
448 }
449 }
450 DF->addBasicBlock(NewBB, NewDFSet);
451 }
Devang Patel3304e462007-06-28 00:49:00 +0000452}
453
Chris Lattnerf48f7772004-04-19 18:07:02 +0000454/// CloneLoop - Recursively clone the specified loop and all of its children,
455/// mapping the blocks with the specified map.
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000456static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000457 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000458 Loop *New = new Loop();
459
Devang Patel901a27d2007-03-07 00:26:10 +0000460 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000461
462 // Add all of the blocks in L to the new loop.
463 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
464 I != E; ++I)
465 if (LI->getLoopFor(*I) == L)
466 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
467
468 // Add all of the subloops to the new loop.
469 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000470 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471
Chris Lattnerf48f7772004-04-19 18:07:02 +0000472 return New;
473}
474
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000475/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
476/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
477/// code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000478void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
479 BasicBlock *TrueDest,
480 BasicBlock *FalseDest,
481 Instruction *InsertPt) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000482 // Insert a conditional branch on LIC to the two preheaders. The original
483 // code is the true version and the new code is the false version.
484 Value *BranchVal = LIC;
Reid Spencera94d3942007-01-19 21:13:56 +0000485 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencer266e42b2006-12-23 06:05:41 +0000486 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000487 else if (Val != ConstantInt::getTrue())
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000488 // We want to enter the new loop when the condition is true.
489 std::swap(TrueDest, FalseDest);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000490
491 // Insert the new branch.
Devang Patel3304e462007-06-28 00:49:00 +0000492 BranchInst *BRI = new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
493
494 // Update dominator info.
Devang Patel0975c6d2007-06-29 23:11:49 +0000495 // BranchVal is a new preheader so it dominates true and false destination
496 // loop headers.
Devang Patel3304e462007-06-28 00:49:00 +0000497 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Devang Patel3304e462007-06-28 00:49:00 +0000498 DT->changeImmediateDominator(TrueDest, BRI->getParent());
499 DT->changeImmediateDominator(FalseDest, BRI->getParent());
500 }
Devang Patel0975c6d2007-06-29 23:11:49 +0000501 // No need to update DominanceFrontier. BRI->getParent() dominated TrueDest
502 // and FalseDest anyway. Now it immediately dominates them.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000503}
504
505
Chris Lattnered7a67b2006-02-10 01:24:09 +0000506/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
507/// condition in it (a cond branch from its header block to its latch block,
508/// where the path through the loop that doesn't execute its body has no
509/// side-effects), unswitch it. This doesn't involve any code duplication, just
510/// moving the conditional branch outside of the loop and updating loop info.
511void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattner8a5a3242006-02-22 06:37:14 +0000512 Constant *Val,
Chris Lattner49354172006-02-10 02:01:22 +0000513 BasicBlock *ExitBlock) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000514 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
515 << L->getHeader()->getName() << " [" << L->getBlocks().size()
516 << " blocks] in Function " << L->getHeader()->getParent()->getName()
517 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner3fc31482006-02-10 01:36:35 +0000518
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000519 // First step, split the preheader, so that we know that there is a safe place
Chris Lattnered7a67b2006-02-10 01:24:09 +0000520 // to insert the conditional branch. We will change 'OrigPH' to have a
521 // conditional branch on Cond.
522 BasicBlock *OrigPH = L->getLoopPreheader();
Devang Patel12358b42007-07-06 22:03:47 +0000523 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader(), this);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000524
525 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000526 // to branch to: this is the exit block out of the loop that we should
527 // short-circuit to.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000528
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000529 // Split this block now, so that the loop maintains its exit block, and so
530 // that the jump from the preheader can execute the contents of the exit block
531 // without actually branching to it (the exit block should be dominated by the
532 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000533 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel12358b42007-07-06 22:03:47 +0000534 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000535
Chris Lattnered7a67b2006-02-10 01:24:09 +0000536 // Okay, now we have a position to branch from and a position to branch to,
537 // insert the new conditional branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000538 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
539 OrigPH->getTerminator());
Chris Lattnered7a67b2006-02-10 01:24:09 +0000540 OrigPH->getTerminator()->eraseFromParent();
541
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000542 // We need to reprocess this loop, it could be unswitched again.
Devang Patel901a27d2007-03-07 00:26:10 +0000543 LPM->redoLoop(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000544
Chris Lattnered7a67b2006-02-10 01:24:09 +0000545 // Now that we know that the loop is never entered when this condition is a
546 // particular value, rewrite the loop with this info. We know that this will
547 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000548 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000549 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000550}
551
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000552/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
553/// equal Val. Split it into loop versions and test the condition outside of
554/// either loop. Return the loops created as Out1/Out2.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000555void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
556 Loop *L) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000557 Function *F = L->getHeader()->getParent();
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000558 DOUT << "loop-unswitch: Unswitching loop %"
559 << L->getHeader()->getName() << " [" << L->getBlocks().size()
560 << " blocks] in Function " << F->getName()
561 << " when '" << *Val << "' == " << *LIC << "\n";
Chris Lattnerf48f7772004-04-19 18:07:02 +0000562
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000563 // LoopBlocks contains all of the basic blocks of the loop, including the
564 // preheader of the loop, the body of the loop, and the exit blocks of the
565 // loop, in that order.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000566 std::vector<BasicBlock*> LoopBlocks;
567
568 // First step, split the preheader and exit blocks, and add these blocks to
569 // the LoopBlocks list.
570 BasicBlock *OrigPreheader = L->getLoopPreheader();
Devang Patel12358b42007-07-06 22:03:47 +0000571 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader(), this));
Chris Lattnerf48f7772004-04-19 18:07:02 +0000572
573 // We want the loop to come after the preheader, but before the exit blocks.
574 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
575
576 std::vector<BasicBlock*> ExitBlocks;
Devang Patelf489d0f2006-08-29 22:29:16 +0000577 L->getUniqueExitBlocks(ExitBlocks);
578
Owen Andersonf52351e2006-06-26 07:44:36 +0000579 // Split all of the edges from inside the loop to their exit blocks. Update
580 // the appropriate Phi nodes as we do so.
Chris Lattnered7a67b2006-02-10 01:24:09 +0000581 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000582 BasicBlock *ExitBlock = ExitBlocks[i];
583 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
584
585 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel12358b42007-07-06 22:03:47 +0000586 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Owen Andersonf52351e2006-06-26 07:44:36 +0000587 BasicBlock* StartBlock = Preds[j];
588 BasicBlock* EndBlock;
589 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
590 EndBlock = MiddleBlock;
591 MiddleBlock = EndBlock->getSinglePredecessor();;
592 } else {
593 EndBlock = ExitBlock;
594 }
595
596 std::set<PHINode*> InsertedPHIs;
597 PHINode* OldLCSSA = 0;
598 for (BasicBlock::iterator I = EndBlock->begin();
599 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
600 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
601 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
602 OldLCSSA->getName() + ".us-lcssa",
603 MiddleBlock->getTerminator());
604 NewLCSSA->addIncoming(OldValue, StartBlock);
605 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
606 NewLCSSA);
607 InsertedPHIs.insert(NewLCSSA);
608 }
609
Owen Anderson00b974c2006-07-19 03:51:48 +0000610 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Andersonf52351e2006-06-26 07:44:36 +0000611 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
612 for (BasicBlock::iterator I = MiddleBlock->begin();
613 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
614 ++I) {
615 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
616 OldLCSSA->getName() + ".us-lcssa",
617 InsertPt);
618 OldLCSSA->replaceAllUsesWith(NewLCSSA);
619 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
620 }
621 }
Chris Lattnered7a67b2006-02-10 01:24:09 +0000622 }
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000623
624 // The exit blocks may have been changed due to edge splitting, recompute.
625 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000626 L->getUniqueExitBlocks(ExitBlocks);
627
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000628 // Add exit blocks to the loop blocks.
629 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000630
631 // Next step, clone all of the basic blocks that make up the loop (including
632 // the loop preheader and exit blocks), keeping track of the mapping between
633 // the instructions and blocks.
634 std::vector<BasicBlock*> NewBlocks;
635 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000636 DenseMap<const Value*, Value*> ValueMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000637 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000638 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
639 NewBlocks.push_back(New);
640 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000641 }
642
Devang Patel3304e462007-06-28 00:49:00 +0000643 // Update dominator info
Devang Patel0975c6d2007-06-29 23:11:49 +0000644 DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>();
Devang Patel3304e462007-06-28 00:49:00 +0000645 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>())
646 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
647 BasicBlock *LBB = LoopBlocks[i];
648 BasicBlock *NBB = NewBlocks[i];
Devang Patel0975c6d2007-06-29 23:11:49 +0000649 CloneDomInfo(NBB, LBB, L, DT, DF, ValueMap);
Devang Patel3304e462007-06-28 00:49:00 +0000650 }
651
Chris Lattnerf48f7772004-04-19 18:07:02 +0000652 // Splice the newly inserted blocks into the function right before the
653 // original preheader.
654 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
655 NewBlocks[0], F->end());
656
657 // Now we create the new Loop object for the versioned loop.
Devang Patel901a27d2007-03-07 00:26:10 +0000658 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000659 Loop *ParentLoop = L->getParentLoop();
660 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000661 // Make sure to add the cloned preheader and exit blocks to the parent loop
662 // as well.
Chris Lattnerf1b15162006-02-10 23:26:14 +0000663 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
664 }
665
666 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
667 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000668 // The new exit block should be in the same loop as the old one.
669 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
670 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000671
672 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
673 "Exit block should have been split to have one successor!");
674 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
675
676 // If the successor of the exit block had PHI nodes, add an entry for
677 // NewExit.
678 PHINode *PN;
679 for (BasicBlock::iterator I = ExitSucc->begin();
680 (PN = dyn_cast<PHINode>(I)); ++I) {
681 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000682 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000683 if (It != ValueMap.end()) V = It->second;
684 PN->addIncoming(V, NewExit);
685 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000686 }
687
688 // Rewrite the code to refer to itself.
689 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
690 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
691 E = NewBlocks[i]->end(); I != E; ++I)
692 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000693
Chris Lattnerf48f7772004-04-19 18:07:02 +0000694 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000695 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
696 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +0000697 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +0000698
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000699 // Emit the new branch that selects between the two versions of this loop.
700 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
701 OldBR->eraseFromParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000702
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000703 LoopProcessWorklist.push_back(NewLoop);
Devang Patel901a27d2007-03-07 00:26:10 +0000704 LPM->redoLoop(L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000705
706 // Now we rewrite the original code to know that the condition is true and the
707 // new code to know that the condition is false.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000708 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
709
710 // It's possible that simplifying one loop could cause the other to be
711 // deleted. If so, don't simplify it.
712 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
713 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000714}
715
Chris Lattner6fd13622006-02-17 00:31:07 +0000716/// RemoveFromWorklist - Remove all instances of I from the worklist vector
717/// specified.
718static void RemoveFromWorklist(Instruction *I,
719 std::vector<Instruction*> &Worklist) {
720 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
721 Worklist.end(), I);
722 while (WI != Worklist.end()) {
723 unsigned Offset = WI-Worklist.begin();
724 Worklist.erase(WI);
725 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
726 }
727}
728
729/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
730/// program, replacing all uses with V and update the worklist.
731static void ReplaceUsesOfWith(Instruction *I, Value *V,
732 std::vector<Instruction*> &Worklist) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000733 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000734
735 // Add uses to the worklist, which may be dead now.
736 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
737 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
738 Worklist.push_back(Use);
739
740 // Add users to the worklist which may be simplified now.
741 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
742 UI != E; ++UI)
743 Worklist.push_back(cast<Instruction>(*UI));
744 I->replaceAllUsesWith(V);
745 I->eraseFromParent();
746 RemoveFromWorklist(I, Worklist);
747 ++NumSimplify;
748}
749
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000750/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
751/// information, and remove any dead successors it has.
752///
753void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
754 std::vector<Instruction*> &Worklist) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000755 if (pred_begin(BB) != pred_end(BB)) {
756 // This block isn't dead, since an edge to BB was just removed, see if there
757 // are any easy simplifications we can do now.
758 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
759 // If it has one pred, fold phi nodes in BB.
760 while (isa<PHINode>(BB->begin()))
761 ReplaceUsesOfWith(BB->begin(),
762 cast<PHINode>(BB->begin())->getIncomingValue(0),
763 Worklist);
764
765 // If this is the header of a loop and the only pred is the latch, we now
766 // have an unreachable loop.
767 if (Loop *L = LI->getLoopFor(BB))
768 if (L->getHeader() == BB && L->contains(Pred)) {
769 // Remove the branch from the latch to the header block, this makes
770 // the header dead, which will make the latch dead (because the header
771 // dominates the latch).
772 Pred->getTerminator()->eraseFromParent();
773 new UnreachableInst(Pred);
774
775 // The loop is now broken, remove it from LI.
776 RemoveLoopFromHierarchy(L);
777
778 // Reprocess the header, which now IS dead.
779 RemoveBlockIfDead(BB, Worklist);
780 return;
781 }
782
783 // If pred ends in a uncond branch, add uncond branch to worklist so that
784 // the two blocks will get merged.
785 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
786 if (BI->isUnconditional())
787 Worklist.push_back(BI);
788 }
789 return;
790 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000791
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000792 DOUT << "Nuking dead block: " << *BB;
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000793
794 // Remove the instructions in the basic block from the worklist.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000795 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000796 RemoveFromWorklist(I, Worklist);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000797
798 // Anything that uses the instructions in this basic block should have their
799 // uses replaced with undefs.
800 if (!I->use_empty())
801 I->replaceAllUsesWith(UndefValue::get(I->getType()));
802 }
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000803
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000804 // If this is the edge to the header block for a loop, remove the loop and
805 // promote all subloops.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000806 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000807 if (BBLoop->getLoopLatch() == BB)
808 RemoveLoopFromHierarchy(BBLoop);
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000809 }
810
811 // Remove the block from the loop info, which removes it from any loops it
812 // was in.
813 LI->removeBlock(BB);
814
815
816 // Remove phi node entries in successors for this block.
817 TerminatorInst *TI = BB->getTerminator();
818 std::vector<BasicBlock*> Succs;
819 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
820 Succs.push_back(TI->getSuccessor(i));
821 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattner29f771b2006-02-18 01:27:45 +0000822 }
823
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000824 // Unique the successors, remove anything with multiple uses.
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000825 std::sort(Succs.begin(), Succs.end());
826 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
827
828 // Remove the basic block, including all of the instructions contained in it.
829 BB->eraseFromParent();
830
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000831 // Remove successor blocks here that are not dead, so that we know we only
832 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
833 // then getting removed before we revisit them, which is badness.
834 //
835 for (unsigned i = 0; i != Succs.size(); ++i)
836 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
837 // One exception is loop headers. If this block was the preheader for a
838 // loop, then we DO want to visit the loop so the loop gets deleted.
839 // We know that if the successor is a loop header, that this loop had to
840 // be the preheader: the case where this was the latch block was handled
841 // above and headers can only have two predecessors.
842 if (!LI->isLoopHeader(Succs[i])) {
843 Succs.erase(Succs.begin()+i);
844 --i;
845 }
846 }
847
Chris Lattner19fa8ac2006-02-18 02:42:34 +0000848 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
849 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattner29f771b2006-02-18 01:27:45 +0000850}
Chris Lattner6fd13622006-02-17 00:31:07 +0000851
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000852/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
853/// become unwrapped, either because the backedge was deleted, or because the
854/// edge into the header was removed. If the edge into the header from the
855/// latch block was removed, the loop is unwrapped but subloops are still alive,
856/// so they just reparent loops. If the loops are actually dead, they will be
857/// removed later.
858void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel901a27d2007-03-07 00:26:10 +0000859 LPM->deleteLoopFromQueue(L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000860 RemoveLoopFromWorklist(L);
861}
862
863
864
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000865// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
866// the value specified by Val in the specified loop, or we know it does NOT have
867// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000868void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000869 Constant *Val,
870 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +0000871 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000872
Chris Lattnerf48f7772004-04-19 18:07:02 +0000873 // FIXME: Support correlated properties, like:
874 // for (...)
875 // if (li1 < li2)
876 // ...
877 // if (li1 > li2)
878 // ...
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000879
Chris Lattner6e263152006-02-10 02:30:37 +0000880 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
881 // selects, switches.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000882 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner6fd13622006-02-17 00:31:07 +0000883 std::vector<Instruction*> Worklist;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000884
Chris Lattner6fd13622006-02-17 00:31:07 +0000885 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
886 // in the loop with the appropriate one directly.
Reid Spencer542964f2007-01-11 18:21:29 +0000887 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattner8a5a3242006-02-22 06:37:14 +0000888 Value *Replacement;
889 if (IsEqual)
890 Replacement = Val;
891 else
Reid Spencercddc9df2007-01-12 04:24:46 +0000892 Replacement = ConstantInt::get(Type::Int1Ty,
893 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner6fd13622006-02-17 00:31:07 +0000894
895 for (unsigned i = 0, e = Users.size(); i != e; ++i)
896 if (Instruction *U = cast<Instruction>(Users[i])) {
897 if (!L->contains(U->getParent()))
898 continue;
899 U->replaceUsesOfWith(LIC, Replacement);
900 Worklist.push_back(U);
901 }
902 } else {
903 // Otherwise, we don't know the precise value of LIC, but we do know that it
904 // is certainly NOT "Val". As such, simplify any uses in the loop that we
905 // can. This case occurs when we unswitch switch statements.
906 for (unsigned i = 0, e = Users.size(); i != e; ++i)
907 if (Instruction *U = cast<Instruction>(Users[i])) {
908 if (!L->contains(U->getParent()))
909 continue;
910
911 Worklist.push_back(U);
912
Chris Lattnerfa335f62006-02-16 19:36:22 +0000913 // If we know that LIC is not Val, use this info to simplify code.
914 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
915 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
916 if (SI->getCaseValue(i) == Val) {
917 // Found a dead case value. Don't remove PHI nodes in the
918 // successor if they become single-entry, those PHI nodes may
919 // be in the Users list.
Owen Andersonf52351e2006-06-26 07:44:36 +0000920
921 // FIXME: This is a hack. We need to keep the successor around
922 // and hooked up so as to preserve the loop structure, because
923 // trying to update it is complicated. So instead we preserve the
924 // loop structure and put the block on an dead code path.
925
926 BasicBlock* Old = SI->getParent();
Devang Patel12358b42007-07-06 22:03:47 +0000927 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Andersonf52351e2006-06-26 07:44:36 +0000928
929 Instruction* OldTerm = Old->getTerminator();
Reid Spencerde46e482006-11-02 20:25:50 +0000930 new BranchInst(Split, SI->getSuccessor(i),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000931 ConstantInt::getTrue(), OldTerm);
Owen Andersonf52351e2006-06-26 07:44:36 +0000932
933 Old->getTerminator()->eraseFromParent();
934
Owen Andersonbb3ae5e2006-06-27 22:26:09 +0000935
936 PHINode *PN;
937 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
938 (PN = dyn_cast<PHINode>(II)); ++II) {
939 Value *InVal = PN->removeIncomingValue(Split, false);
940 PN->addIncoming(InVal, Old);
Owen Andersonf52351e2006-06-26 07:44:36 +0000941 }
942
Chris Lattnerfa335f62006-02-16 19:36:22 +0000943 SI->removeCase(i);
944 break;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000945 }
946 }
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000947 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000948
949 // TODO: We could do other simplifications, for example, turning
950 // LIC == Val -> false.
Chris Lattnerfa335f62006-02-16 19:36:22 +0000951 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000952 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000953
954 SimplifyCode(Worklist);
955}
956
957/// SimplifyCode - Okay, now that we have simplified some instructions in the
958/// loop, walk over it and constant prop, dce, and fold control flow where
959/// possible. Note that this is effectively a very simple loop-structure-aware
960/// optimizer. During processing of this loop, L could very well be deleted, so
961/// it must not be used.
962///
963/// FIXME: When the loop optimizer is more mature, separate this out to a new
964/// pass.
965///
966void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner6fd13622006-02-17 00:31:07 +0000967 while (!Worklist.empty()) {
968 Instruction *I = Worklist.back();
969 Worklist.pop_back();
970
971 // Simple constant folding.
972 if (Constant *C = ConstantFoldInstruction(I)) {
973 ReplaceUsesOfWith(I, C, Worklist);
974 continue;
Chris Lattnerfa335f62006-02-16 19:36:22 +0000975 }
Chris Lattner6fd13622006-02-17 00:31:07 +0000976
977 // Simple DCE.
978 if (isInstructionTriviallyDead(I)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000979 DOUT << "Remove dead instruction '" << *I;
Chris Lattner6fd13622006-02-17 00:31:07 +0000980
981 // Add uses to the worklist, which may be dead now.
982 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
983 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
984 Worklist.push_back(Use);
985 I->eraseFromParent();
986 RemoveFromWorklist(I, Worklist);
987 ++NumSimplify;
988 continue;
989 }
990
991 // Special case hacks that appear commonly in unswitched code.
992 switch (I->getOpcode()) {
993 case Instruction::Select:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000994 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Reid Spencercddc9df2007-01-12 04:24:46 +0000995 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +0000996 continue;
997 }
998 break;
999 case Instruction::And:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001000 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001001 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001002 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001003 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001004 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001005 if (CB->isOne()) // X & 1 -> X
Zhou Sheng75b871f2007-01-11 12:24:14 +00001006 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1007 else // X & 0 -> 0
1008 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1009 continue;
1010 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001011 break;
1012 case Instruction::Or:
Zhou Sheng75b871f2007-01-11 12:24:14 +00001013 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00001014 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner6fd13622006-02-17 00:31:07 +00001015 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001016 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00001017 if (CB->getType() == Type::Int1Ty) {
Reid Spencer558990e2007-03-02 23:35:28 +00001018 if (CB->isOne()) // X | 1 -> 1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001019 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1020 else // X | 0 -> X
1021 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1022 continue;
1023 }
Chris Lattner6fd13622006-02-17 00:31:07 +00001024 break;
1025 case Instruction::Br: {
1026 BranchInst *BI = cast<BranchInst>(I);
1027 if (BI->isUnconditional()) {
1028 // If BI's parent is the only pred of the successor, fold the two blocks
1029 // together.
1030 BasicBlock *Pred = BI->getParent();
1031 BasicBlock *Succ = BI->getSuccessor(0);
1032 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1033 if (!SinglePred) continue; // Nothing to do.
1034 assert(SinglePred == Pred && "CFG broken");
1035
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001036 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1037 << Succ->getName() << "\n";
Chris Lattner6fd13622006-02-17 00:31:07 +00001038
1039 // Resolve any single entry PHI nodes in Succ.
1040 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1041 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1042
1043 // Move all of the successor contents from Succ to Pred.
1044 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1045 Succ->end());
1046 BI->eraseFromParent();
1047 RemoveFromWorklist(BI, Worklist);
1048
1049 // If Succ has any successors with PHI nodes, update them to have
1050 // entries coming from Pred instead of Succ.
1051 Succ->replaceAllUsesWith(Pred);
1052
1053 // Remove Succ from the loop tree.
1054 LI->removeBlock(Succ);
1055 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001056 ++NumSimplify;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001057 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001058 // Conditional branch. Turn it into an unconditional branch, then
1059 // remove dead blocks.
Chris Lattner8a5a3242006-02-22 06:37:14 +00001060 break; // FIXME: Enable.
1061
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001062 DOUT << "Folded branch: " << *BI;
Reid Spencercddc9df2007-01-12 04:24:46 +00001063 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1064 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner19fa8ac2006-02-18 02:42:34 +00001065 DeadSucc->removePredecessor(BI->getParent(), true);
1066 Worklist.push_back(new BranchInst(LiveSucc, BI));
1067 BI->eraseFromParent();
1068 RemoveFromWorklist(BI, Worklist);
1069 ++NumSimplify;
1070
1071 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner6fd13622006-02-17 00:31:07 +00001072 }
1073 break;
1074 }
1075 }
1076 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001077}