blob: f52110f8851321850ad7720dafa89e09a44c5c6e [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);
Nick Lewycky9683f182009-06-19 04:56:29 +000078 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
Chris Lattner78567252009-11-06 18:15:14 +000079
80 typedef SmallVectorImpl<std::pair<ConstantInt*,
81 BasicBlock*> > PredValueInfo;
82
83 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
84 PredValueInfo &Result);
85 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB);
86
87
Chris Lattner421fa9e2008-12-03 07:48:08 +000088 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000089 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000090
Chris Lattnerd38c14e2008-04-22 06:36:15 +000091 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattner69e067f2008-11-27 05:07:53 +000092
93 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000094 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000095}
96
Dan Gohman844731a2008-05-13 00:00:25 +000097char JumpThreading::ID = 0;
98static RegisterPass<JumpThreading>
99X("jump-threading", "Jump Threading");
100
Chris Lattner8383a7b2008-04-20 20:35:01 +0000101// Public interface to the Jump Threading pass
102FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
103
104/// runOnFunction - Top level algorithm.
105///
106bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000107 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000108 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000109
Mike Stumpfe095f32009-05-04 18:40:41 +0000110 FindLoopHeaders(F);
111
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000112 bool AnotherIteration = true, EverChanged = false;
113 while (AnotherIteration) {
114 AnotherIteration = false;
115 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000116 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
117 BasicBlock *BB = I;
118 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000119 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000120
121 ++I;
122
123 // If the block is trivially dead, zap it. This eliminates the successor
124 // edges which simplifies the CFG.
125 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000126 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000127 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000128 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000129 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000130 DeleteDeadBlock(BB);
131 Changed = true;
132 }
133 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000134 AnotherIteration = Changed;
135 EverChanged |= Changed;
136 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000137
138 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000139 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000140}
Chris Lattner177480b2008-04-20 21:13:06 +0000141
Chris Lattner78c552e2009-10-11 07:24:57 +0000142/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
143/// thread across it.
144static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
145 /// Ignore PHI nodes, these will be flattened when duplication happens.
146 BasicBlock::const_iterator I = BB->getFirstNonPHI();
147
148 // Sum up the cost of each instruction until we get to the terminator. Don't
149 // include the terminator because the copy won't include it.
150 unsigned Size = 0;
151 for (; !isa<TerminatorInst>(I); ++I) {
152 // Debugger intrinsics don't incur code size.
153 if (isa<DbgInfoIntrinsic>(I)) continue;
154
155 // If this is a pointer->pointer bitcast, it is free.
156 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
157 continue;
158
159 // All other instructions count for at least one unit.
160 ++Size;
161
162 // Calls are more expensive. If they are non-intrinsic calls, we model them
163 // as having cost of 4. If they are a non-vector intrinsic, we model them
164 // as having cost of 2 total, and if they are a vector intrinsic, we model
165 // them as having cost 1.
166 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
167 if (!isa<IntrinsicInst>(CI))
168 Size += 3;
169 else if (!isa<VectorType>(CI->getType()))
170 Size += 1;
171 }
172 }
173
174 // Threading through a switch statement is particularly profitable. If this
175 // block ends in a switch, decrease its cost to make it more likely to happen.
176 if (isa<SwitchInst>(I))
177 Size = Size > 6 ? Size-6 : 0;
178
179 return Size;
180}
181
182
183
Mike Stumpfe095f32009-05-04 18:40:41 +0000184/// FindLoopHeaders - We do not want jump threading to turn proper loop
185/// structures into irreducible loops. Doing this breaks up the loop nesting
186/// hierarchy and pessimizes later transformations. To prevent this from
187/// happening, we first have to find the loop headers. Here we approximate this
188/// by finding targets of backedges in the CFG.
189///
190/// Note that there definitely are cases when we want to allow threading of
191/// edges across a loop header. For example, threading a jump from outside the
192/// loop (the preheader) to an exit block of the loop is definitely profitable.
193/// It is also almost always profitable to thread backedges from within the loop
194/// to exit blocks, and is often profitable to thread backedges to other blocks
195/// within the loop (forming a nested loop). This simple analysis is not rich
196/// enough to track all of these properties and keep it up-to-date as the CFG
197/// mutates, so we don't allow any of these transformations.
198///
199void JumpThreading::FindLoopHeaders(Function &F) {
200 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
201 FindFunctionBackedges(F, Edges);
202
203 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
204 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
205}
206
207
Chris Lattner6bf77502008-04-22 07:05:46 +0000208/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
209/// value for the PHI, factor them together so we get one block to thread for
210/// the whole group.
211/// This is important for things like "phi i1 [true, true, false, true, x]"
212/// where we only need to clone the block for the true blocks once.
213///
Nick Lewycky9683f182009-06-19 04:56:29 +0000214BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
Chris Lattner6bf77502008-04-22 07:05:46 +0000215 SmallVector<BasicBlock*, 16> CommonPreds;
216 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Nick Lewycky9683f182009-06-19 04:56:29 +0000217 if (PN->getIncomingValue(i) == Val)
Chris Lattner6bf77502008-04-22 07:05:46 +0000218 CommonPreds.push_back(PN->getIncomingBlock(i));
219
220 if (CommonPreds.size() == 1)
221 return CommonPreds[0];
222
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000223 DEBUG(errs() << " Factoring out " << CommonPreds.size()
224 << " common predecessors.\n");
Chris Lattner6bf77502008-04-22 07:05:46 +0000225 return SplitBlockPredecessors(PN->getParent(),
226 &CommonPreds[0], CommonPreds.size(),
227 ".thr_comm", this);
228}
Chris Lattner78567252009-11-06 18:15:14 +0000229
230/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
231/// hand sides of the compare instruction, try to determine the result. If the
232/// result can not be determined, a null pointer is returned.
233static Constant *GetResultOfComparison(CmpInst::Predicate pred,
234 Value *LHS, Value *RHS) {
235 if (Constant *CLHS = dyn_cast<Constant>(LHS))
236 if (Constant *CRHS = dyn_cast<Constant>(RHS))
237 return ConstantExpr::getCompare(pred, CLHS, CRHS);
Chris Lattner6bf77502008-04-22 07:05:46 +0000238
Chris Lattner78567252009-11-06 18:15:14 +0000239 if (LHS == RHS)
240 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
241 if (ICmpInst::isTrueWhenEqual(pred))
242 return ConstantInt::getTrue(LHS->getContext());
243 else
244 return ConstantInt::getFalse(LHS->getContext());
245 return 0;
246}
247
248
249/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
250/// if we can infer that the value is a known ConstantInt in any of our
251/// predecessors. If so, return the known the list of value and pred BB in the
252/// result vector. If a value is known to be undef, it is returned as null.
253///
254/// The BB basic block is known to start with a PHI node.
255///
256/// This returns true if there were any known values.
257///
258///
259/// TODO: Per PR2563, we could infer value range information about a predecessor
260/// based on its terminator.
261bool JumpThreading::
262ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
263 PHINode *TheFirstPHI = cast<PHINode>(BB->begin());
264
265 // If V is a constantint, then it is known in all predecessors.
266 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
267 ConstantInt *CI = dyn_cast<ConstantInt>(V);
268 Result.resize(TheFirstPHI->getNumIncomingValues());
269 for (unsigned i = 0, e = Result.size(); i != e; ++i)
270 Result.push_back(std::make_pair(CI, TheFirstPHI->getIncomingBlock(i)));
271 return true;
272 }
273
274 // If V is a non-instruction value, or an instruction in a different block,
275 // then it can't be derived from a PHI.
276 Instruction *I = dyn_cast<Instruction>(V);
277 if (I == 0 || I->getParent() != BB)
278 return false;
279
280 /// If I is a PHI node, then we know the incoming values for any constants.
281 if (PHINode *PN = dyn_cast<PHINode>(I)) {
282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
283 Value *InVal = PN->getIncomingValue(i);
284 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
285 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
286 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
287 }
288 }
289 return !Result.empty();
290 }
291
292 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
293
294 // Handle some boolean conditions.
295 if (I->getType()->getPrimitiveSizeInBits() == 1) {
296 // X | true -> true
297 // X & false -> false
298 if (I->getOpcode() == Instruction::Or ||
299 I->getOpcode() == Instruction::And) {
300 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
301 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
302
303 if (LHSVals.empty() && RHSVals.empty())
304 return false;
305
306 ConstantInt *InterestingVal;
307 if (I->getOpcode() == Instruction::Or)
308 InterestingVal = ConstantInt::getTrue(I->getContext());
309 else
310 InterestingVal = ConstantInt::getFalse(I->getContext());
311
312 // Scan for the sentinel.
313 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
314 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0)
315 Result.push_back(LHSVals[i]);
316 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
317 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0)
318 Result.push_back(RHSVals[i]);
319 return !Result.empty();
320 }
321
322 // TODO: Should handle the NOT form of XOR.
323
324 }
325
326 // Handle compare with phi operand, where the PHI is defined in this block.
327 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
328 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
329 if (PN && PN->getParent() == BB) {
330 // We can do this simplification if any comparisons fold to true or false.
331 // See if any do.
332 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
333 BasicBlock *PredBB = PN->getIncomingBlock(i);
334 Value *LHS = PN->getIncomingValue(i);
335 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
336
337 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), LHS, RHS);
338 if (Res == 0) continue;
339
340 if (isa<UndefValue>(Res))
341 Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
342 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
343 Result.push_back(std::make_pair(CI, PredBB));
344 }
345
346 return !Result.empty();
347 }
348
349 // TODO: We could also recurse to see if we can determine constants another
350 // way.
351 }
352 return false;
353}
354
355
Chris Lattner6bf77502008-04-22 07:05:46 +0000356
Chris Lattnere33583b2009-10-11 04:18:15 +0000357/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
358/// in an undefined jump, decide which block is best to revector to.
359///
360/// Since we can pick an arbitrary destination, we pick the successor with the
361/// fewest predecessors. This should reduce the in-degree of the others.
362///
363static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
364 TerminatorInst *BBTerm = BB->getTerminator();
365 unsigned MinSucc = 0;
366 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
367 // Compute the successor with the minimum number of predecessors.
368 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
369 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
370 TestBB = BBTerm->getSuccessor(i);
371 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
372 if (NumPreds < MinNumPreds)
373 MinSucc = i;
374 }
375
376 return MinSucc;
377}
378
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000379/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000380/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000381bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000382 // If this block has a single predecessor, and if that pred has a single
383 // successor, merge the blocks. This encourages recursive jump threading
384 // because now the condition in this block can be threaded through
385 // predecessors of our predecessor block.
Chris Lattner78567252009-11-06 18:15:14 +0000386 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000387 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
388 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000389 // If SinglePred was a loop header, BB becomes one.
390 if (LoopHeaders.erase(SinglePred))
391 LoopHeaders.insert(BB);
392
Chris Lattner3d86d242008-11-27 19:25:19 +0000393 // Remember if SinglePred was the entry block of the function. If so, we
394 // will need to move BB back to the entry position.
395 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000396 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000397
398 if (isEntry && BB != &BB->getParent()->getEntryBlock())
399 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000400 return true;
401 }
Chris Lattner78567252009-11-06 18:15:14 +0000402 }
403
404 // Look to see if the terminator is a branch of switch, if not we can't thread
405 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000406 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000407 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
408 // Can't thread an unconditional jump.
409 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000410 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000411 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000412 Condition = SI->getCondition();
413 else
414 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000415
416 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000417 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000418 // other blocks.
419 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000420 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000421 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000422 ++NumFolds;
423 ConstantFoldTerminator(BB);
424 return true;
425 }
426
Chris Lattner421fa9e2008-12-03 07:48:08 +0000427 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000428 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000429 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000430 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000431
432 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000433 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000434 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000435 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000436 BBTerm->getSuccessor(i)->removePredecessor(BB);
437 }
438
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000439 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000440 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000441 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000442 BBTerm->eraseFromParent();
443 return true;
444 }
445
446 Instruction *CondInst = dyn_cast<Instruction>(Condition);
447
448 // If the condition is an instruction defined in another block, see if a
449 // predecessor has the same condition:
450 // br COND, BBX, BBY
451 // BBX:
452 // br COND, BBZ, BBW
453 if (!Condition->hasOneUse() && // Multiple uses.
454 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
455 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
456 if (isa<BranchInst>(BB->getTerminator())) {
457 for (; PI != E; ++PI)
458 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
459 if (PBI->isConditional() && PBI->getCondition() == Condition &&
460 ProcessBranchOnDuplicateCond(*PI, BB))
461 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000462 } else {
463 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
464 for (; PI != E; ++PI)
465 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
466 if (PSI->getCondition() == Condition &&
467 ProcessSwitchOnDuplicateCond(*PI, BB))
468 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000469 }
470 }
471
Chris Lattner421fa9e2008-12-03 07:48:08 +0000472 // All the rest of our checks depend on the condition being an instruction.
473 if (CondInst == 0)
474 return false;
475
Chris Lattner177480b2008-04-20 21:13:06 +0000476 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000477 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
478 if (PN->getParent() == BB)
479 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000480
Nick Lewycky9683f182009-06-19 04:56:29 +0000481 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Chris Lattner90b92472009-11-06 18:24:32 +0000482 if (!isa<PHINode>(CondCmp->getOperand(0)) ||
483 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) {
484 // If we have a comparison, loop over the predecessors to see if there is
485 // a condition with a lexically identical value.
486 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
487 for (; PI != E; ++PI)
488 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
489 if (PBI->isConditional() && *PI != BB) {
490 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
491 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
492 CI->getOperand(1) == CondCmp->getOperand(1) &&
493 CI->getPredicate() == CondCmp->getPredicate()) {
494 // TODO: Could handle things like (x != 4) --> (x == 17)
495 if (ProcessBranchOnDuplicateCond(*PI, BB))
496 return true;
497 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000498 }
499 }
Chris Lattner90b92472009-11-06 18:24:32 +0000500 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000501 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000502
503 // Check for some cases that are worth simplifying. Right now we want to look
504 // for loads that are used by a switch or by the condition for the branch. If
505 // we see one, check to see if it's partially redundant. If so, insert a PHI
506 // which can then be used to thread the values.
507 //
508 // This is particularly important because reg2mem inserts loads and stores all
509 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000510 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000511 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
512 if (isa<Constant>(CondCmp->getOperand(1)))
513 SimplifyValue = CondCmp->getOperand(0);
514
515 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
516 if (SimplifyPartiallyRedundantLoad(LI))
517 return true;
518
Chris Lattner78567252009-11-06 18:15:14 +0000519
520 // Handle a variety of cases where we are branching on something derived from
521 // a PHI node in the current block. If we can prove that any predecessors
522 // compute a predictable value based on a PHI node, thread those predecessors.
523 //
524 // We only bother doing this if the current block has a PHI node and if the
525 // conditional instruction lives in the current block. If either condition
526 // fail, this won't be a computable value anyway.
527 if (CondInst->getParent() == BB && isa<PHINode>(BB->front()))
528 if (ProcessThreadableEdges(CondInst, BB))
529 return true;
530
531
Chris Lattner69e067f2008-11-27 05:07:53 +0000532 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
533 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000534
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000535 return false;
536}
537
Chris Lattner421fa9e2008-12-03 07:48:08 +0000538/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
539/// block that jump on exactly the same condition. This means that we almost
540/// always know the direction of the edge in the DESTBB:
541/// PREDBB:
542/// br COND, DESTBB, BBY
543/// DESTBB:
544/// br COND, BBZ, BBW
545///
546/// If DESTBB has multiple predecessors, we can't just constant fold the branch
547/// in DESTBB, we have to thread over it.
548bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
549 BasicBlock *BB) {
550 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
551
552 // If both successors of PredBB go to DESTBB, we don't know anything. We can
553 // fold the branch to an unconditional one, which allows other recursive
554 // simplifications.
555 bool BranchDir;
556 if (PredBI->getSuccessor(1) != BB)
557 BranchDir = true;
558 else if (PredBI->getSuccessor(0) != BB)
559 BranchDir = false;
560 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000561 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000562 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000563 ++NumFolds;
564 ConstantFoldTerminator(PredBB);
565 return true;
566 }
567
568 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
569
570 // If the dest block has one predecessor, just fix the branch condition to a
571 // constant and fold it.
572 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000573 DEBUG(errs() << " In block '" << BB->getName()
574 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000575 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000576 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000577 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000578 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
579 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000580 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000581 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000582 return true;
583 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000584
Chris Lattner421fa9e2008-12-03 07:48:08 +0000585
586 // Next, figure out which successor we are threading to.
587 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
588
Mike Stumpfe095f32009-05-04 18:40:41 +0000589 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000590 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000591}
592
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000593/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
594/// block that switch on exactly the same condition. This means that we almost
595/// always know the direction of the edge in the DESTBB:
596/// PREDBB:
597/// switch COND [... DESTBB, BBY ... ]
598/// DESTBB:
599/// switch COND [... BBZ, BBW ]
600///
601/// Optimizing switches like this is very important, because simplifycfg builds
602/// switches out of repeated 'if' conditions.
603bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
604 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000605 // Can't thread edge to self.
606 if (PredBB == DestBB)
607 return false;
608
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000609 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
610 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
611
612 // There are a variety of optimizations that we can potentially do on these
613 // blocks: we order them from most to least preferable.
614
615 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
616 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000617 // growth. Skip debug info first.
618 BasicBlock::iterator BBI = DestBB->begin();
619 while (isa<DbgInfoIntrinsic>(BBI))
620 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000621
622 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000623 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000624 bool MadeChange = false;
625 // Ignore the default edge for now.
626 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
627 ConstantInt *DestVal = DestSI->getCaseValue(i);
628 BasicBlock *DestSucc = DestSI->getSuccessor(i);
629
630 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
631 // PredSI has an explicit case for it. If so, forward. If it is covered
632 // by the default case, we can't update PredSI.
633 unsigned PredCase = PredSI->findCaseValue(DestVal);
634 if (PredCase == 0) continue;
635
636 // If PredSI doesn't go to DestBB on this value, then it won't reach the
637 // case on this condition.
638 if (PredSI->getSuccessor(PredCase) != DestBB &&
639 DestSI->getSuccessor(i) != DestBB)
640 continue;
641
642 // Otherwise, we're safe to make the change. Make sure that the edge from
643 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000644 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
645 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000646
647 // If the destination has PHI nodes, just split the edge for updating
648 // simplicity.
649 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
650 SplitCriticalEdge(DestSI, i, this);
651 DestSucc = DestSI->getSuccessor(i);
652 }
653 FoldSingleEntryPHINodes(DestSucc);
654 PredSI->setSuccessor(PredCase, DestSucc);
655 MadeChange = true;
656 }
657
658 if (MadeChange)
659 return true;
660 }
661
662 return false;
663}
664
665
Chris Lattner69e067f2008-11-27 05:07:53 +0000666/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
667/// load instruction, eliminate it by replacing it with a PHI node. This is an
668/// important optimization that encourages jump threading, and needs to be run
669/// interlaced with other jump threading tasks.
670bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
671 // Don't hack volatile loads.
672 if (LI->isVolatile()) return false;
673
674 // If the load is defined in a block with exactly one predecessor, it can't be
675 // partially redundant.
676 BasicBlock *LoadBB = LI->getParent();
677 if (LoadBB->getSinglePredecessor())
678 return false;
679
680 Value *LoadedPtr = LI->getOperand(0);
681
682 // If the loaded operand is defined in the LoadBB, it can't be available.
683 // FIXME: Could do PHI translation, that would be fun :)
684 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
685 if (PtrOp->getParent() == LoadBB)
686 return false;
687
688 // Scan a few instructions up from the load, to see if it is obviously live at
689 // the entry to its block.
690 BasicBlock::iterator BBIt = LI;
691
Chris Lattner52c95852008-11-27 08:10:05 +0000692 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
693 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000694 // If the value if the load is locally available within the block, just use
695 // it. This frequently occurs for reg2mem'd allocas.
696 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000697
698 // If the returned value is the load itself, replace with an undef. This can
699 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000700 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000701 LI->replaceAllUsesWith(AvailableVal);
702 LI->eraseFromParent();
703 return true;
704 }
705
706 // Otherwise, if we scanned the whole block and got to the top of the block,
707 // we know the block is locally transparent to the load. If not, something
708 // might clobber its value.
709 if (BBIt != LoadBB->begin())
710 return false;
711
712
713 SmallPtrSet<BasicBlock*, 8> PredsScanned;
714 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
715 AvailablePredsTy AvailablePreds;
716 BasicBlock *OneUnavailablePred = 0;
717
718 // If we got here, the loaded value is transparent through to the start of the
719 // block. Check to see if it is available in any of the predecessor blocks.
720 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
721 PI != PE; ++PI) {
722 BasicBlock *PredBB = *PI;
723
724 // If we already scanned this predecessor, skip it.
725 if (!PredsScanned.insert(PredBB))
726 continue;
727
728 // Scan the predecessor to see if the value is available in the pred.
729 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000730 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000731 if (!PredAvailable) {
732 OneUnavailablePred = PredBB;
733 continue;
734 }
735
736 // If so, this load is partially redundant. Remember this info so that we
737 // can create a PHI node.
738 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
739 }
740
741 // If the loaded value isn't available in any predecessor, it isn't partially
742 // redundant.
743 if (AvailablePreds.empty()) return false;
744
745 // Okay, the loaded value is available in at least one (and maybe all!)
746 // predecessors. If the value is unavailable in more than one unique
747 // predecessor, we want to insert a merge block for those common predecessors.
748 // This ensures that we only have to insert one reload, thus not increasing
749 // code size.
750 BasicBlock *UnavailablePred = 0;
751
752 // If there is exactly one predecessor where the value is unavailable, the
753 // already computed 'OneUnavailablePred' block is it. If it ends in an
754 // unconditional branch, we know that it isn't a critical edge.
755 if (PredsScanned.size() == AvailablePreds.size()+1 &&
756 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
757 UnavailablePred = OneUnavailablePred;
758 } else if (PredsScanned.size() != AvailablePreds.size()) {
759 // Otherwise, we had multiple unavailable predecessors or we had a critical
760 // edge from the one.
761 SmallVector<BasicBlock*, 8> PredsToSplit;
762 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
763
764 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
765 AvailablePredSet.insert(AvailablePreds[i].first);
766
767 // Add all the unavailable predecessors to the PredsToSplit list.
768 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
769 PI != PE; ++PI)
770 if (!AvailablePredSet.count(*PI))
771 PredsToSplit.push_back(*PI);
772
773 // Split them out to their own block.
774 UnavailablePred =
775 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
776 "thread-split", this);
777 }
778
779 // If the value isn't available in all predecessors, then there will be
780 // exactly one where it isn't available. Insert a load on that edge and add
781 // it to the AvailablePreds list.
782 if (UnavailablePred) {
783 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
784 "Can't handle critical edge here!");
785 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
786 UnavailablePred->getTerminator());
787 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
788 }
789
790 // Now we know that each predecessor of this block has a value in
791 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000792 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000793
794 // Create a PHI node at the start of the block for the PRE'd load value.
795 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
796 PN->takeName(LI);
797
798 // Insert new entries into the PHI for each predecessor. A single block may
799 // have multiple entries here.
800 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
801 ++PI) {
802 AvailablePredsTy::iterator I =
803 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
804 std::make_pair(*PI, (Value*)0));
805
806 assert(I != AvailablePreds.end() && I->first == *PI &&
807 "Didn't find entry for predecessor!");
808
809 PN->addIncoming(I->second, I->first);
810 }
811
812 //cerr << "PRE: " << *LI << *PN << "\n";
813
814 LI->replaceAllUsesWith(PN);
815 LI->eraseFromParent();
816
817 return true;
818}
819
Chris Lattner78567252009-11-06 18:15:14 +0000820/// FindMostPopularDest - The specified list contains multiple possible
821/// threadable destinations. Pick the one that occurs the most frequently in
822/// the list.
823static BasicBlock *
824FindMostPopularDest(BasicBlock *BB,
825 const SmallVectorImpl<std::pair<BasicBlock*,
826 BasicBlock*> > &PredToDestList) {
827 assert(!PredToDestList.empty());
828
829 // Determine popularity. If there are multiple possible destinations, we
830 // explicitly choose to ignore 'undef' destinations. We prefer to thread
831 // blocks with known and real destinations to threading undef. We'll handle
832 // them later if interesting.
833 DenseMap<BasicBlock*, unsigned> DestPopularity;
834 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
835 if (PredToDestList[i].second)
836 DestPopularity[PredToDestList[i].second]++;
837
838 // Find the most popular dest.
839 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
840 BasicBlock *MostPopularDest = DPI->first;
841 unsigned Popularity = DPI->second;
842 SmallVector<BasicBlock*, 4> SamePopularity;
843
844 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
845 // If the popularity of this entry isn't higher than the popularity we've
846 // seen so far, ignore it.
847 if (DPI->second < Popularity)
848 ; // ignore.
849 else if (DPI->second == Popularity) {
850 // If it is the same as what we've seen so far, keep track of it.
851 SamePopularity.push_back(DPI->first);
852 } else {
853 // If it is more popular, remember it.
854 SamePopularity.clear();
855 MostPopularDest = DPI->first;
856 Popularity = DPI->second;
857 }
858 }
859
860 // Okay, now we know the most popular destination. If there is more than
861 // destination, we need to determine one. This is arbitrary, but we need
862 // to make a deterministic decision. Pick the first one that appears in the
863 // successor list.
864 if (!SamePopularity.empty()) {
865 SamePopularity.push_back(MostPopularDest);
866 TerminatorInst *TI = BB->getTerminator();
867 for (unsigned i = 0; ; ++i) {
868 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
869
870 if (std::find(SamePopularity.begin(), SamePopularity.end(),
871 TI->getSuccessor(i)) == SamePopularity.end())
872 continue;
873
874 MostPopularDest = TI->getSuccessor(i);
875 break;
876 }
877 }
878
879 // Okay, we have finally picked the most popular destination.
880 return MostPopularDest;
881}
882
883bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst,
884 BasicBlock *BB) {
885 // If threading this would thread across a loop header, don't even try to
886 // thread the edge.
887 if (LoopHeaders.count(BB))
888 return false;
889
890
891
892 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
893 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues))
894 return false;
895 assert(!PredValues.empty() &&
896 "ComputeValueKnownInPredecessors returned true with no values");
897
898 DEBUG(errs() << "IN BB: " << *BB;
899 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
900 errs() << " BB '" << BB->getName() << "': FOUND condition = ";
901 if (PredValues[i].first)
902 errs() << *PredValues[i].first;
903 else
904 errs() << "UNDEF";
905 errs() << " for pred '" << PredValues[i].second->getName()
906 << "'.\n";
907 });
908
909 // Decide what we want to thread through. Convert our list of known values to
910 // a list of known destinations for each pred. This also discards duplicate
911 // predecessors and keeps track of the undefined inputs (which are represented
912 // as a null dest in the PredToDestList.
913 SmallPtrSet<BasicBlock*, 16> SeenPreds;
914 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
915
916 BasicBlock *OnlyDest = 0;
917 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
918
919 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
920 BasicBlock *Pred = PredValues[i].second;
921 if (!SeenPreds.insert(Pred))
922 continue; // Duplicate predecessor entry.
923
924 // If the predecessor ends with an indirect goto, we can't change its
925 // destination.
926 if (isa<IndirectBrInst>(Pred->getTerminator()))
927 continue;
928
929 ConstantInt *Val = PredValues[i].first;
930
931 BasicBlock *DestBB;
932 if (Val == 0) // Undef.
933 DestBB = 0;
934 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
935 DestBB = BI->getSuccessor(Val->isZero());
936 else {
937 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
938 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
939 }
940
941 // If we have exactly one destination, remember it for efficiency below.
942 if (i == 0)
943 OnlyDest = DestBB;
944 else if (OnlyDest != DestBB)
945 OnlyDest = MultipleDestSentinel;
946
947 PredToDestList.push_back(std::make_pair(Pred, DestBB));
948 }
949
950 // If all edges were unthreadable, we fail.
951 if (PredToDestList.empty())
952 return false;
953
954 // Determine which is the most common successor. If we have many inputs and
955 // this block is a switch, we want to start by threading the batch that goes
956 // to the most popular destination first. If we only know about one
957 // threadable destination (the common case) we can avoid this.
958 BasicBlock *MostPopularDest = OnlyDest;
959
960 if (MostPopularDest == MultipleDestSentinel)
961 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
962
963 // Now that we know what the most popular destination is, factor all
964 // predecessors that will jump to it into a single predecessor.
965 SmallVector<BasicBlock*, 16> PredsToFactor;
966 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
967 if (PredToDestList[i].second == MostPopularDest)
968 PredsToFactor.push_back(PredToDestList[i].first);
969
970 BasicBlock *PredToThread;
971 if (PredsToFactor.size() == 1)
972 PredToThread = PredsToFactor[0];
973 else {
974 DEBUG(errs() << " Factoring out " << PredsToFactor.size()
975 << " common predecessors.\n");
976 PredToThread = SplitBlockPredecessors(BB, &PredsToFactor[0],
977 PredsToFactor.size(),
978 ".thr_comm", this);
979 }
980
981 // If the threadable edges are branching on an undefined value, we get to pick
982 // the destination that these predecessors should get to.
983 if (MostPopularDest == 0)
984 MostPopularDest = BB->getTerminator()->
985 getSuccessor(GetBestDestForJumpOnUndef(BB));
986
987 // Ok, try to thread it!
988 return ThreadEdge(BB, PredToThread, MostPopularDest);
989}
Chris Lattner69e067f2008-11-27 05:07:53 +0000990
Chris Lattnere33583b2009-10-11 04:18:15 +0000991/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000992/// the current block. See if there are any simplifications we can do based on
993/// inputs to the phi node.
994///
995bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000996 BasicBlock *BB = PN->getParent();
997
Chris Lattnerf7807f62009-11-06 18:22:54 +0000998 // If any of the predecessor blocks end in an unconditional branch, we can
999 // *duplicate* the jump into that block in order to further encourage jump
1000 // threading and to eliminate cases where we have branch on a phi of an icmp
1001 // (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +00001002
1003 // We don't want to do this tranformation for switches, because we don't
1004 // really want to duplicate a switch.
1005 if (isa<SwitchInst>(BB->getTerminator()))
1006 return false;
1007
1008 // Look for unconditional branch predecessors.
1009 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1010 BasicBlock *PredBB = PN->getIncomingBlock(i);
1011 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1012 if (PredBr->isUnconditional() &&
1013 // Try to duplicate BB into PredBB.
1014 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
1015 return true;
1016 }
1017
Chris Lattner6b65f472009-10-11 04:40:21 +00001018 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001019}
1020
Chris Lattnera5ddb592008-04-22 21:40:39 +00001021
Chris Lattner78c552e2009-10-11 07:24:57 +00001022/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1023/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1024/// NewPred using the entries from OldPred (suitably mapped).
1025static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1026 BasicBlock *OldPred,
1027 BasicBlock *NewPred,
1028 DenseMap<Instruction*, Value*> &ValueMap) {
1029 for (BasicBlock::iterator PNI = PHIBB->begin();
1030 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1031 // Ok, we have a PHI node. Figure out what the incoming value was for the
1032 // DestBlock.
1033 Value *IV = PN->getIncomingValueForBlock(OldPred);
1034
1035 // Remap the value if necessary.
1036 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1037 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1038 if (I != ValueMap.end())
1039 IV = I->second;
1040 }
1041
1042 PN->addIncoming(IV, NewPred);
1043 }
1044}
Chris Lattner6bf77502008-04-22 07:05:46 +00001045
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001046/// ThreadEdge - We have decided that it is safe and profitable to thread an
1047/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
1048/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +00001049bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001050 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001051 // If threading to the same block as we come from, we would infinite loop.
1052 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001053 DEBUG(errs() << " Not threading across BB '" << BB->getName()
1054 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001055 return false;
1056 }
1057
1058 // If threading this would thread across a loop header, don't thread the edge.
1059 // See the comments above FindLoopHeaders for justifications and caveats.
1060 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001061 DEBUG(errs() << " Not threading from '" << PredBB->getName()
1062 << "' across loop header BB '" << BB->getName()
1063 << "' to dest BB '" << SuccBB->getName()
1064 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001065 return false;
1066 }
1067
Chris Lattner78c552e2009-10-11 07:24:57 +00001068 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1069 if (JumpThreadCost > Threshold) {
1070 DEBUG(errs() << " Not threading BB '" << BB->getName()
1071 << "' - Cost is too high: " << JumpThreadCost << "\n");
1072 return false;
1073 }
1074
Mike Stumpfe095f32009-05-04 18:40:41 +00001075 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001076 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001077 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001078 << ", across block:\n "
1079 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001080
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001081 // We are going to have to map operands from the original BB block to the new
1082 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1083 // account for entry from PredBB.
1084 DenseMap<Instruction*, Value*> ValueMapping;
1085
Owen Anderson1d0be152009-08-13 21:58:54 +00001086 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1087 BB->getName()+".thread",
1088 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001089 NewBB->moveAfter(PredBB);
1090
1091 BasicBlock::iterator BI = BB->begin();
1092 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1093 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1094
1095 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1096 // mapping and using it to remap operands in the cloned instructions.
1097 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001098 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001099 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001100 NewBB->getInstList().push_back(New);
1101 ValueMapping[BI] = New;
1102
1103 // Remap operands to patch up intra-block references.
1104 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001105 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1106 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1107 if (I != ValueMapping.end())
1108 New->setOperand(i, I->second);
1109 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001110 }
1111
1112 // We didn't copy the terminator from BB over to NewBB, because there is now
1113 // an unconditional jump to SuccBB. Insert the unconditional jump.
1114 BranchInst::Create(SuccBB, NewBB);
1115
1116 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1117 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001118 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001119
Chris Lattner433a0db2009-10-10 09:05:58 +00001120 // If there were values defined in BB that are used outside the block, then we
1121 // now have to update all uses of the value to use either the original value,
1122 // the cloned value, or some PHI derived value. This can require arbitrary
1123 // PHI insertion, of which we are prepared to do, clean these up now.
1124 SSAUpdater SSAUpdate;
1125 SmallVector<Use*, 16> UsesToRename;
1126 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1127 // Scan all uses of this instruction to see if it is used outside of its
1128 // block, and if so, record them in UsesToRename.
1129 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1130 ++UI) {
1131 Instruction *User = cast<Instruction>(*UI);
1132 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1133 if (UserPN->getIncomingBlock(UI) == BB)
1134 continue;
1135 } else if (User->getParent() == BB)
1136 continue;
1137
1138 UsesToRename.push_back(&UI.getUse());
1139 }
1140
1141 // If there are no uses outside the block, we're done with this instruction.
1142 if (UsesToRename.empty())
1143 continue;
1144
1145 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1146
1147 // We found a use of I outside of BB. Rename all uses of I that are outside
1148 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1149 // with the two values we know.
1150 SSAUpdate.Initialize(I);
1151 SSAUpdate.AddAvailableValue(BB, I);
1152 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1153
1154 while (!UsesToRename.empty())
1155 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1156 DEBUG(errs() << "\n");
1157 }
1158
1159
Chris Lattneref0c6742008-12-01 04:48:07 +00001160 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001161 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1162 // us to simplify any PHI nodes in BB.
1163 TerminatorInst *PredTerm = PredBB->getTerminator();
1164 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1165 if (PredTerm->getSuccessor(i) == BB) {
1166 BB->removePredecessor(PredBB);
1167 PredTerm->setSuccessor(i, NewBB);
1168 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001169
1170 // At this point, the IR is fully up to date and consistent. Do a quick scan
1171 // over the new instructions and zap any that are constants or dead. This
1172 // frequently happens because of phi translation.
1173 BI = NewBB->begin();
1174 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1175 Instruction *Inst = BI++;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001176 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001177 Inst->replaceAllUsesWith(C);
1178 Inst->eraseFromParent();
1179 continue;
1180 }
1181
1182 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1183 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001184
1185 // Threaded an edge!
1186 ++NumThreads;
1187 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001188}
Chris Lattner78c552e2009-10-11 07:24:57 +00001189
1190/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1191/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1192/// If we can duplicate the contents of BB up into PredBB do so now, this
1193/// improves the odds that the branch will be on an analyzable instruction like
1194/// a compare.
1195bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1196 BasicBlock *PredBB) {
1197 // If BB is a loop header, then duplicating this block outside the loop would
1198 // cause us to transform this into an irreducible loop, don't do this.
1199 // See the comments above FindLoopHeaders for justifications and caveats.
1200 if (LoopHeaders.count(BB)) {
1201 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1202 << "' into predecessor block '" << PredBB->getName()
1203 << "' - it might create an irreducible loop!\n");
1204 return false;
1205 }
1206
1207 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1208 if (DuplicationCost > Threshold) {
1209 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1210 << "' - Cost is too high: " << DuplicationCost << "\n");
1211 return false;
1212 }
1213
1214 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1215 // of PredBB.
1216 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1217 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1218 << DuplicationCost << " block is:" << *BB << "\n");
1219
1220 // We are going to have to map operands from the original BB block into the
1221 // PredBB block. Evaluate PHI nodes in BB.
1222 DenseMap<Instruction*, Value*> ValueMapping;
1223
1224 BasicBlock::iterator BI = BB->begin();
1225 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1226 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1227
1228 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1229
1230 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1231 // mapping and using it to remap operands in the cloned instructions.
1232 for (; BI != BB->end(); ++BI) {
1233 Instruction *New = BI->clone();
1234 New->setName(BI->getName());
1235 PredBB->getInstList().insert(OldPredBranch, New);
1236 ValueMapping[BI] = New;
1237
1238 // Remap operands to patch up intra-block references.
1239 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1240 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1241 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1242 if (I != ValueMapping.end())
1243 New->setOperand(i, I->second);
1244 }
1245 }
1246
1247 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1248 // add entries to the PHI nodes for branch from PredBB now.
1249 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1250 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1251 ValueMapping);
1252 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1253 ValueMapping);
1254
1255 // If there were values defined in BB that are used outside the block, then we
1256 // now have to update all uses of the value to use either the original value,
1257 // the cloned value, or some PHI derived value. This can require arbitrary
1258 // PHI insertion, of which we are prepared to do, clean these up now.
1259 SSAUpdater SSAUpdate;
1260 SmallVector<Use*, 16> UsesToRename;
1261 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1262 // Scan all uses of this instruction to see if it is used outside of its
1263 // block, and if so, record them in UsesToRename.
1264 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1265 ++UI) {
1266 Instruction *User = cast<Instruction>(*UI);
1267 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1268 if (UserPN->getIncomingBlock(UI) == BB)
1269 continue;
1270 } else if (User->getParent() == BB)
1271 continue;
1272
1273 UsesToRename.push_back(&UI.getUse());
1274 }
1275
1276 // If there are no uses outside the block, we're done with this instruction.
1277 if (UsesToRename.empty())
1278 continue;
1279
1280 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1281
1282 // We found a use of I outside of BB. Rename all uses of I that are outside
1283 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1284 // with the two values we know.
1285 SSAUpdate.Initialize(I);
1286 SSAUpdate.AddAvailableValue(BB, I);
1287 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1288
1289 while (!UsesToRename.empty())
1290 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1291 DEBUG(errs() << "\n");
1292 }
1293
1294 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1295 // that we nuked.
1296 BB->removePredecessor(PredBB);
1297
1298 // Remove the unconditional branch at the end of the PredBB block.
1299 OldPredBranch->eraseFromParent();
1300
1301 ++NumDupes;
1302 return true;
1303}
1304
1305