blob: e623f9176629586d9f876d42b123a59f1ac71fcd [file] [log] [blame]
Chris Lattner8383a7b2008-04-20 20:35:01 +00001//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner177480b2008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattner8383a7b2008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner177480b2008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Owen Anderson1ff50b32009-07-03 00:54:20 +000017#include "llvm/LLVMContext.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000018#include "llvm/Pass.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000019#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner433a0db2009-10-10 09:05:58 +000022#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000023#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/SmallSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner177480b2008-04-20 21:13:06 +000030#include "llvm/Support/Debug.h"
Daniel Dunbar93b67e42009-07-26 07:49:05 +000031#include "llvm/Support/raw_ostream.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000032using namespace llvm;
33
Chris Lattnerbd3401f2008-04-20 22:39:42 +000034STATISTIC(NumThreads, "Number of jumps threaded");
35STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner78c552e2009-10-11 07:24:57 +000036STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
Chris Lattner8383a7b2008-04-20 20:35:01 +000037
Chris Lattner177480b2008-04-20 21:13:06 +000038static cl::opt<unsigned>
39Threshold("jump-threading-threshold",
40 cl::desc("Max block size to duplicate for jump threading"),
41 cl::init(6), cl::Hidden);
42
Chris Lattner8383a7b2008-04-20 20:35:01 +000043namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000044 /// This pass performs 'jump threading', which looks at blocks that have
45 /// multiple predecessors and multiple successors. If one or more of the
46 /// predecessors of the block can be proven to always jump to one of the
47 /// successors, we forward the edge from the predecessor to the successor by
48 /// duplicating the contents of this block.
49 ///
50 /// An example of when this can occur is code like this:
51 ///
52 /// if () { ...
53 /// X = 4;
54 /// }
55 /// if (X < 3) {
56 ///
57 /// In this case, the unconditional branch at the end of the first if can be
58 /// revectored to the false side of the second if.
59 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 class JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000061 TargetData *TD;
Mike Stumpfe095f32009-05-04 18:40:41 +000062#ifdef NDEBUG
63 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
64#else
65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
66#endif
Chris Lattner8383a7b2008-04-20 20:35:01 +000067 public:
68 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000069 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000070
71 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000072 void FindLoopHeaders(Function &F);
73
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000074 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbdbf1a12009-10-11 04:33:43 +000075 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +000076 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
77 BasicBlock *PredBB);
Devang Patel12d53db2009-11-07 01:32:59 +000078
79 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
Chris Lattner421fa9e2008-12-03 07:48:08 +000080 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000081 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000082
Chris Lattnerd38c14e2008-04-22 06:36:15 +000083 bool ProcessJumpOnPHI(PHINode *PN);
Devang Patel12d53db2009-11-07 01:32:59 +000084 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
85 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000086
87 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000088 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char JumpThreading::ID = 0;
92static RegisterPass<JumpThreading>
93X("jump-threading", "Jump Threading");
94
Chris Lattner8383a7b2008-04-20 20:35:01 +000095// Public interface to the Jump Threading pass
96FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
97
98/// runOnFunction - Top level algorithm.
99///
100bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000101 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000102 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000103
Mike Stumpfe095f32009-05-04 18:40:41 +0000104 FindLoopHeaders(F);
105
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000106 bool AnotherIteration = true, EverChanged = false;
107 while (AnotherIteration) {
108 AnotherIteration = false;
109 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000110 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
111 BasicBlock *BB = I;
112 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000113 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000114
115 ++I;
116
117 // If the block is trivially dead, zap it. This eliminates the successor
118 // edges which simplifies the CFG.
119 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000120 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000121 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000122 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000123 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000124 DeleteDeadBlock(BB);
125 Changed = true;
126 }
127 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000128 AnotherIteration = Changed;
129 EverChanged |= Changed;
130 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000131
132 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000133 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000134}
Chris Lattner177480b2008-04-20 21:13:06 +0000135
Chris Lattner78c552e2009-10-11 07:24:57 +0000136/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
137/// thread across it.
138static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
139 /// Ignore PHI nodes, these will be flattened when duplication happens.
140 BasicBlock::const_iterator I = BB->getFirstNonPHI();
141
142 // Sum up the cost of each instruction until we get to the terminator. Don't
143 // include the terminator because the copy won't include it.
144 unsigned Size = 0;
145 for (; !isa<TerminatorInst>(I); ++I) {
146 // Debugger intrinsics don't incur code size.
147 if (isa<DbgInfoIntrinsic>(I)) continue;
148
149 // If this is a pointer->pointer bitcast, it is free.
150 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
151 continue;
152
153 // All other instructions count for at least one unit.
154 ++Size;
155
156 // Calls are more expensive. If they are non-intrinsic calls, we model them
157 // as having cost of 4. If they are a non-vector intrinsic, we model them
158 // as having cost of 2 total, and if they are a vector intrinsic, we model
159 // them as having cost 1.
160 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
161 if (!isa<IntrinsicInst>(CI))
162 Size += 3;
163 else if (!isa<VectorType>(CI->getType()))
164 Size += 1;
165 }
166 }
167
168 // Threading through a switch statement is particularly profitable. If this
169 // block ends in a switch, decrease its cost to make it more likely to happen.
170 if (isa<SwitchInst>(I))
171 Size = Size > 6 ? Size-6 : 0;
172
173 return Size;
174}
175
176
177
Mike Stumpfe095f32009-05-04 18:40:41 +0000178/// FindLoopHeaders - We do not want jump threading to turn proper loop
179/// structures into irreducible loops. Doing this breaks up the loop nesting
180/// hierarchy and pessimizes later transformations. To prevent this from
181/// happening, we first have to find the loop headers. Here we approximate this
182/// by finding targets of backedges in the CFG.
183///
184/// Note that there definitely are cases when we want to allow threading of
185/// edges across a loop header. For example, threading a jump from outside the
186/// loop (the preheader) to an exit block of the loop is definitely profitable.
187/// It is also almost always profitable to thread backedges from within the loop
188/// to exit blocks, and is often profitable to thread backedges to other blocks
189/// within the loop (forming a nested loop). This simple analysis is not rich
190/// enough to track all of these properties and keep it up-to-date as the CFG
191/// mutates, so we don't allow any of these transformations.
192///
193void JumpThreading::FindLoopHeaders(Function &F) {
194 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
195 FindFunctionBackedges(F, Edges);
196
197 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
198 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
199}
200
Devang Patel12d53db2009-11-07 01:32:59 +0000201/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
202/// value for the PHI, factor them together so we get one block to thread for
203/// the whole group.
204/// This is important for things like "phi i1 [true, true, false, true, x]"
205/// where we only need to clone the block for the true blocks once.
206///
207BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
208 SmallVector<BasicBlock*, 16> CommonPreds;
209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
210 if (PN->getIncomingValue(i) == Val)
211 CommonPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner6bf77502008-04-22 07:05:46 +0000212
Devang Patel12d53db2009-11-07 01:32:59 +0000213 if (CommonPreds.size() == 1)
214 return CommonPreds[0];
215
216 DEBUG(errs() << " Factoring out " << CommonPreds.size()
217 << " common predecessors.\n");
218 return SplitBlockPredecessors(PN->getParent(),
219 &CommonPreds[0], CommonPreds.size(),
220 ".thr_comm", this);
Chris Lattner78567252009-11-06 18:15:14 +0000221}
Chris Lattner78567252009-11-06 18:15:14 +0000222
Chris Lattner6bf77502008-04-22 07:05:46 +0000223
Chris Lattnere33583b2009-10-11 04:18:15 +0000224/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
225/// in an undefined jump, decide which block is best to revector to.
226///
227/// Since we can pick an arbitrary destination, we pick the successor with the
228/// fewest predecessors. This should reduce the in-degree of the others.
229///
230static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
231 TerminatorInst *BBTerm = BB->getTerminator();
232 unsigned MinSucc = 0;
233 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
234 // Compute the successor with the minimum number of predecessors.
235 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
236 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
237 TestBB = BBTerm->getSuccessor(i);
238 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
239 if (NumPreds < MinNumPreds)
240 MinSucc = i;
241 }
242
243 return MinSucc;
244}
245
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000246/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000247/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000248bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000249 // If this block has a single predecessor, and if that pred has a single
250 // successor, merge the blocks. This encourages recursive jump threading
251 // because now the condition in this block can be threaded through
252 // predecessors of our predecessor block.
Devang Patel12d53db2009-11-07 01:32:59 +0000253 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000254 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
255 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000256 // If SinglePred was a loop header, BB becomes one.
257 if (LoopHeaders.erase(SinglePred))
258 LoopHeaders.insert(BB);
259
Chris Lattner3d86d242008-11-27 19:25:19 +0000260 // Remember if SinglePred was the entry block of the function. If so, we
261 // will need to move BB back to the entry position.
262 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000263 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000264
265 if (isEntry && BB != &BB->getParent()->getEntryBlock())
266 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000267 return true;
268 }
Devang Patel12d53db2009-11-07 01:32:59 +0000269
270 // See if this block ends with a branch or switch. If so, see if the
271 // condition is a phi node. If so, and if an entry of the phi node is a
272 // constant, we can thread the block.
Chris Lattner177480b2008-04-20 21:13:06 +0000273 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000274 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
275 // Can't thread an unconditional jump.
276 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000277 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000278 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000279 Condition = SI->getCondition();
280 else
281 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000282
283 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000284 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000285 // other blocks.
286 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000287 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000288 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000289 ++NumFolds;
290 ConstantFoldTerminator(BB);
291 return true;
292 }
293
Chris Lattner421fa9e2008-12-03 07:48:08 +0000294 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000295 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000296 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000297 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000298
299 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000300 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000301 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000302 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000303 BBTerm->getSuccessor(i)->removePredecessor(BB);
304 }
305
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000306 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000307 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000308 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000309 BBTerm->eraseFromParent();
310 return true;
311 }
312
313 Instruction *CondInst = dyn_cast<Instruction>(Condition);
314
315 // If the condition is an instruction defined in another block, see if a
316 // predecessor has the same condition:
317 // br COND, BBX, BBY
318 // BBX:
319 // br COND, BBZ, BBW
320 if (!Condition->hasOneUse() && // Multiple uses.
321 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
322 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
323 if (isa<BranchInst>(BB->getTerminator())) {
324 for (; PI != E; ++PI)
325 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
326 if (PBI->isConditional() && PBI->getCondition() == Condition &&
327 ProcessBranchOnDuplicateCond(*PI, BB))
328 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000329 } else {
330 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
331 for (; PI != E; ++PI)
332 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
333 if (PSI->getCondition() == Condition &&
334 ProcessSwitchOnDuplicateCond(*PI, BB))
335 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000336 }
337 }
338
Chris Lattner421fa9e2008-12-03 07:48:08 +0000339 // All the rest of our checks depend on the condition being an instruction.
340 if (CondInst == 0)
341 return false;
342
Chris Lattner177480b2008-04-20 21:13:06 +0000343 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000344 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
345 if (PN->getParent() == BB)
346 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000347
Devang Patel12d53db2009-11-07 01:32:59 +0000348 // If this is a conditional branch whose condition is and/or of a phi, try to
349 // simplify it.
350 if ((CondInst->getOpcode() == Instruction::And ||
351 CondInst->getOpcode() == Instruction::Or) &&
352 isa<BranchInst>(BB->getTerminator()) &&
353 ProcessBranchOnLogical(CondInst, BB,
354 CondInst->getOpcode() == Instruction::And))
355 return true;
356
Nick Lewycky9683f182009-06-19 04:56:29 +0000357 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Devang Patel12d53db2009-11-07 01:32:59 +0000358 if (isa<PHINode>(CondCmp->getOperand(0))) {
359 // If we have "br (phi != 42)" and the phi node has any constant values
360 // as operands, we can thread through this block.
361 //
362 // If we have "br (cmp phi, x)" and the phi node contains x such that the
363 // comparison uniquely identifies the branch target, we can thread
364 // through this block.
365
366 if (ProcessBranchOnCompare(CondCmp, BB))
367 return true;
368 }
369
370 // If we have a comparison, loop over the predecessors to see if there is
371 // a condition with the same value.
372 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
373 for (; PI != E; ++PI)
374 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
375 if (PBI->isConditional() && *PI != BB) {
376 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
377 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
378 CI->getOperand(1) == CondCmp->getOperand(1) &&
379 CI->getPredicate() == CondCmp->getPredicate()) {
380 // TODO: Could handle things like (x != 4) --> (x == 17)
381 if (ProcessBranchOnDuplicateCond(*PI, BB))
382 return true;
Chris Lattner79c740f2009-06-19 16:27:56 +0000383 }
384 }
Devang Patel12d53db2009-11-07 01:32:59 +0000385 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000386 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000387
388 // Check for some cases that are worth simplifying. Right now we want to look
389 // for loads that are used by a switch or by the condition for the branch. If
390 // we see one, check to see if it's partially redundant. If so, insert a PHI
391 // which can then be used to thread the values.
392 //
393 // This is particularly important because reg2mem inserts loads and stores all
394 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000395 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000396 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
397 if (isa<Constant>(CondCmp->getOperand(1)))
398 SimplifyValue = CondCmp->getOperand(0);
399
400 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
401 if (SimplifyPartiallyRedundantLoad(LI))
402 return true;
403
404 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
405 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000406
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000407 return false;
408}
409
Chris Lattner421fa9e2008-12-03 07:48:08 +0000410/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
411/// block that jump on exactly the same condition. This means that we almost
412/// always know the direction of the edge in the DESTBB:
413/// PREDBB:
414/// br COND, DESTBB, BBY
415/// DESTBB:
416/// br COND, BBZ, BBW
417///
418/// If DESTBB has multiple predecessors, we can't just constant fold the branch
419/// in DESTBB, we have to thread over it.
420bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
421 BasicBlock *BB) {
422 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
423
424 // If both successors of PredBB go to DESTBB, we don't know anything. We can
425 // fold the branch to an unconditional one, which allows other recursive
426 // simplifications.
427 bool BranchDir;
428 if (PredBI->getSuccessor(1) != BB)
429 BranchDir = true;
430 else if (PredBI->getSuccessor(0) != BB)
431 BranchDir = false;
432 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000433 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000434 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000435 ++NumFolds;
436 ConstantFoldTerminator(PredBB);
437 return true;
438 }
439
440 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
441
442 // If the dest block has one predecessor, just fix the branch condition to a
443 // constant and fold it.
444 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000445 DEBUG(errs() << " In block '" << BB->getName()
446 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000447 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000448 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000449 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000450 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
451 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000452 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000453 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000454 return true;
455 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000456
Chris Lattner421fa9e2008-12-03 07:48:08 +0000457
458 // Next, figure out which successor we are threading to.
459 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
460
Mike Stumpfe095f32009-05-04 18:40:41 +0000461 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000462 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000463}
464
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000465/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
466/// block that switch on exactly the same condition. This means that we almost
467/// always know the direction of the edge in the DESTBB:
468/// PREDBB:
469/// switch COND [... DESTBB, BBY ... ]
470/// DESTBB:
471/// switch COND [... BBZ, BBW ]
472///
473/// Optimizing switches like this is very important, because simplifycfg builds
474/// switches out of repeated 'if' conditions.
475bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
476 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000477 // Can't thread edge to self.
478 if (PredBB == DestBB)
479 return false;
480
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000481 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
482 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
483
484 // There are a variety of optimizations that we can potentially do on these
485 // blocks: we order them from most to least preferable.
486
487 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
488 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000489 // growth. Skip debug info first.
490 BasicBlock::iterator BBI = DestBB->begin();
491 while (isa<DbgInfoIntrinsic>(BBI))
492 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000493
494 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000495 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000496 bool MadeChange = false;
497 // Ignore the default edge for now.
498 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
499 ConstantInt *DestVal = DestSI->getCaseValue(i);
500 BasicBlock *DestSucc = DestSI->getSuccessor(i);
501
502 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
503 // PredSI has an explicit case for it. If so, forward. If it is covered
504 // by the default case, we can't update PredSI.
505 unsigned PredCase = PredSI->findCaseValue(DestVal);
506 if (PredCase == 0) continue;
507
508 // If PredSI doesn't go to DestBB on this value, then it won't reach the
509 // case on this condition.
510 if (PredSI->getSuccessor(PredCase) != DestBB &&
511 DestSI->getSuccessor(i) != DestBB)
512 continue;
513
514 // Otherwise, we're safe to make the change. Make sure that the edge from
515 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000516 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
517 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000518
519 // If the destination has PHI nodes, just split the edge for updating
520 // simplicity.
521 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
522 SplitCriticalEdge(DestSI, i, this);
523 DestSucc = DestSI->getSuccessor(i);
524 }
525 FoldSingleEntryPHINodes(DestSucc);
526 PredSI->setSuccessor(PredCase, DestSucc);
527 MadeChange = true;
528 }
529
530 if (MadeChange)
531 return true;
532 }
533
534 return false;
535}
536
537
Chris Lattner69e067f2008-11-27 05:07:53 +0000538/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
539/// load instruction, eliminate it by replacing it with a PHI node. This is an
540/// important optimization that encourages jump threading, and needs to be run
541/// interlaced with other jump threading tasks.
542bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
543 // Don't hack volatile loads.
544 if (LI->isVolatile()) return false;
545
546 // If the load is defined in a block with exactly one predecessor, it can't be
547 // partially redundant.
548 BasicBlock *LoadBB = LI->getParent();
549 if (LoadBB->getSinglePredecessor())
550 return false;
551
552 Value *LoadedPtr = LI->getOperand(0);
553
554 // If the loaded operand is defined in the LoadBB, it can't be available.
555 // FIXME: Could do PHI translation, that would be fun :)
556 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
557 if (PtrOp->getParent() == LoadBB)
558 return false;
559
560 // Scan a few instructions up from the load, to see if it is obviously live at
561 // the entry to its block.
562 BasicBlock::iterator BBIt = LI;
563
Chris Lattner52c95852008-11-27 08:10:05 +0000564 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
565 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000566 // If the value if the load is locally available within the block, just use
567 // it. This frequently occurs for reg2mem'd allocas.
568 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000569
570 // If the returned value is the load itself, replace with an undef. This can
571 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000572 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000573 LI->replaceAllUsesWith(AvailableVal);
574 LI->eraseFromParent();
575 return true;
576 }
577
578 // Otherwise, if we scanned the whole block and got to the top of the block,
579 // we know the block is locally transparent to the load. If not, something
580 // might clobber its value.
581 if (BBIt != LoadBB->begin())
582 return false;
583
584
585 SmallPtrSet<BasicBlock*, 8> PredsScanned;
586 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
587 AvailablePredsTy AvailablePreds;
588 BasicBlock *OneUnavailablePred = 0;
589
590 // If we got here, the loaded value is transparent through to the start of the
591 // block. Check to see if it is available in any of the predecessor blocks.
592 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
593 PI != PE; ++PI) {
594 BasicBlock *PredBB = *PI;
595
596 // If we already scanned this predecessor, skip it.
597 if (!PredsScanned.insert(PredBB))
598 continue;
599
600 // Scan the predecessor to see if the value is available in the pred.
601 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000602 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000603 if (!PredAvailable) {
604 OneUnavailablePred = PredBB;
605 continue;
606 }
607
608 // If so, this load is partially redundant. Remember this info so that we
609 // can create a PHI node.
610 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
611 }
612
613 // If the loaded value isn't available in any predecessor, it isn't partially
614 // redundant.
615 if (AvailablePreds.empty()) return false;
616
617 // Okay, the loaded value is available in at least one (and maybe all!)
618 // predecessors. If the value is unavailable in more than one unique
619 // predecessor, we want to insert a merge block for those common predecessors.
620 // This ensures that we only have to insert one reload, thus not increasing
621 // code size.
622 BasicBlock *UnavailablePred = 0;
623
624 // If there is exactly one predecessor where the value is unavailable, the
625 // already computed 'OneUnavailablePred' block is it. If it ends in an
626 // unconditional branch, we know that it isn't a critical edge.
627 if (PredsScanned.size() == AvailablePreds.size()+1 &&
628 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
629 UnavailablePred = OneUnavailablePred;
630 } else if (PredsScanned.size() != AvailablePreds.size()) {
631 // Otherwise, we had multiple unavailable predecessors or we had a critical
632 // edge from the one.
633 SmallVector<BasicBlock*, 8> PredsToSplit;
634 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
635
636 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
637 AvailablePredSet.insert(AvailablePreds[i].first);
638
639 // Add all the unavailable predecessors to the PredsToSplit list.
640 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
641 PI != PE; ++PI)
642 if (!AvailablePredSet.count(*PI))
643 PredsToSplit.push_back(*PI);
644
645 // Split them out to their own block.
646 UnavailablePred =
647 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
648 "thread-split", this);
649 }
650
651 // If the value isn't available in all predecessors, then there will be
652 // exactly one where it isn't available. Insert a load on that edge and add
653 // it to the AvailablePreds list.
654 if (UnavailablePred) {
655 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
656 "Can't handle critical edge here!");
657 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
658 UnavailablePred->getTerminator());
659 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
660 }
661
662 // Now we know that each predecessor of this block has a value in
663 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000664 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000665
666 // Create a PHI node at the start of the block for the PRE'd load value.
667 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
668 PN->takeName(LI);
669
670 // Insert new entries into the PHI for each predecessor. A single block may
671 // have multiple entries here.
672 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
673 ++PI) {
674 AvailablePredsTy::iterator I =
675 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
676 std::make_pair(*PI, (Value*)0));
677
678 assert(I != AvailablePreds.end() && I->first == *PI &&
679 "Didn't find entry for predecessor!");
680
681 PN->addIncoming(I->second, I->first);
682 }
683
684 //cerr << "PRE: " << *LI << *PN << "\n";
685
686 LI->replaceAllUsesWith(PN);
687 LI->eraseFromParent();
688
689 return true;
690}
691
692
Chris Lattnere33583b2009-10-11 04:18:15 +0000693/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000694/// the current block. See if there are any simplifications we can do based on
695/// inputs to the phi node.
696///
697bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000698 BasicBlock *BB = PN->getParent();
699
Devang Patel12d53db2009-11-07 01:32:59 +0000700 // See if the phi node has any constant integer or undef values. If so, we
701 // can determine where the corresponding predecessor will branch.
702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
703 Value *PredVal = PN->getIncomingValue(i);
704
705 // Check to see if this input is a constant integer. If so, the direction
706 // of the branch is predictable.
707 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
708 // Merge any common predecessors that will act the same.
709 BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI);
710
711 BasicBlock *SuccBB;
712 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
713 SuccBB = BI->getSuccessor(CI->isZero());
714 else {
715 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
716 SuccBB = SI->getSuccessor(SI->findCaseValue(CI));
717 }
718
719 // Ok, try to thread it!
720 return ThreadEdge(BB, PredBB, SuccBB);
721 }
722
723 // If the input is an undef, then it doesn't matter which way it will go.
724 // Pick an arbitrary dest and thread the edge.
725 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
726 // Merge any common predecessors that will act the same.
727 BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV);
728 BasicBlock *SuccBB =
729 BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB));
730
731 // Ok, try to thread it!
732 return ThreadEdge(BB, PredBB, SuccBB);
733 }
734 }
735
736 // If the incoming values are all variables, we don't know the destination of
737 // any predecessors. However, if any of the predecessor blocks end in an
738 // unconditional branch, we can *duplicate* the jump into that block in order
739 // to further encourage jump threading and to eliminate cases where we have
740 // branch on a phi of an icmp (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +0000741
742 // We don't want to do this tranformation for switches, because we don't
743 // really want to duplicate a switch.
744 if (isa<SwitchInst>(BB->getTerminator()))
745 return false;
746
747 // Look for unconditional branch predecessors.
748 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
749 BasicBlock *PredBB = PN->getIncomingBlock(i);
750 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
751 if (PredBr->isUnconditional() &&
752 // Try to duplicate BB into PredBB.
753 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
754 return true;
755 }
756
Chris Lattner6b65f472009-10-11 04:40:21 +0000757 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000758}
759
Chris Lattnera5ddb592008-04-22 21:40:39 +0000760
Devang Patel12d53db2009-11-07 01:32:59 +0000761/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
762/// whose condition is an AND/OR where one side is PN. If PN has constant
763/// operands that permit us to evaluate the condition for some operand, thread
764/// through the block. For example with:
765/// br (and X, phi(Y, Z, false))
766/// the predecessor corresponding to the 'false' will always jump to the false
767/// destination of the branch.
768///
769bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
770 bool isAnd) {
771 // If this is a binary operator tree of the same AND/OR opcode, check the
772 // LHS/RHS.
773 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
774 if ((isAnd && BO->getOpcode() == Instruction::And) ||
775 (!isAnd && BO->getOpcode() == Instruction::Or)) {
776 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
777 return true;
778 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
779 return true;
780 }
781
782 // If this isn't a PHI node, we can't handle it.
783 PHINode *PN = dyn_cast<PHINode>(V);
784 if (!PN || PN->getParent() != BB) return false;
785
786 // We can only do the simplification for phi nodes of 'false' with AND or
787 // 'true' with OR. See if we have any entries in the phi for this.
788 unsigned PredNo = ~0U;
789 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
790 !isAnd);
791 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
792 if (PN->getIncomingValue(i) == PredCst) {
793 PredNo = i;
794 break;
795 }
796 }
797
798 // If no match, bail out.
799 if (PredNo == ~0U)
800 return false;
801
802 // If so, we can actually do this threading. Merge any common predecessors
803 // that will act the same.
804 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
805
806 // Next, figure out which successor we are threading to. If this was an AND,
807 // the constant must be FALSE, and we must be targeting the 'false' block.
808 // If this is an OR, the constant must be TRUE, and we must be targeting the
809 // 'true' block.
810 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
811
812 // Ok, try to thread it!
813 return ThreadEdge(BB, PredBB, SuccBB);
814}
815
816/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
817/// hand sides of the compare instruction, try to determine the result. If the
818/// result can not be determined, a null pointer is returned.
819static Constant *GetResultOfComparison(CmpInst::Predicate pred,
820 Value *LHS, Value *RHS,
821 LLVMContext &Context) {
822 if (Constant *CLHS = dyn_cast<Constant>(LHS))
823 if (Constant *CRHS = dyn_cast<Constant>(RHS))
824 return ConstantExpr::getCompare(pred, CLHS, CRHS);
825
826 if (LHS == RHS)
827 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
828 return ICmpInst::isTrueWhenEqual(pred) ?
829 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
830
831 return 0;
832}
833
834/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
835/// node and a value. If we can identify when the comparison is true between
836/// the phi inputs and the value, we can fold the compare for that edge and
837/// thread through it.
838bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
839 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
840 Value *RHS = Cmp->getOperand(1);
841
842 // If the phi isn't in the current block, an incoming edge to this block
843 // doesn't control the destination.
844 if (PN->getParent() != BB)
845 return false;
846
847 // We can do this simplification if any comparisons fold to true or false.
848 // See if any do.
849 Value *PredVal = 0;
850 bool TrueDirection = false;
851 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
852 PredVal = PN->getIncomingValue(i);
853
854 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
855 RHS, Cmp->getContext());
856 if (!Res) {
857 PredVal = 0;
858 continue;
859 }
860
861 // If this folded to a constant expr, we can't do anything.
862 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
863 TrueDirection = ResC->getZExtValue();
864 break;
865 }
866 // If this folded to undef, just go the false way.
867 if (isa<UndefValue>(Res)) {
868 TrueDirection = false;
869 break;
870 }
871
872 // Otherwise, we can't fold this input.
873 PredVal = 0;
874 }
875
876 // If no match, bail out.
877 if (PredVal == 0)
878 return false;
879
880 // If so, we can actually do this threading. Merge any common predecessors
881 // that will act the same.
882 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
883
884 // Next, get our successor.
885 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
886
887 // Ok, try to thread it!
888 return ThreadEdge(BB, PredBB, SuccBB);
889}
890
891
Chris Lattner78c552e2009-10-11 07:24:57 +0000892/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
893/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
894/// NewPred using the entries from OldPred (suitably mapped).
895static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
896 BasicBlock *OldPred,
897 BasicBlock *NewPred,
898 DenseMap<Instruction*, Value*> &ValueMap) {
899 for (BasicBlock::iterator PNI = PHIBB->begin();
900 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
901 // Ok, we have a PHI node. Figure out what the incoming value was for the
902 // DestBlock.
903 Value *IV = PN->getIncomingValueForBlock(OldPred);
904
905 // Remap the value if necessary.
906 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
907 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
908 if (I != ValueMap.end())
909 IV = I->second;
910 }
911
912 PN->addIncoming(IV, NewPred);
913 }
914}
Chris Lattner6bf77502008-04-22 07:05:46 +0000915
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000916/// ThreadEdge - We have decided that it is safe and profitable to thread an
917/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
918/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +0000919bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000920 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000921 // If threading to the same block as we come from, we would infinite loop.
922 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000923 DEBUG(errs() << " Not threading across BB '" << BB->getName()
924 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000925 return false;
926 }
927
928 // If threading this would thread across a loop header, don't thread the edge.
929 // See the comments above FindLoopHeaders for justifications and caveats.
930 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000931 DEBUG(errs() << " Not threading from '" << PredBB->getName()
932 << "' across loop header BB '" << BB->getName()
933 << "' to dest BB '" << SuccBB->getName()
934 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000935 return false;
936 }
937
Chris Lattner78c552e2009-10-11 07:24:57 +0000938 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
939 if (JumpThreadCost > Threshold) {
940 DEBUG(errs() << " Not threading BB '" << BB->getName()
941 << "' - Cost is too high: " << JumpThreadCost << "\n");
942 return false;
943 }
944
Mike Stumpfe095f32009-05-04 18:40:41 +0000945 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000946 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +0000947 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000948 << ", across block:\n "
949 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000950
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000951 // We are going to have to map operands from the original BB block to the new
952 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
953 // account for entry from PredBB.
954 DenseMap<Instruction*, Value*> ValueMapping;
955
Owen Anderson1d0be152009-08-13 21:58:54 +0000956 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
957 BB->getName()+".thread",
958 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000959 NewBB->moveAfter(PredBB);
960
961 BasicBlock::iterator BI = BB->begin();
962 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
963 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
964
965 // Clone the non-phi instructions of BB into NewBB, keeping track of the
966 // mapping and using it to remap operands in the cloned instructions.
967 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +0000968 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +0000969 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000970 NewBB->getInstList().push_back(New);
971 ValueMapping[BI] = New;
972
973 // Remap operands to patch up intra-block references.
974 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +0000975 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
976 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
977 if (I != ValueMapping.end())
978 New->setOperand(i, I->second);
979 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000980 }
981
982 // We didn't copy the terminator from BB over to NewBB, because there is now
983 // an unconditional jump to SuccBB. Insert the unconditional jump.
984 BranchInst::Create(SuccBB, NewBB);
985
986 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
987 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +0000988 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000989
Chris Lattner433a0db2009-10-10 09:05:58 +0000990 // If there were values defined in BB that are used outside the block, then we
991 // now have to update all uses of the value to use either the original value,
992 // the cloned value, or some PHI derived value. This can require arbitrary
993 // PHI insertion, of which we are prepared to do, clean these up now.
994 SSAUpdater SSAUpdate;
995 SmallVector<Use*, 16> UsesToRename;
996 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
997 // Scan all uses of this instruction to see if it is used outside of its
998 // block, and if so, record them in UsesToRename.
999 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1000 ++UI) {
1001 Instruction *User = cast<Instruction>(*UI);
1002 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1003 if (UserPN->getIncomingBlock(UI) == BB)
1004 continue;
1005 } else if (User->getParent() == BB)
1006 continue;
1007
1008 UsesToRename.push_back(&UI.getUse());
1009 }
1010
1011 // If there are no uses outside the block, we're done with this instruction.
1012 if (UsesToRename.empty())
1013 continue;
1014
1015 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1016
1017 // We found a use of I outside of BB. Rename all uses of I that are outside
1018 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1019 // with the two values we know.
1020 SSAUpdate.Initialize(I);
1021 SSAUpdate.AddAvailableValue(BB, I);
1022 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1023
1024 while (!UsesToRename.empty())
1025 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1026 DEBUG(errs() << "\n");
1027 }
1028
1029
Chris Lattneref0c6742008-12-01 04:48:07 +00001030 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001031 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1032 // us to simplify any PHI nodes in BB.
1033 TerminatorInst *PredTerm = PredBB->getTerminator();
1034 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1035 if (PredTerm->getSuccessor(i) == BB) {
1036 BB->removePredecessor(PredBB);
1037 PredTerm->setSuccessor(i, NewBB);
1038 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001039
1040 // At this point, the IR is fully up to date and consistent. Do a quick scan
1041 // over the new instructions and zap any that are constants or dead. This
1042 // frequently happens because of phi translation.
1043 BI = NewBB->begin();
1044 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1045 Instruction *Inst = BI++;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001046 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001047 Inst->replaceAllUsesWith(C);
1048 Inst->eraseFromParent();
1049 continue;
1050 }
1051
1052 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1053 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001054
1055 // Threaded an edge!
1056 ++NumThreads;
1057 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001058}
Chris Lattner78c552e2009-10-11 07:24:57 +00001059
1060/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1061/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1062/// If we can duplicate the contents of BB up into PredBB do so now, this
1063/// improves the odds that the branch will be on an analyzable instruction like
1064/// a compare.
1065bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1066 BasicBlock *PredBB) {
1067 // If BB is a loop header, then duplicating this block outside the loop would
1068 // cause us to transform this into an irreducible loop, don't do this.
1069 // See the comments above FindLoopHeaders for justifications and caveats.
1070 if (LoopHeaders.count(BB)) {
1071 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1072 << "' into predecessor block '" << PredBB->getName()
1073 << "' - it might create an irreducible loop!\n");
1074 return false;
1075 }
1076
1077 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1078 if (DuplicationCost > Threshold) {
1079 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1080 << "' - Cost is too high: " << DuplicationCost << "\n");
1081 return false;
1082 }
1083
1084 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1085 // of PredBB.
1086 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1087 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1088 << DuplicationCost << " block is:" << *BB << "\n");
1089
1090 // We are going to have to map operands from the original BB block into the
1091 // PredBB block. Evaluate PHI nodes in BB.
1092 DenseMap<Instruction*, Value*> ValueMapping;
1093
1094 BasicBlock::iterator BI = BB->begin();
1095 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1096 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1097
1098 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1099
1100 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1101 // mapping and using it to remap operands in the cloned instructions.
1102 for (; BI != BB->end(); ++BI) {
1103 Instruction *New = BI->clone();
1104 New->setName(BI->getName());
1105 PredBB->getInstList().insert(OldPredBranch, New);
1106 ValueMapping[BI] = New;
1107
1108 // Remap operands to patch up intra-block references.
1109 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1110 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1111 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1112 if (I != ValueMapping.end())
1113 New->setOperand(i, I->second);
1114 }
1115 }
1116
1117 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1118 // add entries to the PHI nodes for branch from PredBB now.
1119 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1120 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1121 ValueMapping);
1122 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1123 ValueMapping);
1124
1125 // If there were values defined in BB that are used outside the block, then we
1126 // now have to update all uses of the value to use either the original value,
1127 // the cloned value, or some PHI derived value. This can require arbitrary
1128 // PHI insertion, of which we are prepared to do, clean these up now.
1129 SSAUpdater SSAUpdate;
1130 SmallVector<Use*, 16> UsesToRename;
1131 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1132 // Scan all uses of this instruction to see if it is used outside of its
1133 // block, and if so, record them in UsesToRename.
1134 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1135 ++UI) {
1136 Instruction *User = cast<Instruction>(*UI);
1137 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1138 if (UserPN->getIncomingBlock(UI) == BB)
1139 continue;
1140 } else if (User->getParent() == BB)
1141 continue;
1142
1143 UsesToRename.push_back(&UI.getUse());
1144 }
1145
1146 // If there are no uses outside the block, we're done with this instruction.
1147 if (UsesToRename.empty())
1148 continue;
1149
1150 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1151
1152 // We found a use of I outside of BB. Rename all uses of I that are outside
1153 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1154 // with the two values we know.
1155 SSAUpdate.Initialize(I);
1156 SSAUpdate.AddAvailableValue(BB, I);
1157 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1158
1159 while (!UsesToRename.empty())
1160 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1161 DEBUG(errs() << "\n");
1162 }
1163
1164 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1165 // that we nuked.
1166 BB->removePredecessor(PredBB);
1167
1168 // Remove the unconditional branch at the end of the PredBB block.
1169 OldPredBranch->eraseFromParent();
1170
1171 ++NumDupes;
1172 return true;
1173}
1174
1175