blob: 009ee7b95eaba6dfca1aeabc78cc82be7e7e0f83 [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"
Dan Gohman597c5e22009-10-13 20:12:23 +000036#include "llvm/Analysis/InlineCost.h"
Chris Lattner4f1f6f62010-04-20 05:33:18 +000037#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner18f16092004-04-19 18:07:02 +000038#include "llvm/Analysis/LoopInfo.h"
Devang Patel1bc89362007-03-07 00:26:10 +000039#include "llvm/Analysis/LoopPass.h"
Devang Patelcce624a2007-06-28 00:49:00 +000040#include "llvm/Analysis/Dominators.h"
Chris Lattner18f16092004-04-19 18:07:02 +000041#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
Devang Patelfb688d42007-02-26 20:22:50 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnera3522002008-12-01 06:52:57 +000046#include "llvm/ADT/STLExtras.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000047#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000048#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000050#include <algorithm>
Chris Lattner2f4b8982006-02-09 19:14:52 +000051#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000052using namespace llvm;
53
Chris Lattner0e5f4992006-12-19 21:40:18 +000054STATISTIC(NumBranches, "Number of branches unswitched");
55STATISTIC(NumSwitches, "Number of switches unswitched");
56STATISTIC(NumSelects , "Number of selects unswitched");
57STATISTIC(NumTrivial , "Number of unswitches that are trivial");
58STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
59
Dan Gohmanb24f6c72009-10-13 17:50:43 +000060// The specific value of 50 here was chosen based only on intuition and a
61// few specific examples.
Dan Gohman844731a2008-05-13 00:00:25 +000062static cl::opt<unsigned>
63Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Dan Gohmanb24f6c72009-10-13 17:50:43 +000064 cl::init(50), cl::Hidden);
Chris Lattnere487abb2006-02-09 20:15:48 +000065
Dan Gohman844731a2008-05-13 00:00:25 +000066namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000067 class LoopUnswitch : public LoopPass {
Chris Lattner18f16092004-04-19 18:07:02 +000068 LoopInfo *LI; // Loop information
Devang Patel1bc89362007-03-07 00:26:10 +000069 LPPassManager *LPM;
Chris Lattnera6fc94b2006-02-18 07:57:38 +000070
Devang Patel1bc89362007-03-07 00:26:10 +000071 // LoopProcessWorklist - Used to check if second loop needs processing
72 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnera6fc94b2006-02-18 07:57:38 +000073 std::vector<Loop*> LoopProcessWorklist;
Devang Patelfb688d42007-02-26 20:22:50 +000074 SmallPtrSet<Value *,8> UnswitchedVals;
Devang Patel743f7e82007-06-06 00:21:03 +000075
76 bool OptimizeForSize;
Devang Patel6f62af62007-07-30 23:07:10 +000077 bool redoLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000078
Devang Patele6962df2008-07-02 01:18:13 +000079 Loop *currentLoop;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000080 DominatorTree *DT;
Devang Patele6962df2008-07-02 01:18:13 +000081 BasicBlock *loopHeader;
82 BasicBlock *loopPreheader;
Devang Patel5c4cd0d2007-10-05 22:29:34 +000083
Devang Patel1e41f6d2008-07-02 01:44:29 +000084 // LoopBlocks contains all of the basic blocks of the loop, including the
85 // preheader of the loop, the body of the loop, and the exit blocks of the
86 // loop, in that order.
87 std::vector<BasicBlock*> LoopBlocks;
88 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
89 std::vector<BasicBlock*> NewBlocks;
Devang Patel77a01132008-07-03 17:37:52 +000090
Chris Lattner18f16092004-04-19 18:07:02 +000091 public:
Devang Patel19974732007-05-03 01:11:54 +000092 static char ID; // Pass ID, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000093 explicit LoopUnswitch(bool Os = false) :
Owen Anderson90c579d2010-08-06 18:33:48 +000094 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Chris Lattnerea109232010-08-29 17:23:19 +000095 currentLoop(NULL), DT(NULL), loopHeader(NULL),
Owen Anderson081c34b2010-10-19 17:21:58 +000096 loopPreheader(NULL) {
97 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
98 }
Devang Patel794fd752007-05-01 21:15:47 +000099
Devang Patel1bc89362007-03-07 00:26:10 +0000100 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patele6962df2008-07-02 01:18:13 +0000101 bool processCurrentLoop();
Chris Lattner18f16092004-04-19 18:07:02 +0000102
103 /// This transformation requires natural loop information & requires that
Chris Lattnerea109232010-08-29 17:23:19 +0000104 /// loop preheaders be inserted into the CFG.
Chris Lattner18f16092004-04-19 18:07:02 +0000105 ///
106 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
107 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +0000108 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +0000109 AU.addRequired<LoopInfo>();
110 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +0000111 AU.addRequiredID(LCSSAID);
Devang Patel15c260a2007-07-31 08:03:26 +0000112 AU.addPreservedID(LCSSAID);
Devang Patel4be7d292008-07-03 06:48:21 +0000113 AU.addPreserved<DominatorTree>();
Chris Lattner18f16092004-04-19 18:07:02 +0000114 }
115
116 private:
Devang Patel15c260a2007-07-31 08:03:26 +0000117
Dan Gohman5c89b522009-09-08 15:45:00 +0000118 virtual void releaseMemory() {
119 UnswitchedVals.clear();
120 }
121
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000122 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
123 /// remove it.
124 void RemoveLoopFromWorklist(Loop *L) {
125 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
126 LoopProcessWorklist.end(), L);
127 if (I != LoopProcessWorklist.end())
128 LoopProcessWorklist.erase(I);
129 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000130
Devang Patele6962df2008-07-02 01:18:13 +0000131 void initLoopData() {
132 loopHeader = currentLoop->getHeader();
133 loopPreheader = currentLoop->getLoopPreheader();
134 }
135
Chris Lattner48a80b02008-04-21 00:25:49 +0000136 /// Split all of the edges from inside the loop to their exit blocks.
137 /// Update the appropriate Phi nodes as we do so.
Devang Patel77a01132008-07-03 17:37:52 +0000138 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000139
Devang Patele6962df2008-07-02 01:18:13 +0000140 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000141 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000142 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000143 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000144
145 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
146 Constant *Val, bool isEqual);
Devang Patelcce624a2007-06-28 00:49:00 +0000147
148 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
149 BasicBlock *TrueDest,
150 BasicBlock *FalseDest,
151 Instruction *InsertPt);
152
Devang Patel15c260a2007-07-31 08:03:26 +0000153 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerdb410242006-02-18 02:42:34 +0000154 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000155 std::vector<Instruction*> &Worklist, Loop *l);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000156 void RemoveLoopFromHierarchy(Loop *L);
Devang Patele6962df2008-07-02 01:18:13 +0000157 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
158 BasicBlock **LoopExit = 0);
159
Chris Lattner18f16092004-04-19 18:07:02 +0000160 };
Chris Lattner18f16092004-04-19 18:07:02 +0000161}
Dan Gohman844731a2008-05-13 00:00:25 +0000162char LoopUnswitch::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000163INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
164 false, false)
165INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166INITIALIZE_PASS_DEPENDENCY(LoopInfo)
167INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000168INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
169 false, false)
Chris Lattner18f16092004-04-19 18:07:02 +0000170
Daniel Dunbar394f0442008-10-22 23:32:42 +0000171Pass *llvm::createLoopUnswitchPass(bool Os) {
Devang Patel743f7e82007-06-06 00:21:03 +0000172 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) {
Chris Lattner3d606bb2010-02-02 02:26:54 +0000179 // We can never unswitch on vector conditions.
Duncan Sands1df98592010-02-16 11:11:14 +0000180 if (Cond->getType()->isVectorTy())
Chris Lattner3d606bb2010-02-02 02:26:54 +0000181 return 0;
182
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000183 // Constants should be folded, not unswitched on!
Dan Gohmana1fcd772008-10-17 00:56:52 +0000184 if (isa<Constant>(Cond)) return 0;
Devang Patel558f1b82007-06-28 00:44:10 +0000185
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000186 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patel265ca5d2008-11-03 19:38:07 +0000187
Dan Gohman0df6e092009-07-14 01:37:59 +0000188 // Hoist simple values out.
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000189 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman0df6e092009-07-14 01:37:59 +0000190 return Cond;
Dan Gohman0df6e092009-07-14 01:37:59 +0000191
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000192 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
193 if (BO->getOpcode() == Instruction::And ||
194 BO->getOpcode() == Instruction::Or) {
195 // If either the left or right side is invariant, we can unswitch on this,
196 // which will cause the branch to go away in one loop and the condition to
197 // simplify in the other one.
198 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
199 return LHS;
200 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
201 return RHS;
202 }
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000203
204 return 0;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000205}
206
Devang Patel1bc89362007-03-07 00:26:10 +0000207bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Devang Patel1bc89362007-03-07 00:26:10 +0000208 LI = &getAnalysis<LoopInfo>();
209 LPM = &LPM_Ref;
Duncan Sands1465d612009-01-28 13:14:17 +0000210 DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patele6962df2008-07-02 01:18:13 +0000211 currentLoop = L;
Devang Pateldeafefa2008-09-04 22:43:59 +0000212 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000213 bool Changed = false;
Devang Patel6f62af62007-07-30 23:07:10 +0000214 do {
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000215 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel6f62af62007-07-30 23:07:10 +0000216 redoLoop = false;
Devang Patele6962df2008-07-02 01:18:13 +0000217 Changed |= processCurrentLoop();
Devang Patel6f62af62007-07-30 23:07:10 +0000218 } while(redoLoop);
219
Devang Pateldeafefa2008-09-04 22:43:59 +0000220 if (Changed) {
221 // FIXME: Reconstruct dom info, because it is not preserved properly.
222 if (DT)
223 DT->runOnFunction(*F);
Devang Pateldeafefa2008-09-04 22:43:59 +0000224 }
Devang Patel6f62af62007-07-30 23:07:10 +0000225 return Changed;
226}
227
Devang Patele6962df2008-07-02 01:18:13 +0000228/// processCurrentLoop - Do actual work and unswitch loop if possible
229/// and profitable.
230bool LoopUnswitch::processCurrentLoop() {
Devang Patel6f62af62007-07-30 23:07:10 +0000231 bool Changed = false;
Owen Andersone922c022009-07-22 00:24:57 +0000232 LLVMContext &Context = currentLoop->getHeader()->getContext();
Devang Patel6f62af62007-07-30 23:07:10 +0000233
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000234 // Loop over all of the basic blocks in the loop. If we find an interior
235 // block that is branching on a loop-invariant condition, we can unswitch this
236 // loop.
Devang Patele6962df2008-07-02 01:18:13 +0000237 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattner9e185802010-04-05 21:18:32 +0000238 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000239 TerminatorInst *TI = (*I)->getTerminator();
240 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
241 // If this isn't branching on an invariant condition, we can't unswitch
242 // it.
243 if (BI->isConditional()) {
244 // See if this, or some part of it, is loop invariant. If so, we can
245 // unswitch on it if we desire.
Devang Patele6962df2008-07-02 01:18:13 +0000246 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
247 currentLoop, Changed);
248 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000249 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000250 ++NumBranches;
251 return true;
252 }
253 }
254 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000255 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
256 currentLoop, Changed);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000257 if (LoopCond && SI->getNumCases() > 1) {
258 // Find a value to unswitch on:
259 // FIXME: this should chose the most expensive case!
260 Constant *UnswitchVal = SI->getCaseValue(1);
Devang Patel52956922007-02-26 19:31:58 +0000261 // Do not process same value again and again.
Devang Patelfb688d42007-02-26 20:22:50 +0000262 if (!UnswitchedVals.insert(UnswitchVal))
Devang Patel52956922007-02-26 19:31:58 +0000263 continue;
Devang Patel52956922007-02-26 19:31:58 +0000264
Devang Patele6962df2008-07-02 01:18:13 +0000265 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000266 ++NumSwitches;
267 return true;
268 }
269 }
270 }
271
272 // Scan the instructions to check for unswitchable values.
273 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
274 BBI != E; ++BBI)
275 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patele6962df2008-07-02 01:18:13 +0000276 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
277 currentLoop, Changed);
278 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson5defacc2009-07-31 17:39:07 +0000279 ConstantInt::getTrue(Context))) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000280 ++NumSelects;
281 return true;
282 }
283 }
284 }
Chris Lattner18f16092004-04-19 18:07:02 +0000285 return Changed;
286}
287
Dan Gohmanb0a57212010-09-01 21:46:45 +0000288/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
289/// loop with no side effects (including infinite loops).
Chris Lattner4e132392006-02-15 22:03:36 +0000290///
Dan Gohmanb0a57212010-09-01 21:46:45 +0000291/// If true, we return true and set ExitBB to the block we
Chris Lattner4e132392006-02-15 22:03:36 +0000292/// exit through.
293///
294static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
295 BasicBlock *&ExitBB,
296 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000297 if (!Visited.insert(BB).second) {
Dan Gohmanb0a57212010-09-01 21:46:45 +0000298 // Already visited. Without more analysis, this could indicate an infinte loop.
299 return false;
Chris Lattner0017d482006-02-17 06:39:56 +0000300 } else if (!L->contains(BB)) {
301 // Otherwise, this is a loop exit, this is fine so long as this is the
302 // first exit.
303 if (ExitBB != 0) return false;
304 ExitBB = BB;
Edward O'Callaghan25798432009-11-25 05:38:41 +0000305 return true;
Chris Lattner0017d482006-02-17 06:39:56 +0000306 }
307
308 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000309 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000310 // Check to see if the successor is a trivial loop exit.
311 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
312 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000313 }
Chris Lattner4e132392006-02-15 22:03:36 +0000314
315 // Okay, everything after this looks good, check to make sure that this block
316 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000317 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000318 if (I->mayHaveSideEffects())
Chris Lattner4e132392006-02-15 22:03:36 +0000319 return false;
320
321 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000322}
323
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000324/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
325/// leads to an exit from the specified loop, and has no side-effects in the
326/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000327static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
328 std::set<BasicBlock*> Visited;
Dan Gohmanb0a57212010-09-01 21:46:45 +0000329 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Chris Lattner4e132392006-02-15 22:03:36 +0000330 BasicBlock *ExitBB = 0;
331 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
332 return ExitBB;
333 return 0;
334}
Chris Lattner708e1a52006-02-10 02:30:37 +0000335
Chris Lattner4c41d492006-02-10 01:24:09 +0000336/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
337/// trivial: that is, that the condition controls whether or not the loop does
338/// anything at all. If this is a trivial condition, unswitching produces no
339/// code duplications (equivalently, it produces a simpler loop and a new empty
340/// loop, which gets deleted).
341///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000342/// If this is a trivial condition, return true, otherwise return false. When
343/// returning true, this sets Cond and Val to the condition that controls the
344/// trivial condition: when Cond dynamically equals Val, the loop is known to
345/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
346/// Cond == Val.
347///
Devang Patele6962df2008-07-02 01:18:13 +0000348bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
349 BasicBlock **LoopExit) {
350 BasicBlock *Header = currentLoop->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000351 TerminatorInst *HeaderTerm = Header->getTerminator();
Owen Andersone922c022009-07-22 00:24:57 +0000352 LLVMContext &Context = Header->getContext();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000353
Chris Lattnera48654e2006-02-15 22:52:05 +0000354 BasicBlock *LoopExitBB = 0;
355 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
356 // If the header block doesn't end with a conditional branch on Cond, we
357 // can't handle it.
358 if (!BI->isConditional() || BI->getCondition() != Cond)
359 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000360
Dan Gohmanb0a57212010-09-01 21:46:45 +0000361 // Check to see if a successor of the branch is guaranteed to
362 // exit through a unique exit block without having any
Chris Lattnera48654e2006-02-15 22:52:05 +0000363 // side-effects. If so, determine the value of Cond that causes it to do
364 // this.
Devang Patele6962df2008-07-02 01:18:13 +0000365 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
366 BI->getSuccessor(0)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000367 if (Val) *Val = ConstantInt::getTrue(Context);
Devang Patele6962df2008-07-02 01:18:13 +0000368 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
369 BI->getSuccessor(1)))) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000370 if (Val) *Val = ConstantInt::getFalse(Context);
Chris Lattnera48654e2006-02-15 22:52:05 +0000371 }
372 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
373 // If this isn't a switch on Cond, we can't handle it.
374 if (SI->getCondition() != Cond) return false;
375
376 // Check to see if a successor of the switch is guaranteed to go to the
377 // latch block or exit through a one exit block without having any
378 // side-effects. If so, determine the value of Cond that causes it to do
379 // this. Note that we can't trivially unswitch on the default case.
380 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patele6962df2008-07-02 01:18:13 +0000381 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
382 SI->getSuccessor(i)))) {
Chris Lattnera48654e2006-02-15 22:52:05 +0000383 // Okay, we found a trivial case, remember the value that is trivial.
384 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000385 break;
386 }
Chris Lattner4e132392006-02-15 22:03:36 +0000387 }
388
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000389 // If we didn't find a single unique LoopExit block, or if the loop exit block
390 // contains phi nodes, this isn't trivial.
391 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000392 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000393
Chris Lattnera48654e2006-02-15 22:52:05 +0000394 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000395
396 // We already know that nothing uses any scalar values defined inside of this
397 // loop. As such, we just have to check to see if this loop will execute any
398 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000399 // part of the loop that the code *would* execute. We already checked the
400 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000401 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
Duncan Sands7af1c782009-05-06 06:49:50 +0000402 if (I->mayHaveSideEffects())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000403 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000404 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000405}
406
Devang Patele6962df2008-07-02 01:18:13 +0000407/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Chris Lattnerc2358092006-02-11 00:43:37 +0000408/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
409/// unswitch the loop, reprocess the pieces, then return true.
Chris Lattner3d606bb2010-02-02 02:26:54 +0000410bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
Devang Patel10b359c2008-09-04 18:55:13 +0000411
Devang Patel027bb922008-09-04 20:36:36 +0000412 initLoopData();
Devang Patel10b359c2008-09-04 18:55:13 +0000413
Dan Gohman03e896b2009-11-05 21:11:53 +0000414 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
415 if (!loopPreheader)
416 return false;
417
Dan Gohmanf68d0c12009-12-09 22:55:01 +0000418 Function *F = loopHeader->getParent();
419
Evan Cheng02720242010-04-03 02:23:43 +0000420 Constant *CondVal = 0;
421 BasicBlock *ExitBlock = 0;
Devang Patele6962df2008-07-02 01:18:13 +0000422 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
Evan Cheng02720242010-04-03 02:23:43 +0000423 // If the condition is trivial, always unswitch. There is no code growth
424 // for this case.
Devang Patele6962df2008-07-02 01:18:13 +0000425 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Evan Cheng02720242010-04-03 02:23:43 +0000426 return true;
Chris Lattnerc2358092006-02-11 00:43:37 +0000427 }
Devang Patel4be7d292008-07-03 06:48:21 +0000428
Evan Cheng02720242010-04-03 02:23:43 +0000429 // Check to see if it would be profitable to unswitch current loop.
430
431 // Do not do non-trivial unswitch while optimizing for size.
432 if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
433 return false;
434
435 // FIXME: This is overly conservative because it does not take into
436 // consideration code simplification opportunities and code that can
437 // be shared by the resultant unswitched loops.
438 CodeMetrics Metrics;
439 for (Loop::block_iterator I = currentLoop->block_begin(),
440 E = currentLoop->block_end();
441 I != E; ++I)
442 Metrics.analyzeBasicBlock(*I);
443
444 // Limit the number of instructions to avoid causing significant code
445 // expansion, and the number of basic blocks, to avoid loops with
446 // large numbers of branches which cause loop unswitching to go crazy.
447 // This is a very ad-hoc heuristic.
448 if (Metrics.NumInsts > Threshold ||
449 Metrics.NumBlocks * 5 > Threshold ||
Kenneth Uildriks42c7d232010-06-09 15:11:37 +0000450 Metrics.containsIndirectBr || Metrics.isRecursive) {
Evan Cheng02720242010-04-03 02:23:43 +0000451 DEBUG(dbgs() << "NOT unswitching loop %"
452 << currentLoop->getHeader()->getName() << ", cost too high: "
453 << currentLoop->getBlocks().size() << "\n");
454 return false;
455 }
456
457 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Chris Lattnerc2358092006-02-11 00:43:37 +0000458 return true;
459}
460
Misha Brukmanfd939082005-04-21 23:48:37 +0000461// RemapInstruction - Convert the instruction operands from referencing the
Devang Patele9916a32010-06-24 00:33:28 +0000462// current values into those specified by VMap.
Chris Lattner18f16092004-04-19 18:07:02 +0000463//
Misha Brukmanfd939082005-04-21 23:48:37 +0000464static inline void RemapInstruction(Instruction *I,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000465 ValueToValueMapTy &VMap) {
Chris Lattner18f16092004-04-19 18:07:02 +0000466 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
467 Value *Op = I->getOperand(op);
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000468 ValueToValueMapTy::iterator It = VMap.find(Op);
Devang Patele9916a32010-06-24 00:33:28 +0000469 if (It != VMap.end()) Op = It->second;
Chris Lattner18f16092004-04-19 18:07:02 +0000470 I->setOperand(op, Op);
471 }
472}
473
474/// CloneLoop - Recursively clone the specified loop and all of its children,
475/// mapping the blocks with the specified map.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000476static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel1bc89362007-03-07 00:26:10 +0000477 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattner18f16092004-04-19 18:07:02 +0000478 Loop *New = new Loop();
Devang Patel1bc89362007-03-07 00:26:10 +0000479 LPM->insertLoop(New, PL);
Chris Lattner18f16092004-04-19 18:07:02 +0000480
481 // Add all of the blocks in L to the new loop.
482 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
483 I != E; ++I)
484 if (LI->getLoopFor(*I) == L)
Owen Andersond735ee82007-11-27 03:43:35 +0000485 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Chris Lattner18f16092004-04-19 18:07:02 +0000486
487 // Add all of the subloops to the new loop.
488 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel1bc89362007-03-07 00:26:10 +0000489 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanfd939082005-04-21 23:48:37 +0000490
Chris Lattner18f16092004-04-19 18:07:02 +0000491 return New;
492}
493
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000494/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
495/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
496/// code immediately before InsertPt.
Devang Patelcce624a2007-06-28 00:49:00 +0000497void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
498 BasicBlock *TrueDest,
499 BasicBlock *FalseDest,
500 Instruction *InsertPt) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000501 // Insert a conditional branch on LIC to the two preheaders. The original
502 // code is the true version and the new code is the false version.
503 Value *BranchVal = LIC;
Owen Anderson1d0be152009-08-13 21:58:54 +0000504 if (!isa<ConstantInt>(Val) ||
505 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Owen Anderson333c4002009-07-09 23:48:35 +0000506 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val, "tmp");
Owen Anderson5defacc2009-07-31 17:39:07 +0000507 else if (Val != ConstantInt::getTrue(Val->getContext()))
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000508 // We want to enter the new loop when the condition is true.
509 std::swap(TrueDest, FalseDest);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000510
511 // Insert the new branch.
Dan Gohman5c89b522009-09-08 15:45:00 +0000512 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
513
514 // If either edge is critical, split it. This helps preserve LoopSimplify
515 // form for enclosing loops.
516 SplitCriticalEdge(BI, 0, this);
517 SplitCriticalEdge(BI, 1, this);
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000518}
519
Chris Lattner4c41d492006-02-10 01:24:09 +0000520/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
521/// condition in it (a cond branch from its header block to its latch block,
522/// where the path through the loop that doesn't execute its body has no
523/// side-effects), unswitch it. This doesn't involve any code duplication, just
524/// moving the conditional branch outside of the loop and updating loop info.
525void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000526 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000527 BasicBlock *ExitBlock) {
David Greened4c56fb2010-01-05 01:27:04 +0000528 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000529 << loopHeader->getName() << " [" << L->getBlocks().size()
530 << " blocks] in Function " << L->getHeader()->getParent()->getName()
531 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner4d1ca942006-02-10 01:36:35 +0000532
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000533 // First step, split the preheader, so that we know that there is a safe place
Devang Patele6962df2008-07-02 01:18:13 +0000534 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattner4c41d492006-02-10 01:24:09 +0000535 // conditional branch on Cond.
Devang Patele6962df2008-07-02 01:18:13 +0000536 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000537
538 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000539 // to branch to: this is the exit block out of the loop that we should
540 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000541
Chris Lattner4e132392006-02-15 22:03:36 +0000542 // Split this block now, so that the loop maintains its exit block, and so
543 // that the jump from the preheader can execute the contents of the exit block
544 // without actually branching to it (the exit block should be dominated by the
545 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000546 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Devang Patel05c1dc62007-07-06 22:03:47 +0000547 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000548
Chris Lattner4c41d492006-02-10 01:24:09 +0000549 // Okay, now we have a position to branch from and a position to branch to,
550 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000551 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patele6962df2008-07-02 01:18:13 +0000552 loopPreheader->getTerminator());
Devang Patele6962df2008-07-02 01:18:13 +0000553 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
554 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattner4c41d492006-02-10 01:24:09 +0000555
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000556 // We need to reprocess this loop, it could be unswitched again.
Devang Patel6f62af62007-07-30 23:07:10 +0000557 redoLoop = true;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000558
Chris Lattner4c41d492006-02-10 01:24:09 +0000559 // Now that we know that the loop is never entered when this condition is a
560 // particular value, rewrite the loop with this info. We know that this will
561 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000562 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000563 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000564}
565
Chris Lattner48a80b02008-04-21 00:25:49 +0000566/// SplitExitEdges - Split all of the edges from inside the loop to their exit
567/// blocks. Update the appropriate Phi nodes as we do so.
568void LoopUnswitch::SplitExitEdges(Loop *L,
Chris Lattner9e185802010-04-05 21:18:32 +0000569 const SmallVector<BasicBlock *, 8> &ExitBlocks){
Devang Patel5c4cd0d2007-10-05 22:29:34 +0000570
Chris Lattner4c41d492006-02-10 01:24:09 +0000571 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000572 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman5c89b522009-09-08 15:45:00 +0000573 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
574 pred_end(ExitBlock));
575 SplitBlockPredecessors(ExitBlock, Preds.data(), Preds.size(),
576 ".us-lcssa", this);
Chris Lattner4c41d492006-02-10 01:24:09 +0000577 }
Devang Patelf476e8e2007-10-03 21:16:08 +0000578}
579
Devang Patelc1e26602007-10-03 21:17:43 +0000580/// UnswitchNontrivialCondition - We determined that the loop is profitable
581/// to unswitch when LIC equal Val. Split it into loop versions and test the
582/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Patelf476e8e2007-10-03 21:16:08 +0000583void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
584 Loop *L) {
Devang Patele6962df2008-07-02 01:18:13 +0000585 Function *F = loopHeader->getParent();
David Greened4c56fb2010-01-05 01:27:04 +0000586 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000587 << loopHeader->getName() << " [" << L->getBlocks().size()
588 << " blocks] in Function " << F->getName()
589 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patelf476e8e2007-10-03 21:16:08 +0000590
Devang Patel1e41f6d2008-07-02 01:44:29 +0000591 LoopBlocks.clear();
592 NewBlocks.clear();
Devang Patelf476e8e2007-10-03 21:16:08 +0000593
594 // First step, split the preheader and exit blocks, and add these blocks to
595 // the LoopBlocks list.
Devang Patele6962df2008-07-02 01:18:13 +0000596 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Patelf476e8e2007-10-03 21:16:08 +0000597 LoopBlocks.push_back(NewPreheader);
598
599 // We want the loop to come after the preheader, but before the exit blocks.
600 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
601
602 SmallVector<BasicBlock*, 8> ExitBlocks;
603 L->getUniqueExitBlocks(ExitBlocks);
604
605 // Split all of the edges from inside the loop to their exit blocks. Update
606 // the appropriate Phi nodes as we do so.
Devang Patel77a01132008-07-03 17:37:52 +0000607 SplitExitEdges(L, ExitBlocks);
Devang Patelf476e8e2007-10-03 21:16:08 +0000608
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000609 // The exit blocks may have been changed due to edge splitting, recompute.
610 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000611 L->getUniqueExitBlocks(ExitBlocks);
612
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000613 // Add exit blocks to the loop blocks.
614 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000615
616 // Next step, clone all of the basic blocks that make up the loop (including
617 // the loop preheader and exit blocks), keeping track of the mapping between
618 // the instructions and blocks.
Chris Lattner18f16092004-04-19 18:07:02 +0000619 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000620 ValueToValueMapTy VMap;
Chris Lattner18f16092004-04-19 18:07:02 +0000621 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000622 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Evan Cheng0f1666b2010-04-05 21:16:25 +0000623 NewBlocks.push_back(NewBB);
Devang Patele9916a32010-06-24 00:33:28 +0000624 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000625 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattner18f16092004-04-19 18:07:02 +0000626 }
627
628 // Splice the newly inserted blocks into the function right before the
629 // original preheader.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000630 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattner18f16092004-04-19 18:07:02 +0000631 NewBlocks[0], F->end());
632
633 // Now we create the new Loop object for the versioned loop.
Devang Patele9916a32010-06-24 00:33:28 +0000634 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Chris Lattnere8255932006-02-10 23:26:14 +0000635 Loop *ParentLoop = L->getParentLoop();
636 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000637 // Make sure to add the cloned preheader and exit blocks to the parent loop
638 // as well.
Owen Andersond735ee82007-11-27 03:43:35 +0000639 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000640 }
641
642 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000643 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000644 // The new exit block should be in the same loop as the old one.
645 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersond735ee82007-11-27 03:43:35 +0000646 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Chris Lattnere8255932006-02-10 23:26:14 +0000647
648 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
649 "Exit block should have been split to have one successor!");
650 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Patel77a01132008-07-03 17:37:52 +0000651
Chris Lattnere8255932006-02-10 23:26:14 +0000652 // If the successor of the exit block had PHI nodes, add an entry for
653 // NewExit.
654 PHINode *PN;
Evan Cheng0f1666b2010-04-05 21:16:25 +0000655 for (BasicBlock::iterator I = ExitSucc->begin(); isa<PHINode>(I); ++I) {
656 PN = cast<PHINode>(I);
Chris Lattnere8255932006-02-10 23:26:14 +0000657 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000658 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patele9916a32010-06-24 00:33:28 +0000659 if (It != VMap.end()) V = It->second;
Chris Lattnere8255932006-02-10 23:26:14 +0000660 PN->addIncoming(V, NewExit);
661 }
Chris Lattner18f16092004-04-19 18:07:02 +0000662 }
663
664 // Rewrite the code to refer to itself.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000665 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
666 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
667 E = NewBlocks[i]->end(); I != E; ++I)
Devang Patele9916a32010-06-24 00:33:28 +0000668 RemapInstruction(I, VMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000669
Chris Lattner18f16092004-04-19 18:07:02 +0000670 // Rewrite the original preheader to select between versions of the loop.
Devang Patele6962df2008-07-02 01:18:13 +0000671 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000672 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000673 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000674
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000675 // Emit the new branch that selects between the two versions of this loop.
676 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patel15c260a2007-07-31 08:03:26 +0000677 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000678 OldBR->eraseFromParent();
Devang Patel1ff61382007-08-02 15:25:57 +0000679
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000680 LoopProcessWorklist.push_back(NewLoop);
Devang Patel6f62af62007-07-30 23:07:10 +0000681 redoLoop = true;
Chris Lattner18f16092004-04-19 18:07:02 +0000682
Chris Lattnera78130c2010-04-20 05:09:16 +0000683 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
684 // deletes the instruction (for example by simplifying a PHI that feeds into
685 // the condition that we're unswitching on), we don't rewrite the second
686 // iteration.
687 WeakVH LICHandle(LIC);
688
Chris Lattner18f16092004-04-19 18:07:02 +0000689 // Now we rewrite the original code to know that the condition is true and the
690 // new code to know that the condition is false.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000691 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Patel77a01132008-07-03 17:37:52 +0000692
Chris Lattnera78130c2010-04-20 05:09:16 +0000693 // It's possible that simplifying one loop could cause the other to be
694 // changed to another value or a constant. If its a constant, don't simplify
695 // it.
696 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
697 LICHandle && !isa<Constant>(LICHandle))
698 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000699}
700
Chris Lattner52221f72006-02-17 00:31:07 +0000701/// RemoveFromWorklist - Remove all instances of I from the worklist vector
702/// specified.
703static void RemoveFromWorklist(Instruction *I,
704 std::vector<Instruction*> &Worklist) {
705 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
706 Worklist.end(), I);
707 while (WI != Worklist.end()) {
708 unsigned Offset = WI-Worklist.begin();
709 Worklist.erase(WI);
710 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
711 }
712}
713
714/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
715/// program, replacing all uses with V and update the worklist.
716static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patel15c260a2007-07-31 08:03:26 +0000717 std::vector<Instruction*> &Worklist,
718 Loop *L, LPPassManager *LPM) {
David Greened4c56fb2010-01-05 01:27:04 +0000719 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000720
721 // Add uses to the worklist, which may be dead now.
722 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
723 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
724 Worklist.push_back(Use);
725
726 // Add users to the worklist which may be simplified now.
727 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
728 UI != E; ++UI)
729 Worklist.push_back(cast<Instruction>(*UI));
Devang Patel15c260a2007-07-31 08:03:26 +0000730 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000731 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000732 I->replaceAllUsesWith(V);
733 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000734 ++NumSimplify;
735}
736
Chris Lattnerdb410242006-02-18 02:42:34 +0000737/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
738/// information, and remove any dead successors it has.
739///
740void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patel15c260a2007-07-31 08:03:26 +0000741 std::vector<Instruction*> &Worklist,
742 Loop *L) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000743 if (pred_begin(BB) != pred_end(BB)) {
744 // This block isn't dead, since an edge to BB was just removed, see if there
745 // are any easy simplifications we can do now.
746 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
747 // If it has one pred, fold phi nodes in BB.
748 while (isa<PHINode>(BB->begin()))
749 ReplaceUsesOfWith(BB->begin(),
750 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patel15c260a2007-07-31 08:03:26 +0000751 Worklist, L, LPM);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000752
753 // If this is the header of a loop and the only pred is the latch, we now
754 // have an unreachable loop.
755 if (Loop *L = LI->getLoopFor(BB))
Devang Patele6962df2008-07-02 01:18:13 +0000756 if (loopHeader == BB && L->contains(Pred)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000757 // Remove the branch from the latch to the header block, this makes
758 // the header dead, which will make the latch dead (because the header
759 // dominates the latch).
Devang Patel15c260a2007-07-31 08:03:26 +0000760 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000761 Pred->getTerminator()->eraseFromParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000762 new UnreachableInst(BB->getContext(), Pred);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000763
764 // The loop is now broken, remove it from LI.
765 RemoveLoopFromHierarchy(L);
766
767 // Reprocess the header, which now IS dead.
Devang Patel15c260a2007-07-31 08:03:26 +0000768 RemoveBlockIfDead(BB, Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000769 return;
770 }
771
772 // If pred ends in a uncond branch, add uncond branch to worklist so that
773 // the two blocks will get merged.
774 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
775 if (BI->isUnconditional())
776 Worklist.push_back(BI);
777 }
778 return;
779 }
Chris Lattner52221f72006-02-17 00:31:07 +0000780
David Greened4c56fb2010-01-05 01:27:04 +0000781 DEBUG(dbgs() << "Nuking dead block: " << *BB);
Chris Lattnerdb410242006-02-18 02:42:34 +0000782
783 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000784 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +0000785 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000786
787 // Anything that uses the instructions in this basic block should have their
788 // uses replaced with undefs.
Devang Patel228ebd02009-10-13 22:56:32 +0000789 // If I is not void type then replaceAllUsesWith undef.
790 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +0000791 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +0000792 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000793 }
Chris Lattnerdb410242006-02-18 02:42:34 +0000794
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000795 // If this is the edge to the header block for a loop, remove the loop and
796 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +0000797 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000798 if (BBLoop->getLoopLatch() == BB)
799 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +0000800 }
801
802 // Remove the block from the loop info, which removes it from any loops it
803 // was in.
804 LI->removeBlock(BB);
805
806
807 // Remove phi node entries in successors for this block.
808 TerminatorInst *TI = BB->getTerminator();
Chris Lattnera3522002008-12-01 06:52:57 +0000809 SmallVector<BasicBlock*, 4> Succs;
Chris Lattnerdb410242006-02-18 02:42:34 +0000810 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
811 Succs.push_back(TI->getSuccessor(i));
812 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000813 }
814
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000815 // Unique the successors, remove anything with multiple uses.
Chris Lattnera3522002008-12-01 06:52:57 +0000816 array_pod_sort(Succs.begin(), Succs.end());
Chris Lattnerdb410242006-02-18 02:42:34 +0000817 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
818
819 // Remove the basic block, including all of the instructions contained in it.
Devang Patel15c260a2007-07-31 08:03:26 +0000820 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patel9ee49c52007-09-20 23:45:50 +0000821 BB->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000822 // Remove successor blocks here that are not dead, so that we know we only
823 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
824 // then getting removed before we revisit them, which is badness.
825 //
826 for (unsigned i = 0; i != Succs.size(); ++i)
827 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
828 // One exception is loop headers. If this block was the preheader for a
829 // loop, then we DO want to visit the loop so the loop gets deleted.
830 // We know that if the successor is a loop header, that this loop had to
831 // be the preheader: the case where this was the latch block was handled
832 // above and headers can only have two predecessors.
833 if (!LI->isLoopHeader(Succs[i])) {
834 Succs.erase(Succs.begin()+i);
835 --i;
836 }
837 }
838
Chris Lattnerdb410242006-02-18 02:42:34 +0000839 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patel15c260a2007-07-31 08:03:26 +0000840 RemoveBlockIfDead(Succs[i], Worklist, L);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000841}
Chris Lattner52221f72006-02-17 00:31:07 +0000842
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000843/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
844/// become unwrapped, either because the backedge was deleted, or because the
845/// edge into the header was removed. If the edge into the header from the
846/// latch block was removed, the loop is unwrapped but subloops are still alive,
847/// so they just reparent loops. If the loops are actually dead, they will be
848/// removed later.
849void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
Devang Patel1bc89362007-03-07 00:26:10 +0000850 LPM->deleteLoopFromQueue(L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000851 RemoveLoopFromWorklist(L);
852}
853
Chris Lattnerc2358092006-02-11 00:43:37 +0000854// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
855// the value specified by Val in the specified loop, or we know it does NOT have
856// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000857void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000858 Constant *Val,
859 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000860 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +0000861
Chris Lattner18f16092004-04-19 18:07:02 +0000862 // FIXME: Support correlated properties, like:
863 // for (...)
864 // if (li1 < li2)
865 // ...
866 // if (li1 > li2)
867 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +0000868
Chris Lattner708e1a52006-02-10 02:30:37 +0000869 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
870 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +0000871 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +0000872 std::vector<Instruction*> Worklist;
Owen Andersone922c022009-07-22 00:24:57 +0000873 LLVMContext &Context = Val->getContext();
874
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000875
Chris Lattner52221f72006-02-17 00:31:07 +0000876 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
877 // in the loop with the appropriate one directly.
Owen Anderson1d0be152009-08-13 21:58:54 +0000878 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000879 Val->getType()->isIntegerTy(1))) {
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000880 Value *Replacement;
881 if (IsEqual)
882 Replacement = Val;
883 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000884 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencer579dca12007-01-12 04:24:46 +0000885 !cast<ConstantInt>(Val)->getZExtValue());
Chris Lattner52221f72006-02-17 00:31:07 +0000886
887 for (unsigned i = 0, e = Users.size(); i != e; ++i)
888 if (Instruction *U = cast<Instruction>(Users[i])) {
Dan Gohman92329c72009-12-18 01:24:09 +0000889 if (!L->contains(U))
Chris Lattner52221f72006-02-17 00:31:07 +0000890 continue;
891 U->replaceUsesOfWith(LIC, Replacement);
892 Worklist.push_back(U);
893 }
Chris Lattner9e185802010-04-05 21:18:32 +0000894 SimplifyCode(Worklist, L);
895 return;
896 }
897
898 // Otherwise, we don't know the precise value of LIC, but we do know that it
899 // is certainly NOT "Val". As such, simplify any uses in the loop that we
900 // can. This case occurs when we unswitch switch statements.
901 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
902 Instruction *U = cast<Instruction>(Users[i]);
903 if (!L->contains(U))
904 continue;
Chris Lattner52221f72006-02-17 00:31:07 +0000905
Chris Lattner9e185802010-04-05 21:18:32 +0000906 Worklist.push_back(U);
Chris Lattner52221f72006-02-17 00:31:07 +0000907
Chris Lattner9e185802010-04-05 21:18:32 +0000908 // TODO: We could do other simplifications, for example, turning
909 // 'icmp eq LIC, Val' -> false.
910
911 // If we know that LIC is not Val, use this info to simplify code.
912 SwitchInst *SI = dyn_cast<SwitchInst>(U);
913 if (SI == 0 || !isa<ConstantInt>(Val)) continue;
914
915 unsigned DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
916 if (DeadCase == 0) continue; // Default case is live for multiple values.
917
918 // Found a dead case value. Don't remove PHI nodes in the
919 // successor if they become single-entry, those PHI nodes may
920 // be in the Users list.
Chris Lattner52221f72006-02-17 00:31:07 +0000921
Chris Lattner9e185802010-04-05 21:18:32 +0000922 // FIXME: This is a hack. We need to keep the successor around
923 // and hooked up so as to preserve the loop structure, because
924 // trying to update it is complicated. So instead we preserve the
925 // loop structure and put the block on a dead code path.
926 BasicBlock *Switch = SI->getParent();
927 SplitEdge(Switch, SI->getSuccessor(DeadCase), this);
928 // Compute the successors instead of relying on the return value
929 // of SplitEdge, since it may have split the switch successor
930 // after PHI nodes.
931 BasicBlock *NewSISucc = SI->getSuccessor(DeadCase);
932 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
933 // Create an "unreachable" destination.
934 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
935 Switch->getParent(),
936 OldSISucc);
937 new UnreachableInst(Context, Abort);
938 // Force the new case destination to branch to the "unreachable"
939 // block while maintaining a (dead) CFG edge to the old block.
940 NewSISucc->getTerminator()->eraseFromParent();
941 BranchInst::Create(Abort, OldSISucc,
942 ConstantInt::getTrue(Context), NewSISucc);
943 // Release the PHI operands for this edge.
944 for (BasicBlock::iterator II = NewSISucc->begin();
945 PHINode *PN = dyn_cast<PHINode>(II); ++II)
946 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
947 UndefValue::get(PN->getType()));
948 // Tell the domtree about the new block. We don't fully update the
949 // domtree here -- instead we force it to do a full recomputation
950 // after the pass is complete -- but we do need to inform it of
951 // new blocks.
952 if (DT)
953 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner52221f72006-02-17 00:31:07 +0000954 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000955
Devang Patel15c260a2007-07-31 08:03:26 +0000956 SimplifyCode(Worklist, L);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000957}
958
Mike Stumpc02f0d72009-09-09 17:57:16 +0000959/// SimplifyCode - Okay, now that we have simplified some instructions in the
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000960/// loop, walk over it and constant prop, dce, and fold control flow where
961/// possible. Note that this is effectively a very simple loop-structure-aware
962/// optimizer. During processing of this loop, L could very well be deleted, so
963/// it must not be used.
964///
965/// FIXME: When the loop optimizer is more mature, separate this out to a new
966/// pass.
967///
Devang Patel15c260a2007-07-31 08:03:26 +0000968void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Chris Lattner52221f72006-02-17 00:31:07 +0000969 while (!Worklist.empty()) {
970 Instruction *I = Worklist.back();
971 Worklist.pop_back();
972
973 // Simple constant folding.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000974 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patel15c260a2007-07-31 08:03:26 +0000975 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +0000976 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000977 }
Chris Lattner52221f72006-02-17 00:31:07 +0000978
979 // Simple DCE.
980 if (isInstructionTriviallyDead(I)) {
David Greened4c56fb2010-01-05 01:27:04 +0000981 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Chris Lattner52221f72006-02-17 00:31:07 +0000982
983 // Add uses to the worklist, which may be dead now.
984 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
985 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
986 Worklist.push_back(Use);
Devang Patel15c260a2007-07-31 08:03:26 +0000987 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner52221f72006-02-17 00:31:07 +0000988 RemoveFromWorklist(I, Worklist);
Devang Patel9ee49c52007-09-20 23:45:50 +0000989 I->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +0000990 ++NumSimplify;
991 continue;
992 }
993
Chris Lattner4f1f6f62010-04-20 05:33:18 +0000994 // See if instruction simplification can hack this up. This is common for
995 // things like "select false, X, Y" after unswitching made the condition be
996 // 'false'.
Duncan Sandseff05812010-11-14 18:36:10 +0000997 if (Value *V = SimplifyInstruction(I, 0, DT)) {
Chris Lattner4f1f6f62010-04-20 05:33:18 +0000998 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
999 continue;
1000 }
Chris Lattnera78130c2010-04-20 05:09:16 +00001001
Chris Lattner52221f72006-02-17 00:31:07 +00001002 // Special case hacks that appear commonly in unswitched code.
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001003 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner52221f72006-02-17 00:31:07 +00001004 if (BI->isUnconditional()) {
1005 // If BI's parent is the only pred of the successor, fold the two blocks
1006 // together.
1007 BasicBlock *Pred = BI->getParent();
1008 BasicBlock *Succ = BI->getSuccessor(0);
1009 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1010 if (!SinglePred) continue; // Nothing to do.
1011 assert(SinglePred == Pred && "CFG broken");
1012
David Greened4c56fb2010-01-05 01:27:04 +00001013 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001014 << Succ->getName() << "\n");
Chris Lattner52221f72006-02-17 00:31:07 +00001015
1016 // Resolve any single entry PHI nodes in Succ.
1017 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patel15c260a2007-07-31 08:03:26 +00001018 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Chris Lattner52221f72006-02-17 00:31:07 +00001019
1020 // Move all of the successor contents from Succ to Pred.
1021 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1022 Succ->end());
Devang Patel15c260a2007-07-31 08:03:26 +00001023 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001024 BI->eraseFromParent();
Chris Lattner52221f72006-02-17 00:31:07 +00001025 RemoveFromWorklist(BI, Worklist);
1026
1027 // If Succ has any successors with PHI nodes, update them to have
1028 // entries coming from Pred instead of Succ.
1029 Succ->replaceAllUsesWith(Pred);
1030
1031 // Remove Succ from the loop tree.
1032 LI->removeBlock(Succ);
Devang Patel15c260a2007-07-31 08:03:26 +00001033 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001034 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001035 ++NumSimplify;
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001036 continue;
Chris Lattner9e185802010-04-05 21:18:32 +00001037 }
1038
1039 if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001040 // Conditional branch. Turn it into an unconditional branch, then
1041 // remove dead blocks.
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001042 continue; // FIXME: Enable.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001043
David Greened4c56fb2010-01-05 01:27:04 +00001044 DEBUG(dbgs() << "Folded branch: " << *BI);
Reid Spencer579dca12007-01-12 04:24:46 +00001045 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1046 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnerdb410242006-02-18 02:42:34 +00001047 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greif051a9502008-04-06 20:25:17 +00001048 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patel15c260a2007-07-31 08:03:26 +00001049 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel9ee49c52007-09-20 23:45:50 +00001050 BI->eraseFromParent();
Chris Lattnerdb410242006-02-18 02:42:34 +00001051 RemoveFromWorklist(BI, Worklist);
1052 ++NumSimplify;
1053
Devang Patel15c260a2007-07-31 08:03:26 +00001054 RemoveBlockIfDead(DeadSucc, Worklist, L);
Chris Lattner52221f72006-02-17 00:31:07 +00001055 }
Chris Lattner4f1f6f62010-04-20 05:33:18 +00001056 continue;
Chris Lattner52221f72006-02-17 00:31:07 +00001057 }
1058 }
Chris Lattner18f16092004-04-19 18:07:02 +00001059}