blob: 62f7d51ff8c8432047acc2687b749a1adaa88e25 [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);
Chris Lattner78567252009-11-06 18:15:14 +000078
79 typedef SmallVectorImpl<std::pair<ConstantInt*,
80 BasicBlock*> > PredValueInfo;
81
82 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
83 PredValueInfo &Result);
84 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
85
86
Chris Lattner421fa9e2008-12-03 07:48:08 +000087 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000088 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000089
Chris Lattnerd38c14e2008-04-22 06:36:15 +000090 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattner69e067f2008-11-27 05:07:53 +000091
92 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000093 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000094}
95
Dan Gohman844731a2008-05-13 00:00:25 +000096char JumpThreading::ID = 0;
97static RegisterPass<JumpThreading>
98X("jump-threading", "Jump Threading");
99
Chris Lattner8383a7b2008-04-20 20:35:01 +0000100// Public interface to the Jump Threading pass
101FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
102
103/// runOnFunction - Top level algorithm.
104///
105bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000106 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000107 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000108
Mike Stumpfe095f32009-05-04 18:40:41 +0000109 FindLoopHeaders(F);
110
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000111 bool AnotherIteration = true, EverChanged = false;
112 while (AnotherIteration) {
113 AnotherIteration = false;
114 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000115 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
116 BasicBlock *BB = I;
117 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000118 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000119
120 ++I;
121
122 // If the block is trivially dead, zap it. This eliminates the successor
123 // edges which simplifies the CFG.
124 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000125 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000126 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000127 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000128 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000129 DeleteDeadBlock(BB);
130 Changed = true;
131 }
132 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000133 AnotherIteration = Changed;
134 EverChanged |= Changed;
135 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000136
137 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000138 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000139}
Chris Lattner177480b2008-04-20 21:13:06 +0000140
Chris Lattner78c552e2009-10-11 07:24:57 +0000141/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
142/// thread across it.
143static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
144 /// Ignore PHI nodes, these will be flattened when duplication happens.
145 BasicBlock::const_iterator I = BB->getFirstNonPHI();
146
147 // Sum up the cost of each instruction until we get to the terminator. Don't
148 // include the terminator because the copy won't include it.
149 unsigned Size = 0;
150 for (; !isa<TerminatorInst>(I); ++I) {
151 // Debugger intrinsics don't incur code size.
152 if (isa<DbgInfoIntrinsic>(I)) continue;
153
154 // If this is a pointer->pointer bitcast, it is free.
155 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
156 continue;
157
158 // All other instructions count for at least one unit.
159 ++Size;
160
161 // Calls are more expensive. If they are non-intrinsic calls, we model them
162 // as having cost of 4. If they are a non-vector intrinsic, we model them
163 // as having cost of 2 total, and if they are a vector intrinsic, we model
164 // them as having cost 1.
165 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
166 if (!isa<IntrinsicInst>(CI))
167 Size += 3;
168 else if (!isa<VectorType>(CI->getType()))
169 Size += 1;
170 }
171 }
172
173 // Threading through a switch statement is particularly profitable. If this
174 // block ends in a switch, decrease its cost to make it more likely to happen.
175 if (isa<SwitchInst>(I))
176 Size = Size > 6 ? Size-6 : 0;
177
178 return Size;
179}
180
181
182
Mike Stumpfe095f32009-05-04 18:40:41 +0000183/// FindLoopHeaders - We do not want jump threading to turn proper loop
184/// structures into irreducible loops. Doing this breaks up the loop nesting
185/// hierarchy and pessimizes later transformations. To prevent this from
186/// happening, we first have to find the loop headers. Here we approximate this
187/// by finding targets of backedges in the CFG.
188///
189/// Note that there definitely are cases when we want to allow threading of
190/// edges across a loop header. For example, threading a jump from outside the
191/// loop (the preheader) to an exit block of the loop is definitely profitable.
192/// It is also almost always profitable to thread backedges from within the loop
193/// to exit blocks, and is often profitable to thread backedges to other blocks
194/// within the loop (forming a nested loop). This simple analysis is not rich
195/// enough to track all of these properties and keep it up-to-date as the CFG
196/// mutates, so we don't allow any of these transformations.
197///
198void JumpThreading::FindLoopHeaders(Function &F) {
199 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
200 FindFunctionBackedges(F, Edges);
201
202 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
203 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
204}
205
Chris Lattner78567252009-11-06 18:15:14 +0000206/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
207/// hand sides of the compare instruction, try to determine the result. If the
208/// result can not be determined, a null pointer is returned.
209static Constant *GetResultOfComparison(CmpInst::Predicate pred,
210 Value *LHS, Value *RHS) {
211 if (Constant *CLHS = dyn_cast<Constant>(LHS))
212 if (Constant *CRHS = dyn_cast<Constant>(RHS))
213 return ConstantExpr::getCompare(pred, CLHS, CRHS);
Chris Lattner6bf77502008-04-22 07:05:46 +0000214
Chris Lattner78567252009-11-06 18:15:14 +0000215 if (LHS == RHS)
216 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
217 if (ICmpInst::isTrueWhenEqual(pred))
218 return ConstantInt::getTrue(LHS->getContext());
219 else
220 return ConstantInt::getFalse(LHS->getContext());
221 return 0;
222}
223
224
225/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
226/// if we can infer that the value is a known ConstantInt in any of our
227/// predecessors. If so, return the known the list of value and pred BB in the
228/// result vector. If a value is known to be undef, it is returned as null.
229///
230/// The BB basic block is known to start with a PHI node.
231///
232/// This returns true if there were any known values.
233///
234///
235/// TODO: Per PR2563, we could infer value range information about a predecessor
236/// based on its terminator.
237bool JumpThreading::
238ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
239 PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
240
241 // If V is a constantint, then it is known in all predecessors.
242 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
243 ConstantInt *CI = dyn_cast<ConstantInt>(V);
244 Result.resize(TheFirstPHI->getNumIncomingValues());
245 for (unsigned i = 0, e = Result.size(); i != e; ++i)
Chris Lattner82114b92009-11-06 19:21:48 +0000246 Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i));
Chris Lattner78567252009-11-06 18:15:14 +0000247 return true;
248 }
249
250 // If V is a non-instruction value, or an instruction in a different block,
251 // then it can't be derived from a PHI.
252 Instruction *I = dyn_cast<Instruction>(V);
253 if (I == 0 || I->getParent() != BB)
254 return false;
255
256 /// If I is a PHI node, then we know the incoming values for any constants.
257 if (PHINode *PN = dyn_cast<PHINode>(I)) {
258 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
259 Value *InVal = PN->getIncomingValue(i);
260 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
261 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
262 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
263 }
264 }
265 return !Result.empty();
266 }
267
268 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
269
270 // Handle some boolean conditions.
271 if (I->getType()->getPrimitiveSizeInBits() == 1) {
272 // X | true -> true
273 // X & false -> false
274 if (I->getOpcode() == Instruction::Or ||
275 I->getOpcode() == Instruction::And) {
276 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
277 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
278
279 if (LHSVals.empty() && RHSVals.empty())
280 return false;
281
282 ConstantInt *InterestingVal;
283 if (I->getOpcode() == Instruction::Or)
284 InterestingVal = ConstantInt::getTrue(I->getContext());
285 else
286 InterestingVal = ConstantInt::getFalse(I->getContext());
287
288 // Scan for the sentinel.
289 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
290 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
291 Result.push_back(LHSVals[i]);
292 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
293 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
294 Result.push_back(RHSVals[i]);
295 return !Result.empty();
296 }
297
298 // TODO: Should handle the NOT form of XOR.
299
300 }
301
302 // Handle compare with phi operand, where the PHI is defined in this block.
303 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
304 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
305 if (PN && PN->getParent() == BB) {
306 // We can do this simplification if any comparisons fold to true or false.
307 // See if any do.
308 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
309 BasicBlock *PredBB = PN->getIncomingBlock(i);
310 Value *LHS = PN->getIncomingValue(i);
311 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
312
313 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), LHS, RHS);
314 if (Res == 0) continue;
315
316 if (isa<UndefValue>(Res))
317 Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
318 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
319 Result.push_back(std::make_pair(CI, PredBB));
320 }
321
322 return !Result.empty();
323 }
324
325 // TODO: We could also recurse to see if we can determine constants another
326 // way.
327 }
328 return false;
329}
330
331
Chris Lattner6bf77502008-04-22 07:05:46 +0000332
Chris Lattnere33583b2009-10-11 04:18:15 +0000333/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
334/// in an undefined jump, decide which block is best to revector to.
335///
336/// Since we can pick an arbitrary destination, we pick the successor with the
337/// fewest predecessors. This should reduce the in-degree of the others.
338///
339static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
340 TerminatorInst *BBTerm = BB->getTerminator();
341 unsigned MinSucc = 0;
342 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
343 // Compute the successor with the minimum number of predecessors.
344 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
345 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
346 TestBB = BBTerm->getSuccessor(i);
347 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
348 if (NumPreds < MinNumPreds)
349 MinSucc = i;
350 }
351
352 return MinSucc;
353}
354
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000355/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000356/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000357bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000358 // If this block has a single predecessor, and if that pred has a single
359 // successor, merge the blocks. This encourages recursive jump threading
360 // because now the condition in this block can be threaded through
361 // predecessors of our predecessor block.
Chris Lattner78567252009-11-06 18:15:14 +0000362 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000363 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
364 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000365 // If SinglePred was a loop header, BB becomes one.
366 if (LoopHeaders.erase(SinglePred))
367 LoopHeaders.insert(BB);
368
Chris Lattner3d86d242008-11-27 19:25:19 +0000369 // Remember if SinglePred was the entry block of the function. If so, we
370 // will need to move BB back to the entry position.
371 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000372 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000373
374 if (isEntry && BB != &BB->getParent()->getEntryBlock())
375 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000376 return true;
377 }
Chris Lattner78567252009-11-06 18:15:14 +0000378 }
379
380 // Look to see if the terminator is a branch of switch, if not we can't thread
381 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000382 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000383 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
384 // Can't thread an unconditional jump.
385 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000386 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000387 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000388 Condition = SI->getCondition();
389 else
390 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000391
392 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000393 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000394 // other blocks.
395 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000396 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000397 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000398 ++NumFolds;
399 ConstantFoldTerminator(BB);
400 return true;
401 }
402
Chris Lattner421fa9e2008-12-03 07:48:08 +0000403 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000404 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000405 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000406 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000407
408 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000409 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000410 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000411 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000412 BBTerm->getSuccessor(i)->removePredecessor(BB);
413 }
414
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000415 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000416 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000417 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000418 BBTerm->eraseFromParent();
419 return true;
420 }
421
422 Instruction *CondInst = dyn_cast<Instruction>(Condition);
423
424 // If the condition is an instruction defined in another block, see if a
425 // predecessor has the same condition:
426 // br COND, BBX, BBY
427 // BBX:
428 // br COND, BBZ, BBW
429 if (!Condition->hasOneUse() && // Multiple uses.
430 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
431 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
432 if (isa<BranchInst>(BB->getTerminator())) {
433 for (; PI != E; ++PI)
434 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
435 if (PBI->isConditional() && PBI->getCondition() == Condition &&
436 ProcessBranchOnDuplicateCond(*PI, BB))
437 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000438 } else {
439 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
440 for (; PI != E; ++PI)
441 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
442 if (PSI->getCondition() == Condition &&
443 ProcessSwitchOnDuplicateCond(*PI, BB))
444 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000445 }
446 }
447
Chris Lattner421fa9e2008-12-03 07:48:08 +0000448 // All the rest of our checks depend on the condition being an instruction.
449 if (CondInst == 0)
450 return false;
451
Chris Lattner177480b2008-04-20 21:13:06 +0000452 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000453 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
454 if (PN->getParent() == BB)
455 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000456
Nick Lewycky9683f182009-06-19 04:56:29 +0000457 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Chris Lattner90b92472009-11-06 18:24:32 +0000458 if (!isa<PHINode>(CondCmp->getOperand(0)) ||
459 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
460 // If we have a comparison, loop over the predecessors to see if there is
461 // a condition with a lexically identical value.
462 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
463 for (; PI != E; ++PI)
464 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
465 if (PBI->isConditional() && *PI != BB) {
466 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
467 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
468 CI->getOperand(1) == CondCmp->getOperand(1) &&
469 CI->getPredicate() == CondCmp->getPredicate()) {
470 // TODO: Could handle things like (x != 4) --> (x == 17)
471 if (ProcessBranchOnDuplicateCond(*PI, BB))
472 return true;
473 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000474 }
475 }
Chris Lattner90b92472009-11-06 18:24:32 +0000476 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000477 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000478
479 // Check for some cases that are worth simplifying. Right now we want to look
480 // for loads that are used by a switch or by the condition for the branch. If
481 // we see one, check to see if it's partially redundant. If so, insert a PHI
482 // which can then be used to thread the values.
483 //
484 // This is particularly important because reg2mem inserts loads and stores all
485 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000486 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000487 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
488 if (isa<Constant>(CondCmp->getOperand(1)))
489 SimplifyValue = CondCmp->getOperand(0);
490
491 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
492 if (SimplifyPartiallyRedundantLoad(LI))
493 return true;
494
Chris Lattner78567252009-11-06 18:15:14 +0000495
496 // Handle a variety of cases where we are branching on something derived from
497 // a PHI node in the current block. If we can prove that any predecessors
498 // compute a predictable value based on a PHI node, thread those predecessors.
499 //
500 // We only bother doing this if the current block has a PHI node and if the
501 // conditional instruction lives in the current block. If either condition
502 // fail, this won't be a computable value anyway.
503 if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
504 if (ProcessThreadableEdges(CondInst, BB))
505 return true;
506
507
Chris Lattner69e067f2008-11-27 05:07:53 +0000508 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
509 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000510
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000511 return false;
512}
513
Chris Lattner421fa9e2008-12-03 07:48:08 +0000514/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
515/// block that jump on exactly the same condition. This means that we almost
516/// always know the direction of the edge in the DESTBB:
517/// PREDBB:
518/// br COND, DESTBB, BBY
519/// DESTBB:
520/// br COND, BBZ, BBW
521///
522/// If DESTBB has multiple predecessors, we can't just constant fold the branch
523/// in DESTBB, we have to thread over it.
524bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
525 BasicBlock *BB) {
526 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
527
528 // If both successors of PredBB go to DESTBB, we don't know anything. We can
529 // fold the branch to an unconditional one, which allows other recursive
530 // simplifications.
531 bool BranchDir;
532 if (PredBI->getSuccessor(1) != BB)
533 BranchDir = true;
534 else if (PredBI->getSuccessor(0) != BB)
535 BranchDir = false;
536 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000537 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000538 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000539 ++NumFolds;
540 ConstantFoldTerminator(PredBB);
541 return true;
542 }
543
544 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
545
546 // If the dest block has one predecessor, just fix the branch condition to a
547 // constant and fold it.
548 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000549 DEBUG(errs() << " In block '" << BB->getName()
550 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000551 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000552 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000553 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000554 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
555 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000556 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000557 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000558 return true;
559 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000560
Chris Lattner421fa9e2008-12-03 07:48:08 +0000561
562 // Next, figure out which successor we are threading to.
563 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
564
Mike Stumpfe095f32009-05-04 18:40:41 +0000565 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000566 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000567}
568
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000569/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
570/// block that switch on exactly the same condition. This means that we almost
571/// always know the direction of the edge in the DESTBB:
572/// PREDBB:
573/// switch COND [... DESTBB, BBY ... ]
574/// DESTBB:
575/// switch COND [... BBZ, BBW ]
576///
577/// Optimizing switches like this is very important, because simplifycfg builds
578/// switches out of repeated 'if' conditions.
579bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
580 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000581 // Can't thread edge to self.
582 if (PredBB == DestBB)
583 return false;
584
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000585 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
586 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
587
588 // There are a variety of optimizations that we can potentially do on these
589 // blocks: we order them from most to least preferable.
590
591 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
592 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000593 // growth. Skip debug info first.
594 BasicBlock::iterator BBI = DestBB->begin();
595 while (isa<DbgInfoIntrinsic>(BBI))
596 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000597
598 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000599 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000600 bool MadeChange = false;
601 // Ignore the default edge for now.
602 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
603 ConstantInt *DestVal = DestSI->getCaseValue(i);
604 BasicBlock *DestSucc = DestSI->getSuccessor(i);
605
606 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
607 // PredSI has an explicit case for it. If so, forward. If it is covered
608 // by the default case, we can't update PredSI.
609 unsigned PredCase = PredSI->findCaseValue(DestVal);
610 if (PredCase == 0) continue;
611
612 // If PredSI doesn't go to DestBB on this value, then it won't reach the
613 // case on this condition.
614 if (PredSI->getSuccessor(PredCase) != DestBB &&
615 DestSI->getSuccessor(i) != DestBB)
616 continue;
617
618 // Otherwise, we're safe to make the change. Make sure that the edge from
619 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000620 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
621 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000622
623 // If the destination has PHI nodes, just split the edge for updating
624 // simplicity.
625 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
626 SplitCriticalEdge(DestSI, i, this);
627 DestSucc = DestSI->getSuccessor(i);
628 }
629 FoldSingleEntryPHINodes(DestSucc);
630 PredSI->setSuccessor(PredCase, DestSucc);
631 MadeChange = true;
632 }
633
634 if (MadeChange)
635 return true;
636 }
637
638 return false;
639}
640
641
Chris Lattner69e067f2008-11-27 05:07:53 +0000642/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
643/// load instruction, eliminate it by replacing it with a PHI node. This is an
644/// important optimization that encourages jump threading, and needs to be run
645/// interlaced with other jump threading tasks.
646bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
647 // Don't hack volatile loads.
648 if (LI->isVolatile()) return false;
649
650 // If the load is defined in a block with exactly one predecessor, it can't be
651 // partially redundant.
652 BasicBlock *LoadBB = LI->getParent();
653 if (LoadBB->getSinglePredecessor())
654 return false;
655
656 Value *LoadedPtr = LI->getOperand(0);
657
658 // If the loaded operand is defined in the LoadBB, it can't be available.
659 // FIXME: Could do PHI translation, that would be fun :)
660 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
661 if (PtrOp->getParent() == LoadBB)
662 return false;
663
664 // Scan a few instructions up from the load, to see if it is obviously live at
665 // the entry to its block.
666 BasicBlock::iterator BBIt = LI;
667
Chris Lattner52c95852008-11-27 08:10:05 +0000668 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
669 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000670 // If the value if the load is locally available within the block, just use
671 // it. This frequently occurs for reg2mem'd allocas.
672 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000673
674 // If the returned value is the load itself, replace with an undef. This can
675 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000676 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000677 LI->replaceAllUsesWith(AvailableVal);
678 LI->eraseFromParent();
679 return true;
680 }
681
682 // Otherwise, if we scanned the whole block and got to the top of the block,
683 // we know the block is locally transparent to the load. If not, something
684 // might clobber its value.
685 if (BBIt != LoadBB->begin())
686 return false;
687
688
689 SmallPtrSet<BasicBlock*, 8> PredsScanned;
690 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
691 AvailablePredsTy AvailablePreds;
692 BasicBlock *OneUnavailablePred = 0;
693
694 // If we got here, the loaded value is transparent through to the start of the
695 // block. Check to see if it is available in any of the predecessor blocks.
696 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
697 PI != PE; ++PI) {
698 BasicBlock *PredBB = *PI;
699
700 // If we already scanned this predecessor, skip it.
701 if (!PredsScanned.insert(PredBB))
702 continue;
703
704 // Scan the predecessor to see if the value is available in the pred.
705 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000706 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000707 if (!PredAvailable) {
708 OneUnavailablePred = PredBB;
709 continue;
710 }
711
712 // If so, this load is partially redundant. Remember this info so that we
713 // can create a PHI node.
714 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
715 }
716
717 // If the loaded value isn't available in any predecessor, it isn't partially
718 // redundant.
719 if (AvailablePreds.empty()) return false;
720
721 // Okay, the loaded value is available in at least one (and maybe all!)
722 // predecessors. If the value is unavailable in more than one unique
723 // predecessor, we want to insert a merge block for those common predecessors.
724 // This ensures that we only have to insert one reload, thus not increasing
725 // code size.
726 BasicBlock *UnavailablePred = 0;
727
728 // If there is exactly one predecessor where the value is unavailable, the
729 // already computed 'OneUnavailablePred' block is it. If it ends in an
730 // unconditional branch, we know that it isn't a critical edge.
731 if (PredsScanned.size() == AvailablePreds.size()+1 &&
732 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
733 UnavailablePred = OneUnavailablePred;
734 } else if (PredsScanned.size() != AvailablePreds.size()) {
735 // Otherwise, we had multiple unavailable predecessors or we had a critical
736 // edge from the one.
737 SmallVector<BasicBlock*, 8> PredsToSplit;
738 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
739
740 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
741 AvailablePredSet.insert(AvailablePreds[i].first);
742
743 // Add all the unavailable predecessors to the PredsToSplit list.
744 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
745 PI != PE; ++PI)
746 if (!AvailablePredSet.count(*PI))
747 PredsToSplit.push_back(*PI);
748
749 // Split them out to their own block.
750 UnavailablePred =
751 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
752 "thread-split", this);
753 }
754
755 // If the value isn't available in all predecessors, then there will be
756 // exactly one where it isn't available. Insert a load on that edge and add
757 // it to the AvailablePreds list.
758 if (UnavailablePred) {
759 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
760 "Can't handle critical edge here!");
761 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
762 UnavailablePred->getTerminator());
763 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
764 }
765
766 // Now we know that each predecessor of this block has a value in
767 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000768 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000769
770 // Create a PHI node at the start of the block for the PRE'd load value.
771 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
772 PN->takeName(LI);
773
774 // Insert new entries into the PHI for each predecessor. A single block may
775 // have multiple entries here.
776 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
777 ++PI) {
778 AvailablePredsTy::iterator I =
779 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
780 std::make_pair(*PI, (Value*)0));
781
782 assert(I != AvailablePreds.end() && I->first == *PI &&
783 "Didn't find entry for predecessor!");
784
785 PN->addIncoming(I->second, I->first);
786 }
787
788 //cerr << "PRE: " << *LI << *PN << "\n";
789
790 LI->replaceAllUsesWith(PN);
791 LI->eraseFromParent();
792
793 return true;
794}
795
Chris Lattner78567252009-11-06 18:15:14 +0000796/// FindMostPopularDest - The specified list contains multiple possible
797/// threadable destinations. Pick the one that occurs the most frequently in
798/// the list.
799static BasicBlock *
800FindMostPopularDest(BasicBlock *BB,
801 const SmallVectorImpl<std::pair<BasicBlock*,
802 BasicBlock*> > &PredToDestList) {
803 assert(!PredToDestList.empty());
804
805 // Determine popularity. If there are multiple possible destinations, we
806 // explicitly choose to ignore 'undef' destinations. We prefer to thread
807 // blocks with known and real destinations to threading undef. We'll handle
808 // them later if interesting.
809 DenseMap<BasicBlock*, unsigned> DestPopularity;
810 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
811 if (PredToDestList[i].second)
812 DestPopularity[PredToDestList[i].second]++;
813
814 // Find the most popular dest.
815 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
816 BasicBlock *MostPopularDest = DPI->first;
817 unsigned Popularity = DPI->second;
818 SmallVector<BasicBlock*, 4> SamePopularity;
819
820 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
821 // If the popularity of this entry isn't higher than the popularity we've
822 // seen so far, ignore it.
823 if (DPI->second < Popularity)
824 ; // ignore.
825 else if (DPI->second == Popularity) {
826 // If it is the same as what we've seen so far, keep track of it.
827 SamePopularity.push_back(DPI->first);
828 } else {
829 // If it is more popular, remember it.
830 SamePopularity.clear();
831 MostPopularDest = DPI->first;
832 Popularity = DPI->second;
833 }
834 }
835
836 // Okay, now we know the most popular destination. If there is more than
837 // destination, we need to determine one. This is arbitrary, but we need
838 // to make a deterministic decision. Pick the first one that appears in the
839 // successor list.
840 if (!SamePopularity.empty()) {
841 SamePopularity.push_back(MostPopularDest);
842 TerminatorInst *TI = BB->getTerminator();
843 for (unsigned i = 0; ; ++i) {
844 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
845
846 if (std::find(SamePopularity.begin(), SamePopularity.end(),
847 TI->getSuccessor(i)) == SamePopularity.end())
848 continue;
849
850 MostPopularDest = TI->getSuccessor(i);
851 break;
852 }
853 }
854
855 // Okay, we have finally picked the most popular destination.
856 return MostPopularDest;
857}
858
859bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
860 BasicBlock *BB) {
861 // If threading this would thread across a loop header, don't even try to
862 // thread the edge.
863 if (LoopHeaders.count(BB))
864 return false;
865
866
867
868 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
869 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
870 return false;
871 assert(!PredValues.empty() &&
872 "ComputeValueKnownInPredecessors returned true with no values");
873
874 DEBUG(errs() << "IN BB: " << *BB;
875 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
876 errs() << " BB '" << BB->getName() << "': FOUND condition = ";
877 if (PredValues[i].first)
878 errs() << *PredValues[i].first;
879 else
880 errs() << "UNDEF";
881 errs() << " for pred '" << PredValues[i].second->getName()
882 << "'.\n";
883 });
884
885 // Decide what we want to thread through. Convert our list of known values to
886 // a list of known destinations for each pred. This also discards duplicate
887 // predecessors and keeps track of the undefined inputs (which are represented
888 // as a null dest in the PredToDestList.
889 SmallPtrSet<BasicBlock*, 16> SeenPreds;
890 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
891
892 BasicBlock *OnlyDest = 0;
893 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
894
895 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
896 BasicBlock *Pred = PredValues[i].second;
897 if (!SeenPreds.insert(Pred))
898 continue; // Duplicate predecessor entry.
899
900 // If the predecessor ends with an indirect goto, we can't change its
901 // destination.
902 if (isa<IndirectBrInst>(Pred->getTerminator()))
903 continue;
904
905 ConstantInt *Val = PredValues[i].first;
906
907 BasicBlock *DestBB;
908 if (Val == 0) // Undef.
909 DestBB = 0;
910 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
911 DestBB = BI->getSuccessor(Val->isZero());
912 else {
913 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
914 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
915 }
916
917 // If we have exactly one destination, remember it for efficiency below.
918 if (i == 0)
919 OnlyDest = DestBB;
920 else if (OnlyDest != DestBB)
921 OnlyDest = MultipleDestSentinel;
922
923 PredToDestList.push_back(std::make_pair(Pred, DestBB));
924 }
925
926 // If all edges were unthreadable, we fail.
927 if (PredToDestList.empty())
928 return false;
929
930 // Determine which is the most common successor. If we have many inputs and
931 // this block is a switch, we want to start by threading the batch that goes
932 // to the most popular destination first. If we only know about one
933 // threadable destination (the common case) we can avoid this.
934 BasicBlock *MostPopularDest = OnlyDest;
935
936 if (MostPopularDest == MultipleDestSentinel)
937 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
938
939 // Now that we know what the most popular destination is, factor all
940 // predecessors that will jump to it into a single predecessor.
941 SmallVector<BasicBlock*, 16> PredsToFactor;
942 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
943 if (PredToDestList[i].second == MostPopularDest)
944 PredsToFactor.push_back(PredToDestList[i].first);
945
946 BasicBlock *PredToThread;
947 if (PredsToFactor.size() == 1)
948 PredToThread = PredsToFactor[0];
949 else {
950 DEBUG(errs() << " Factoring out " << PredsToFactor.size()
951 << " common predecessors.\n");
952 PredToThread = SplitBlockPredecessors(BB, &PredsToFactor[0],
953 PredsToFactor.size(),
954 ".thr_comm", this);
955 }
956
957 // If the threadable edges are branching on an undefined value, we get to pick
958 // the destination that these predecessors should get to.
959 if (MostPopularDest == 0)
960 MostPopularDest = BB->getTerminator()->
961 getSuccessor(GetBestDestForJumpOnUndef(BB));
962
963 // Ok, try to thread it!
964 return ThreadEdge(BB, PredToThread, MostPopularDest);
965}
Chris Lattner69e067f2008-11-27 05:07:53 +0000966
Chris Lattnere33583b2009-10-11 04:18:15 +0000967/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000968/// the current block. See if there are any simplifications we can do based on
969/// inputs to the phi node.
970///
971bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000972 BasicBlock *BB = PN->getParent();
973
Chris Lattnerf7807f62009-11-06 18:22:54 +0000974 // If any of the predecessor blocks end in an unconditional branch, we can
975 // *duplicate* the jump into that block in order to further encourage jump
976 // threading and to eliminate cases where we have branch on a phi of an icmp
977 // (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +0000978
979 // We don't want to do this tranformation for switches, because we don't
980 // really want to duplicate a switch.
981 if (isa<SwitchInst>(BB->getTerminator()))
982 return false;
983
984 // Look for unconditional branch predecessors.
985 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
986 BasicBlock *PredBB = PN->getIncomingBlock(i);
987 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
988 if (PredBr->isUnconditional() &&
989 // Try to duplicate BB into PredBB.
990 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
991 return true;
992 }
993
Chris Lattner6b65f472009-10-11 04:40:21 +0000994 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000995}
996
Chris Lattnera5ddb592008-04-22 21:40:39 +0000997
Chris Lattner78c552e2009-10-11 07:24:57 +0000998/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
999/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1000/// NewPred using the entries from OldPred (suitably mapped).
1001static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1002 BasicBlock *OldPred,
1003 BasicBlock *NewPred,
1004 DenseMap<Instruction*, Value*> &ValueMap) {
1005 for (BasicBlock::iterator PNI = PHIBB->begin();
1006 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1007 // Ok, we have a PHI node. Figure out what the incoming value was for the
1008 // DestBlock.
1009 Value *IV = PN->getIncomingValueForBlock(OldPred);
1010
1011 // Remap the value if necessary.
1012 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1013 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1014 if (I != ValueMap.end())
1015 IV = I->second;
1016 }
1017
1018 PN->addIncoming(IV, NewPred);
1019 }
1020}
Chris Lattner6bf77502008-04-22 07:05:46 +00001021
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001022/// ThreadEdge - We have decided that it is safe and profitable to thread an
1023/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
1024/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +00001025bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001026 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001027 // If threading to the same block as we come from, we would infinite loop.
1028 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001029 DEBUG(errs() << " Not threading across BB '" << BB->getName()
1030 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001031 return false;
1032 }
1033
1034 // If threading this would thread across a loop header, don't thread the edge.
1035 // See the comments above FindLoopHeaders for justifications and caveats.
1036 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001037 DEBUG(errs() << " Not threading from '" << PredBB->getName()
1038 << "' across loop header BB '" << BB->getName()
1039 << "' to dest BB '" << SuccBB->getName()
1040 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001041 return false;
1042 }
1043
Chris Lattner78c552e2009-10-11 07:24:57 +00001044 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1045 if (JumpThreadCost > Threshold) {
1046 DEBUG(errs() << " Not threading BB '" << BB->getName()
1047 << "' - Cost is too high: " << JumpThreadCost << "\n");
1048 return false;
1049 }
1050
Mike Stumpfe095f32009-05-04 18:40:41 +00001051 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001052 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001053 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001054 << ", across block:\n "
1055 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001056
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001057 // We are going to have to map operands from the original BB block to the new
1058 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1059 // account for entry from PredBB.
1060 DenseMap<Instruction*, Value*> ValueMapping;
1061
Owen Anderson1d0be152009-08-13 21:58:54 +00001062 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1063 BB->getName()+".thread",
1064 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001065 NewBB->moveAfter(PredBB);
1066
1067 BasicBlock::iterator BI = BB->begin();
1068 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1069 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1070
1071 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1072 // mapping and using it to remap operands in the cloned instructions.
1073 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001074 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001075 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001076 NewBB->getInstList().push_back(New);
1077 ValueMapping[BI] = New;
1078
1079 // Remap operands to patch up intra-block references.
1080 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001081 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1082 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1083 if (I != ValueMapping.end())
1084 New->setOperand(i, I->second);
1085 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001086 }
1087
1088 // We didn't copy the terminator from BB over to NewBB, because there is now
1089 // an unconditional jump to SuccBB. Insert the unconditional jump.
1090 BranchInst::Create(SuccBB, NewBB);
1091
1092 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1093 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001094 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001095
Chris Lattner433a0db2009-10-10 09:05:58 +00001096 // If there were values defined in BB that are used outside the block, then we
1097 // now have to update all uses of the value to use either the original value,
1098 // the cloned value, or some PHI derived value. This can require arbitrary
1099 // PHI insertion, of which we are prepared to do, clean these up now.
1100 SSAUpdater SSAUpdate;
1101 SmallVector<Use*, 16> UsesToRename;
1102 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1103 // Scan all uses of this instruction to see if it is used outside of its
1104 // block, and if so, record them in UsesToRename.
1105 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1106 ++UI) {
1107 Instruction *User = cast<Instruction>(*UI);
1108 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1109 if (UserPN->getIncomingBlock(UI) == BB)
1110 continue;
1111 } else if (User->getParent() == BB)
1112 continue;
1113
1114 UsesToRename.push_back(&UI.getUse());
1115 }
1116
1117 // If there are no uses outside the block, we're done with this instruction.
1118 if (UsesToRename.empty())
1119 continue;
1120
1121 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1122
1123 // We found a use of I outside of BB. Rename all uses of I that are outside
1124 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1125 // with the two values we know.
1126 SSAUpdate.Initialize(I);
1127 SSAUpdate.AddAvailableValue(BB, I);
1128 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1129
1130 while (!UsesToRename.empty())
1131 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1132 DEBUG(errs() << "\n");
1133 }
1134
1135
Chris Lattneref0c6742008-12-01 04:48:07 +00001136 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001137 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1138 // us to simplify any PHI nodes in BB.
1139 TerminatorInst *PredTerm = PredBB->getTerminator();
1140 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1141 if (PredTerm->getSuccessor(i) == BB) {
1142 BB->removePredecessor(PredBB);
1143 PredTerm->setSuccessor(i, NewBB);
1144 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001145
1146 // At this point, the IR is fully up to date and consistent. Do a quick scan
1147 // over the new instructions and zap any that are constants or dead. This
1148 // frequently happens because of phi translation.
1149 BI = NewBB->begin();
1150 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1151 Instruction *Inst = BI++;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001152 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001153 Inst->replaceAllUsesWith(C);
1154 Inst->eraseFromParent();
1155 continue;
1156 }
1157
1158 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1159 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001160
1161 // Threaded an edge!
1162 ++NumThreads;
1163 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001164}
Chris Lattner78c552e2009-10-11 07:24:57 +00001165
1166/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1167/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1168/// If we can duplicate the contents of BB up into PredBB do so now, this
1169/// improves the odds that the branch will be on an analyzable instruction like
1170/// a compare.
1171bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1172 BasicBlock *PredBB) {
1173 // If BB is a loop header, then duplicating this block outside the loop would
1174 // cause us to transform this into an irreducible loop, don't do this.
1175 // See the comments above FindLoopHeaders for justifications and caveats.
1176 if (LoopHeaders.count(BB)) {
1177 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1178 << "' into predecessor block '" << PredBB->getName()
1179 << "' - it might create an irreducible loop!\n");
1180 return false;
1181 }
1182
1183 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1184 if (DuplicationCost > Threshold) {
1185 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1186 << "' - Cost is too high: " << DuplicationCost << "\n");
1187 return false;
1188 }
1189
1190 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1191 // of PredBB.
1192 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1193 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1194 << DuplicationCost << " block is:" << *BB << "\n");
1195
1196 // We are going to have to map operands from the original BB block into the
1197 // PredBB block. Evaluate PHI nodes in BB.
1198 DenseMap<Instruction*, Value*> ValueMapping;
1199
1200 BasicBlock::iterator BI = BB->begin();
1201 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1202 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1203
1204 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1205
1206 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1207 // mapping and using it to remap operands in the cloned instructions.
1208 for (; BI != BB->end(); ++BI) {
1209 Instruction *New = BI->clone();
1210 New->setName(BI->getName());
1211 PredBB->getInstList().insert(OldPredBranch, New);
1212 ValueMapping[BI] = New;
1213
1214 // Remap operands to patch up intra-block references.
1215 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1216 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1217 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1218 if (I != ValueMapping.end())
1219 New->setOperand(i, I->second);
1220 }
1221 }
1222
1223 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1224 // add entries to the PHI nodes for branch from PredBB now.
1225 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1226 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1227 ValueMapping);
1228 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1229 ValueMapping);
1230
1231 // If there were values defined in BB that are used outside the block, then we
1232 // now have to update all uses of the value to use either the original value,
1233 // the cloned value, or some PHI derived value. This can require arbitrary
1234 // PHI insertion, of which we are prepared to do, clean these up now.
1235 SSAUpdater SSAUpdate;
1236 SmallVector<Use*, 16> UsesToRename;
1237 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1238 // Scan all uses of this instruction to see if it is used outside of its
1239 // block, and if so, record them in UsesToRename.
1240 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1241 ++UI) {
1242 Instruction *User = cast<Instruction>(*UI);
1243 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1244 if (UserPN->getIncomingBlock(UI) == BB)
1245 continue;
1246 } else if (User->getParent() == BB)
1247 continue;
1248
1249 UsesToRename.push_back(&UI.getUse());
1250 }
1251
1252 // If there are no uses outside the block, we're done with this instruction.
1253 if (UsesToRename.empty())
1254 continue;
1255
1256 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1257
1258 // We found a use of I outside of BB. Rename all uses of I that are outside
1259 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1260 // with the two values we know.
1261 SSAUpdate.Initialize(I);
1262 SSAUpdate.AddAvailableValue(BB, I);
1263 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1264
1265 while (!UsesToRename.empty())
1266 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1267 DEBUG(errs() << "\n");
1268 }
1269
1270 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1271 // that we nuked.
1272 BB->removePredecessor(PredBB);
1273
1274 // Remove the unconditional branch at the end of the PredBB block.
1275 OldPredBranch->eraseFromParent();
1276
1277 ++NumDupes;
1278 return true;
1279}
1280
1281