blob: 1b94d9c29d0161e73543a9f192e97968bc3da959 [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);
115 AU.addPreserved<DominatorTree>();
116 AU.addPreserved<DominanceFrontier>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 }
118
119 private:
Devang Patelf73276b2007-07-31 08:03:26 +0000120
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
122 /// remove it.
123 void RemoveLoopFromWorklist(Loop *L) {
124 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
125 LoopProcessWorklist.end(), L);
126 if (I != LoopProcessWorklist.end())
127 LoopProcessWorklist.erase(I);
128 }
Devang Pateld39af172007-10-03 21:16:08 +0000129
Devang Patelff3d3e52008-07-02 01:18:13 +0000130 void initLoopData() {
131 loopHeader = currentLoop->getHeader();
132 loopPreheader = currentLoop->getLoopPreheader();
133 }
134
Chris Lattnerdb47e722008-04-21 00:25:49 +0000135 /// Split all of the edges from inside the loop to their exit blocks.
136 /// Update the appropriate Phi nodes as we do so.
Devang Patel122c81f2007-10-05 22:29:34 +0000137 void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Pateld39af172007-10-03 21:16:08 +0000138 SmallVector<BasicBlock *, 8> &MiddleBlocks);
Devang Patel122c81f2007-10-05 22:29:34 +0000139
Chris Lattnerdb47e722008-04-21 00:25:49 +0000140 /// If BB's dominance frontier has a member that is not part of loop L then
Devang Patel122c81f2007-10-05 22:29:34 +0000141 /// remove it. Add NewDFMember in BB's dominance frontier.
142 void ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
143 BasicBlock *NewDFMember);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
Devang Patelff3d3e52008-07-02 01:18:13 +0000145 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
146 unsigned getLoopUnswitchCost(Value *LIC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
148 BasicBlock *ExitBlock);
149 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
150
151 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
152 Constant *Val, bool isEqual);
153
154 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
155 BasicBlock *TrueDest,
156 BasicBlock *FalseDest,
157 Instruction *InsertPt);
158
Devang Patelf73276b2007-07-31 08:03:26 +0000159 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 void RemoveBlockIfDead(BasicBlock *BB,
Devang Patelf73276b2007-07-31 08:03:26 +0000161 std::vector<Instruction*> &Worklist, Loop *l);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 void RemoveLoopFromHierarchy(Loop *L);
Devang Patelff3d3e52008-07-02 01:18:13 +0000163 bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
164 BasicBlock **LoopExit = 0);
165
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167}
Dan Gohman089efff2008-05-13 00:00:25 +0000168char LoopUnswitch::ID = 0;
169static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171LoopPass *llvm::createLoopUnswitchPass(bool Os) {
172 return new LoopUnswitch(Os);
173}
174
175/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
176/// invariant in the loop, or has an invariant piece, return the invariant.
177/// Otherwise, return null.
178static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
179 // Constants should be folded, not unswitched on!
180 if (isa<Constant>(Cond)) return false;
181
182 // TODO: Handle: br (VARIANT|INVARIANT).
183 // TODO: Hoist simple expressions out of loops.
184 if (L->isLoopInvariant(Cond)) return Cond;
185
186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
187 if (BO->getOpcode() == Instruction::And ||
188 BO->getOpcode() == Instruction::Or) {
189 // If either the left or right side is invariant, we can unswitch on this,
190 // which will cause the branch to go away in one loop and the condition to
191 // simplify in the other one.
192 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
193 return LHS;
194 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
195 return RHS;
196 }
Devang Patel122c81f2007-10-05 22:29:34 +0000197
198 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199}
200
201bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 LI = &getAnalysis<LoopInfo>();
203 LPM = &LPM_Ref;
Devang Patel122c81f2007-10-05 22:29:34 +0000204 DF = getAnalysisToUpdate<DominanceFrontier>();
205 DT = getAnalysisToUpdate<DominatorTree>();
Devang Patelff3d3e52008-07-02 01:18:13 +0000206 currentLoop = L;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 bool Changed = false;
Devang Pateleec0d372007-07-30 23:07:10 +0000208
209 do {
Devang Patelff3d3e52008-07-02 01:18:13 +0000210 assert(currentLoop->isLCSSAForm());
Devang Pateleec0d372007-07-30 23:07:10 +0000211 redoLoop = false;
Devang Patelff3d3e52008-07-02 01:18:13 +0000212 Changed |= processCurrentLoop();
Devang Pateleec0d372007-07-30 23:07:10 +0000213 } while(redoLoop);
214
215 return Changed;
216}
217
Devang Patelff3d3e52008-07-02 01:18:13 +0000218/// processCurrentLoop - Do actual work and unswitch loop if possible
219/// and profitable.
220bool LoopUnswitch::processCurrentLoop() {
Devang Pateleec0d372007-07-30 23:07:10 +0000221 bool Changed = false;
222
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 // Loop over all of the basic blocks in the loop. If we find an interior
224 // block that is branching on a loop-invariant condition, we can unswitch this
225 // loop.
Devang Patelff3d3e52008-07-02 01:18:13 +0000226 for (Loop::block_iterator I = currentLoop->block_begin(),
227 E = currentLoop->block_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 I != E; ++I) {
229 TerminatorInst *TI = (*I)->getTerminator();
230 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
231 // If this isn't branching on an invariant condition, we can't unswitch
232 // it.
233 if (BI->isConditional()) {
234 // See if this, or some part of it, is loop invariant. If so, we can
235 // unswitch on it if we desire.
Devang Patelff3d3e52008-07-02 01:18:13 +0000236 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
237 currentLoop, Changed);
238 if (LoopCond && UnswitchIfProfitable(LoopCond,
239 ConstantInt::getTrue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 ++NumBranches;
241 return true;
242 }
243 }
244 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000245 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
246 currentLoop, Changed);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 if (LoopCond && SI->getNumCases() > 1) {
248 // Find a value to unswitch on:
249 // FIXME: this should chose the most expensive case!
250 Constant *UnswitchVal = SI->getCaseValue(1);
251 // Do not process same value again and again.
252 if (!UnswitchedVals.insert(UnswitchVal))
253 continue;
254
Devang Patelff3d3e52008-07-02 01:18:13 +0000255 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 ++NumSwitches;
257 return true;
258 }
259 }
260 }
261
262 // Scan the instructions to check for unswitchable values.
263 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
264 BBI != E; ++BBI)
265 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000266 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
267 currentLoop, Changed);
268 if (LoopCond && UnswitchIfProfitable(LoopCond,
269 ConstantInt::getTrue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 ++NumSelects;
271 return true;
272 }
273 }
274 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 return Changed;
276}
277
278/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
279/// 1. Exit the loop with no side effects.
280/// 2. Branch to the latch block with no side-effects.
281///
282/// If these conditions are true, we return true and set ExitBB to the block we
283/// exit through.
284///
285static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
286 BasicBlock *&ExitBB,
287 std::set<BasicBlock*> &Visited) {
288 if (!Visited.insert(BB).second) {
289 // Already visited and Ok, end of recursion.
290 return true;
291 } else if (!L->contains(BB)) {
292 // Otherwise, this is a loop exit, this is fine so long as this is the
293 // first exit.
294 if (ExitBB != 0) return false;
295 ExitBB = BB;
296 return true;
297 }
298
299 // Otherwise, this is an unvisited intra-loop node. Check all successors.
300 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
301 // Check to see if the successor is a trivial loop exit.
302 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
303 return false;
304 }
305
306 // Okay, everything after this looks good, check to make sure that this block
307 // doesn't include any side effects.
308 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
309 if (I->mayWriteToMemory())
310 return false;
311
312 return true;
313}
314
315/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
316/// leads to an exit from the specified loop, and has no side-effects in the
317/// process. If so, return the block that is exited to, otherwise return null.
318static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
319 std::set<BasicBlock*> Visited;
320 Visited.insert(L->getHeader()); // Branches to header are ok.
321 BasicBlock *ExitBB = 0;
322 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
323 return ExitBB;
324 return 0;
325}
326
327/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
328/// trivial: that is, that the condition controls whether or not the loop does
329/// anything at all. If this is a trivial condition, unswitching produces no
330/// code duplications (equivalently, it produces a simpler loop and a new empty
331/// loop, which gets deleted).
332///
333/// If this is a trivial condition, return true, otherwise return false. When
334/// returning true, this sets Cond and Val to the condition that controls the
335/// trivial condition: when Cond dynamically equals Val, the loop is known to
336/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
337/// Cond == Val.
338///
Devang Patelff3d3e52008-07-02 01:18:13 +0000339bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
340 BasicBlock **LoopExit) {
341 BasicBlock *Header = currentLoop->getHeader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 TerminatorInst *HeaderTerm = Header->getTerminator();
343
344 BasicBlock *LoopExitBB = 0;
345 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
346 // If the header block doesn't end with a conditional branch on Cond, we
347 // can't handle it.
348 if (!BI->isConditional() || BI->getCondition() != Cond)
349 return false;
350
351 // Check to see if a successor of the branch is guaranteed to go to the
352 // latch block or exit through a one exit block without having any
353 // side-effects. If so, determine the value of Cond that causes it to do
354 // this.
Devang Patelff3d3e52008-07-02 01:18:13 +0000355 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
356 BI->getSuccessor(0)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 if (Val) *Val = ConstantInt::getTrue();
Devang Patelff3d3e52008-07-02 01:18:13 +0000358 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
359 BI->getSuccessor(1)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 if (Val) *Val = ConstantInt::getFalse();
361 }
362 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
363 // If this isn't a switch on Cond, we can't handle it.
364 if (SI->getCondition() != Cond) return false;
365
366 // Check to see if a successor of the switch is guaranteed to go to the
367 // latch block or exit through a one exit block without having any
368 // side-effects. If so, determine the value of Cond that causes it to do
369 // this. Note that we can't trivially unswitch on the default case.
370 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
Devang Patelff3d3e52008-07-02 01:18:13 +0000371 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
372 SI->getSuccessor(i)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 // Okay, we found a trivial case, remember the value that is trivial.
374 if (Val) *Val = SI->getCaseValue(i);
375 break;
376 }
377 }
378
379 // If we didn't find a single unique LoopExit block, or if the loop exit block
380 // contains phi nodes, this isn't trivial.
381 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
382 return false; // Can't handle this.
383
384 if (LoopExit) *LoopExit = LoopExitBB;
385
386 // We already know that nothing uses any scalar values defined inside of this
387 // loop. As such, we just have to check to see if this loop will execute any
388 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
389 // part of the loop that the code *would* execute. We already checked the
390 // tail, check the header now.
391 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
392 if (I->mayWriteToMemory())
393 return false;
394 return true;
395}
396
397/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
Devang Patelff3d3e52008-07-02 01:18:13 +0000398/// we choose to unswitch current loop on the specified value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399///
Devang Patelff3d3e52008-07-02 01:18:13 +0000400unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 // If the condition is trivial, always unswitch. There is no code growth for
402 // this case.
Devang Patelff3d3e52008-07-02 01:18:13 +0000403 if (IsTrivialUnswitchCondition(LIC))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 return 0;
405
406 // FIXME: This is really overly conservative. However, more liberal
407 // estimations have thus far resulted in excessive unswitching, which is bad
408 // both in compile time and in code size. This should be replaced once
409 // someone figures out how a good estimation.
Devang Patelff3d3e52008-07-02 01:18:13 +0000410 return currentLoop->getBlocks().size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411
412 unsigned Cost = 0;
413 // FIXME: this is brain dead. It should take into consideration code
414 // shrinkage.
Devang Patelff3d3e52008-07-02 01:18:13 +0000415 for (Loop::block_iterator I = currentLoop->block_begin(),
416 E = currentLoop->block_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 I != E; ++I) {
418 BasicBlock *BB = *I;
419 // Do not include empty blocks in the cost calculation. This happen due to
420 // loop canonicalization and will be removed.
421 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
422 continue;
423
424 // Count basic blocks.
425 ++Cost;
426 }
427
428 return Cost;
429}
430
Devang Patelff3d3e52008-07-02 01:18:13 +0000431/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
433/// unswitch the loop, reprocess the pieces, then return true.
Devang Patelff3d3e52008-07-02 01:18:13 +0000434bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
435 // Check to see if it would be profitable to unswitch current loop.
436 unsigned Cost = getLoopUnswitchCost(LoopCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437
438 // Do not do non-trivial unswitch while optimizing for size.
439 if (Cost && OptimizeForSize)
440 return false;
441
442 if (Cost > Threshold) {
443 // FIXME: this should estimate growth by the amount of code shared by the
444 // resultant unswitched loops.
445 //
446 DOUT << "NOT unswitching loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000447 << currentLoop->getHeader()->getName() << ", cost too high: "
448 << currentLoop->getBlocks().size() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 return false;
450 }
Devang Patelff3d3e52008-07-02 01:18:13 +0000451
452 initLoopData();
453
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 Constant *CondVal;
455 BasicBlock *ExitBlock;
Devang Patelff3d3e52008-07-02 01:18:13 +0000456 if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
457 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 } else {
Devang Patelff3d3e52008-07-02 01:18:13 +0000459 UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 }
461
462 return true;
463}
464
465// RemapInstruction - Convert the instruction operands from referencing the
466// current values into those specified by ValueMap.
467//
468static inline void RemapInstruction(Instruction *I,
469 DenseMap<const Value *, Value*> &ValueMap) {
470 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
471 Value *Op = I->getOperand(op);
472 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
473 if (It != ValueMap.end()) Op = It->second;
474 I->setOperand(op, Op);
475 }
476}
477
Chris Lattner03dc7d72007-08-02 16:53:43 +0000478// CloneDomInfo - NewBB is cloned from Orig basic block. Now clone Dominator
479// Info.
Devang Patelf9739582007-07-18 23:48:20 +0000480//
481// If Orig block's immediate dominator is mapped in VM then use corresponding
482// immediate dominator from the map. Otherwise Orig block's dominator is also
483// NewBB's dominator.
484//
Devang Pateld6868a72007-07-18 23:50:19 +0000485// OrigPreheader is loop pre-header before this pass started
Devang Patelf9739582007-07-18 23:48:20 +0000486// updating CFG. NewPrehader is loops new pre-header. However, after CFG
Devang Pateld6868a72007-07-18 23:50:19 +0000487// manipulation, loop L may not exist. So rely on input parameter NewPreheader.
Dan Gohman089efff2008-05-13 00:00:25 +0000488static void CloneDomInfo(BasicBlock *NewBB, BasicBlock *Orig,
489 BasicBlock *NewPreheader, BasicBlock *OrigPreheader,
490 BasicBlock *OrigHeader,
491 DominatorTree *DT, DominanceFrontier *DF,
492 DenseMap<const Value*, Value*> &VM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493
Devang Patelf9739582007-07-18 23:48:20 +0000494 // If NewBB alreay has found its place in domiantor tree then no need to do
495 // anything.
496 if (DT->getNode(NewBB))
497 return;
498
499 // If Orig does not have any immediate domiantor then its clone, NewBB, does
500 // not need any immediate dominator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 DomTreeNode *OrigNode = DT->getNode(Orig);
502 if (!OrigNode)
503 return;
Devang Patelf9739582007-07-18 23:48:20 +0000504 DomTreeNode *OrigIDomNode = OrigNode->getIDom();
505 if (!OrigIDomNode)
506 return;
507
508 BasicBlock *OrigIDom = NULL;
509
510 // If Orig is original loop header then its immediate dominator is
511 // NewPreheader.
512 if (Orig == OrigHeader)
513 OrigIDom = NewPreheader;
514
515 // If Orig is new pre-header then its immediate dominator is
516 // original pre-header.
517 else if (Orig == NewPreheader)
518 OrigIDom = OrigPreheader;
519
Devang Patelf1a33042008-07-02 01:31:19 +0000520 // Otherwise ask DT to find Orig's immediate dominator.
Devang Patelf9739582007-07-18 23:48:20 +0000521 else
522 OrigIDom = OrigIDomNode->getBlock();
523
Devang Patelc5685122007-07-30 21:10:44 +0000524 // Initially use Orig's immediate dominator as NewBB's immediate dominator.
525 BasicBlock *NewIDom = OrigIDom;
526 DenseMap<const Value*, Value*>::iterator I = VM.find(OrigIDom);
527 if (I != VM.end()) {
528 NewIDom = cast<BasicBlock>(I->second);
529
530 // If NewIDom does not have corresponding dominatore tree node then
531 // get one.
532 if (!DT->getNode(NewIDom))
Devang Patelf9739582007-07-18 23:48:20 +0000533 CloneDomInfo(NewIDom, OrigIDom, NewPreheader, OrigPreheader,
534 OrigHeader, DT, DF, VM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 }
Devang Patelc5685122007-07-30 21:10:44 +0000536
537 DT->addNewBlock(NewBB, NewIDom);
538
539 // Copy cloned dominance frontiner set
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 DominanceFrontier::DomSetType NewDFSet;
541 if (DF) {
542 DominanceFrontier::iterator DFI = DF->find(Orig);
543 if ( DFI != DF->end()) {
544 DominanceFrontier::DomSetType S = DFI->second;
545 for (DominanceFrontier::DomSetType::iterator I = S.begin(), E = S.end();
546 I != E; ++I) {
547 BasicBlock *BB = *I;
Chuck Rose III9a2da442007-07-27 18:26:35 +0000548 DenseMap<const Value*, Value*>::iterator IDM = VM.find(BB);
549 if (IDM != VM.end())
550 NewDFSet.insert(cast<BasicBlock>(IDM->second));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551 else
552 NewDFSet.insert(BB);
553 }
554 }
555 DF->addBasicBlock(NewBB, NewDFSet);
556 }
557}
558
559/// CloneLoop - Recursively clone the specified loop and all of its children,
560/// mapping the blocks with the specified map.
561static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
562 LoopInfo *LI, LPPassManager *LPM) {
563 Loop *New = new Loop();
564
565 LPM->insertLoop(New, PL);
566
567 // Add all of the blocks in L to the new loop.
568 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
569 I != E; ++I)
570 if (LI->getLoopFor(*I) == L)
Owen Andersonca0b9d42007-11-27 03:43:35 +0000571 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572
573 // Add all of the subloops to the new loop.
574 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
575 CloneLoop(*I, New, VM, LI, LPM);
576
577 return New;
578}
579
580/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
581/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
582/// code immediately before InsertPt.
583void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
584 BasicBlock *TrueDest,
585 BasicBlock *FalseDest,
586 Instruction *InsertPt) {
587 // Insert a conditional branch on LIC to the two preheaders. The original
588 // code is the true version and the new code is the false version.
589 Value *BranchVal = LIC;
590 if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
591 BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
592 else if (Val != ConstantInt::getTrue())
593 // We want to enter the new loop when the condition is true.
594 std::swap(TrueDest, FalseDest);
595
596 // Insert the new branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000597 BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598}
599
600
601/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
602/// condition in it (a cond branch from its header block to its latch block,
603/// where the path through the loop that doesn't execute its body has no
604/// side-effects), unswitch it. This doesn't involve any code duplication, just
605/// moving the conditional branch outside of the loop and updating loop info.
606void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
607 Constant *Val,
608 BasicBlock *ExitBlock) {
609 DOUT << "loop-unswitch: Trivial-Unswitch loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000610 << loopHeader->getName() << " [" << L->getBlocks().size()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 << " blocks] in Function " << L->getHeader()->getParent()->getName()
612 << " on cond: " << *Val << " == " << *Cond << "\n";
613
614 // First step, split the preheader, so that we know that there is a safe place
Devang Patelff3d3e52008-07-02 01:18:13 +0000615 // to insert the conditional branch. We will change loopPreheader to have a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 // conditional branch on Cond.
Devang Patelff3d3e52008-07-02 01:18:13 +0000617 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618
619 // Now that we have a place to insert the conditional branch, create a place
620 // to branch to: this is the exit block out of the loop that we should
621 // short-circuit to.
622
623 // Split this block now, so that the loop maintains its exit block, and so
624 // that the jump from the preheader can execute the contents of the exit block
625 // without actually branching to it (the exit block should be dominated by the
626 // loop header, not the preheader).
627 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
628 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
629
630 // Okay, now we have a position to branch from and a position to branch to,
631 // insert the new conditional branch.
632 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Devang Patelff3d3e52008-07-02 01:18:13 +0000633 loopPreheader->getTerminator());
Devang Patel52f93c02008-06-02 22:52:56 +0000634 if (DT) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000635 DT->changeImmediateDominator(NewExit, loopPreheader);
636 DT->changeImmediateDominator(NewPH, loopPreheader);
Devang Patel52f93c02008-06-02 22:52:56 +0000637 }
Devang Patel6dfc4382008-06-18 02:16:38 +0000638
639 if (DF) {
640 // NewExit is now part of NewPH and Loop Header's dominance
641 // frontier.
642 DominanceFrontier::iterator DFI = DF->find(NewPH);
643 if (DFI != DF->end())
644 DF->addToFrontier(DFI, NewExit);
Devang Patelff3d3e52008-07-02 01:18:13 +0000645 DFI = DF->find(loopHeader);
Devang Patel6dfc4382008-06-18 02:16:38 +0000646 DF->addToFrontier(DFI, NewExit);
647
648 // ExitBlock does not have successors then NewExit is part of
649 // its dominance frontier.
650 if (succ_begin(ExitBlock) == succ_end(ExitBlock)) {
651 DFI = DF->find(ExitBlock);
652 DF->addToFrontier(DFI, NewExit);
653 }
654 }
Devang Patelff3d3e52008-07-02 01:18:13 +0000655 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
656 loopPreheader->getTerminator()->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657
658 // We need to reprocess this loop, it could be unswitched again.
Devang Pateleec0d372007-07-30 23:07:10 +0000659 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660
661 // Now that we know that the loop is never entered when this condition is a
662 // particular value, rewrite the loop with this info. We know that this will
663 // at least eliminate the old branch.
664 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
665 ++NumTrivial;
666}
667
Devang Patel122c81f2007-10-05 22:29:34 +0000668/// ReplaceLoopExternalDFMember -
669/// If BB's dominance frontier has a member that is not part of loop L then
670/// remove it. Add NewDFMember in BB's dominance frontier.
671void LoopUnswitch::ReplaceLoopExternalDFMember(Loop *L, BasicBlock *BB,
672 BasicBlock *NewDFMember) {
673
674 DominanceFrontier::iterator DFI = DF->find(BB);
675 if (DFI == DF->end())
676 return;
677
678 DominanceFrontier::DomSetType &DFSet = DFI->second;
679 for (DominanceFrontier::DomSetType::iterator DI = DFSet.begin(),
Devang Patel969f07a2007-10-09 21:31:36 +0000680 DE = DFSet.end(); DI != DE;) {
681 BasicBlock *B = *DI++;
Devang Patel122c81f2007-10-05 22:29:34 +0000682 if (L->contains(B))
683 continue;
David Greene932e8b62007-12-17 17:40:29 +0000684
Devang Patel122c81f2007-10-05 22:29:34 +0000685 DF->removeFromFrontier(DFI, B);
686 LoopDF.insert(B);
687 }
688
689 DF->addToFrontier(DFI, NewDFMember);
690}
691
Chris Lattnerdb47e722008-04-21 00:25:49 +0000692/// SplitExitEdges - Split all of the edges from inside the loop to their exit
693/// blocks. Update the appropriate Phi nodes as we do so.
694void LoopUnswitch::SplitExitEdges(Loop *L,
695 const SmallVector<BasicBlock *, 8> &ExitBlocks,
Devang Pateld39af172007-10-03 21:16:08 +0000696 SmallVector<BasicBlock *, 8> &MiddleBlocks) {
Devang Patel122c81f2007-10-05 22:29:34 +0000697
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
699 BasicBlock *ExitBlock = ExitBlocks[i];
700 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
701
702 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
703 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock, this);
Devang Patel0ea2da12007-08-02 15:25:57 +0000704 MiddleBlocks.push_back(MiddleBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 BasicBlock* StartBlock = Preds[j];
706 BasicBlock* EndBlock;
707 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
708 EndBlock = MiddleBlock;
709 MiddleBlock = EndBlock->getSinglePredecessor();;
710 } else {
711 EndBlock = ExitBlock;
712 }
713
Devang Patel122c81f2007-10-05 22:29:34 +0000714 OrigLoopExitMap[StartBlock] = EndBlock;
715
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 std::set<PHINode*> InsertedPHIs;
717 PHINode* OldLCSSA = 0;
718 for (BasicBlock::iterator I = EndBlock->begin();
719 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
720 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000721 PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
722 OldLCSSA->getName() + ".us-lcssa",
723 MiddleBlock->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 NewLCSSA->addIncoming(OldValue, StartBlock);
725 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
726 NewLCSSA);
727 InsertedPHIs.insert(NewLCSSA);
728 }
729
Dan Gohman514277c2008-05-23 21:05:58 +0000730 BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 for (BasicBlock::iterator I = MiddleBlock->begin();
732 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
733 ++I) {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000734 PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
735 OldLCSSA->getName() + ".us-lcssa",
736 InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 OldLCSSA->replaceAllUsesWith(NewLCSSA);
738 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
739 }
Devang Patel122c81f2007-10-05 22:29:34 +0000740
741 if (DF && DT) {
742 // StartBlock -- > MiddleBlock -- > EndBlock
743 // StartBlock is loop exiting block. EndBlock will become merge point
744 // of two loop exits after loop unswitch.
745
746 // If StartBlock's DF member includes a block that is not loop member
747 // then replace that DF member with EndBlock.
748
749 // If MiddleBlock's DF member includes a block that is not loop member
750 // tnen replace that DF member with EndBlock.
751
752 ReplaceLoopExternalDFMember(L, StartBlock, EndBlock);
753 ReplaceLoopExternalDFMember(L, MiddleBlock, EndBlock);
754 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 }
756 }
Devang Patel122c81f2007-10-05 22:29:34 +0000757
Devang Pateld39af172007-10-03 21:16:08 +0000758}
759
Devang Patel55410702007-10-03 21:17:43 +0000760/// UnswitchNontrivialCondition - We determined that the loop is profitable
761/// to unswitch when LIC equal Val. Split it into loop versions and test the
762/// condition outside of either loop. Return the loops created as Out1/Out2.
Devang Pateld39af172007-10-03 21:16:08 +0000763void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
764 Loop *L) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000765 Function *F = loopHeader->getParent();
Devang Pateld39af172007-10-03 21:16:08 +0000766 DOUT << "loop-unswitch: Unswitching loop %"
Devang Patelff3d3e52008-07-02 01:18:13 +0000767 << loopHeader->getName() << " [" << L->getBlocks().size()
Devang Pateld39af172007-10-03 21:16:08 +0000768 << " blocks] in Function " << F->getName()
769 << " when '" << *Val << "' == " << *LIC << "\n";
770
Devang Pateld6aef782008-07-02 01:44:29 +0000771 LoopBlocks.clear();
772 NewBlocks.clear();
Devang Pateld39af172007-10-03 21:16:08 +0000773
774 // First step, split the preheader and exit blocks, and add these blocks to
775 // the LoopBlocks list.
Devang Patelff3d3e52008-07-02 01:18:13 +0000776 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
Devang Pateld39af172007-10-03 21:16:08 +0000777 LoopBlocks.push_back(NewPreheader);
778
779 // We want the loop to come after the preheader, but before the exit blocks.
780 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
781
782 SmallVector<BasicBlock*, 8> ExitBlocks;
783 L->getUniqueExitBlocks(ExitBlocks);
784
785 // Split all of the edges from inside the loop to their exit blocks. Update
786 // the appropriate Phi nodes as we do so.
787 SmallVector<BasicBlock *,8> MiddleBlocks;
Devang Patel122c81f2007-10-05 22:29:34 +0000788 SplitExitEdges(L, ExitBlocks, MiddleBlocks);
Devang Pateld39af172007-10-03 21:16:08 +0000789
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790 // The exit blocks may have been changed due to edge splitting, recompute.
791 ExitBlocks.clear();
792 L->getUniqueExitBlocks(ExitBlocks);
793
794 // Add exit blocks to the loop blocks.
795 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
796
797 // Next step, clone all of the basic blocks that make up the loop (including
798 // the loop preheader and exit blocks), keeping track of the mapping between
799 // the instructions and blocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 NewBlocks.reserve(LoopBlocks.size());
801 DenseMap<const Value*, Value*> ValueMap;
802 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
803 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
804 NewBlocks.push_back(New);
805 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Devang Patelf73276b2007-07-31 08:03:26 +0000806 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 }
808
Devang Patel0ea2da12007-08-02 15:25:57 +0000809 // OutSiders are basic block that are dominated by original header and
810 // at the same time they are not part of loop.
811 SmallPtrSet<BasicBlock *, 8> OutSiders;
812 if (DT) {
Devang Patelff3d3e52008-07-02 01:18:13 +0000813 DomTreeNode *OrigHeaderNode = DT->getNode(loopHeader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000814 for(std::vector<DomTreeNode*>::iterator DI = OrigHeaderNode->begin(),
815 DE = OrigHeaderNode->end(); DI != DE; ++DI) {
816 BasicBlock *B = (*DI)->getBlock();
817
818 DenseMap<const Value*, Value*>::iterator VI = ValueMap.find(B);
819 if (VI == ValueMap.end())
820 OutSiders.insert(B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 }
Devang Patel0ea2da12007-08-02 15:25:57 +0000822 }
823
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 // Splice the newly inserted blocks into the function right before the
825 // original preheader.
826 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
827 NewBlocks[0], F->end());
828
829 // Now we create the new Loop object for the versioned loop.
830 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
831 Loop *ParentLoop = L->getParentLoop();
832 if (ParentLoop) {
833 // Make sure to add the cloned preheader and exit blocks to the parent loop
834 // as well.
Owen Andersonca0b9d42007-11-27 03:43:35 +0000835 ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 }
837
838 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
839 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
840 // The new exit block should be in the same loop as the old one.
841 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Owen Andersonca0b9d42007-11-27 03:43:35 +0000842 ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843
844 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
845 "Exit block should have been split to have one successor!");
846 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
847
848 // If the successor of the exit block had PHI nodes, add an entry for
849 // NewExit.
850 PHINode *PN;
851 for (BasicBlock::iterator I = ExitSucc->begin();
852 (PN = dyn_cast<PHINode>(I)); ++I) {
853 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
854 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
855 if (It != ValueMap.end()) V = It->second;
856 PN->addIncoming(V, NewExit);
857 }
858 }
859
860 // Rewrite the code to refer to itself.
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000861 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
862 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
863 E = NewBlocks[i]->end(); I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 RemapInstruction(I, ValueMap);
865
866 // Rewrite the original preheader to select between versions of the loop.
Devang Patelff3d3e52008-07-02 01:18:13 +0000867 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
869 "Preheader splitting did not work correctly!");
870
871 // Emit the new branch that selects between the two versions of this loop.
872 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
Devang Patelf73276b2007-07-31 08:03:26 +0000873 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +0000874 OldBR->eraseFromParent();
Devang Patel0ea2da12007-08-02 15:25:57 +0000875
876 // Update dominator info
877 if (DF && DT) {
878
Devang Patel122c81f2007-10-05 22:29:34 +0000879 SmallVector<BasicBlock *,4> ExitingBlocks;
880 L->getExitingBlocks(ExitingBlocks);
881
Devang Patel0ea2da12007-08-02 15:25:57 +0000882 // Clone dominator info for all cloned basic block.
883 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
884 BasicBlock *LBB = LoopBlocks[i];
885 BasicBlock *NBB = NewBlocks[i];
Devang Patelff3d3e52008-07-02 01:18:13 +0000886 CloneDomInfo(NBB, LBB, NewPreheader, loopPreheader,
887 loopHeader, DT, DF, ValueMap);
Devang Patel0ea2da12007-08-02 15:25:57 +0000888
Devang Patel122c81f2007-10-05 22:29:34 +0000889 // If LBB's dominance frontier includes DFMember
890 // such that DFMember is also a member of LoopDF then
891 // - Remove DFMember from LBB's dominance frontier
Chris Lattnerdb47e722008-04-21 00:25:49 +0000892 // - Copy loop exiting blocks', that are dominated by BB,
893 // dominance frontier member in BB's dominance frontier
Devang Patel0ea2da12007-08-02 15:25:57 +0000894
Devang Patel122c81f2007-10-05 22:29:34 +0000895 DominanceFrontier::iterator LBBI = DF->find(LBB);
Devang Patel0ea2da12007-08-02 15:25:57 +0000896 DominanceFrontier::iterator NBBI = DF->find(NBB);
Devang Patel122c81f2007-10-05 22:29:34 +0000897 if (LBBI == DF->end())
898 continue;
899
900 DominanceFrontier::DomSetType &LBSet = LBBI->second;
901 for (DominanceFrontier::DomSetType::iterator LI = LBSet.begin(),
902 LE = LBSet.end(); LI != LE; /* NULL */) {
903 BasicBlock *B = *LI++;
Devang Patelff3d3e52008-07-02 01:18:13 +0000904 if (B == LBB && B == loopHeader)
Devang Patel122c81f2007-10-05 22:29:34 +0000905 continue;
906 bool removeB = false;
907 if (!LoopDF.count(B))
908 continue;
909
910 // If LBB dominates loop exits then insert loop exit block's DF
911 // into B's DF.
Chris Lattnerdb47e722008-04-21 00:25:49 +0000912 for(SmallVector<BasicBlock *, 4>::iterator
913 LExitI = ExitingBlocks.begin(),
Devang Patel122c81f2007-10-05 22:29:34 +0000914 LExitE = ExitingBlocks.end(); LExitI != LExitE; ++LExitI) {
915 BasicBlock *E = *LExitI;
916
917 if (!DT->dominates(LBB,E))
918 continue;
919
920 DenseMap<BasicBlock *, BasicBlock *>::iterator DFBI =
921 OrigLoopExitMap.find(E);
922 if (DFBI == OrigLoopExitMap.end())
923 continue;
924
925 BasicBlock *DFB = DFBI->second;
926 DF->addToFrontier(LBBI, DFB);
927 DF->addToFrontier(NBBI, DFB);
928 removeB = true;
929 }
930
Chris Lattnerdb47e722008-04-21 00:25:49 +0000931 // If B's replacement is inserted in DF then now is the time to remove
932 // B.
Devang Patel122c81f2007-10-05 22:29:34 +0000933 if (removeB) {
934 DF->removeFromFrontier(LBBI, B);
935 if (L->contains(B))
936 DF->removeFromFrontier(NBBI, cast<BasicBlock>(ValueMap[B]));
937 else
Devang Patel0ea2da12007-08-02 15:25:57 +0000938 DF->removeFromFrontier(NBBI, B);
939 }
940 }
Devang Patel122c81f2007-10-05 22:29:34 +0000941
Devang Patel0ea2da12007-08-02 15:25:57 +0000942 }
943
944 // MiddleBlocks are dominated by original pre header. SplitEdge updated
945 // MiddleBlocks' dominance frontier appropriately.
946 for (unsigned i = 0, e = MiddleBlocks.size(); i != e; ++i) {
947 BasicBlock *MBB = MiddleBlocks[i];
948 if (!MBB->getSinglePredecessor())
Devang Patelff3d3e52008-07-02 01:18:13 +0000949 DT->changeImmediateDominator(MBB, loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000950 }
951
952 // All Outsiders are now dominated by original pre header.
953 for (SmallPtrSet<BasicBlock *, 8>::iterator OI = OutSiders.begin(),
954 OE = OutSiders.end(); OI != OE; ++OI) {
955 BasicBlock *OB = *OI;
Devang Patelff3d3e52008-07-02 01:18:13 +0000956 DT->changeImmediateDominator(OB, loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000957 }
958
959 // New loop headers are dominated by original preheader
Devang Patelff3d3e52008-07-02 01:18:13 +0000960 DT->changeImmediateDominator(NewBlocks[0], loopPreheader);
961 DT->changeImmediateDominator(LoopBlocks[0], loopPreheader);
Devang Patel0ea2da12007-08-02 15:25:57 +0000962 }
963
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 LoopProcessWorklist.push_back(NewLoop);
Devang Pateleec0d372007-07-30 23:07:10 +0000965 redoLoop = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // Now we rewrite the original code to know that the condition is true and the
968 // new code to know that the condition is false.
969 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
970
971 // It's possible that simplifying one loop could cause the other to be
972 // deleted. If so, don't simplify it.
973 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
974 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
975}
976
977/// RemoveFromWorklist - Remove all instances of I from the worklist vector
978/// specified.
979static void RemoveFromWorklist(Instruction *I,
980 std::vector<Instruction*> &Worklist) {
981 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
982 Worklist.end(), I);
983 while (WI != Worklist.end()) {
984 unsigned Offset = WI-Worklist.begin();
985 Worklist.erase(WI);
986 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
987 }
988}
989
990/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
991/// program, replacing all uses with V and update the worklist.
992static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Patelf73276b2007-07-31 08:03:26 +0000993 std::vector<Instruction*> &Worklist,
994 Loop *L, LPPassManager *LPM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 DOUT << "Replace with '" << *V << "': " << *I;
996
997 // Add uses to the worklist, which may be dead now.
998 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
999 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1000 Worklist.push_back(Use);
1001
1002 // Add users to the worklist which may be simplified now.
1003 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1004 UI != E; ++UI)
1005 Worklist.push_back(cast<Instruction>(*UI));
Devang Patelf73276b2007-07-31 08:03:26 +00001006 LPM->deleteSimpleAnalysisValue(I, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 RemoveFromWorklist(I, Worklist);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001008 I->replaceAllUsesWith(V);
1009 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 ++NumSimplify;
1011}
1012
1013/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
1014/// information, and remove any dead successors it has.
1015///
1016void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
Devang Patelf73276b2007-07-31 08:03:26 +00001017 std::vector<Instruction*> &Worklist,
1018 Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 if (pred_begin(BB) != pred_end(BB)) {
1020 // This block isn't dead, since an edge to BB was just removed, see if there
1021 // are any easy simplifications we can do now.
1022 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1023 // If it has one pred, fold phi nodes in BB.
1024 while (isa<PHINode>(BB->begin()))
1025 ReplaceUsesOfWith(BB->begin(),
1026 cast<PHINode>(BB->begin())->getIncomingValue(0),
Devang Patelf73276b2007-07-31 08:03:26 +00001027 Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 // If this is the header of a loop and the only pred is the latch, we now
1030 // have an unreachable loop.
1031 if (Loop *L = LI->getLoopFor(BB))
Devang Patelff3d3e52008-07-02 01:18:13 +00001032 if (loopHeader == BB && L->contains(Pred)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 // Remove the branch from the latch to the header block, this makes
1034 // the header dead, which will make the latch dead (because the header
1035 // dominates the latch).
Devang Patelf73276b2007-07-31 08:03:26 +00001036 LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001037 Pred->getTerminator()->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 new UnreachableInst(Pred);
1039
1040 // The loop is now broken, remove it from LI.
1041 RemoveLoopFromHierarchy(L);
1042
1043 // Reprocess the header, which now IS dead.
Devang Patelf73276b2007-07-31 08:03:26 +00001044 RemoveBlockIfDead(BB, Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 return;
1046 }
1047
1048 // If pred ends in a uncond branch, add uncond branch to worklist so that
1049 // the two blocks will get merged.
1050 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
1051 if (BI->isUnconditional())
1052 Worklist.push_back(BI);
1053 }
1054 return;
1055 }
1056
1057 DOUT << "Nuking dead block: " << *BB;
1058
1059 // Remove the instructions in the basic block from the worklist.
1060 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1061 RemoveFromWorklist(I, Worklist);
1062
1063 // Anything that uses the instructions in this basic block should have their
1064 // uses replaced with undefs.
1065 if (!I->use_empty())
1066 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1067 }
1068
1069 // If this is the edge to the header block for a loop, remove the loop and
1070 // promote all subloops.
1071 if (Loop *BBLoop = LI->getLoopFor(BB)) {
1072 if (BBLoop->getLoopLatch() == BB)
1073 RemoveLoopFromHierarchy(BBLoop);
1074 }
1075
1076 // Remove the block from the loop info, which removes it from any loops it
1077 // was in.
1078 LI->removeBlock(BB);
1079
1080
1081 // Remove phi node entries in successors for this block.
1082 TerminatorInst *TI = BB->getTerminator();
1083 std::vector<BasicBlock*> Succs;
1084 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1085 Succs.push_back(TI->getSuccessor(i));
1086 TI->getSuccessor(i)->removePredecessor(BB);
1087 }
1088
1089 // Unique the successors, remove anything with multiple uses.
1090 std::sort(Succs.begin(), Succs.end());
1091 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
1092
1093 // Remove the basic block, including all of the instructions contained in it.
Devang Patelf73276b2007-07-31 08:03:26 +00001094 LPM->deleteSimpleAnalysisValue(BB, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001095 BB->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 // Remove successor blocks here that are not dead, so that we know we only
1097 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
1098 // then getting removed before we revisit them, which is badness.
1099 //
1100 for (unsigned i = 0; i != Succs.size(); ++i)
1101 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
1102 // One exception is loop headers. If this block was the preheader for a
1103 // loop, then we DO want to visit the loop so the loop gets deleted.
1104 // We know that if the successor is a loop header, that this loop had to
1105 // be the preheader: the case where this was the latch block was handled
1106 // above and headers can only have two predecessors.
1107 if (!LI->isLoopHeader(Succs[i])) {
1108 Succs.erase(Succs.begin()+i);
1109 --i;
1110 }
1111 }
1112
1113 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
Devang Patelf73276b2007-07-31 08:03:26 +00001114 RemoveBlockIfDead(Succs[i], Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115}
1116
1117/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
1118/// become unwrapped, either because the backedge was deleted, or because the
1119/// edge into the header was removed. If the edge into the header from the
1120/// latch block was removed, the loop is unwrapped but subloops are still alive,
1121/// so they just reparent loops. If the loops are actually dead, they will be
1122/// removed later.
1123void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
1124 LPM->deleteLoopFromQueue(L);
1125 RemoveLoopFromWorklist(L);
1126}
1127
1128
1129
1130// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1131// the value specified by Val in the specified loop, or we know it does NOT have
1132// that value. Rewrite any uses of LIC or of properties correlated to it.
1133void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1134 Constant *Val,
1135 bool IsEqual) {
1136 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1137
1138 // FIXME: Support correlated properties, like:
1139 // for (...)
1140 // if (li1 < li2)
1141 // ...
1142 // if (li1 > li2)
1143 // ...
1144
1145 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1146 // selects, switches.
1147 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
1148 std::vector<Instruction*> Worklist;
1149
1150 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1151 // in the loop with the appropriate one directly.
1152 if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
1153 Value *Replacement;
1154 if (IsEqual)
1155 Replacement = Val;
1156 else
1157 Replacement = ConstantInt::get(Type::Int1Ty,
1158 !cast<ConstantInt>(Val)->getZExtValue());
1159
1160 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1161 if (Instruction *U = cast<Instruction>(Users[i])) {
1162 if (!L->contains(U->getParent()))
1163 continue;
1164 U->replaceUsesOfWith(LIC, Replacement);
1165 Worklist.push_back(U);
1166 }
1167 } else {
1168 // Otherwise, we don't know the precise value of LIC, but we do know that it
1169 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1170 // can. This case occurs when we unswitch switch statements.
1171 for (unsigned i = 0, e = Users.size(); i != e; ++i)
1172 if (Instruction *U = cast<Instruction>(Users[i])) {
1173 if (!L->contains(U->getParent()))
1174 continue;
1175
1176 Worklist.push_back(U);
1177
1178 // If we know that LIC is not Val, use this info to simplify code.
1179 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
1180 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
1181 if (SI->getCaseValue(i) == Val) {
1182 // Found a dead case value. Don't remove PHI nodes in the
1183 // successor if they become single-entry, those PHI nodes may
1184 // be in the Users list.
1185
1186 // FIXME: This is a hack. We need to keep the successor around
1187 // and hooked up so as to preserve the loop structure, because
1188 // trying to update it is complicated. So instead we preserve the
1189 // loop structure and put the block on an dead code path.
1190
1191 BasicBlock* Old = SI->getParent();
1192 BasicBlock* Split = SplitBlock(Old, SI, this);
1193
1194 Instruction* OldTerm = Old->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001195 BranchInst::Create(Split, SI->getSuccessor(i),
1196 ConstantInt::getTrue(), OldTerm);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001197
Chris Lattnerdb47e722008-04-21 00:25:49 +00001198 LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 Old->getTerminator()->eraseFromParent();
1200
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 PHINode *PN;
1202 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
1203 (PN = dyn_cast<PHINode>(II)); ++II) {
1204 Value *InVal = PN->removeIncomingValue(Split, false);
1205 PN->addIncoming(InVal, Old);
1206 }
1207
1208 SI->removeCase(i);
1209 break;
1210 }
1211 }
1212 }
1213
1214 // TODO: We could do other simplifications, for example, turning
1215 // LIC == Val -> false.
1216 }
1217 }
1218
Devang Patelf73276b2007-07-31 08:03:26 +00001219 SimplifyCode(Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220}
1221
1222/// SimplifyCode - Okay, now that we have simplified some instructions in the
1223/// loop, walk over it and constant prop, dce, and fold control flow where
1224/// possible. Note that this is effectively a very simple loop-structure-aware
1225/// optimizer. During processing of this loop, L could very well be deleted, so
1226/// it must not be used.
1227///
1228/// FIXME: When the loop optimizer is more mature, separate this out to a new
1229/// pass.
1230///
Devang Patelf73276b2007-07-31 08:03:26 +00001231void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 while (!Worklist.empty()) {
1233 Instruction *I = Worklist.back();
1234 Worklist.pop_back();
1235
1236 // Simple constant folding.
1237 if (Constant *C = ConstantFoldInstruction(I)) {
Devang Patelf73276b2007-07-31 08:03:26 +00001238 ReplaceUsesOfWith(I, C, Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 continue;
1240 }
1241
1242 // Simple DCE.
1243 if (isInstructionTriviallyDead(I)) {
1244 DOUT << "Remove dead instruction '" << *I;
1245
1246 // Add uses to the worklist, which may be dead now.
1247 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1248 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1249 Worklist.push_back(Use);
Devang Patelf73276b2007-07-31 08:03:26 +00001250 LPM->deleteSimpleAnalysisValue(I, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 RemoveFromWorklist(I, Worklist);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001252 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 ++NumSimplify;
1254 continue;
1255 }
1256
1257 // Special case hacks that appear commonly in unswitched code.
1258 switch (I->getOpcode()) {
1259 case Instruction::Select:
1260 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
Chris Lattner03dc7d72007-08-02 16:53:43 +00001261 ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1262 LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 continue;
1264 }
1265 break;
1266 case Instruction::And:
1267 if (isa<ConstantInt>(I->getOperand(0)) &&
1268 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1269 cast<BinaryOperator>(I)->swapOperands();
1270 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1271 if (CB->getType() == Type::Int1Ty) {
1272 if (CB->isOne()) // X & 1 -> X
Devang Patelf73276b2007-07-31 08:03:26 +00001273 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 else // X & 0 -> 0
Devang Patelf73276b2007-07-31 08:03:26 +00001275 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 continue;
1277 }
1278 break;
1279 case Instruction::Or:
1280 if (isa<ConstantInt>(I->getOperand(0)) &&
1281 I->getOperand(0)->getType() == Type::Int1Ty) // constant -> RHS
1282 cast<BinaryOperator>(I)->swapOperands();
1283 if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1284 if (CB->getType() == Type::Int1Ty) {
1285 if (CB->isOne()) // X | 1 -> 1
Devang Patelf73276b2007-07-31 08:03:26 +00001286 ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 else // X | 0 -> X
Devang Patelf73276b2007-07-31 08:03:26 +00001288 ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 continue;
1290 }
1291 break;
1292 case Instruction::Br: {
1293 BranchInst *BI = cast<BranchInst>(I);
1294 if (BI->isUnconditional()) {
1295 // If BI's parent is the only pred of the successor, fold the two blocks
1296 // together.
1297 BasicBlock *Pred = BI->getParent();
1298 BasicBlock *Succ = BI->getSuccessor(0);
1299 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1300 if (!SinglePred) continue; // Nothing to do.
1301 assert(SinglePred == Pred && "CFG broken");
1302
1303 DOUT << "Merging blocks: " << Pred->getName() << " <- "
1304 << Succ->getName() << "\n";
1305
1306 // Resolve any single entry PHI nodes in Succ.
1307 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Patelf73276b2007-07-31 08:03:26 +00001308 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309
1310 // Move all of the successor contents from Succ to Pred.
1311 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1312 Succ->end());
Devang Patelf73276b2007-07-31 08:03:26 +00001313 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001314 BI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 RemoveFromWorklist(BI, Worklist);
1316
1317 // If Succ has any successors with PHI nodes, update them to have
1318 // entries coming from Pred instead of Succ.
1319 Succ->replaceAllUsesWith(Pred);
1320
1321 // Remove Succ from the loop tree.
1322 LI->removeBlock(Succ);
Devang Patelf73276b2007-07-31 08:03:26 +00001323 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001324 Succ->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 ++NumSimplify;
1326 } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1327 // Conditional branch. Turn it into an unconditional branch, then
1328 // remove dead blocks.
1329 break; // FIXME: Enable.
1330
1331 DOUT << "Folded branch: " << *BI;
1332 BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1333 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1334 DeadSucc->removePredecessor(BI->getParent(), true);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001335 Worklist.push_back(BranchInst::Create(LiveSucc, BI));
Devang Patelf73276b2007-07-31 08:03:26 +00001336 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patelc04a7cf2007-09-20 23:45:50 +00001337 BI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 RemoveFromWorklist(BI, Worklist);
1339 ++NumSimplify;
1340
Devang Patelf73276b2007-07-31 08:03:26 +00001341 RemoveBlockIfDead(DeadSucc, Worklist, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 }
1343 break;
1344 }
1345 }
1346 }
1347}