blob: f57b7bb5194043fc6fb8ccc383720b099a0ace31 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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"
32#include "llvm/DerivedTypes.h"
33#include "llvm/Function.h"
34#include "llvm/Instructions.h"
35#include "llvm/Analysis/ConstantFolding.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/LoopPass.h"
38#include "llvm/Analysis/Dominators.h"
39#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
47#include <algorithm>
48#include <set>
49using namespace llvm;
50
51STATISTIC(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 Gohman089efff2008-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060
Dan Gohman089efff2008-05-13 00:00:25 +000061namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63 LoopInfo *LI; // Loop information
64 LPPassManager *LPM;
65
66 // LoopProcessWorklist - Used to check if second loop needs processing
67 // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68 std::vector<Loop*> LoopProcessWorklist;
69 SmallPtrSet<Value *,8> UnswitchedVals;
70
71 bool OptimizeForSize;
Devang Pateleec0d372007-07-30 23:07:10 +000072 bool redoLoop;
Devang Patel122c81f2007-10-05 22:29:34 +000073
Devang Patelff3d3e52008-07-02 01:18:13 +000074 Loop *currentLoop;
Devang Patel122c81f2007-10-05 22:29:34 +000075 DominanceFrontier *DF;
76 DominatorTree *DT;
Devang Patelff3d3e52008-07-02 01:18:13 +000077 BasicBlock *loopHeader;
78 BasicBlock *loopPreheader;
Devang Patel122c81f2007-10-05 22:29:34 +000079
80 /// LoopDF - Loop's dominance frontier. This set is a collection of
81 /// loop exiting blocks' DF member blocks. However this does set does not
82 /// includes basic blocks that are inside loop.
83 SmallPtrSet<BasicBlock *, 8> LoopDF;
84
85 /// OrigLoopExitMap - This is used to map loop exiting block with
86 /// corresponding loop exit block, before updating CFG.
87 DenseMap<BasicBlock *, BasicBlock *> OrigLoopExitMap;
Devang Pateld6aef782008-07-02 01:44:29 +000088
89 // LoopBlocks contains all of the basic blocks of the loop, including the
90 // preheader of the loop, the body of the loop, and the exit blocks of the
91 // loop, in that order.
92 std::vector<BasicBlock*> LoopBlocks;
93 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
94 std::vector<BasicBlock*> NewBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 public:
96 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +000097 explicit LoopUnswitch(bool Os = false) :
Devang Patelff3d3e52008-07-02 01:18:13 +000098 LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false),
99 currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
100 loopPreheader(NULL) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101
102 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patelff3d3e52008-07-02 01:18:13 +0000103 bool processCurrentLoop();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104
105 /// This transformation requires natural loop information & requires that
106 /// loop preheaders be inserted into the CFG...
107 ///
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addPreservedID(LoopSimplifyID);
111 AU.addRequired<LoopInfo>();
112 AU.addPreserved<LoopInfo>();
113 AU.addRequiredID(LCSSAID);
Devang Patelf73276b2007-07-31 08:03:26 +0000114 AU.addPreservedID(LCSSAID);
Devang Patela7e8b722008-07-03 05:55:03 +0000115 // FIXME: Loop Unswitch does not preserve dominator info in all cases.
116 // AU.addPreserved<DominatorTree>();
117 // AU.addPreserved<DominanceFrontier>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 }
119
120 private:
Devang Patelf73276b2007-07-31 08:03:26 +0000121
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Pateld39af172007-10-03 21:16:08 +0000130
Devang Patelff3d3e52008-07-02 01:18:13 +0000131 void initLoopData() {
132 loopHeader = currentLoop->getHeader();
133 loopPreheader = currentLoop->getLoopPreheader();
134 }
135
Chris Lattnerdb47e722008-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 Patel122c81f2007-10-05 22:29:34 +0000138 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Pateld39af172007-10-03 21:16:08 +0000139 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel122c81f2007-10-05 22:29:34 +0000140
Chris Lattnerdb47e722008-04-21 00:25:49 +0000141 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel122c81f2007-10-05 22:29:34 +0000142 /// remove it. Add NewDFMember in BB's dominance frontier.
143 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
144 BasicBlock *NewDFMember);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145
Devang Patelff3d3e52008-07-02 01:18:13 +0000146 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
147 unsigned getLoopUnswitchCost(Value *LIC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
149 BasicBlock *ExitBlock);
150 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
151
152 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
153 Constant *Val, bool isEqual);
154
155 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
156 BasicBlock *TrueDest,
157 BasicBlock *FalseDest,
158 Instruction *InsertPt);
159
Devang Patelf73276b2007-07-31 08:03:26 +0000160 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patelf73276b2007-07-31 08:03:26 +0000162 std::vector<Instruction*> &Worklist, Loop *l);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 void RemoveLoopFromHierarchy(Loop *L);
Devang Patelff3d3e52008-07-02 01:18:13 +0000164 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
165 BasicBlock **LoopExit = 0);
166
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168}
Dan Gohman089efff2008-05-13 00:00:25 +0000169char LoopUnswitch::ID = 0;
170static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171
172LoopPass *llvm::createLoopUnswitchPass(bool Os) {
173 return new LoopUnswitch(Os);
174}
175
176/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
177/// invariant in the loop, or has an invariant piece, return the invariant.
178/// Otherwise, return null.
179static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
180 // Constants should be folded, not unswitched on!
181 if (isa<Constant>(Cond)) return false;
182
183 // TODO: Handle: br (VARIANT|INVARIANT).
184 // TODO: Hoist simple expressions out of loops.
185 if (L->isLoopInvariant(Cond)) return Cond;
186
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
188 if (BO->getOpcode() == Instruction::And ||
189 BO->getOpcode() == Instruction::Or) {
190 // If either the left or right side is invariant, we can unswitch on this,
191 // which will cause the branch to go away in one loop and the condition to
192 // simplify in the other one.
193 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
194 return LHS;
195 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
196 return RHS;
197 }
Devang Patel122c81f2007-10-05 22:29:34 +0000198
199 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200}
201
202bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 LI = &getAnalysis<LoopInfo>();
204 LPM = &LPM_Ref;
Devang Patel122c81f2007-10-05 22:29:34 +0000205 DF = getAnalysisToUpdate<DominanceFrontier>();
206 DT = getAnalysisToUpdate<DominatorTree>();
Devang Patelff3d3e52008-07-02 01:18:13 +0000207 currentLoop = L;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 bool Changed = false;
Devang Pateleec0d372007-07-30 23:07:10 +0000209
210 do {
Devang Patelff3d3e52008-07-02 01:18:13 +0000211 assert(currentLoop->isLCSSAForm());
Devang Pateleec0d372007-07-30 23:07:10 +0000212 redoLoop = false;
Devang Patelff3d3e52008-07-02 01:18:13 +0000213 Changed |= processCurrentLoop();
Devang Pateleec0d372007-07-30 23:07:10 +0000214 } while(redoLoop);
215
216 return Changed;
217}
218
Devang Patelff3d3e52008-07-02 01:18:13 +0000219/// processCurrentLoop - Do actual work and unswitch loop if possible
220/// and profitable.
221bool LoopUnswitch::processCurrentLoop() {
Devang Pateleec0d372007-07-30 23:07:10 +0000222 bool Changed = false;
223
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 // Loop over all of the basic blocks in the loop. If we find an interior
225 // block that is branching on a loop-invariant condition, we can unswitch this
226 // loop.
Devang Patelff3d3e52008-07-02 01:18:13 +0000227 for (Loop::block_iterator I = currentLoop->block_begin(),
228 E = currentLoop->block_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 I != E; ++I) {
230 TerminatorInst *TI = (*I)->getTerminator();
231 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
232 // If this isn't branching on an invariant condition, we can't unswitch
233 // it.
234 if (BI->isConditional()) {
235 // See if this, or some part of it, is loop invariant. If so, we can
236 // unswitch on it if we desire.
Devang Patelff3d3e52008-07-02 01:18:13 +0000237 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
238 currentLoop, Changed);
239 if (LoopCond && UnswitchIfProfitable(LoopCond,
240 ConstantInt::getTrue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 ++NumBranches;
242 return true;
243 }
244 }
245 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000246 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
247 currentLoop, Changed);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 if (LoopCond && SI->getNumCases() > 1) {
249 // Find a value to unswitch on:
250 // FIXME: this should chose the most expensive case!
251 Constant *UnswitchVal = SI->getCaseValue(1);
252 // Do not process same value again and again.
253 if (!UnswitchedVals.insert(UnswitchVal))
254 continue;
255
Devang Patelff3d3e52008-07-02 01:18:13 +0000256 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 ++NumSwitches;
258 return true;
259 }
260 }
261 }
262
263 // Scan the instructions to check for unswitchable values.
264 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
265 BBI != E; ++BBI)
266 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000267 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
268 currentLoop, Changed);
269 if (LoopCond && UnswitchIfProfitable(LoopCond,
270 ConstantInt::getTrue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 ++NumSelects;
272 return true;
273 }
274 }
275 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 return Changed;
277}
278
279/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
280/// 1. Exit the loop with no side effects.
281/// 2. Branch to the latch block with no side-effects.
282///
283/// If these conditions are true, we return true and set ExitBB to the block we
284/// exit through.
285///
286static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
287 BasicBlock *&ExitBB,
288 std::set<BasicBlock*> &Visited) {
289 if (!Visited.insert(BB).second) {
290 // Already visited and Ok, end of recursion.
291 return true;
292 } else if (!L->contains(BB)) {
293 // Otherwise, this is a loop exit, this is fine so long as this is the
294 // first exit.
295 if (ExitBB != 0) return false;
296 ExitBB = BB;
297 return true;
298 }
299
300 // Otherwise, this is an unvisited intra-loop node. Check all successors.
301 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
302 // Check to see if the successor is a trivial loop exit.
303 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
304 return false;
305 }
306
307 // Okay, everything after this looks good, check to make sure that this block
308 // doesn't include any side effects.
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310 if (I->mayWriteToMemory())
311 return false;
312
313 return true;
314}
315
316/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
317/// leads to an exit from the specified loop, and has no side-effects in the
318/// process. If so, return the block that is exited to, otherwise return null.
319static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
320 std::set<BasicBlock*> Visited;
321 Visited.insert(L->getHeader()); // Branches to header are ok.
322 BasicBlock *ExitBB = 0;
323 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
324 return ExitBB;
325 return 0;
326}
327
328/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
329/// trivial: that is, that the condition controls whether or not the loop does
330/// anything at all. If this is a trivial condition, unswitching produces no
331/// code duplications (equivalently, it produces a simpler loop and a new empty
332/// loop, which gets deleted).
333///
334/// If this is a trivial condition, return true, otherwise return false. When
335/// returning true, this sets Cond and Val to the condition that controls the
336/// trivial condition: when Cond dynamically equals Val, the loop is known to
337/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
338/// Cond == Val.
339///
Devang Patelff3d3e52008-07-02 01:18:13 +0000340bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
341 BasicBlock **LoopExit) {
342 BasicBlock *Header = currentLoop->getHeader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 TerminatorInst *HeaderTerm = Header->getTerminator();
344
345 BasicBlock *LoopExitBB = 0;
346 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
347 // If the header block doesn't end with a conditional branch on Cond, we
348 // can't handle it.
349 if (!BI->isConditional() || BI->getCondition() != Cond)
350 return false;
351
352 // Check to see if a successor of the branch is guaranteed to go to the
353 // latch block or exit through a one exit block without having any
354 // side-effects. If so, determine the value of Cond that causes it to do
355 // this.
Devang Patelff3d3e52008-07-02 01:18:13 +0000356 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
357 BI->getSuccessor(0)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 if (Val) *Val = ConstantInt::getTrue();
Devang Patelff3d3e52008-07-02 01:18:13 +0000359 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
360 BI->getSuccessor(1)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 if (Val) *Val = ConstantInt::getFalse();
362 }
363 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
364 // If this isn't a switch on Cond, we can't handle it.
365 if (SI->getCondition() != Cond) return false;
366
367 // Check to see if a successor of the switch is guaranteed to go to the
368 // latch block or exit through a one exit block without having any
369 // side-effects. If so, determine the value of Cond that causes it to do
370 // this. Note that we can't trivially unswitch on the default case.
371 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patelff3d3e52008-07-02 01:18:13 +0000372 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
373 SI->getSuccessor(i)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 // Okay, we found a trivial case, remember the value that is trivial.
375 if (Val) *Val = SI->getCaseValue(i);
376 break;
377 }
378 }
379
380 // If we didn't find a single unique LoopExit block, or if the loop exit block
381 // contains phi nodes, this isn't trivial.
382 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
383 return false; // Can't handle this.
384
385 if (LoopExit) *LoopExit = LoopExitBB;
386
387 // We already know that nothing uses any scalar values defined inside of this
388 // loop. As such, we just have to check to see if this loop will execute any
389 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
390 // part of the loop that the code *would* execute. We already checked the
391 // tail, check the header now.
392 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
393 if (I->mayWriteToMemory())
394 return false;
395 return true;
396}
397
398/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patelff3d3e52008-07-02 01:18:13 +0000399/// we choose to unswitch current loop on the specified value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400///
Devang Patelff3d3e52008-07-02 01:18:13 +0000401unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 // If the condition is trivial, always unswitch. There is no code growth for
403 // this case.
Devang Patelff3d3e52008-07-02 01:18:13 +0000404 if (IsTrivialUnswitchCondition(LIC))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 return 0;
406
407 // FIXME: This is really overly conservative. However, more liberal
408 // estimations have thus far resulted in excessive unswitching, which is bad
409 // both in compile time and in code size. This should be replaced once
410 // someone figures out how a good estimation.
Devang Patelff3d3e52008-07-02 01:18:13 +0000411 return currentLoop->getBlocks().size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
413 unsigned Cost = 0;
414 // FIXME: this is brain dead. It should take into consideration code
415 // shrinkage.
Devang Patelff3d3e52008-07-02 01:18:13 +0000416 for (Loop::block_iterator I = currentLoop->block_begin(),
417 E = currentLoop->block_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 I != E; ++I) {
419 BasicBlock *BB = *I;
420 // Do not include empty blocks in the cost calculation. This happen due to
421 // loop canonicalization and will be removed.
422 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
423 continue;
424
425 // Count basic blocks.
426 ++Cost;
427 }
428
429 return Cost;
430}
431
Devang Patelff3d3e52008-07-02 01:18:13 +0000432/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
434/// unswitch the loop, reprocess the pieces, then return true.
Devang Patelff3d3e52008-07-02 01:18:13 +0000435bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
436 // Check to see if it would be profitable to unswitch current loop.
437 unsigned Cost = getLoopUnswitchCost(LoopCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438
439 // Do not do non-trivial unswitch while optimizing for size.
440 if (Cost && OptimizeForSize)
441 return false;
442
443 if (Cost > Threshold) {
444 // FIXME: this should estimate growth by the amount of code shared by the
445 // resultant unswitched loops.
446 //
447 DOUT << "NOT unswitching loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000448 << currentLoop->getHeader()->getName() << ", cost too high: "
449 << currentLoop->getBlocks().size() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 return false;
451 }
Devang Patelff3d3e52008-07-02 01:18:13 +0000452
453 initLoopData();
454
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455 Constant *CondVal;
456 BasicBlock *ExitBlock;
Devang Patelff3d3e52008-07-02 01:18:13 +0000457 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
458 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 } else {
Devang Patelff3d3e52008-07-02 01:18:13 +0000460 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 }
462
463 return true;
464}
465
466// RemapInstruction - Convert the instruction operands from referencing the
467// current values into those specified by ValueMap.
468//
469static inline void RemapInstruction(Instruction *I,
470 DenseMap<const Value *, Value*> &ValueMap) {
471 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
472 Value *Op = I->getOperand(op);
473 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
474 if (It != ValueMap.end()) Op = It->second;
475 I->setOperand(op, Op);
476 }
477}
478
Chris Lattner03dc7d72007-08-02 16:53:43 +0000479// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
480// Info.
Devang Patelf9739582007-07-18 23:48:20 +0000481//
482// If Orig block's immediate dominator is mapped in VM then use corresponding
483// immediate dominator from the map. Otherwise Orig block's dominator is also
484// NewBB's dominator.
485//
Devang Pateld6868a72007-07-18 23:50:19 +0000486// OrigPreheader is loop pre-header before this pass started
Devang Patelf9739582007-07-18 23:48:20 +0000487// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Pateld6868a72007-07-18 23:50:19 +0000488// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman089efff2008-05-13 00:00:25 +0000489static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
490 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
491 BasicBlock *OrigHeader,
492 DominatorTree *DT, DominanceFrontier *DF,
493 DenseMap<const Value*, Value*> &VM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494
Devang Patelf9739582007-07-18 23:48:20 +0000495 // If NewBB alreay has found its place in domiantor tree then no need to do
496 // anything.
497 if (DT->getNode(NewBB))
498 return;
499
500 // If Orig does not have any immediate domiantor then its clone, NewBB, does
501 // not need any immediate dominator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 DomTreeNode *OrigNode = DT->getNode(Orig);
503 if (!OrigNode)
504 return;
Devang Patelf9739582007-07-18 23:48:20 +0000505 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
506 if (!OrigIDomNode)
507 return;
508
509 BasicBlock *OrigIDom = NULL;
510
511 // If Orig is original loop header then its immediate dominator is
512 // NewPreheader.
513 if (Orig == OrigHeader)
514 OrigIDom = NewPreheader;
515
516 // If Orig is new pre-header then its immediate dominator is
517 // original pre-header.
518 else if (Orig == NewPreheader)
519 OrigIDom = OrigPreheader;
520
Devang Patelf1a33042008-07-02 01:31:19 +0000521 // Otherwise ask DT to find Orig's immediate dominator.
Devang Patelf9739582007-07-18 23:48:20 +0000522 else
523 OrigIDom = OrigIDomNode->getBlock();
524
Devang Patelc5685122007-07-30 21:10:44 +0000525 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
526 BasicBlock *NewIDom = OrigIDom;
527 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
528 if (I != VM.end()) {
529 NewIDom = cast<BasicBlock>(I->second);
530
531 // If NewIDom does not have corresponding dominatore tree node then
532 // get one.
533 if (!DT->getNode(NewIDom))
Devang Patelf9739582007-07-18 23:48:20 +0000534 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
535 OrigHeader, DT, DF, VM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 }
Devang Patelc5685122007-07-30 21:10:44 +0000537
538 DT->addNewBlock(NewBB, NewIDom);
539
540 // Copy cloned dominance frontiner set
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 DominanceFrontier::DomSetType NewDFSet;
542 if (DF) {
543 DominanceFrontier::iterator DFI = DF->find(Orig);
544 if ( DFI != DF->end()) {
545 DominanceFrontier::DomSetType S = DFI->second;
546 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
547 I != E; ++I) {
548 BasicBlock *BB = *I;
Chuck Rose III9a2da442007-07-27 18:26:35 +0000549 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
550 if (IDM != VM.end())
551 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 else
553 NewDFSet.insert(BB);
554 }
555 }
556 DF->addBasicBlock(NewBB, NewDFSet);
557 }
558}
559
560/// CloneLoop - Recursively clone the specified loop and all of its children,
561/// mapping the blocks with the specified map.
562static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
563 LoopInfo *LI, LPPassManager *LPM) {
564 Loop *New = new Loop();
565
566 LPM->insertLoop(New, PL);
567
568 // Add all of the blocks in L to the new loop.
569 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
570 I != E; ++I)
571 if (LI->getLoopFor(*I) == L)
Owen Andersonca0b9d42007-11-27 03:43:35 +0000572 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573
574 // Add all of the subloops to the new loop.
575 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
576 CloneLoop(*I, New, VM, LI, LPM);
577
578 return New;
579}
580
581/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
582/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
583/// code immediately before InsertPt.
584void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
585 BasicBlock *TrueDest,
586 BasicBlock *FalseDest,
587 Instruction *InsertPt) {
588 // Insert a conditional branch on LIC to the two preheaders. The original
589 // code is the true version and the new code is the false version.
590 Value *BranchVal = LIC;
591 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
592 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
593 else if (Val != ConstantInt::getTrue())
594 // We want to enter the new loop when the condition is true.
595 std::swap(TrueDest, FalseDest);
596
597 // Insert the new branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000598 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599}
600
601
602/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
603/// condition in it (a cond branch from its header block to its latch block,
604/// where the path through the loop that doesn't execute its body has no
605/// side-effects), unswitch it. This doesn't involve any code duplication, just
606/// moving the conditional branch outside of the loop and updating loop info.
607void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
608 Constant *Val,
609 BasicBlock *ExitBlock) {
610 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000611 << loopHeader->getName() << " [" << L->getBlocks().size()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 << " blocks] in Function " << L->getHeader()->getParent()->getName()
613 << " on cond: " << *Val << " == " << *Cond << "\n";
614
615 // First step, split the preheader, so that we know that there is a safe place
Devang Patelff3d3e52008-07-02 01:18:13 +0000616 // to insert the conditional branch. We will change loopPreheader to have a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 // conditional branch on Cond.
Devang Patelff3d3e52008-07-02 01:18:13 +0000618 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619
620 // Now that we have a place to insert the conditional branch, create a place
621 // to branch to: this is the exit block out of the loop that we should
622 // short-circuit to.
623
624 // Split this block now, so that the loop maintains its exit block, and so
625 // that the jump from the preheader can execute the contents of the exit block
626 // without actually branching to it (the exit block should be dominated by the
627 // loop header, not the preheader).
628 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
629 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
630
631 // Okay, now we have a position to branch from and a position to branch to,
632 // insert the new conditional branch.
633 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patelff3d3e52008-07-02 01:18:13 +0000634 loopPreheader->getTerminator());
Devang Patel52f93c02008-06-02 22:52:56 +0000635 if (DT) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000636 DT->changeImmediateDominator(NewExit, loopPreheader);
637 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel52f93c02008-06-02 22:52:56 +0000638 }
Devang Patel6dfc4382008-06-18 02:16:38 +0000639
640 if (DF) {
641 // NewExit is now part of NewPH and Loop Header's dominance
642 // frontier.
643 DominanceFrontier::iterator DFI = DF->find(NewPH);
644 if (DFI != DF->end())
645 DF->addToFrontier(DFI, NewExit);
Devang Patelff3d3e52008-07-02 01:18:13 +0000646 DFI = DF->find(loopHeader);
Devang Patel6dfc4382008-06-18 02:16:38 +0000647 DF->addToFrontier(DFI, NewExit);
648
649 // ExitBlock does not have successors then NewExit is part of
650 // its dominance frontier.
651 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
652 DFI = DF->find(ExitBlock);
653 DF->addToFrontier(DFI, NewExit);
654 }
655 }
Devang Patelff3d3e52008-07-02 01:18:13 +0000656 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
657 loopPreheader->getTerminator()->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658
659 // We need to reprocess this loop, it could be unswitched again.
Devang Pateleec0d372007-07-30 23:07:10 +0000660 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661
662 // Now that we know that the loop is never entered when this condition is a
663 // particular value, rewrite the loop with this info. We know that this will
664 // at least eliminate the old branch.
665 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
666 ++NumTrivial;
667}
668
Devang Patel122c81f2007-10-05 22:29:34 +0000669/// ReplaceLoopExternalDFMember -
670/// If BB's dominance frontier has a member that is not part of loop L then
671/// remove it. Add NewDFMember in BB's dominance frontier.
672void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
673 BasicBlock *NewDFMember) {
674
675 DominanceFrontier::iterator DFI = DF->find(BB);
676 if (DFI == DF->end())
677 return;
678
679 DominanceFrontier::DomSetType &DFSet = DFI->second;
680 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patel969f07a2007-10-09 21:31:36 +0000681 DE = DFSet.end(); DI != DE;) {
682 BasicBlock *B = *DI++;
Devang Patel122c81f2007-10-05 22:29:34 +0000683 if (L->contains(B))
684 continue;
David Greene932e8b62007-12-17 17:40:29 +0000685
Devang Patel122c81f2007-10-05 22:29:34 +0000686 DF->removeFromFrontier(DFI, B);
687 LoopDF.insert(B);
688 }
689
690 DF->addToFrontier(DFI, NewDFMember);
691}
692
Chris Lattnerdb47e722008-04-21 00:25:49 +0000693/// SplitExitEdges - Split all of the edges from inside the loop to their exit
694/// blocks. Update the appropriate Phi nodes as we do so.
695void LoopUnswitch::SplitExitEdges(Loop *L,
696 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Pateld39af172007-10-03 21:16:08 +0000697 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel122c81f2007-10-05 22:29:34 +0000698
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
700 BasicBlock *ExitBlock = ExitBlocks[i];
701 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
702
703 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
704 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel0ea2da12007-08-02 15:25:57 +0000705 MiddleBlocks.push_back(MiddleBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 BasicBlock* StartBlock = Preds[j];
707 BasicBlock* EndBlock;
708 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
709 EndBlock = MiddleBlock;
710 MiddleBlock = EndBlock->getSinglePredecessor();;
711 } else {
712 EndBlock = ExitBlock;
713 }
714
Devang Patel122c81f2007-10-05 22:29:34 +0000715 OrigLoopExitMap[StartBlock] = EndBlock;
716
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 std::set<PHINode*> InsertedPHIs;
718 PHINode* OldLCSSA = 0;
719 for (BasicBlock::iterator I = EndBlock->begin();
720 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
721 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000722 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
723 OldLCSSA->getName() + ".us-lcssa",
724 MiddleBlock->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 NewLCSSA->addIncoming(OldValue, StartBlock);
726 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
727 NewLCSSA);
728 InsertedPHIs.insert(NewLCSSA);
729 }
730
Dan Gohman514277c2008-05-23 21:05:58 +0000731 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 for (BasicBlock::iterator I = MiddleBlock->begin();
733 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
734 ++I) {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000735 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
736 OldLCSSA->getName() + ".us-lcssa",
737 InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 OldLCSSA->replaceAllUsesWith(NewLCSSA);
739 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
740 }
Devang Patel122c81f2007-10-05 22:29:34 +0000741
742 if (DF && DT) {
743 // StartBlock -- > MiddleBlock -- > EndBlock
744 // StartBlock is loop exiting block. EndBlock will become merge point
745 // of two loop exits after loop unswitch.
746
747 // If StartBlock's DF member includes a block that is not loop member
748 // then replace that DF member with EndBlock.
749
750 // If MiddleBlock's DF member includes a block that is not loop member
751 // tnen replace that DF member with EndBlock.
752
753 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
754 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
755 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 }
757 }
Devang Patel122c81f2007-10-05 22:29:34 +0000758
Devang Pateld39af172007-10-03 21:16:08 +0000759}
760
Devang Patel1a56d002008-07-02 22:58:54 +0000761/// addBBToDomFrontier - Helper function. Insert DFBB in Basic Block BB's
762/// dominance frontier using iterator DFI.
763static void addBBToDomFrontier(DominanceFrontier &DF,
764 DominanceFrontier::iterator &DFI,
765 BasicBlock *BB, BasicBlock *DFBB) {
766 if (DFI != DF.end()) {
767 DF.addToFrontier(DFI, DFBB);
768 return;
769 }
770
771 DominanceFrontier::DomSetType NSet;
772 NSet.insert(DFBB);
773 DF.addBasicBlock(BB, NSet);
774 DFI = DF.find(BB);
775}
776
Devang Patel55410702007-10-03 21:17:43 +0000777/// UnswitchNontrivialCondition - We determined that the loop is profitable
778/// to unswitch when LIC equal Val. Split it into loop versions and test the
779/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Pateld39af172007-10-03 21:16:08 +0000780void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
781 Loop *L) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000782 Function *F = loopHeader->getParent();
Devang Pateld39af172007-10-03 21:16:08 +0000783 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000784 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Pateld39af172007-10-03 21:16:08 +0000785 << " blocks] in Function " << F->getName()
786 << " when '" << *Val << "' == " << *LIC << "\n";
787
Devang Pateld6aef782008-07-02 01:44:29 +0000788 LoopBlocks.clear();
789 NewBlocks.clear();
Devang Pateld39af172007-10-03 21:16:08 +0000790
791 // First step, split the preheader and exit blocks, and add these blocks to
792 // the LoopBlocks list.
Devang Patelff3d3e52008-07-02 01:18:13 +0000793 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Pateld39af172007-10-03 21:16:08 +0000794 LoopBlocks.push_back(NewPreheader);
795
796 // We want the loop to come after the preheader, but before the exit blocks.
797 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
798
799 SmallVector<BasicBlock*, 8> ExitBlocks;
800 L->getUniqueExitBlocks(ExitBlocks);
801
802 // Split all of the edges from inside the loop to their exit blocks. Update
803 // the appropriate Phi nodes as we do so.
804 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel122c81f2007-10-05 22:29:34 +0000805 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Pateld39af172007-10-03 21:16:08 +0000806
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 // The exit blocks may have been changed due to edge splitting, recompute.
808 ExitBlocks.clear();
809 L->getUniqueExitBlocks(ExitBlocks);
810
811 // Add exit blocks to the loop blocks.
812 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
813
814 // Next step, clone all of the basic blocks that make up the loop (including
815 // the loop preheader and exit blocks), keeping track of the mapping between
816 // the instructions and blocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 NewBlocks.reserve(LoopBlocks.size());
818 DenseMap<const Value*, Value*> ValueMap;
819 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
820 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
821 NewBlocks.push_back(New);
822 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patelf73276b2007-07-31 08:03:26 +0000823 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
825
Devang Patel0ea2da12007-08-02 15:25:57 +0000826 // OutSiders are basic block that are dominated by original header and
827 // at the same time they are not part of loop.
828 SmallPtrSet<BasicBlock *, 8> OutSiders;
829 if (DT) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000830 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000831 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
832 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
833 BasicBlock *B = (*DI)->getBlock();
834
835 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
836 if (VI == ValueMap.end())
837 OutSiders.insert(B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 }
Devang Patel0ea2da12007-08-02 15:25:57 +0000839 }
840
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 // Splice the newly inserted blocks into the function right before the
842 // original preheader.
843 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
844 NewBlocks[0], F->end());
845
846 // Now we create the new Loop object for the versioned loop.
847 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
848 Loop *ParentLoop = L->getParentLoop();
849 if (ParentLoop) {
850 // Make sure to add the cloned preheader and exit blocks to the parent loop
851 // as well.
Owen Andersonca0b9d42007-11-27 03:43:35 +0000852 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 }
854
855 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
856 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
857 // The new exit block should be in the same loop as the old one.
858 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersonca0b9d42007-11-27 03:43:35 +0000859 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860
861 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
862 "Exit block should have been split to have one successor!");
863 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
864
865 // If the successor of the exit block had PHI nodes, add an entry for
866 // NewExit.
867 PHINode *PN;
868 for (BasicBlock::iterator I = ExitSucc->begin();
869 (PN = dyn_cast<PHINode>(I)); ++I) {
870 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
871 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
872 if (It != ValueMap.end()) V = It->second;
873 PN->addIncoming(V, NewExit);
874 }
875 }
876
877 // Rewrite the code to refer to itself.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000878 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
879 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
880 E = NewBlocks[i]->end(); I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 RemapInstruction(I, ValueMap);
882
883 // Rewrite the original preheader to select between versions of the loop.
Devang Patelff3d3e52008-07-02 01:18:13 +0000884 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
886 "Preheader splitting did not work correctly!");
887
888 // Emit the new branch that selects between the two versions of this loop.
889 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patelf73276b2007-07-31 08:03:26 +0000890 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +0000891 OldBR->eraseFromParent();
Devang Patel0ea2da12007-08-02 15:25:57 +0000892
893 // Update dominator info
894 if (DF && DT) {
895
Devang Patel122c81f2007-10-05 22:29:34 +0000896 SmallVector<BasicBlock *,4> ExitingBlocks;
897 L->getExitingBlocks(ExitingBlocks);
898
Devang Patel0ea2da12007-08-02 15:25:57 +0000899 // Clone dominator info for all cloned basic block.
900 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
901 BasicBlock *LBB = LoopBlocks[i];
902 BasicBlock *NBB = NewBlocks[i];
Devang Patelff3d3e52008-07-02 01:18:13 +0000903 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
904 loopHeader, DT, DF, ValueMap);
Devang Patel0ea2da12007-08-02 15:25:57 +0000905
Devang Patel122c81f2007-10-05 22:29:34 +0000906 // If LBB's dominance frontier includes DFMember
907 // such that DFMember is also a member of LoopDF then
908 // - Remove DFMember from LBB's dominance frontier
Chris Lattnerdb47e722008-04-21 00:25:49 +0000909 // - Copy loop exiting blocks', that are dominated by BB,
910 // dominance frontier member in BB's dominance frontier
Devang Patel0ea2da12007-08-02 15:25:57 +0000911
Devang Patel122c81f2007-10-05 22:29:34 +0000912 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel0ea2da12007-08-02 15:25:57 +0000913 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel122c81f2007-10-05 22:29:34 +0000914 if (LBBI == DF->end())
915 continue;
916
917 DominanceFrontier::DomSetType &LBSet = LBBI->second;
918 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
919 LE = LBSet.end(); LI != LE; /* NULL */) {
920 BasicBlock *B = *LI++;
Devang Patelff3d3e52008-07-02 01:18:13 +0000921 if (B == LBB && B == loopHeader)
Devang Patel122c81f2007-10-05 22:29:34 +0000922 continue;
923 bool removeB = false;
924 if (!LoopDF.count(B))
925 continue;
926
927 // If LBB dominates loop exits then insert loop exit block's DF
928 // into B's DF.
Chris Lattnerdb47e722008-04-21 00:25:49 +0000929 for(SmallVector<BasicBlock *, 4>::iterator
930 LExitI = ExitingBlocks.begin(),
Devang Patel122c81f2007-10-05 22:29:34 +0000931 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
932 BasicBlock *E = *LExitI;
933
934 if (!DT->dominates(LBB,E))
935 continue;
936
937 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
938 OrigLoopExitMap.find(E);
939 if (DFBI == OrigLoopExitMap.end())
940 continue;
941
942 BasicBlock *DFB = DFBI->second;
943 DF->addToFrontier(LBBI, DFB);
944 DF->addToFrontier(NBBI, DFB);
945 removeB = true;
946 }
947
Chris Lattnerdb47e722008-04-21 00:25:49 +0000948 // If B's replacement is inserted in DF then now is the time to remove
949 // B.
Devang Patel122c81f2007-10-05 22:29:34 +0000950 if (removeB) {
951 DF->removeFromFrontier(LBBI, B);
952 if (L->contains(B))
953 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
954 else
Devang Patel0ea2da12007-08-02 15:25:57 +0000955 DF->removeFromFrontier(NBBI, B);
956 }
957 }
Devang Patel122c81f2007-10-05 22:29:34 +0000958
Devang Patel0ea2da12007-08-02 15:25:57 +0000959 }
960
961 // MiddleBlocks are dominated by original pre header. SplitEdge updated
962 // MiddleBlocks' dominance frontier appropriately.
963 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
964 BasicBlock *MBB = MiddleBlocks[i];
965 if (!MBB->getSinglePredecessor())
Devang Patelff3d3e52008-07-02 01:18:13 +0000966 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000967 }
968
969 // All Outsiders are now dominated by original pre header.
970 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
971 OE = OutSiders.end(); OI != OE; ++OI) {
972 BasicBlock *OB = *OI;
Devang Patelff3d3e52008-07-02 01:18:13 +0000973 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000974 }
975
976 // New loop headers are dominated by original preheader
Devang Patelff3d3e52008-07-02 01:18:13 +0000977 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
978 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000979 }
980
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 LoopProcessWorklist.push_back(NewLoop);
Devang Pateleec0d372007-07-30 23:07:10 +0000982 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983
984 // Now we rewrite the original code to know that the condition is true and the
985 // new code to know that the condition is false.
986 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
987
988 // It's possible that simplifying one loop could cause the other to be
989 // deleted. If so, don't simplify it.
990 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
991 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
992}
993
994/// RemoveFromWorklist - Remove all instances of I from the worklist vector
995/// specified.
996static void RemoveFromWorklist(Instruction *I,
997 std::vector<Instruction*> &Worklist) {
998 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
999 Worklist.end(), I);
1000 while (WI != Worklist.end()) {
1001 unsigned Offset = WI-Worklist.begin();
1002 Worklist.erase(WI);
1003 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
1004 }
1005}
1006
1007/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1008/// program, replacing all uses with V and update the worklist.
1009static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patelf73276b2007-07-31 08:03:26 +00001010 std::vector<Instruction*> &Worklist,
1011 Loop *L, LPPassManager *LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 DOUT << "Replace with '" << *V << "': " << *I;
1013
1014 // Add uses to the worklist, which may be dead now.
1015 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1016 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1017 Worklist.push_back(Use);
1018
1019 // Add users to the worklist which may be simplified now.
1020 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1021 UI != E; ++UI)
1022 Worklist.push_back(cast<Instruction>(*UI));
Devang Patelf73276b2007-07-31 08:03:26 +00001023 LPM->deleteSimpleAnalysisValue(I, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 RemoveFromWorklist(I, Worklist);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001025 I->replaceAllUsesWith(V);
1026 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 ++NumSimplify;
1028}
1029
1030/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1031/// information, and remove any dead successors it has.
1032///
1033void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patelf73276b2007-07-31 08:03:26 +00001034 std::vector<Instruction*> &Worklist,
1035 Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 if (pred_begin(BB) != pred_end(BB)) {
1037 // This block isn't dead, since an edge to BB was just removed, see if there
1038 // are any easy simplifications we can do now.
1039 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1040 // If it has one pred, fold phi nodes in BB.
1041 while (isa<PHINode>(BB->begin()))
1042 ReplaceUsesOfWith(BB->begin(),
1043 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patelf73276b2007-07-31 08:03:26 +00001044 Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045
1046 // If this is the header of a loop and the only pred is the latch, we now
1047 // have an unreachable loop.
1048 if (Loop *L = LI->getLoopFor(BB))
Devang Patelff3d3e52008-07-02 01:18:13 +00001049 if (loopHeader == BB && L->contains(Pred)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 // Remove the branch from the latch to the header block, this makes
1051 // the header dead, which will make the latch dead (because the header
1052 // dominates the latch).
Devang Patelf73276b2007-07-31 08:03:26 +00001053 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001054 Pred->getTerminator()->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 new UnreachableInst(Pred);
1056
1057 // The loop is now broken, remove it from LI.
1058 RemoveLoopFromHierarchy(L);
1059
1060 // Reprocess the header, which now IS dead.
Devang Patelf73276b2007-07-31 08:03:26 +00001061 RemoveBlockIfDead(BB, Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 return;
1063 }
1064
1065 // If pred ends in a uncond branch, add uncond branch to worklist so that
1066 // the two blocks will get merged.
1067 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1068 if (BI->isUnconditional())
1069 Worklist.push_back(BI);
1070 }
1071 return;
1072 }
1073
1074 DOUT << "Nuking dead block: " << *BB;
1075
1076 // Remove the instructions in the basic block from the worklist.
1077 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1078 RemoveFromWorklist(I, Worklist);
1079
1080 // Anything that uses the instructions in this basic block should have their
1081 // uses replaced with undefs.
1082 if (!I->use_empty())
1083 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1084 }
1085
1086 // If this is the edge to the header block for a loop, remove the loop and
1087 // promote all subloops.
1088 if (Loop *BBLoop = LI->getLoopFor(BB)) {
1089 if (BBLoop->getLoopLatch() == BB)
1090 RemoveLoopFromHierarchy(BBLoop);
1091 }
1092
1093 // Remove the block from the loop info, which removes it from any loops it
1094 // was in.
1095 LI->removeBlock(BB);
1096
1097
1098 // Remove phi node entries in successors for this block.
1099 TerminatorInst *TI = BB->getTerminator();
1100 std::vector<BasicBlock*> Succs;
1101 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1102 Succs.push_back(TI->getSuccessor(i));
1103 TI->getSuccessor(i)->removePredecessor(BB);
1104 }
1105
1106 // Unique the successors, remove anything with multiple uses.
1107 std::sort(Succs.begin(), Succs.end());
1108 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1109
1110 // Remove the basic block, including all of the instructions contained in it.
Devang Patelf73276b2007-07-31 08:03:26 +00001111 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001112 BB->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // Remove successor blocks here that are not dead, so that we know we only
1114 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1115 // then getting removed before we revisit them, which is badness.
1116 //
1117 for (unsigned i = 0; i != Succs.size(); ++i)
1118 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1119 // One exception is loop headers. If this block was the preheader for a
1120 // loop, then we DO want to visit the loop so the loop gets deleted.
1121 // We know that if the successor is a loop header, that this loop had to
1122 // be the preheader: the case where this was the latch block was handled
1123 // above and headers can only have two predecessors.
1124 if (!LI->isLoopHeader(Succs[i])) {
1125 Succs.erase(Succs.begin()+i);
1126 --i;
1127 }
1128 }
1129
1130 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patelf73276b2007-07-31 08:03:26 +00001131 RemoveBlockIfDead(Succs[i], Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132}
1133
1134/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1135/// become unwrapped, either because the backedge was deleted, or because the
1136/// edge into the header was removed. If the edge into the header from the
1137/// latch block was removed, the loop is unwrapped but subloops are still alive,
1138/// so they just reparent loops. If the loops are actually dead, they will be
1139/// removed later.
1140void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
1141 LPM->deleteLoopFromQueue(L);
1142 RemoveLoopFromWorklist(L);
1143}
1144
1145
1146
1147// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1148// the value specified by Val in the specified loop, or we know it does NOT have
1149// that value. Rewrite any uses of LIC or of properties correlated to it.
1150void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1151 Constant *Val,
1152 bool IsEqual) {
1153 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1154
1155 // FIXME: Support correlated properties, like:
1156 // for (...)
1157 // if (li1 < li2)
1158 // ...
1159 // if (li1 > li2)
1160 // ...
1161
1162 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1163 // selects, switches.
1164 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1165 std::vector<Instruction*> Worklist;
1166
1167 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1168 // in the loop with the appropriate one directly.
1169 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1170 Value *Replacement;
1171 if (IsEqual)
1172 Replacement = Val;
1173 else
1174 Replacement = ConstantInt::get(Type::Int1Ty,
1175 !cast<ConstantInt>(Val)->getZExtValue());
1176
1177 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1178 if (Instruction *U = cast<Instruction>(Users[i])) {
1179 if (!L->contains(U->getParent()))
1180 continue;
1181 U->replaceUsesOfWith(LIC, Replacement);
1182 Worklist.push_back(U);
1183 }
1184 } else {
1185 // Otherwise, we don't know the precise value of LIC, but we do know that it
1186 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1187 // can. This case occurs when we unswitch switch statements.
1188 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1189 if (Instruction *U = cast<Instruction>(Users[i])) {
1190 if (!L->contains(U->getParent()))
1191 continue;
1192
1193 Worklist.push_back(U);
1194
1195 // If we know that LIC is not Val, use this info to simplify code.
1196 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1197 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1198 if (SI->getCaseValue(i) == Val) {
1199 // Found a dead case value. Don't remove PHI nodes in the
1200 // successor if they become single-entry, those PHI nodes may
1201 // be in the Users list.
1202
1203 // FIXME: This is a hack. We need to keep the successor around
1204 // and hooked up so as to preserve the loop structure, because
1205 // trying to update it is complicated. So instead we preserve the
1206 // loop structure and put the block on an dead code path.
1207
1208 BasicBlock* Old = SI->getParent();
1209 BasicBlock* Split = SplitBlock(Old, SI, this);
1210
1211 Instruction* OldTerm = Old->getTerminator();
Devang Patel7e50e3d2008-07-03 00:08:13 +00001212 BranchInst::Create(Split, SI->getSuccessor(i),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001213 ConstantInt::getTrue(), OldTerm);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001214
Chris Lattnerdb47e722008-04-21 00:25:49 +00001215 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 Old->getTerminator()->eraseFromParent();
1217
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218 PHINode *PN;
Devang Patel7e50e3d2008-07-03 00:08:13 +00001219 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 (PN = dyn_cast<PHINode>(II)); ++II) {
1221 Value *InVal = PN->removeIncomingValue(Split, false);
1222 PN->addIncoming(InVal, Old);
1223 }
1224
1225 SI->removeCase(i);
1226 break;
1227 }
1228 }
1229 }
1230
1231 // TODO: We could do other simplifications, for example, turning
1232 // LIC == Val -> false.
1233 }
1234 }
1235
Devang Patelf73276b2007-07-31 08:03:26 +00001236 SimplifyCode(Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237}
1238
1239/// SimplifyCode - Okay, now that we have simplified some instructions in the
1240/// loop, walk over it and constant prop, dce, and fold control flow where
1241/// possible. Note that this is effectively a very simple loop-structure-aware
1242/// optimizer. During processing of this loop, L could very well be deleted, so
1243/// it must not be used.
1244///
1245/// FIXME: When the loop optimizer is more mature, separate this out to a new
1246/// pass.
1247///
Devang Patelf73276b2007-07-31 08:03:26 +00001248void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 while (!Worklist.empty()) {
1250 Instruction *I = Worklist.back();
1251 Worklist.pop_back();
1252
1253 // Simple constant folding.
1254 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patelf73276b2007-07-31 08:03:26 +00001255 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 continue;
1257 }
1258
1259 // Simple DCE.
1260 if (isInstructionTriviallyDead(I)) {
1261 DOUT << "Remove dead instruction '" << *I;
1262
1263 // Add uses to the worklist, which may be dead now.
1264 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1265 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1266 Worklist.push_back(Use);
Devang Patelf73276b2007-07-31 08:03:26 +00001267 LPM->deleteSimpleAnalysisValue(I, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 RemoveFromWorklist(I, Worklist);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001269 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 ++NumSimplify;
1271 continue;
1272 }
1273
1274 // Special case hacks that appear commonly in unswitched code.
1275 switch (I->getOpcode()) {
1276 case Instruction::Select:
1277 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner03dc7d72007-08-02 16:53:43 +00001278 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1279 LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 continue;
1281 }
1282 break;
1283 case Instruction::And:
1284 if (isa<ConstantInt>(I->getOperand(0)) &&
1285 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1286 cast<BinaryOperator>(I)->swapOperands();
1287 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1288 if (CB->getType() == Type::Int1Ty) {
1289 if (CB->isOne()) // X & 1 -> X
Devang Patelf73276b2007-07-31 08:03:26 +00001290 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 else // X & 0 -> 0
Devang Patelf73276b2007-07-31 08:03:26 +00001292 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 continue;
1294 }
1295 break;
1296 case Instruction::Or:
1297 if (isa<ConstantInt>(I->getOperand(0)) &&
1298 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1299 cast<BinaryOperator>(I)->swapOperands();
1300 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1301 if (CB->getType() == Type::Int1Ty) {
1302 if (CB->isOne()) // X | 1 -> 1
Devang Patelf73276b2007-07-31 08:03:26 +00001303 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 else // X | 0 -> X
Devang Patelf73276b2007-07-31 08:03:26 +00001305 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 continue;
1307 }
1308 break;
1309 case Instruction::Br: {
1310 BranchInst *BI = cast<BranchInst>(I);
1311 if (BI->isUnconditional()) {
1312 // If BI's parent is the only pred of the successor, fold the two blocks
1313 // together.
1314 BasicBlock *Pred = BI->getParent();
1315 BasicBlock *Succ = BI->getSuccessor(0);
1316 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1317 if (!SinglePred) continue; // Nothing to do.
1318 assert(SinglePred == Pred && "CFG broken");
1319
1320 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1321 << Succ->getName() << "\n";
1322
1323 // Resolve any single entry PHI nodes in Succ.
1324 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patelf73276b2007-07-31 08:03:26 +00001325 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326
1327 // Move all of the successor contents from Succ to Pred.
1328 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1329 Succ->end());
Devang Patelf73276b2007-07-31 08:03:26 +00001330 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001331 BI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 RemoveFromWorklist(BI, Worklist);
1333
1334 // If Succ has any successors with PHI nodes, update them to have
1335 // entries coming from Pred instead of Succ.
1336 Succ->replaceAllUsesWith(Pred);
1337
1338 // Remove Succ from the loop tree.
1339 LI->removeBlock(Succ);
Devang Patelf73276b2007-07-31 08:03:26 +00001340 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001341 Succ->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 ++NumSimplify;
1343 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1344 // Conditional branch. Turn it into an unconditional branch, then
1345 // remove dead blocks.
1346 break; // FIXME: Enable.
1347
1348 DOUT << "Folded branch: " << *BI;
1349 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1350 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1351 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001352 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patelf73276b2007-07-31 08:03:26 +00001353 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001354 BI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 RemoveFromWorklist(BI, Worklist);
1356 ++NumSimplify;
1357
Devang Patelf73276b2007-07-31 08:03:26 +00001358 RemoveBlockIfDead(DeadSucc, Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 }
1360 break;
1361 }
1362 }
1363 }
1364}