blob: 28051fa2101cd535f84d2fc51b378215269287ed [file] [log] [blame]
Chris Lattner18f16092004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner18f16092004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner18f16092004-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 Spencerc1030572007-01-19 21:13:56 +000032#include "llvm/DerivedTypes.h"
Chris Lattner18f16092004-04-19 18:07:02 +000033#include "llvm/Function.h"
34#include "llvm/Instructions.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner18f16092004-04-19 18:07:02 +000036#include "llvm/Analysis/LoopInfo.h"
Devang Patel1bc89362007-03-07 00:26:10 +000037#include "llvm/Analysis/LoopPass.h"
Devang Patelcce624a2007-06-28 00:49:00 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattner18f16092004-04-19 18:07:02 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
Devang Patelfb688d42007-02-26 20:22:50 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000044#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000045#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000047#include <algorithm>
Chris Lattner2f4b8982006-02-09 19:14:52 +000048#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000049using namespace llvm;
50
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(NumBranches, "Number of branches unswitched");
52STATISTIC(NumSwitches, "Number of switches unswitched");
53STATISTIC(NumSelects , "Number of selects unswitched");
54STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
Dan Gohman844731a2008-05-13 00:00:25 +000057static cl::opt<unsigned>
58Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
59 cl::init(10), cl::Hidden);
Chris Lattnere487abb2006-02-09 20:15:48 +000060
Dan Gohman844731a2008-05-13 00:00:25 +000061namespace {
Devang Patel1bc89362007-03-07 00:26:10 +000062 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +000063 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +000064 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +000065
Devang Patel1bc89362007-03-07 00:26:10 +000066 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +000068 std::vector<Loop*> LoopProcessWorklist;
Devang Patelfb688d42007-02-26 20:22:50 +000069 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel743f7e82007-06-06 00:21:03 +000070
71 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +000072 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000073
Devang Patele6962df2008-07-02 01:18:13 +000074 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000075 DominanceFrontier *DF;
76 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +000077 BasicBlock *loopHeader;
78 BasicBlock *loopPreheader;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000079
80 /// LoopDF - Loop's dominance frontier. This set is a collection of
81 /// loop exiting blocks' DF member blocks. However this does set does not
82 /// includes basic blocks that are inside loop.
83 SmallPtrSet<BasicBlock *, 8> LoopDF;
84
85 /// OrigLoopExitMap - This is used to map loop exiting block with
86 /// corresponding loop exit block, before updating CFG.
87 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
Devang Patel1e41f6d2008-07-02 01:44:29 +000088
89 // LoopBlocks contains all of the basic blocks of the loop, including the
90 // preheader of the loop, the body of the loop, and the exit blocks of the
91 // loop, in that order.
92 std::vector<BasicBlock*> LoopBlocks;
93 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94 std::vector<BasicBlock*> NewBlocks;
Chris Lattner18f16092004-04-19 18:07:02 +000095 public:
Devang Patel19974732007-05-03 01:11:54 +000096 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000097 explicit LoopUnswitch(bool Os = false) :
Devang Patele6962df2008-07-02 01:18:13 +000098 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
99 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100 loopPreheader(NULL) {}
Devang Patel794fd752007-05-01 21:15:47 +0000101
Devang Patel1bc89362007-03-07 00:26:10 +0000102 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +0000103 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000104
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
107 ///
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000110 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000111 AU.addRequired<LoopInfo>();
112 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000113 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000114 AU.addPreservedID(LCSSAID);
Devang Patel4be7d292008-07-03 06:48:21 +0000115 AU.addPreserved<DominatorTree>();
116 AU.addPreserved<DominanceFrontier>();
Chris Lattner18f16092004-04-19 18:07:02 +0000117 }
118
119 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000120
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000121 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
122 /// remove it.
123 void RemoveLoopFromWorklist(Loop *L) {
124 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
125 LoopProcessWorklist.end(), L);
126 if (I != LoopProcessWorklist.end())
127 LoopProcessWorklist.erase(I);
128 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000129
Devang Patele6962df2008-07-02 01:18:13 +0000130 void initLoopData() {
131 loopHeader = currentLoop->getHeader();
132 loopPreheader = currentLoop->getLoopPreheader();
133 }
134
Chris Lattner48a80b02008-04-21 00:25:49 +0000135 /// Split all of the edges from inside the loop to their exit blocks.
136 /// Update the appropriate Phi nodes as we do so.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000137 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000138 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000139
Chris Lattner48a80b02008-04-21 00:25:49 +0000140 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000141 /// remove it. Add NewDFMember in BB's dominance frontier.
142 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
143 BasicBlock *NewDFMember);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000144
Devang Patele6962df2008-07-02 01:18:13 +0000145 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
146 unsigned getLoopUnswitchCost(Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000147 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000148 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000149 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000150
151 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
152 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000153
154 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
155 BasicBlock *TrueDest,
156 BasicBlock *FalseDest,
157 Instruction *InsertPt);
158
Devang Patel15c260a2007-07-31 08:03:26 +0000159 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000160 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000161 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000162 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000163 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
164 BasicBlock **LoopExit = 0);
165
Chris Lattner18f16092004-04-19 18:07:02 +0000166 };
Chris Lattner18f16092004-04-19 18:07:02 +0000167}
Dan Gohman844731a2008-05-13 00:00:25 +0000168char LoopUnswitch::ID = 0;
169static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000170
Devang Patel743f7e82007-06-06 00:21:03 +0000171LoopPass *llvm::createLoopUnswitchPass(bool Os) {
172 return new LoopUnswitch(Os);
173}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000174
175/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
176/// invariant in the loop, or has an invariant piece, return the invariant.
177/// Otherwise, return null.
178static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
179 // Constants should be folded, not unswitched on!
180 if (isa<Constant>(Cond)) return false;
Devang Patel558f1b82007-06-28 00:44:10 +0000181
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000182 // TODO: Handle: br (VARIANT|INVARIANT).
183 // TODO: Hoist simple expressions out of loops.
184 if (L->isLoopInvariant(Cond)) return Cond;
185
186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
187 if (BO->getOpcode() == Instruction::And ||
188 BO->getOpcode() == Instruction::Or) {
189 // If either the left or right side is invariant, we can unswitch on this,
190 // which will cause the branch to go away in one loop and the condition to
191 // simplify in the other one.
192 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
193 return LHS;
194 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
195 return RHS;
196 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000197
198 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000199}
200
Devang Patel1bc89362007-03-07 00:26:10 +0000201bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000202 LI = &getAnalysis<LoopInfo>();
203 LPM = &LPM_Ref;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000204 DF = getAnalysisToUpdate<DominanceFrontier>();
205 DT = getAnalysisToUpdate<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000206 currentLoop = L;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000207 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000208 do {
Devang Patele6962df2008-07-02 01:18:13 +0000209 assert(currentLoop->isLCSSAForm());
Devang Patel6f62af62007-07-30 23:07:10 +0000210 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000211 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000212 } while(redoLoop);
213
214 return Changed;
215}
216
Devang Patele6962df2008-07-02 01:18:13 +0000217/// processCurrentLoop - Do actual work and unswitch loop if possible
218/// and profitable.
219bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000220 bool Changed = false;
221
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000222 // Loop over all of the basic blocks in the loop. If we find an interior
223 // block that is branching on a loop-invariant condition, we can unswitch this
224 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000225 for (Loop::block_iterator I = currentLoop->block_begin(),
226 E = currentLoop->block_end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000227 I != E; ++I) {
228 TerminatorInst *TI = (*I)->getTerminator();
229 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
230 // If this isn't branching on an invariant condition, we can't unswitch
231 // it.
232 if (BI->isConditional()) {
233 // See if this, or some part of it, is loop invariant. If so, we can
234 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000235 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
236 currentLoop, Changed);
237 if (LoopCond && UnswitchIfProfitable(LoopCond,
238 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000239 ++NumBranches;
240 return true;
241 }
242 }
243 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000244 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
245 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000246 if (LoopCond && SI->getNumCases() > 1) {
247 // Find a value to unswitch on:
248 // FIXME: this should chose the most expensive case!
249 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000250 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000251 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000252 continue;
Devang Patel52956922007-02-26 19:31:58 +0000253
Devang Patele6962df2008-07-02 01:18:13 +0000254 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000255 ++NumSwitches;
256 return true;
257 }
258 }
259 }
260
261 // Scan the instructions to check for unswitchable values.
262 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
263 BBI != E; ++BBI)
264 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000265 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
266 currentLoop, Changed);
267 if (LoopCond && UnswitchIfProfitable(LoopCond,
268 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000269 ++NumSelects;
270 return true;
271 }
272 }
273 }
Chris Lattner18f16092004-04-19 18:07:02 +0000274 return Changed;
275}
276
Chris Lattner4e132392006-02-15 22:03:36 +0000277/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
278/// 1. Exit the loop with no side effects.
279/// 2. Branch to the latch block with no side-effects.
280///
281/// If these conditions are true, we return true and set ExitBB to the block we
282/// exit through.
283///
284static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
285 BasicBlock *&ExitBB,
286 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000287 if (!Visited.insert(BB).second) {
288 // Already visited and Ok, end of recursion.
289 return true;
290 } else if (!L->contains(BB)) {
291 // Otherwise, this is a loop exit, this is fine so long as this is the
292 // first exit.
293 if (ExitBB != 0) return false;
294 ExitBB = BB;
295 return true;
296 }
297
298 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000299 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000300 // Check to see if the successor is a trivial loop exit.
301 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
302 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000303 }
Chris Lattner4e132392006-02-15 22:03:36 +0000304
305 // Okay, everything after this looks good, check to make sure that this block
306 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000307 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000308 if (I->mayWriteToMemory())
309 return false;
310
311 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000312}
313
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000314/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
315/// leads to an exit from the specified loop, and has no side-effects in the
316/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000317static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
318 std::set<BasicBlock*> Visited;
319 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000320 BasicBlock *ExitBB = 0;
321 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
322 return ExitBB;
323 return 0;
324}
Chris Lattner708e1a52006-02-10 02:30:37 +0000325
Chris Lattner4c41d492006-02-10 01:24:09 +0000326/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
327/// trivial: that is, that the condition controls whether or not the loop does
328/// anything at all. If this is a trivial condition, unswitching produces no
329/// code duplications (equivalently, it produces a simpler loop and a new empty
330/// loop, which gets deleted).
331///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000332/// If this is a trivial condition, return true, otherwise return false. When
333/// returning true, this sets Cond and Val to the condition that controls the
334/// trivial condition: when Cond dynamically equals Val, the loop is known to
335/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
336/// Cond == Val.
337///
Devang Patele6962df2008-07-02 01:18:13 +0000338bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
339 BasicBlock **LoopExit) {
340 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000341 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000342
Chris Lattnera48654e2006-02-15 22:52:05 +0000343 BasicBlock *LoopExitBB = 0;
344 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
345 // If the header block doesn't end with a conditional branch on Cond, we
346 // can't handle it.
347 if (!BI->isConditional() || BI->getCondition() != Cond)
348 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000349
Chris Lattnera48654e2006-02-15 22:52:05 +0000350 // Check to see if a successor of the branch is guaranteed to go to the
351 // latch block or exit through a one exit block without having any
352 // side-effects. If so, determine the value of Cond that causes it to do
353 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000354 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
355 BI->getSuccessor(0)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000356 if (Val) *Val = ConstantInt::getTrue();
Devang Patele6962df2008-07-02 01:18:13 +0000357 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
358 BI->getSuccessor(1)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000359 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000360 }
361 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
362 // If this isn't a switch on Cond, we can't handle it.
363 if (SI->getCondition() != Cond) return false;
364
365 // Check to see if a successor of the switch is guaranteed to go to the
366 // latch block or exit through a one exit block without having any
367 // side-effects. If so, determine the value of Cond that causes it to do
368 // this. Note that we can't trivially unswitch on the default case.
369 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000370 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
371 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000372 // Okay, we found a trivial case, remember the value that is trivial.
373 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000374 break;
375 }
Chris Lattner4e132392006-02-15 22:03:36 +0000376 }
377
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000378 // If we didn't find a single unique LoopExit block, or if the loop exit block
379 // contains phi nodes, this isn't trivial.
380 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000381 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000382
Chris Lattnera48654e2006-02-15 22:52:05 +0000383 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000384
385 // We already know that nothing uses any scalar values defined inside of this
386 // loop. As such, we just have to check to see if this loop will execute any
387 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000388 // part of the loop that the code *would* execute. We already checked the
389 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000390 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
391 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000392 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000393 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000394}
395
396/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patele6962df2008-07-02 01:18:13 +0000397/// we choose to unswitch current loop on the specified value.
Chris Lattner4c41d492006-02-10 01:24:09 +0000398///
Devang Patele6962df2008-07-02 01:18:13 +0000399unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000400 // If the condition is trivial, always unswitch. There is no code growth for
401 // this case.
Devang Patele6962df2008-07-02 01:18:13 +0000402 if (IsTrivialUnswitchCondition(LIC))
Chris Lattner4c41d492006-02-10 01:24:09 +0000403 return 0;
404
Owen Anderson372994b2006-06-28 17:47:50 +0000405 // FIXME: This is really overly conservative. However, more liberal
406 // estimations have thus far resulted in excessive unswitching, which is bad
407 // both in compile time and in code size. This should be replaced once
408 // someone figures out how a good estimation.
Devang Patele6962df2008-07-02 01:18:13 +0000409 return currentLoop->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000410
Chris Lattner4c41d492006-02-10 01:24:09 +0000411 unsigned Cost = 0;
412 // FIXME: this is brain dead. It should take into consideration code
413 // shrinkage.
Devang Patele6962df2008-07-02 01:18:13 +0000414 for (Loop::block_iterator I = currentLoop->block_begin(),
415 E = currentLoop->block_end();
Chris Lattner4c41d492006-02-10 01:24:09 +0000416 I != E; ++I) {
417 BasicBlock *BB = *I;
418 // Do not include empty blocks in the cost calculation. This happen due to
419 // loop canonicalization and will be removed.
420 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
421 continue;
422
423 // Count basic blocks.
424 ++Cost;
425 }
426
427 return Cost;
428}
429
Devang Patele6962df2008-07-02 01:18:13 +0000430/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000431/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
432/// unswitch the loop, reprocess the pieces, then return true.
Devang Patele6962df2008-07-02 01:18:13 +0000433bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
434 // Check to see if it would be profitable to unswitch current loop.
435 unsigned Cost = getLoopUnswitchCost(LoopCond);
Devang Patel743f7e82007-06-06 00:21:03 +0000436
437 // Do not do non-trivial unswitch while optimizing for size.
438 if (Cost && OptimizeForSize)
439 return false;
440
Chris Lattner0f862e52006-03-24 07:14:00 +0000441 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000442 // FIXME: this should estimate growth by the amount of code shared by the
443 // resultant unswitched loops.
444 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000445 DOUT << "NOT unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000446 << currentLoop->getHeader()->getName() << ", cost too high: "
447 << currentLoop->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000448 return false;
449 }
Devang Patele6962df2008-07-02 01:18:13 +0000450
451 initLoopData();
452
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000453 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000454 BasicBlock *ExitBlock;
Devang Patele6962df2008-07-02 01:18:13 +0000455 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
456 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000457 } else {
Devang Patele6962df2008-07-02 01:18:13 +0000458 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000459 }
Devang Patel4be7d292008-07-03 06:48:21 +0000460
461 // FIXME: Reconstruct dom info, because it is not preserved properly.
462 Function *F = loopHeader->getParent();
463 if (DT)
464 DT->runOnFunction(*F);
465 if (DF)
466 DF->runOnFunction(*F);
Chris Lattnerc2358092006-02-11 00:43:37 +0000467 return true;
468}
469
Misha Brukmanfd939082005-04-21 23:48:37 +0000470// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000471// current values into those specified by ValueMap.
472//
Misha Brukmanfd939082005-04-21 23:48:37 +0000473static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000474 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000475 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
476 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000477 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000478 if (It != ValueMap.end()) Op = It->second;
479 I->setOperand(op, Op);
480 }
481}
482
Chris Lattner684b22d2007-08-02 16:53:43 +0000483// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
484// Info.
Devang Patel31ad7532007-07-18 23:48:20 +0000485//
486// If Orig block's immediate dominator is mapped in VM then use corresponding
487// immediate dominator from the map. Otherwise Orig block's dominator is also
488// NewBB's dominator.
489//
Devang Patel24857a32007-07-18 23:50:19 +0000490// OrigPreheader is loop pre-header before this pass started
Devang Patel31ad7532007-07-18 23:48:20 +0000491// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel24857a32007-07-18 23:50:19 +0000492// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman844731a2008-05-13 00:00:25 +0000493static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
494 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
495 BasicBlock *OrigHeader,
496 DominatorTree *DT, DominanceFrontier *DF,
497 DenseMap<const Value*, Value*> &VM) {
Devang Patelcce624a2007-06-28 00:49:00 +0000498
Devang Patel31ad7532007-07-18 23:48:20 +0000499 // If NewBB alreay has found its place in domiantor tree then no need to do
500 // anything.
501 if (DT->getNode(NewBB))
502 return;
503
504 // If Orig does not have any immediate domiantor then its clone, NewBB, does
505 // not need any immediate dominator.
Devang Patelcce624a2007-06-28 00:49:00 +0000506 DomTreeNode *OrigNode = DT->getNode(Orig);
507 if (!OrigNode)
508 return;
Devang Patel31ad7532007-07-18 23:48:20 +0000509 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
510 if (!OrigIDomNode)
511 return;
512
513 BasicBlock *OrigIDom = NULL;
514
515 // If Orig is original loop header then its immediate dominator is
516 // NewPreheader.
517 if (Orig == OrigHeader)
518 OrigIDom = NewPreheader;
519
520 // If Orig is new pre-header then its immediate dominator is
521 // original pre-header.
522 else if (Orig == NewPreheader)
523 OrigIDom = OrigPreheader;
524
Devang Patel2095c382008-07-02 01:31:19 +0000525 // Otherwise ask DT to find Orig's immediate dominator.
Devang Patel31ad7532007-07-18 23:48:20 +0000526 else
527 OrigIDom = OrigIDomNode->getBlock();
528
Devang Pateldf5cf202007-07-30 21:10:44 +0000529 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
530 BasicBlock *NewIDom = OrigIDom;
531 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
532 if (I != VM.end()) {
533 NewIDom = cast<BasicBlock>(I->second);
534
535 // If NewIDom does not have corresponding dominatore tree node then
536 // get one.
537 if (!DT->getNode(NewIDom))
Devang Patel31ad7532007-07-18 23:48:20 +0000538 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
539 OrigHeader, DT, DF, VM);
Devang Patelcce624a2007-06-28 00:49:00 +0000540 }
Devang Pateldf5cf202007-07-30 21:10:44 +0000541
542 DT->addNewBlock(NewBB, NewIDom);
543
544 // Copy cloned dominance frontiner set
Devang Patelf34a43a2007-06-29 23:11:49 +0000545 DominanceFrontier::DomSetType NewDFSet;
546 if (DF) {
547 DominanceFrontier::iterator DFI = DF->find(Orig);
548 if ( DFI != DF->end()) {
549 DominanceFrontier::DomSetType S = DFI->second;
550 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
551 I != E; ++I) {
552 BasicBlock *BB = *I;
Chuck Rose III936baaa2007-07-27 18:26:35 +0000553 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
554 if (IDM != VM.end())
555 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patelf34a43a2007-06-29 23:11:49 +0000556 else
557 NewDFSet.insert(BB);
558 }
559 }
560 DF->addBasicBlock(NewBB, NewDFSet);
561 }
Devang Patelcce624a2007-06-28 00:49:00 +0000562}
563
Chris Lattner18f16092004-04-19 18:07:02 +0000564/// CloneLoop - Recursively clone the specified loop and all of its children,
565/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000566static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000567 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000568 Loop *New = new Loop();
569
Devang Patel1bc89362007-03-07 00:26:10 +0000570 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000571
572 // Add all of the blocks in L to the new loop.
573 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
574 I != E; ++I)
575 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000576 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000577
578 // Add all of the subloops to the new loop.
579 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000580 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000581
Chris Lattner18f16092004-04-19 18:07:02 +0000582 return New;
583}
584
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000585/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
586/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
587/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000588void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
589 BasicBlock *TrueDest,
590 BasicBlock *FalseDest,
591 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000592 // Insert a conditional branch on LIC to the two preheaders. The original
593 // code is the true version and the new code is the false version.
594 Value *BranchVal = LIC;
Reid Spencerc1030572007-01-19 21:13:56 +0000595 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000596 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000597 else if (Val != ConstantInt::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000598 // We want to enter the new loop when the condition is true.
599 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000600
601 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000602 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000603}
604
605
Chris Lattner4c41d492006-02-10 01:24:09 +0000606/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
607/// condition in it (a cond branch from its header block to its latch block,
608/// where the path through the loop that doesn't execute its body has no
609/// side-effects), unswitch it. This doesn't involve any code duplication, just
610/// moving the conditional branch outside of the loop and updating loop info.
611void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000612 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000613 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000614 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000615 << loopHeader->getName() << " [" << L->getBlocks().size()
Bill Wendlingb7427032006-11-26 09:46:52 +0000616 << " blocks] in Function " << L->getHeader()->getParent()->getName()
617 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000618
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000619 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000620 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000621 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000622 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000623
624 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000625 // to branch to: this is the exit block out of the loop that we should
626 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000627
Chris Lattner4e132392006-02-15 22:03:36 +0000628 // Split this block now, so that the loop maintains its exit block, and so
629 // that the jump from the preheader can execute the contents of the exit block
630 // without actually branching to it (the exit block should be dominated by the
631 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000632 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000633 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000634
Chris Lattner4c41d492006-02-10 01:24:09 +0000635 // Okay, now we have a position to branch from and a position to branch to,
636 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000637 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000638 loopPreheader->getTerminator());
Devang Patel2f170992008-06-02 22:52:56 +0000639 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000640 DT->changeImmediateDominator(NewExit, loopPreheader);
641 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel2f170992008-06-02 22:52:56 +0000642 }
Devang Patel64cd6582008-06-18 02:16:38 +0000643
644 if (DF) {
645 // NewExit is now part of NewPH and Loop Header's dominance
646 // frontier.
647 DominanceFrontier::iterator DFI = DF->find(NewPH);
648 if (DFI != DF->end())
649 DF->addToFrontier(DFI, NewExit);
Devang Patele6962df2008-07-02 01:18:13 +0000650 DFI = DF->find(loopHeader);
Devang Patel64cd6582008-06-18 02:16:38 +0000651 DF->addToFrontier(DFI, NewExit);
652
653 // ExitBlock does not have successors then NewExit is part of
654 // its dominance frontier.
655 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
656 DFI = DF->find(ExitBlock);
657 DF->addToFrontier(DFI, NewExit);
658 }
659 }
Devang Patele6962df2008-07-02 01:18:13 +0000660 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
661 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000662
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000663 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000664 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000665
Chris Lattner4c41d492006-02-10 01:24:09 +0000666 // Now that we know that the loop is never entered when this condition is a
667 // particular value, rewrite the loop with this info. We know that this will
668 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000669 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000670 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000671}
672
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000673/// ReplaceLoopExternalDFMember -
674/// If BB's dominance frontier has a member that is not part of loop L then
675/// remove it. Add NewDFMember in BB's dominance frontier.
676void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
677 BasicBlock *NewDFMember) {
678
679 DominanceFrontier::iterator DFI = DF->find(BB);
680 if (DFI == DF->end())
681 return;
682
683 DominanceFrontier::DomSetType &DFSet = DFI->second;
684 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patelb5938982007-10-09 21:31:36 +0000685 DE = DFSet.end(); DI != DE;) {
686 BasicBlock *B = *DI++;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000687 if (L->contains(B))
688 continue;
David Greene60f75152007-12-17 17:40:29 +0000689
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000690 DF->removeFromFrontier(DFI, B);
691 LoopDF.insert(B);
692 }
693
694 DF->addToFrontier(DFI, NewDFMember);
695}
696
Chris Lattner48a80b02008-04-21 00:25:49 +0000697/// SplitExitEdges - Split all of the edges from inside the loop to their exit
698/// blocks. Update the appropriate Phi nodes as we do so.
699void LoopUnswitch::SplitExitEdges(Loop *L,
700 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000701 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000702
Chris Lattner4c41d492006-02-10 01:24:09 +0000703 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000704 BasicBlock *ExitBlock = ExitBlocks[i];
705 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
706
707 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel05c1dc62007-07-06 22:03:47 +0000708 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel1ff61382007-08-02 15:25:57 +0000709 MiddleBlocks.push_back(MiddleBlock);
Owen Anderson2b67f072006-06-26 07:44:36 +0000710 BasicBlock* StartBlock = Preds[j];
711 BasicBlock* EndBlock;
712 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
713 EndBlock = MiddleBlock;
714 MiddleBlock = EndBlock->getSinglePredecessor();;
715 } else {
716 EndBlock = ExitBlock;
717 }
718
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000719 OrigLoopExitMap[StartBlock] = EndBlock;
720
Owen Anderson2b67f072006-06-26 07:44:36 +0000721 std::set<PHINode*> InsertedPHIs;
722 PHINode* OldLCSSA = 0;
723 for (BasicBlock::iterator I = EndBlock->begin();
724 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
725 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greif051a9502008-04-06 20:25:17 +0000726 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
727 OldLCSSA->getName() + ".us-lcssa",
728 MiddleBlock->getTerminator());
Owen Anderson2b67f072006-06-26 07:44:36 +0000729 NewLCSSA->addIncoming(OldValue, StartBlock);
730 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
731 NewLCSSA);
732 InsertedPHIs.insert(NewLCSSA);
733 }
734
Dan Gohman02dea8b2008-05-23 21:05:58 +0000735 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Owen Anderson2b67f072006-06-26 07:44:36 +0000736 for (BasicBlock::iterator I = MiddleBlock->begin();
737 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
738 ++I) {
Gabor Greif051a9502008-04-06 20:25:17 +0000739 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
740 OldLCSSA->getName() + ".us-lcssa",
741 InsertPt);
Owen Anderson2b67f072006-06-26 07:44:36 +0000742 OldLCSSA->replaceAllUsesWith(NewLCSSA);
743 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
744 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000745
746 if (DF && DT) {
747 // StartBlock -- > MiddleBlock -- > EndBlock
748 // StartBlock is loop exiting block. EndBlock will become merge point
749 // of two loop exits after loop unswitch.
750
751 // If StartBlock's DF member includes a block that is not loop member
752 // then replace that DF member with EndBlock.
753
754 // If MiddleBlock's DF member includes a block that is not loop member
755 // tnen replace that DF member with EndBlock.
756
757 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
758 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
759 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000760 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000761 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000762
Devang Patelf476e8e2007-10-03 21:16:08 +0000763}
764
Devang Patelc1e26602007-10-03 21:17:43 +0000765/// UnswitchNontrivialCondition - We determined that the loop is profitable
766/// to unswitch when LIC equal Val. Split it into loop versions and test the
767/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000768void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
769 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000770 Function *F = loopHeader->getParent();
Devang Patelf476e8e2007-10-03 21:16:08 +0000771 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000772 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Patelf476e8e2007-10-03 21:16:08 +0000773 << " blocks] in Function " << F->getName()
774 << " when '" << *Val << "' == " << *LIC << "\n";
775
Devang Patel1e41f6d2008-07-02 01:44:29 +0000776 LoopBlocks.clear();
777 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000778
779 // First step, split the preheader and exit blocks, and add these blocks to
780 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000781 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000782 LoopBlocks.push_back(NewPreheader);
783
784 // We want the loop to come after the preheader, but before the exit blocks.
785 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
786
787 SmallVector<BasicBlock*, 8> ExitBlocks;
788 L->getUniqueExitBlocks(ExitBlocks);
789
790 // Split all of the edges from inside the loop to their exit blocks. Update
791 // the appropriate Phi nodes as we do so.
792 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000793 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000794
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000795 // The exit blocks may have been changed due to edge splitting, recompute.
796 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000797 L->getUniqueExitBlocks(ExitBlocks);
798
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000799 // Add exit blocks to the loop blocks.
800 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000801
802 // Next step, clone all of the basic blocks that make up the loop (including
803 // the loop preheader and exit blocks), keeping track of the mapping between
804 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000805 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000806 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000807 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000808 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
809 NewBlocks.push_back(New);
810 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000811 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000812 }
813
Devang Patel1ff61382007-08-02 15:25:57 +0000814 // OutSiders are basic block that are dominated by original header and
815 // at the same time they are not part of loop.
816 SmallPtrSet<BasicBlock *, 8> OutSiders;
817 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000818 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel1ff61382007-08-02 15:25:57 +0000819 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
820 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
821 BasicBlock *B = (*DI)->getBlock();
822
823 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
824 if (VI == ValueMap.end())
825 OutSiders.insert(B);
Devang Patelcce624a2007-06-28 00:49:00 +0000826 }
Devang Patel1ff61382007-08-02 15:25:57 +0000827 }
828
Chris Lattner18f16092004-04-19 18:07:02 +0000829 // Splice the newly inserted blocks into the function right before the
830 // original preheader.
831 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
832 NewBlocks[0], F->end());
833
834 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000835 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000836 Loop *ParentLoop = L->getParentLoop();
837 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000838 // Make sure to add the cloned preheader and exit blocks to the parent loop
839 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000840 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000841 }
842
843 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
844 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000845 // The new exit block should be in the same loop as the old one.
846 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000847 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000848
849 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
850 "Exit block should have been split to have one successor!");
851 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
852
853 // If the successor of the exit block had PHI nodes, add an entry for
854 // NewExit.
855 PHINode *PN;
856 for (BasicBlock::iterator I = ExitSucc->begin();
857 (PN = dyn_cast<PHINode>(I)); ++I) {
858 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000859 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000860 if (It != ValueMap.end()) V = It->second;
861 PN->addIncoming(V, NewExit);
862 }
Chris Lattner18f16092004-04-19 18:07:02 +0000863 }
864
865 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000866 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
867 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
868 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000869 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000870
Chris Lattner18f16092004-04-19 18:07:02 +0000871 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000872 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000873 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000874 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000875
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000876 // Emit the new branch that selects between the two versions of this loop.
877 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000878 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000879 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000880
881 // Update dominator info
882 if (DF && DT) {
883
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000884 SmallVector<BasicBlock *,4> ExitingBlocks;
885 L->getExitingBlocks(ExitingBlocks);
886
Devang Patel1ff61382007-08-02 15:25:57 +0000887 // Clone dominator info for all cloned basic block.
888 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
889 BasicBlock *LBB = LoopBlocks[i];
890 BasicBlock *NBB = NewBlocks[i];
Devang Patele6962df2008-07-02 01:18:13 +0000891 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
892 loopHeader, DT, DF, ValueMap);
Devang Patel1ff61382007-08-02 15:25:57 +0000893
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000894 // If LBB's dominance frontier includes DFMember
895 // such that DFMember is also a member of LoopDF then
896 // - Remove DFMember from LBB's dominance frontier
Chris Lattner48a80b02008-04-21 00:25:49 +0000897 // - Copy loop exiting blocks', that are dominated by BB,
898 // dominance frontier member in BB's dominance frontier
Devang Patel1ff61382007-08-02 15:25:57 +0000899
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000900 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel1ff61382007-08-02 15:25:57 +0000901 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000902 if (LBBI == DF->end())
903 continue;
904
905 DominanceFrontier::DomSetType &LBSet = LBBI->second;
906 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
907 LE = LBSet.end(); LI != LE; /* NULL */) {
908 BasicBlock *B = *LI++;
Devang Patele6962df2008-07-02 01:18:13 +0000909 if (B == LBB && B == loopHeader)
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000910 continue;
911 bool removeB = false;
912 if (!LoopDF.count(B))
913 continue;
914
915 // If LBB dominates loop exits then insert loop exit block's DF
916 // into B's DF.
Chris Lattner48a80b02008-04-21 00:25:49 +0000917 for(SmallVector<BasicBlock *, 4>::iterator
918 LExitI = ExitingBlocks.begin(),
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000919 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
920 BasicBlock *E = *LExitI;
921
922 if (!DT->dominates(LBB,E))
923 continue;
924
925 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
926 OrigLoopExitMap.find(E);
927 if (DFBI == OrigLoopExitMap.end())
928 continue;
929
930 BasicBlock *DFB = DFBI->second;
931 DF->addToFrontier(LBBI, DFB);
932 DF->addToFrontier(NBBI, DFB);
933 removeB = true;
934 }
935
Chris Lattner48a80b02008-04-21 00:25:49 +0000936 // If B's replacement is inserted in DF then now is the time to remove
937 // B.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000938 if (removeB) {
939 DF->removeFromFrontier(LBBI, B);
940 if (L->contains(B))
941 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
942 else
Devang Patel1ff61382007-08-02 15:25:57 +0000943 DF->removeFromFrontier(NBBI, B);
944 }
945 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000946
Devang Patel1ff61382007-08-02 15:25:57 +0000947 }
948
949 // MiddleBlocks are dominated by original pre header. SplitEdge updated
950 // MiddleBlocks' dominance frontier appropriately.
951 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
952 BasicBlock *MBB = MiddleBlocks[i];
953 if (!MBB->getSinglePredecessor())
Devang Patele6962df2008-07-02 01:18:13 +0000954 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000955 }
956
957 // All Outsiders are now dominated by original pre header.
958 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
959 OE = OutSiders.end(); OI != OE; ++OI) {
960 BasicBlock *OB = *OI;
Devang Patele6962df2008-07-02 01:18:13 +0000961 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000962 }
963
964 // New loop headers are dominated by original preheader
Devang Patele6962df2008-07-02 01:18:13 +0000965 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
966 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000967 }
968
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000969 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000970 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000971
972 // Now we rewrite the original code to know that the condition is true and the
973 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000974 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
975
976 // It's possible that simplifying one loop could cause the other to be
977 // deleted. If so, don't simplify it.
978 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
979 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000980}
981
Chris Lattner52221f72006-02-17 00:31:07 +0000982/// RemoveFromWorklist - Remove all instances of I from the worklist vector
983/// specified.
984static void RemoveFromWorklist(Instruction *I,
985 std::vector<Instruction*> &Worklist) {
986 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
987 Worklist.end(), I);
988 while (WI != Worklist.end()) {
989 unsigned Offset = WI-Worklist.begin();
990 Worklist.erase(WI);
991 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
992 }
993}
994
995/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
996/// program, replacing all uses with V and update the worklist.
997static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000998 std::vector<Instruction*> &Worklist,
999 Loop *L, LPPassManager *LPM) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001000 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001001
1002 // Add uses to the worklist, which may be dead now.
1003 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1004 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1005 Worklist.push_back(Use);
1006
1007 // Add users to the worklist which may be simplified now.
1008 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1009 UI != E; ++UI)
1010 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +00001011 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001012 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001013 I->replaceAllUsesWith(V);
1014 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001015 ++NumSimplify;
1016}
1017
Chris Lattnerdb410242006-02-18 02:42:34 +00001018/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1019/// information, and remove any dead successors it has.
1020///
1021void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +00001022 std::vector<Instruction*> &Worklist,
1023 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001024 if (pred_begin(BB) != pred_end(BB)) {
1025 // This block isn't dead, since an edge to BB was just removed, see if there
1026 // are any easy simplifications we can do now.
1027 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1028 // If it has one pred, fold phi nodes in BB.
1029 while (isa<PHINode>(BB->begin()))
1030 ReplaceUsesOfWith(BB->begin(),
1031 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +00001032 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001033
1034 // If this is the header of a loop and the only pred is the latch, we now
1035 // have an unreachable loop.
1036 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +00001037 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001038 // Remove the branch from the latch to the header block, this makes
1039 // the header dead, which will make the latch dead (because the header
1040 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +00001041 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001042 Pred->getTerminator()->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001043 new UnreachableInst(Pred);
1044
1045 // The loop is now broken, remove it from LI.
1046 RemoveLoopFromHierarchy(L);
1047
1048 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +00001049 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001050 return;
1051 }
1052
1053 // If pred ends in a uncond branch, add uncond branch to worklist so that
1054 // the two blocks will get merged.
1055 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1056 if (BI->isUnconditional())
1057 Worklist.push_back(BI);
1058 }
1059 return;
1060 }
Chris Lattner52221f72006-02-17 00:31:07 +00001061
Bill Wendlingb7427032006-11-26 09:46:52 +00001062 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +00001063
1064 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001065 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +00001066 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001067
1068 // Anything that uses the instructions in this basic block should have their
1069 // uses replaced with undefs.
1070 if (!I->use_empty())
1071 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1072 }
Chris Lattnerdb410242006-02-18 02:42:34 +00001073
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001074 // If this is the edge to the header block for a loop, remove the loop and
1075 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +00001076 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001077 if (BBLoop->getLoopLatch() == BB)
1078 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +00001079 }
1080
1081 // Remove the block from the loop info, which removes it from any loops it
1082 // was in.
1083 LI->removeBlock(BB);
1084
1085
1086 // Remove phi node entries in successors for this block.
1087 TerminatorInst *TI = BB->getTerminator();
1088 std::vector<BasicBlock*> Succs;
1089 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1090 Succs.push_back(TI->getSuccessor(i));
1091 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001092 }
1093
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001094 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +00001095 std::sort(Succs.begin(), Succs.end());
1096 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1097
1098 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +00001099 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001100 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001101 // Remove successor blocks here that are not dead, so that we know we only
1102 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1103 // then getting removed before we revisit them, which is badness.
1104 //
1105 for (unsigned i = 0; i != Succs.size(); ++i)
1106 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1107 // One exception is loop headers. If this block was the preheader for a
1108 // loop, then we DO want to visit the loop so the loop gets deleted.
1109 // We know that if the successor is a loop header, that this loop had to
1110 // be the preheader: the case where this was the latch block was handled
1111 // above and headers can only have two predecessors.
1112 if (!LI->isLoopHeader(Succs[i])) {
1113 Succs.erase(Succs.begin()+i);
1114 --i;
1115 }
1116 }
1117
Chris Lattnerdb410242006-02-18 02:42:34 +00001118 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +00001119 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001120}
Chris Lattner52221f72006-02-17 00:31:07 +00001121
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001122/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1123/// become unwrapped, either because the backedge was deleted, or because the
1124/// edge into the header was removed. If the edge into the header from the
1125/// latch block was removed, the loop is unwrapped but subloops are still alive,
1126/// so they just reparent loops. If the loops are actually dead, they will be
1127/// removed later.
1128void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +00001129 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001130 RemoveLoopFromWorklist(L);
1131}
1132
1133
1134
Chris Lattnerc2358092006-02-11 00:43:37 +00001135// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1136// the value specified by Val in the specified loop, or we know it does NOT have
1137// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +00001138void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +00001139 Constant *Val,
1140 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +00001141 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +00001142
Chris Lattner18f16092004-04-19 18:07:02 +00001143 // FIXME: Support correlated properties, like:
1144 // for (...)
1145 // if (li1 < li2)
1146 // ...
1147 // if (li1 > li2)
1148 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +00001149
Chris Lattner708e1a52006-02-10 02:30:37 +00001150 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1151 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +00001152 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +00001153 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001154
Chris Lattner52221f72006-02-17 00:31:07 +00001155 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1156 // in the loop with the appropriate one directly.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001157 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001158 Value *Replacement;
1159 if (IsEqual)
1160 Replacement = Val;
1161 else
Reid Spencer579dca12007-01-12 04:24:46 +00001162 Replacement = ConstantInt::get(Type::Int1Ty,
1163 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +00001164
1165 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1166 if (Instruction *U = cast<Instruction>(Users[i])) {
1167 if (!L->contains(U->getParent()))
1168 continue;
1169 U->replaceUsesOfWith(LIC, Replacement);
1170 Worklist.push_back(U);
1171 }
1172 } else {
1173 // Otherwise, we don't know the precise value of LIC, but we do know that it
1174 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1175 // can. This case occurs when we unswitch switch statements.
1176 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1177 if (Instruction *U = cast<Instruction>(Users[i])) {
1178 if (!L->contains(U->getParent()))
1179 continue;
1180
1181 Worklist.push_back(U);
1182
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001183 // If we know that LIC is not Val, use this info to simplify code.
1184 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1185 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1186 if (SI->getCaseValue(i) == Val) {
1187 // Found a dead case value. Don't remove PHI nodes in the
1188 // successor if they become single-entry, those PHI nodes may
1189 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +00001190
1191 // FIXME: This is a hack. We need to keep the successor around
1192 // and hooked up so as to preserve the loop structure, because
1193 // trying to update it is complicated. So instead we preserve the
1194 // loop structure and put the block on an dead code path.
1195
1196 BasicBlock* Old = SI->getParent();
Devang Patel05c1dc62007-07-06 22:03:47 +00001197 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Anderson2b67f072006-06-26 07:44:36 +00001198
1199 Instruction* OldTerm = Old->getTerminator();
Devang Patel825cb982008-07-03 00:08:13 +00001200 BranchInst::Create(Split, SI->getSuccessor(i),
Gabor Greif051a9502008-04-06 20:25:17 +00001201 ConstantInt::getTrue(), OldTerm);
Devang Patel9ee49c52007-09-20 23:45:50 +00001202
Chris Lattner48a80b02008-04-21 00:25:49 +00001203 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Owen Anderson2b67f072006-06-26 07:44:36 +00001204 Old->getTerminator()->eraseFromParent();
1205
Owen Andersonbef85082006-06-27 22:26:09 +00001206 PHINode *PN;
Devang Patel825cb982008-07-03 00:08:13 +00001207 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
Owen Andersonbef85082006-06-27 22:26:09 +00001208 (PN = dyn_cast<PHINode>(II)); ++II) {
1209 Value *InVal = PN->removeIncomingValue(Split, false);
1210 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +00001211 }
1212
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001213 SI->removeCase(i);
1214 break;
Chris Lattnerc2358092006-02-11 00:43:37 +00001215 }
1216 }
Chris Lattnerc2358092006-02-11 00:43:37 +00001217 }
Chris Lattner52221f72006-02-17 00:31:07 +00001218
1219 // TODO: We could do other simplifications, for example, turning
1220 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001221 }
Chris Lattner52221f72006-02-17 00:31:07 +00001222 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001223
Devang Patel15c260a2007-07-31 08:03:26 +00001224 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001225}
1226
1227/// SimplifyCode - Okay, now that we have simplified some instructions in the
1228/// loop, walk over it and constant prop, dce, and fold control flow where
1229/// possible. Note that this is effectively a very simple loop-structure-aware
1230/// optimizer. During processing of this loop, L could very well be deleted, so
1231/// it must not be used.
1232///
1233/// FIXME: When the loop optimizer is more mature, separate this out to a new
1234/// pass.
1235///
Devang Patel15c260a2007-07-31 08:03:26 +00001236void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001237 while (!Worklist.empty()) {
1238 Instruction *I = Worklist.back();
1239 Worklist.pop_back();
1240
1241 // Simple constant folding.
1242 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +00001243 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001244 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001245 }
Chris Lattner52221f72006-02-17 00:31:07 +00001246
1247 // Simple DCE.
1248 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001249 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001250
1251 // Add uses to the worklist, which may be dead now.
1252 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1253 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1254 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001255 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001256 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001257 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001258 ++NumSimplify;
1259 continue;
1260 }
1261
1262 // Special case hacks that appear commonly in unswitched code.
1263 switch (I->getOpcode()) {
1264 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001265 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +00001266 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1267 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001268 continue;
1269 }
1270 break;
1271 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001272 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001273 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001274 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001275 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001276 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001277 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001278 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001279 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +00001280 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001281 continue;
1282 }
Chris Lattner52221f72006-02-17 00:31:07 +00001283 break;
1284 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001285 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001286 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001287 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001288 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001289 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001290 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001291 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001292 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001293 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001294 continue;
1295 }
Chris Lattner52221f72006-02-17 00:31:07 +00001296 break;
1297 case Instruction::Br: {
1298 BranchInst *BI = cast<BranchInst>(I);
1299 if (BI->isUnconditional()) {
1300 // If BI's parent is the only pred of the successor, fold the two blocks
1301 // together.
1302 BasicBlock *Pred = BI->getParent();
1303 BasicBlock *Succ = BI->getSuccessor(0);
1304 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1305 if (!SinglePred) continue; // Nothing to do.
1306 assert(SinglePred == Pred && "CFG broken");
1307
Bill Wendlingb7427032006-11-26 09:46:52 +00001308 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1309 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001310
1311 // Resolve any single entry PHI nodes in Succ.
1312 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001313 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001314
1315 // Move all of the successor contents from Succ to Pred.
1316 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1317 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001318 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001319 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001320 RemoveFromWorklist(BI, Worklist);
1321
1322 // If Succ has any successors with PHI nodes, update them to have
1323 // entries coming from Pred instead of Succ.
1324 Succ->replaceAllUsesWith(Pred);
1325
1326 // Remove Succ from the loop tree.
1327 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001328 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001329 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001330 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001331 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001332 // Conditional branch. Turn it into an unconditional branch, then
1333 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001334 break; // FIXME: Enable.
1335
Bill Wendlingb7427032006-11-26 09:46:52 +00001336 DOUT << "Folded branch: " << *BI;
Reid Spencer579dca12007-01-12 04:24:46 +00001337 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1338 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001339 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001340 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001341 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001342 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001343 RemoveFromWorklist(BI, Worklist);
1344 ++NumSimplify;
1345
Devang Patel15c260a2007-07-31 08:03:26 +00001346 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001347 }
1348 break;
1349 }
1350 }
1351 }
Chris Lattner18f16092004-04-19 18:07:02 +00001352}