blob: 239749a5001427aa43083564321cd0fc2a8af1a2 [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;
Chris Lattner18f16092004-04-19 18:07:02 +000088 public:
Devang Patel19974732007-05-03 01:11:54 +000089 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000090 explicit LoopUnswitch(bool Os = false) :
Devang Patele6962df2008-07-02 01:18:13 +000091 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
92 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
93 loopPreheader(NULL) {}
Devang Patel794fd752007-05-01 21:15:47 +000094
Devang Patel1bc89362007-03-07 00:26:10 +000095 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +000096 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +000097
98 /// This transformation requires natural loop information & requires that
99 /// loop preheaders be inserted into the CFG...
100 ///
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000103 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000104 AU.addRequired<LoopInfo>();
105 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000106 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000107 AU.addPreservedID(LCSSAID);
108 AU.addPreserved<DominatorTree>();
109 AU.addPreserved<DominanceFrontier>();
Chris Lattner18f16092004-04-19 18:07:02 +0000110 }
111
112 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000113
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000114 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
115 /// remove it.
116 void RemoveLoopFromWorklist(Loop *L) {
117 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
118 LoopProcessWorklist.end(), L);
119 if (I != LoopProcessWorklist.end())
120 LoopProcessWorklist.erase(I);
121 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000122
Devang Patele6962df2008-07-02 01:18:13 +0000123 void initLoopData() {
124 loopHeader = currentLoop->getHeader();
125 loopPreheader = currentLoop->getLoopPreheader();
126 }
127
Chris Lattner48a80b02008-04-21 00:25:49 +0000128 /// Split all of the edges from inside the loop to their exit blocks.
129 /// Update the appropriate Phi nodes as we do so.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000130 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000131 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000132
Chris Lattner48a80b02008-04-21 00:25:49 +0000133 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000134 /// remove it. Add NewDFMember in BB's dominance frontier.
135 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
136 BasicBlock *NewDFMember);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000137
Devang Patele6962df2008-07-02 01:18:13 +0000138 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
139 unsigned getLoopUnswitchCost(Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000140 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000141 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000142 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000143
144 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
145 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000146
147 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
148 BasicBlock *TrueDest,
149 BasicBlock *FalseDest,
150 Instruction *InsertPt);
151
Devang Patel15c260a2007-07-31 08:03:26 +0000152 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000153 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000154 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000155 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000156 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
157 BasicBlock **LoopExit = 0);
158
Chris Lattner18f16092004-04-19 18:07:02 +0000159 };
Chris Lattner18f16092004-04-19 18:07:02 +0000160}
Dan Gohman844731a2008-05-13 00:00:25 +0000161char LoopUnswitch::ID = 0;
162static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000163
Devang Patel743f7e82007-06-06 00:21:03 +0000164LoopPass *llvm::createLoopUnswitchPass(bool Os) {
165 return new LoopUnswitch(Os);
166}
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000167
168/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
169/// invariant in the loop, or has an invariant piece, return the invariant.
170/// Otherwise, return null.
171static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
172 // Constants should be folded, not unswitched on!
173 if (isa<Constant>(Cond)) return false;
Devang Patel558f1b82007-06-28 00:44:10 +0000174
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000175 // TODO: Handle: br (VARIANT|INVARIANT).
176 // TODO: Hoist simple expressions out of loops.
177 if (L->isLoopInvariant(Cond)) return Cond;
178
179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
180 if (BO->getOpcode() == Instruction::And ||
181 BO->getOpcode() == Instruction::Or) {
182 // If either the left or right side is invariant, we can unswitch on this,
183 // which will cause the branch to go away in one loop and the condition to
184 // simplify in the other one.
185 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
186 return LHS;
187 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
188 return RHS;
189 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000190
191 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000192}
193
Devang Patel1bc89362007-03-07 00:26:10 +0000194bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000195 LI = &getAnalysis<LoopInfo>();
196 LPM = &LPM_Ref;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000197 DF = getAnalysisToUpdate<DominanceFrontier>();
198 DT = getAnalysisToUpdate<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000199 currentLoop = L;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000200 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000201
202 do {
Devang Patele6962df2008-07-02 01:18:13 +0000203 assert(currentLoop->isLCSSAForm());
Devang Patel6f62af62007-07-30 23:07:10 +0000204 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000205 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000206 } while(redoLoop);
207
208 return Changed;
209}
210
Devang Patele6962df2008-07-02 01:18:13 +0000211/// processCurrentLoop - Do actual work and unswitch loop if possible
212/// and profitable.
213bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000214 bool Changed = false;
215
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000216 // Loop over all of the basic blocks in the loop. If we find an interior
217 // block that is branching on a loop-invariant condition, we can unswitch this
218 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000219 for (Loop::block_iterator I = currentLoop->block_begin(),
220 E = currentLoop->block_end();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000221 I != E; ++I) {
222 TerminatorInst *TI = (*I)->getTerminator();
223 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
224 // If this isn't branching on an invariant condition, we can't unswitch
225 // it.
226 if (BI->isConditional()) {
227 // See if this, or some part of it, is loop invariant. If so, we can
228 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000229 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
230 currentLoop, Changed);
231 if (LoopCond && UnswitchIfProfitable(LoopCond,
232 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000233 ++NumBranches;
234 return true;
235 }
236 }
237 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000238 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
239 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000240 if (LoopCond && SI->getNumCases() > 1) {
241 // Find a value to unswitch on:
242 // FIXME: this should chose the most expensive case!
243 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000244 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000245 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000246 continue;
Devang Patel52956922007-02-26 19:31:58 +0000247
Devang Patele6962df2008-07-02 01:18:13 +0000248 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000249 ++NumSwitches;
250 return true;
251 }
252 }
253 }
254
255 // Scan the instructions to check for unswitchable values.
256 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
257 BBI != E; ++BBI)
258 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000259 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
260 currentLoop, Changed);
261 if (LoopCond && UnswitchIfProfitable(LoopCond,
262 ConstantInt::getTrue())) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000263 ++NumSelects;
264 return true;
265 }
266 }
267 }
Chris Lattner18f16092004-04-19 18:07:02 +0000268 return Changed;
269}
270
Chris Lattner4e132392006-02-15 22:03:36 +0000271/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
272/// 1. Exit the loop with no side effects.
273/// 2. Branch to the latch block with no side-effects.
274///
275/// If these conditions are true, we return true and set ExitBB to the block we
276/// exit through.
277///
278static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
279 BasicBlock *&ExitBB,
280 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000281 if (!Visited.insert(BB).second) {
282 // Already visited and Ok, end of recursion.
283 return true;
284 } else if (!L->contains(BB)) {
285 // Otherwise, this is a loop exit, this is fine so long as this is the
286 // first exit.
287 if (ExitBB != 0) return false;
288 ExitBB = BB;
289 return true;
290 }
291
292 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000293 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000294 // Check to see if the successor is a trivial loop exit.
295 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
296 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000297 }
Chris Lattner4e132392006-02-15 22:03:36 +0000298
299 // Okay, everything after this looks good, check to make sure that this block
300 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000302 if (I->mayWriteToMemory())
303 return false;
304
305 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000306}
307
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000308/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
309/// leads to an exit from the specified loop, and has no side-effects in the
310/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000311static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
312 std::set<BasicBlock*> Visited;
313 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000314 BasicBlock *ExitBB = 0;
315 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
316 return ExitBB;
317 return 0;
318}
Chris Lattner708e1a52006-02-10 02:30:37 +0000319
Chris Lattner4c41d492006-02-10 01:24:09 +0000320/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
321/// trivial: that is, that the condition controls whether or not the loop does
322/// anything at all. If this is a trivial condition, unswitching produces no
323/// code duplications (equivalently, it produces a simpler loop and a new empty
324/// loop, which gets deleted).
325///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000326/// If this is a trivial condition, return true, otherwise return false. When
327/// returning true, this sets Cond and Val to the condition that controls the
328/// trivial condition: when Cond dynamically equals Val, the loop is known to
329/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
330/// Cond == Val.
331///
Devang Patele6962df2008-07-02 01:18:13 +0000332bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
333 BasicBlock **LoopExit) {
334 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000335 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000336
Chris Lattnera48654e2006-02-15 22:52:05 +0000337 BasicBlock *LoopExitBB = 0;
338 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
339 // If the header block doesn't end with a conditional branch on Cond, we
340 // can't handle it.
341 if (!BI->isConditional() || BI->getCondition() != Cond)
342 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000343
Chris Lattnera48654e2006-02-15 22:52:05 +0000344 // Check to see if a successor of the branch is guaranteed to go to the
345 // latch block or exit through a one exit block without having any
346 // side-effects. If so, determine the value of Cond that causes it to do
347 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000348 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
349 BI->getSuccessor(0)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000350 if (Val) *Val = ConstantInt::getTrue();
Devang Patele6962df2008-07-02 01:18:13 +0000351 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
352 BI->getSuccessor(1)))) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000353 if (Val) *Val = ConstantInt::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000354 }
355 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
356 // If this isn't a switch on Cond, we can't handle it.
357 if (SI->getCondition() != Cond) return false;
358
359 // Check to see if a successor of the switch is guaranteed to go to the
360 // latch block or exit through a one exit block without having any
361 // side-effects. If so, determine the value of Cond that causes it to do
362 // this. Note that we can't trivially unswitch on the default case.
363 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000364 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
365 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000366 // Okay, we found a trivial case, remember the value that is trivial.
367 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000368 break;
369 }
Chris Lattner4e132392006-02-15 22:03:36 +0000370 }
371
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000372 // If we didn't find a single unique LoopExit block, or if the loop exit block
373 // contains phi nodes, this isn't trivial.
374 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000375 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000376
Chris Lattnera48654e2006-02-15 22:52:05 +0000377 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000378
379 // We already know that nothing uses any scalar values defined inside of this
380 // loop. As such, we just have to check to see if this loop will execute any
381 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000382 // part of the loop that the code *would* execute. We already checked the
383 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000384 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
385 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000386 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000387 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000388}
389
390/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patele6962df2008-07-02 01:18:13 +0000391/// we choose to unswitch current loop on the specified value.
Chris Lattner4c41d492006-02-10 01:24:09 +0000392///
Devang Patele6962df2008-07-02 01:18:13 +0000393unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000394 // If the condition is trivial, always unswitch. There is no code growth for
395 // this case.
Devang Patele6962df2008-07-02 01:18:13 +0000396 if (IsTrivialUnswitchCondition(LIC))
Chris Lattner4c41d492006-02-10 01:24:09 +0000397 return 0;
398
Owen Anderson372994b2006-06-28 17:47:50 +0000399 // FIXME: This is really overly conservative. However, more liberal
400 // estimations have thus far resulted in excessive unswitching, which is bad
401 // both in compile time and in code size. This should be replaced once
402 // someone figures out how a good estimation.
Devang Patele6962df2008-07-02 01:18:13 +0000403 return currentLoop->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000404
Chris Lattner4c41d492006-02-10 01:24:09 +0000405 unsigned Cost = 0;
406 // FIXME: this is brain dead. It should take into consideration code
407 // shrinkage.
Devang Patele6962df2008-07-02 01:18:13 +0000408 for (Loop::block_iterator I = currentLoop->block_begin(),
409 E = currentLoop->block_end();
Chris Lattner4c41d492006-02-10 01:24:09 +0000410 I != E; ++I) {
411 BasicBlock *BB = *I;
412 // Do not include empty blocks in the cost calculation. This happen due to
413 // loop canonicalization and will be removed.
414 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
415 continue;
416
417 // Count basic blocks.
418 ++Cost;
419 }
420
421 return Cost;
422}
423
Devang Patele6962df2008-07-02 01:18:13 +0000424/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000425/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
426/// unswitch the loop, reprocess the pieces, then return true.
Devang Patele6962df2008-07-02 01:18:13 +0000427bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
428 // Check to see if it would be profitable to unswitch current loop.
429 unsigned Cost = getLoopUnswitchCost(LoopCond);
Devang Patel743f7e82007-06-06 00:21:03 +0000430
431 // Do not do non-trivial unswitch while optimizing for size.
432 if (Cost && OptimizeForSize)
433 return false;
434
Chris Lattner0f862e52006-03-24 07:14:00 +0000435 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000436 // FIXME: this should estimate growth by the amount of code shared by the
437 // resultant unswitched loops.
438 //
Bill Wendlingb7427032006-11-26 09:46:52 +0000439 DOUT << "NOT unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000440 << currentLoop->getHeader()->getName() << ", cost too high: "
441 << currentLoop->getBlocks().size() << "\n";
Chris Lattnerc2358092006-02-11 00:43:37 +0000442 return false;
443 }
Devang Patele6962df2008-07-02 01:18:13 +0000444
445 initLoopData();
446
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000447 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000448 BasicBlock *ExitBlock;
Devang Patele6962df2008-07-02 01:18:13 +0000449 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
450 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000451 } else {
Devang Patele6962df2008-07-02 01:18:13 +0000452 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000453 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000454
Chris Lattnerc2358092006-02-11 00:43:37 +0000455 return true;
456}
457
Misha Brukmanfd939082005-04-21 23:48:37 +0000458// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000459// current values into those specified by ValueMap.
460//
Misha Brukmanfd939082005-04-21 23:48:37 +0000461static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000462 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000463 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
464 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000465 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner18f16092004-04-19 18:07:02 +0000466 if (It != ValueMap.end()) Op = It->second;
467 I->setOperand(op, Op);
468 }
469}
470
Chris Lattner684b22d2007-08-02 16:53:43 +0000471// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
472// Info.
Devang Patel31ad7532007-07-18 23:48:20 +0000473//
474// If Orig block's immediate dominator is mapped in VM then use corresponding
475// immediate dominator from the map. Otherwise Orig block's dominator is also
476// NewBB's dominator.
477//
Devang Patel24857a32007-07-18 23:50:19 +0000478// OrigPreheader is loop pre-header before this pass started
Devang Patel31ad7532007-07-18 23:48:20 +0000479// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Patel24857a32007-07-18 23:50:19 +0000480// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman844731a2008-05-13 00:00:25 +0000481static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
482 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
483 BasicBlock *OrigHeader,
484 DominatorTree *DT, DominanceFrontier *DF,
485 DenseMap<const Value*, Value*> &VM) {
Devang Patelcce624a2007-06-28 00:49:00 +0000486
Devang Patel31ad7532007-07-18 23:48:20 +0000487 // If NewBB alreay has found its place in domiantor tree then no need to do
488 // anything.
489 if (DT->getNode(NewBB))
490 return;
491
492 // If Orig does not have any immediate domiantor then its clone, NewBB, does
493 // not need any immediate dominator.
Devang Patelcce624a2007-06-28 00:49:00 +0000494 DomTreeNode *OrigNode = DT->getNode(Orig);
495 if (!OrigNode)
496 return;
Devang Patel31ad7532007-07-18 23:48:20 +0000497 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
498 if (!OrigIDomNode)
499 return;
500
501 BasicBlock *OrigIDom = NULL;
502
503 // If Orig is original loop header then its immediate dominator is
504 // NewPreheader.
505 if (Orig == OrigHeader)
506 OrigIDom = NewPreheader;
507
508 // If Orig is new pre-header then its immediate dominator is
509 // original pre-header.
510 else if (Orig == NewPreheader)
511 OrigIDom = OrigPreheader;
512
513 // Other as DT to find Orig's immediate dominator.
514 else
515 OrigIDom = OrigIDomNode->getBlock();
516
Devang Pateldf5cf202007-07-30 21:10:44 +0000517 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
518 BasicBlock *NewIDom = OrigIDom;
519 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
520 if (I != VM.end()) {
521 NewIDom = cast<BasicBlock>(I->second);
522
523 // If NewIDom does not have corresponding dominatore tree node then
524 // get one.
525 if (!DT->getNode(NewIDom))
Devang Patel31ad7532007-07-18 23:48:20 +0000526 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
527 OrigHeader, DT, DF, VM);
Devang Patelcce624a2007-06-28 00:49:00 +0000528 }
Devang Pateldf5cf202007-07-30 21:10:44 +0000529
530 DT->addNewBlock(NewBB, NewIDom);
531
532 // Copy cloned dominance frontiner set
Devang Patelf34a43a2007-06-29 23:11:49 +0000533 DominanceFrontier::DomSetType NewDFSet;
534 if (DF) {
535 DominanceFrontier::iterator DFI = DF->find(Orig);
536 if ( DFI != DF->end()) {
537 DominanceFrontier::DomSetType S = DFI->second;
538 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
539 I != E; ++I) {
540 BasicBlock *BB = *I;
Chuck Rose III936baaa2007-07-27 18:26:35 +0000541 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
542 if (IDM != VM.end())
543 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Devang Patelf34a43a2007-06-29 23:11:49 +0000544 else
545 NewDFSet.insert(BB);
546 }
547 }
548 DF->addBasicBlock(NewBB, NewDFSet);
549 }
Devang Patelcce624a2007-06-28 00:49:00 +0000550}
551
Chris Lattner18f16092004-04-19 18:07:02 +0000552/// CloneLoop - Recursively clone the specified loop and all of its children,
553/// mapping the blocks with the specified map.
Chris Lattner5e665f52007-02-03 00:08:31 +0000554static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000555 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000556 Loop *New = new Loop();
557
Devang Patel1bc89362007-03-07 00:26:10 +0000558 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000559
560 // Add all of the blocks in L to the new loop.
561 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
562 I != E; ++I)
563 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000564 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000565
566 // Add all of the subloops to the new loop.
567 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000568 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000569
Chris Lattner18f16092004-04-19 18:07:02 +0000570 return New;
571}
572
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000573/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
574/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
575/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000576void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
577 BasicBlock *TrueDest,
578 BasicBlock *FalseDest,
579 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000580 // Insert a conditional branch on LIC to the two preheaders. The original
581 // code is the true version and the new code is the false version.
582 Value *BranchVal = LIC;
Reid Spencerc1030572007-01-19 21:13:56 +0000583 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000585 else if (Val != ConstantInt::getTrue())
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000586 // We want to enter the new loop when the condition is true.
587 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000588
589 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000590 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000591}
592
593
Chris Lattner4c41d492006-02-10 01:24:09 +0000594/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
595/// condition in it (a cond branch from its header block to its latch block,
596/// where the path through the loop that doesn't execute its body has no
597/// side-effects), unswitch it. This doesn't involve any code duplication, just
598/// moving the conditional branch outside of the loop and updating loop info.
599void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000600 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000601 BasicBlock *ExitBlock) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000602 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000603 << loopHeader->getName() << " [" << L->getBlocks().size()
Bill Wendlingb7427032006-11-26 09:46:52 +0000604 << " blocks] in Function " << L->getHeader()->getParent()->getName()
605 << " on cond: " << *Val << " == " << *Cond << "\n";
Chris Lattner4d1ca942006-02-10 01:36:35 +0000606
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000607 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000608 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000609 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000610 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000611
612 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000613 // to branch to: this is the exit block out of the loop that we should
614 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000615
Chris Lattner4e132392006-02-15 22:03:36 +0000616 // Split this block now, so that the loop maintains its exit block, and so
617 // that the jump from the preheader can execute the contents of the exit block
618 // without actually branching to it (the exit block should be dominated by the
619 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000620 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000621 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000622
Chris Lattner4c41d492006-02-10 01:24:09 +0000623 // Okay, now we have a position to branch from and a position to branch to,
624 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000625 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000626 loopPreheader->getTerminator());
Devang Patel2f170992008-06-02 22:52:56 +0000627 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000628 DT->changeImmediateDominator(NewExit, loopPreheader);
629 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel2f170992008-06-02 22:52:56 +0000630 }
Devang Patel64cd6582008-06-18 02:16:38 +0000631
632 if (DF) {
633 // NewExit is now part of NewPH and Loop Header's dominance
634 // frontier.
635 DominanceFrontier::iterator DFI = DF->find(NewPH);
636 if (DFI != DF->end())
637 DF->addToFrontier(DFI, NewExit);
Devang Patele6962df2008-07-02 01:18:13 +0000638 DFI = DF->find(loopHeader);
Devang Patel64cd6582008-06-18 02:16:38 +0000639 DF->addToFrontier(DFI, NewExit);
640
641 // ExitBlock does not have successors then NewExit is part of
642 // its dominance frontier.
643 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
644 DFI = DF->find(ExitBlock);
645 DF->addToFrontier(DFI, NewExit);
646 }
647 }
Devang Patele6962df2008-07-02 01:18:13 +0000648 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
649 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000650
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000651 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000652 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000653
Chris Lattner4c41d492006-02-10 01:24:09 +0000654 // Now that we know that the loop is never entered when this condition is a
655 // particular value, rewrite the loop with this info. We know that this will
656 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000657 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000658 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000659}
660
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000661/// ReplaceLoopExternalDFMember -
662/// If BB's dominance frontier has a member that is not part of loop L then
663/// remove it. Add NewDFMember in BB's dominance frontier.
664void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
665 BasicBlock *NewDFMember) {
666
667 DominanceFrontier::iterator DFI = DF->find(BB);
668 if (DFI == DF->end())
669 return;
670
671 DominanceFrontier::DomSetType &DFSet = DFI->second;
672 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patelb5938982007-10-09 21:31:36 +0000673 DE = DFSet.end(); DI != DE;) {
674 BasicBlock *B = *DI++;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000675 if (L->contains(B))
676 continue;
David Greene60f75152007-12-17 17:40:29 +0000677
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000678 DF->removeFromFrontier(DFI, B);
679 LoopDF.insert(B);
680 }
681
682 DF->addToFrontier(DFI, NewDFMember);
683}
684
Chris Lattner48a80b02008-04-21 00:25:49 +0000685/// SplitExitEdges - Split all of the edges from inside the loop to their exit
686/// blocks. Update the appropriate Phi nodes as we do so.
687void LoopUnswitch::SplitExitEdges(Loop *L,
688 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Patelf476e8e2007-10-03 21:16:08 +0000689 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000690
Chris Lattner4c41d492006-02-10 01:24:09 +0000691 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000692 BasicBlock *ExitBlock = ExitBlocks[i];
693 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
694
695 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
Devang Patel05c1dc62007-07-06 22:03:47 +0000696 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel1ff61382007-08-02 15:25:57 +0000697 MiddleBlocks.push_back(MiddleBlock);
Owen Anderson2b67f072006-06-26 07:44:36 +0000698 BasicBlock* StartBlock = Preds[j];
699 BasicBlock* EndBlock;
700 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
701 EndBlock = MiddleBlock;
702 MiddleBlock = EndBlock->getSinglePredecessor();;
703 } else {
704 EndBlock = ExitBlock;
705 }
706
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000707 OrigLoopExitMap[StartBlock] = EndBlock;
708
Owen Anderson2b67f072006-06-26 07:44:36 +0000709 std::set<PHINode*> InsertedPHIs;
710 PHINode* OldLCSSA = 0;
711 for (BasicBlock::iterator I = EndBlock->begin();
712 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
713 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greif051a9502008-04-06 20:25:17 +0000714 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
715 OldLCSSA->getName() + ".us-lcssa",
716 MiddleBlock->getTerminator());
Owen Anderson2b67f072006-06-26 07:44:36 +0000717 NewLCSSA->addIncoming(OldValue, StartBlock);
718 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
719 NewLCSSA);
720 InsertedPHIs.insert(NewLCSSA);
721 }
722
Dan Gohman02dea8b2008-05-23 21:05:58 +0000723 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Owen Anderson2b67f072006-06-26 07:44:36 +0000724 for (BasicBlock::iterator I = MiddleBlock->begin();
725 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
726 ++I) {
Gabor Greif051a9502008-04-06 20:25:17 +0000727 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
728 OldLCSSA->getName() + ".us-lcssa",
729 InsertPt);
Owen Anderson2b67f072006-06-26 07:44:36 +0000730 OldLCSSA->replaceAllUsesWith(NewLCSSA);
731 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
732 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000733
734 if (DF && DT) {
735 // StartBlock -- > MiddleBlock -- > EndBlock
736 // StartBlock is loop exiting block. EndBlock will become merge point
737 // of two loop exits after loop unswitch.
738
739 // If StartBlock's DF member includes a block that is not loop member
740 // then replace that DF member with EndBlock.
741
742 // If MiddleBlock's DF member includes a block that is not loop member
743 // tnen replace that DF member with EndBlock.
744
745 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
746 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
747 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000748 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000749 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000750
Devang Patelf476e8e2007-10-03 21:16:08 +0000751}
752
Devang Patelc1e26602007-10-03 21:17:43 +0000753/// UnswitchNontrivialCondition - We determined that the loop is profitable
754/// to unswitch when LIC equal Val. Split it into loop versions and test the
755/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000756void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
757 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000758 Function *F = loopHeader->getParent();
Devang Patelf476e8e2007-10-03 21:16:08 +0000759 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patele6962df2008-07-02 01:18:13 +0000760 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Patelf476e8e2007-10-03 21:16:08 +0000761 << " blocks] in Function " << F->getName()
762 << " when '" << *Val << "' == " << *LIC << "\n";
763
764 // LoopBlocks contains all of the basic blocks of the loop, including the
765 // preheader of the loop, the body of the loop, and the exit blocks of the
766 // loop, in that order.
767 std::vector<BasicBlock*> LoopBlocks;
768
769 // First step, split the preheader and exit blocks, and add these blocks to
770 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000771 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000772 LoopBlocks.push_back(NewPreheader);
773
774 // We want the loop to come after the preheader, but before the exit blocks.
775 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
776
777 SmallVector<BasicBlock*, 8> ExitBlocks;
778 L->getUniqueExitBlocks(ExitBlocks);
779
780 // Split all of the edges from inside the loop to their exit blocks. Update
781 // the appropriate Phi nodes as we do so.
782 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000783 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000784
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000785 // The exit blocks may have been changed due to edge splitting, recompute.
786 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000787 L->getUniqueExitBlocks(ExitBlocks);
788
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000789 // Add exit blocks to the loop blocks.
790 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000791
792 // Next step, clone all of the basic blocks that make up the loop (including
793 // the loop preheader and exit blocks), keeping track of the mapping between
794 // the instructions and blocks.
795 std::vector<BasicBlock*> NewBlocks;
796 NewBlocks.reserve(LoopBlocks.size());
Chris Lattner5e665f52007-02-03 00:08:31 +0000797 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000798 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000799 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
800 NewBlocks.push_back(New);
801 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patel15c260a2007-07-31 08:03:26 +0000802 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000803 }
804
Devang Patel1ff61382007-08-02 15:25:57 +0000805 // OutSiders are basic block that are dominated by original header and
806 // at the same time they are not part of loop.
807 SmallPtrSet<BasicBlock *, 8> OutSiders;
808 if (DT) {
Devang Patele6962df2008-07-02 01:18:13 +0000809 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel1ff61382007-08-02 15:25:57 +0000810 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
811 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
812 BasicBlock *B = (*DI)->getBlock();
813
814 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
815 if (VI == ValueMap.end())
816 OutSiders.insert(B);
Devang Patelcce624a2007-06-28 00:49:00 +0000817 }
Devang Patel1ff61382007-08-02 15:25:57 +0000818 }
819
Chris Lattner18f16092004-04-19 18:07:02 +0000820 // Splice the newly inserted blocks into the function right before the
821 // original preheader.
822 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
823 NewBlocks[0], F->end());
824
825 // Now we create the new Loop object for the versioned loop.
Devang Patel1bc89362007-03-07 00:26:10 +0000826 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000827 Loop *ParentLoop = L->getParentLoop();
828 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000829 // Make sure to add the cloned preheader and exit blocks to the parent loop
830 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000831 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000832 }
833
834 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
835 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000836 // The new exit block should be in the same loop as the old one.
837 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000838 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000839
840 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
841 "Exit block should have been split to have one successor!");
842 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
843
844 // If the successor of the exit block had PHI nodes, add an entry for
845 // NewExit.
846 PHINode *PN;
847 for (BasicBlock::iterator I = ExitSucc->begin();
848 (PN = dyn_cast<PHINode>(I)); ++I) {
849 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000850 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
Chris Lattnere8255932006-02-10 23:26:14 +0000851 if (It != ValueMap.end()) V = It->second;
852 PN->addIncoming(V, NewExit);
853 }
Chris Lattner18f16092004-04-19 18:07:02 +0000854 }
855
856 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000857 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
858 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
859 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner18f16092004-04-19 18:07:02 +0000860 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000861
Chris Lattner18f16092004-04-19 18:07:02 +0000862 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000863 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000864 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000865 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000866
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000867 // Emit the new branch that selects between the two versions of this loop.
868 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000869 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000870 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000871
872 // Update dominator info
873 if (DF && DT) {
874
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000875 SmallVector<BasicBlock *,4> ExitingBlocks;
876 L->getExitingBlocks(ExitingBlocks);
877
Devang Patel1ff61382007-08-02 15:25:57 +0000878 // Clone dominator info for all cloned basic block.
879 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
880 BasicBlock *LBB = LoopBlocks[i];
881 BasicBlock *NBB = NewBlocks[i];
Devang Patele6962df2008-07-02 01:18:13 +0000882 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
883 loopHeader, DT, DF, ValueMap);
Devang Patel1ff61382007-08-02 15:25:57 +0000884
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000885 // If LBB's dominance frontier includes DFMember
886 // such that DFMember is also a member of LoopDF then
887 // - Remove DFMember from LBB's dominance frontier
Chris Lattner48a80b02008-04-21 00:25:49 +0000888 // - Copy loop exiting blocks', that are dominated by BB,
889 // dominance frontier member in BB's dominance frontier
Devang Patel1ff61382007-08-02 15:25:57 +0000890
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000891 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel1ff61382007-08-02 15:25:57 +0000892 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000893 if (LBBI == DF->end())
894 continue;
895
896 DominanceFrontier::DomSetType &LBSet = LBBI->second;
897 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
898 LE = LBSet.end(); LI != LE; /* NULL */) {
899 BasicBlock *B = *LI++;
Devang Patele6962df2008-07-02 01:18:13 +0000900 if (B == LBB && B == loopHeader)
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000901 continue;
902 bool removeB = false;
903 if (!LoopDF.count(B))
904 continue;
905
906 // If LBB dominates loop exits then insert loop exit block's DF
907 // into B's DF.
Chris Lattner48a80b02008-04-21 00:25:49 +0000908 for(SmallVector<BasicBlock *, 4>::iterator
909 LExitI = ExitingBlocks.begin(),
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000910 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
911 BasicBlock *E = *LExitI;
912
913 if (!DT->dominates(LBB,E))
914 continue;
915
916 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
917 OrigLoopExitMap.find(E);
918 if (DFBI == OrigLoopExitMap.end())
919 continue;
920
921 BasicBlock *DFB = DFBI->second;
922 DF->addToFrontier(LBBI, DFB);
923 DF->addToFrontier(NBBI, DFB);
924 removeB = true;
925 }
926
Chris Lattner48a80b02008-04-21 00:25:49 +0000927 // If B's replacement is inserted in DF then now is the time to remove
928 // B.
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000929 if (removeB) {
930 DF->removeFromFrontier(LBBI, B);
931 if (L->contains(B))
932 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
933 else
Devang Patel1ff61382007-08-02 15:25:57 +0000934 DF->removeFromFrontier(NBBI, B);
935 }
936 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000937
Devang Patel1ff61382007-08-02 15:25:57 +0000938 }
939
940 // MiddleBlocks are dominated by original pre header. SplitEdge updated
941 // MiddleBlocks' dominance frontier appropriately.
942 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
943 BasicBlock *MBB = MiddleBlocks[i];
944 if (!MBB->getSinglePredecessor())
Devang Patele6962df2008-07-02 01:18:13 +0000945 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000946 }
947
948 // All Outsiders are now dominated by original pre header.
949 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
950 OE = OutSiders.end(); OI != OE; ++OI) {
951 BasicBlock *OB = *OI;
Devang Patele6962df2008-07-02 01:18:13 +0000952 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000953 }
954
955 // New loop headers are dominated by original preheader
Devang Patele6962df2008-07-02 01:18:13 +0000956 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
957 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel1ff61382007-08-02 15:25:57 +0000958 }
959
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000960 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000961 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000962
963 // Now we rewrite the original code to know that the condition is true and the
964 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000965 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
966
967 // It's possible that simplifying one loop could cause the other to be
968 // deleted. If so, don't simplify it.
969 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
970 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000971}
972
Chris Lattner52221f72006-02-17 00:31:07 +0000973/// RemoveFromWorklist - Remove all instances of I from the worklist vector
974/// specified.
975static void RemoveFromWorklist(Instruction *I,
976 std::vector<Instruction*> &Worklist) {
977 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
978 Worklist.end(), I);
979 while (WI != Worklist.end()) {
980 unsigned Offset = WI-Worklist.begin();
981 Worklist.erase(WI);
982 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
983 }
984}
985
986/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
987/// program, replacing all uses with V and update the worklist.
988static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000989 std::vector<Instruction*> &Worklist,
990 Loop *L, LPPassManager *LPM) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000991 DOUT << "Replace with '" << *V << "': " << *I;
Chris Lattner52221f72006-02-17 00:31:07 +0000992
993 // Add uses to the worklist, which may be dead now.
994 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
995 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
996 Worklist.push_back(Use);
997
998 // Add users to the worklist which may be simplified now.
999 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1000 UI != E; ++UI)
1001 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +00001002 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001003 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001004 I->replaceAllUsesWith(V);
1005 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001006 ++NumSimplify;
1007}
1008
Chris Lattnerdb410242006-02-18 02:42:34 +00001009/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1010/// information, and remove any dead successors it has.
1011///
1012void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +00001013 std::vector<Instruction*> &Worklist,
1014 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001015 if (pred_begin(BB) != pred_end(BB)) {
1016 // This block isn't dead, since an edge to BB was just removed, see if there
1017 // are any easy simplifications we can do now.
1018 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1019 // If it has one pred, fold phi nodes in BB.
1020 while (isa<PHINode>(BB->begin()))
1021 ReplaceUsesOfWith(BB->begin(),
1022 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +00001023 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001024
1025 // If this is the header of a loop and the only pred is the latch, we now
1026 // have an unreachable loop.
1027 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +00001028 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001029 // Remove the branch from the latch to the header block, this makes
1030 // the header dead, which will make the latch dead (because the header
1031 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +00001032 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001033 Pred->getTerminator()->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001034 new UnreachableInst(Pred);
1035
1036 // The loop is now broken, remove it from LI.
1037 RemoveLoopFromHierarchy(L);
1038
1039 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +00001040 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001041 return;
1042 }
1043
1044 // If pred ends in a uncond branch, add uncond branch to worklist so that
1045 // the two blocks will get merged.
1046 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1047 if (BI->isUnconditional())
1048 Worklist.push_back(BI);
1049 }
1050 return;
1051 }
Chris Lattner52221f72006-02-17 00:31:07 +00001052
Bill Wendlingb7427032006-11-26 09:46:52 +00001053 DOUT << "Nuking dead block: " << *BB;
Chris Lattnerdb410242006-02-18 02:42:34 +00001054
1055 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001056 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +00001057 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001058
1059 // Anything that uses the instructions in this basic block should have their
1060 // uses replaced with undefs.
1061 if (!I->use_empty())
1062 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1063 }
Chris Lattnerdb410242006-02-18 02:42:34 +00001064
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001065 // If this is the edge to the header block for a loop, remove the loop and
1066 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +00001067 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001068 if (BBLoop->getLoopLatch() == BB)
1069 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +00001070 }
1071
1072 // Remove the block from the loop info, which removes it from any loops it
1073 // was in.
1074 LI->removeBlock(BB);
1075
1076
1077 // Remove phi node entries in successors for this block.
1078 TerminatorInst *TI = BB->getTerminator();
1079 std::vector<BasicBlock*> Succs;
1080 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1081 Succs.push_back(TI->getSuccessor(i));
1082 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001083 }
1084
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001085 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +00001086 std::sort(Succs.begin(), Succs.end());
1087 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1088
1089 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +00001090 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001091 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001092 // Remove successor blocks here that are not dead, so that we know we only
1093 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1094 // then getting removed before we revisit them, which is badness.
1095 //
1096 for (unsigned i = 0; i != Succs.size(); ++i)
1097 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1098 // One exception is loop headers. If this block was the preheader for a
1099 // loop, then we DO want to visit the loop so the loop gets deleted.
1100 // We know that if the successor is a loop header, that this loop had to
1101 // be the preheader: the case where this was the latch block was handled
1102 // above and headers can only have two predecessors.
1103 if (!LI->isLoopHeader(Succs[i])) {
1104 Succs.erase(Succs.begin()+i);
1105 --i;
1106 }
1107 }
1108
Chris Lattnerdb410242006-02-18 02:42:34 +00001109 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +00001110 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +00001111}
Chris Lattner52221f72006-02-17 00:31:07 +00001112
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001113/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1114/// become unwrapped, either because the backedge was deleted, or because the
1115/// edge into the header was removed. If the edge into the header from the
1116/// latch block was removed, the loop is unwrapped but subloops are still alive,
1117/// so they just reparent loops. If the loops are actually dead, they will be
1118/// removed later.
1119void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +00001120 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001121 RemoveLoopFromWorklist(L);
1122}
1123
1124
1125
Chris Lattnerc2358092006-02-11 00:43:37 +00001126// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1127// the value specified by Val in the specified loop, or we know it does NOT have
1128// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +00001129void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +00001130 Constant *Val,
1131 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +00001132 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +00001133
Chris Lattner18f16092004-04-19 18:07:02 +00001134 // FIXME: Support correlated properties, like:
1135 // for (...)
1136 // if (li1 < li2)
1137 // ...
1138 // if (li1 > li2)
1139 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +00001140
Chris Lattner708e1a52006-02-10 02:30:37 +00001141 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1142 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +00001143 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +00001144 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001145
Chris Lattner52221f72006-02-17 00:31:07 +00001146 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1147 // in the loop with the appropriate one directly.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001148 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001149 Value *Replacement;
1150 if (IsEqual)
1151 Replacement = Val;
1152 else
Reid Spencer579dca12007-01-12 04:24:46 +00001153 Replacement = ConstantInt::get(Type::Int1Ty,
1154 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +00001155
1156 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1157 if (Instruction *U = cast<Instruction>(Users[i])) {
1158 if (!L->contains(U->getParent()))
1159 continue;
1160 U->replaceUsesOfWith(LIC, Replacement);
1161 Worklist.push_back(U);
1162 }
1163 } else {
1164 // Otherwise, we don't know the precise value of LIC, but we do know that it
1165 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1166 // can. This case occurs when we unswitch switch statements.
1167 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1168 if (Instruction *U = cast<Instruction>(Users[i])) {
1169 if (!L->contains(U->getParent()))
1170 continue;
1171
1172 Worklist.push_back(U);
1173
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001174 // If we know that LIC is not Val, use this info to simplify code.
1175 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1176 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1177 if (SI->getCaseValue(i) == Val) {
1178 // Found a dead case value. Don't remove PHI nodes in the
1179 // successor if they become single-entry, those PHI nodes may
1180 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +00001181
1182 // FIXME: This is a hack. We need to keep the successor around
1183 // and hooked up so as to preserve the loop structure, because
1184 // trying to update it is complicated. So instead we preserve the
1185 // loop structure and put the block on an dead code path.
1186
1187 BasicBlock* Old = SI->getParent();
Devang Patel05c1dc62007-07-06 22:03:47 +00001188 BasicBlock* Split = SplitBlock(Old, SI, this);
Owen Anderson2b67f072006-06-26 07:44:36 +00001189
1190 Instruction* OldTerm = Old->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001191 BranchInst::Create(Split, SI->getSuccessor(i),
1192 ConstantInt::getTrue(), OldTerm);
Devang Patel9ee49c52007-09-20 23:45:50 +00001193
Chris Lattner48a80b02008-04-21 00:25:49 +00001194 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Owen Anderson2b67f072006-06-26 07:44:36 +00001195 Old->getTerminator()->eraseFromParent();
1196
Owen Andersonbef85082006-06-27 22:26:09 +00001197 PHINode *PN;
1198 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1199 (PN = dyn_cast<PHINode>(II)); ++II) {
1200 Value *InVal = PN->removeIncomingValue(Split, false);
1201 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +00001202 }
1203
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001204 SI->removeCase(i);
1205 break;
Chris Lattnerc2358092006-02-11 00:43:37 +00001206 }
1207 }
Chris Lattnerc2358092006-02-11 00:43:37 +00001208 }
Chris Lattner52221f72006-02-17 00:31:07 +00001209
1210 // TODO: We could do other simplifications, for example, turning
1211 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001212 }
Chris Lattner52221f72006-02-17 00:31:07 +00001213 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001214
Devang Patel15c260a2007-07-31 08:03:26 +00001215 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +00001216}
1217
1218/// SimplifyCode - Okay, now that we have simplified some instructions in the
1219/// loop, walk over it and constant prop, dce, and fold control flow where
1220/// possible. Note that this is effectively a very simple loop-structure-aware
1221/// optimizer. During processing of this loop, L could very well be deleted, so
1222/// it must not be used.
1223///
1224/// FIXME: When the loop optimizer is more mature, separate this out to a new
1225/// pass.
1226///
Devang Patel15c260a2007-07-31 08:03:26 +00001227void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +00001228 while (!Worklist.empty()) {
1229 Instruction *I = Worklist.back();
1230 Worklist.pop_back();
1231
1232 // Simple constant folding.
1233 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +00001234 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001235 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001236 }
Chris Lattner52221f72006-02-17 00:31:07 +00001237
1238 // Simple DCE.
1239 if (isInstructionTriviallyDead(I)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001240 DOUT << "Remove dead instruction '" << *I;
Chris Lattner52221f72006-02-17 00:31:07 +00001241
1242 // Add uses to the worklist, which may be dead now.
1243 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1244 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1245 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +00001246 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001247 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +00001248 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001249 ++NumSimplify;
1250 continue;
1251 }
1252
1253 // Special case hacks that appear commonly in unswitched code.
1254 switch (I->getOpcode()) {
1255 case Instruction::Select:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001256 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner684b22d2007-08-02 16:53:43 +00001257 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1258 LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001259 continue;
1260 }
1261 break;
1262 case Instruction::And:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001263 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001264 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001265 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001266 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001267 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001268 if (CB->isOne()) // X & 1 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001269 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001270 else // X & 0 -> 0
Devang Patel15c260a2007-07-31 08:03:26 +00001271 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001272 continue;
1273 }
Chris Lattner52221f72006-02-17 00:31:07 +00001274 break;
1275 case Instruction::Or:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001276 if (isa<ConstantInt>(I->getOperand(0)) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001277 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
Chris Lattner52221f72006-02-17 00:31:07 +00001278 cast<BinaryOperator>(I)->swapOperands();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001279 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001280 if (CB->getType() == Type::Int1Ty) {
Reid Spencera5dae0c2007-03-02 23:35:28 +00001281 if (CB->isOne()) // X | 1 -> 1
Devang Patel15c260a2007-07-31 08:03:26 +00001282 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001283 else // X | 0 -> X
Devang Patel15c260a2007-07-31 08:03:26 +00001284 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001285 continue;
1286 }
Chris Lattner52221f72006-02-17 00:31:07 +00001287 break;
1288 case Instruction::Br: {
1289 BranchInst *BI = cast<BranchInst>(I);
1290 if (BI->isUnconditional()) {
1291 // If BI's parent is the only pred of the successor, fold the two blocks
1292 // together.
1293 BasicBlock *Pred = BI->getParent();
1294 BasicBlock *Succ = BI->getSuccessor(0);
1295 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1296 if (!SinglePred) continue; // Nothing to do.
1297 assert(SinglePred == Pred && "CFG broken");
1298
Bill Wendlingb7427032006-11-26 09:46:52 +00001299 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1300 << Succ->getName() << "\n";
Chris Lattner52221f72006-02-17 00:31:07 +00001301
1302 // Resolve any single entry PHI nodes in Succ.
1303 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001304 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001305
1306 // Move all of the successor contents from Succ to Pred.
1307 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1308 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001309 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001310 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001311 RemoveFromWorklist(BI, Worklist);
1312
1313 // If Succ has any successors with PHI nodes, update them to have
1314 // entries coming from Pred instead of Succ.
1315 Succ->replaceAllUsesWith(Pred);
1316
1317 // Remove Succ from the loop tree.
1318 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001319 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001320 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001321 ++NumSimplify;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001322 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001323 // Conditional branch. Turn it into an unconditional branch, then
1324 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001325 break; // FIXME: Enable.
1326
Bill Wendlingb7427032006-11-26 09:46:52 +00001327 DOUT << "Folded branch: " << *BI;
Reid Spencer579dca12007-01-12 04:24:46 +00001328 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1329 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001330 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001331 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001332 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001333 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001334 RemoveFromWorklist(BI, Worklist);
1335 ++NumSimplify;
1336
Devang Patel15c260a2007-07-31 08:03:26 +00001337 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001338 }
1339 break;
1340 }
1341 }
1342 }
Chris Lattner18f16092004-04-19 18:07:02 +00001343}