blob: 6fd8ed10efffe0598419192c92961ea08040b880 [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 Lattner9819ef72009-11-09 23:00:14 +000019#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000020#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohmandd9344f2010-05-28 16:19:17 +000021#include "llvm/Analysis/Loads.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000023#include "llvm/Transforms/Utils/Local.h"
Chris Lattner433a0db2009-10-10 09:05:58 +000024#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000025#include "llvm/Target/TargetData.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000026#include "llvm/ADT/DenseMap.h"
Owen Andersoncb211902010-08-31 07:36:34 +000027#include "llvm/ADT/DenseSet.h"
Mike Stumpfe095f32009-05-04 18:40:41 +000028#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000032#include "llvm/Support/CommandLine.h"
Chris Lattner177480b2008-04-20 21:13:06 +000033#include "llvm/Support/Debug.h"
Chris Lattner56608462009-12-28 08:20:46 +000034#include "llvm/Support/ValueHandle.h"
Daniel Dunbar93b67e42009-07-26 07:49:05 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000036using namespace llvm;
37
Chris Lattnerbd3401f2008-04-20 22:39:42 +000038STATISTIC(NumThreads, "Number of jumps threaded");
39STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner78c552e2009-10-11 07:24:57 +000040STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
Chris Lattner8383a7b2008-04-20 20:35:01 +000041
Chris Lattner177480b2008-04-20 21:13:06 +000042static cl::opt<unsigned>
43Threshold("jump-threading-threshold",
44 cl::desc("Max block size to duplicate for jump threading"),
45 cl::init(6), cl::Hidden);
46
Chris Lattnercc4d3b22009-11-11 02:08:33 +000047// Turn on use of LazyValueInfo.
48static cl::opt<bool>
Owen Andersonf35b08d2010-08-05 22:11:31 +000049EnableLVI("enable-jump-threading-lvi",
50 cl::desc("Use LVI for jump threading"),
Owen Anderson53c36c42010-08-24 17:21:18 +000051 cl::init(true),
Owen Andersonf35b08d2010-08-05 22:11:31 +000052 cl::ReallyHidden);
Chris Lattnercc4d3b22009-11-11 02:08:33 +000053
54
55
Chris Lattner8383a7b2008-04-20 20:35:01 +000056namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000057 /// This pass performs 'jump threading', which looks at blocks that have
58 /// multiple predecessors and multiple successors. If one or more of the
59 /// predecessors of the block can be proven to always jump to one of the
60 /// successors, we forward the edge from the predecessor to the successor by
61 /// duplicating the contents of this block.
62 ///
63 /// An example of when this can occur is code like this:
64 ///
65 /// if () { ...
66 /// X = 4;
67 /// }
68 /// if (X < 3) {
69 ///
70 /// In this case, the unconditional branch at the end of the first if can be
71 /// revectored to the false side of the second if.
72 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +000073 class JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000074 TargetData *TD;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000075 LazyValueInfo *LVI;
Mike Stumpfe095f32009-05-04 18:40:41 +000076#ifdef NDEBUG
77 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
78#else
79 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
80#endif
Owen Andersoncb211902010-08-31 07:36:34 +000081 DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
Owen Anderson9ba35362010-08-31 19:24:27 +000082
83 // RAII helper for updating the recursion stack.
84 struct RecursionSetRemover {
85 DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
86 std::pair<Value*, BasicBlock*> ThePair;
87
88 RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
89 std::pair<Value*, BasicBlock*> P)
90 : TheSet(S), ThePair(P) { }
91
92 ~RecursionSetRemover() {
93 TheSet.erase(ThePair);
94 }
95 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000096 public:
97 static char ID; // Pass identification
Owen Anderson90c579d2010-08-06 18:33:48 +000098 JumpThreading() : FunctionPass(ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000099
100 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +0000101
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000102 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson9bfa6fe2010-09-01 18:27:22 +0000103 if (EnableLVI) {
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000104 AU.addRequired<LazyValueInfo>();
Owen Anderson9bfa6fe2010-09-01 18:27:22 +0000105 AU.addPreserved<LazyValueInfo>();
106 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000107 }
108
109 void FindLoopHeaders(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000110 bool ProcessBlock(BasicBlock *BB);
Chris Lattner5729d382009-11-07 08:05:03 +0000111 bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
112 BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +0000113 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
Chris Lattner2249a0b2010-01-12 02:07:17 +0000114 const SmallVectorImpl<BasicBlock *> &PredBBs);
Chris Lattner5729d382009-11-07 08:05:03 +0000115
116 typedef SmallVectorImpl<std::pair<ConstantInt*,
117 BasicBlock*> > PredValueInfo;
118
119 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
120 PredValueInfo &Result);
Chris Lattner1c96b412009-11-12 01:37:43 +0000121 bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB);
Chris Lattner5729d382009-11-07 08:05:03 +0000122
123
Chris Lattner421fa9e2008-12-03 07:48:08 +0000124 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000125 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +0000126
Chris Lattner77beb472010-01-11 23:41:09 +0000127 bool ProcessBranchOnPHI(PHINode *PN);
Chris Lattner2249a0b2010-01-12 02:07:17 +0000128 bool ProcessBranchOnXOR(BinaryOperator *BO);
Chris Lattner69e067f2008-11-27 05:07:53 +0000129
130 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +0000131 };
Chris Lattner8383a7b2008-04-20 20:35:01 +0000132}
133
Dan Gohman844731a2008-05-13 00:00:25 +0000134char JumpThreading::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000135INITIALIZE_PASS(JumpThreading, "jump-threading",
136 "Jump Threading", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +0000137
Chris Lattner8383a7b2008-04-20 20:35:01 +0000138// Public interface to the Jump Threading pass
139FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
140
141/// runOnFunction - Top level algorithm.
142///
143bool JumpThreading::runOnFunction(Function &F) {
David Greenefe7fe662010-01-05 01:27:19 +0000144 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000145 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000146 LVI = EnableLVI ? &getAnalysis<LazyValueInfo>() : 0;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000147
Mike Stumpfe095f32009-05-04 18:40:41 +0000148 FindLoopHeaders(F);
149
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000150 bool Changed, EverChanged = false;
151 do {
152 Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000153 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
154 BasicBlock *BB = I;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000155 // Thread all of the branches we can over this block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000156 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000157 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000158
159 ++I;
160
161 // If the block is trivially dead, zap it. This eliminates the successor
162 // edges which simplifies the CFG.
163 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000164 BB != &BB->getParent()->getEntryBlock()) {
David Greenefe7fe662010-01-05 01:27:19 +0000165 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000166 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000167 LoopHeaders.erase(BB);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000168 if (LVI) LVI->eraseBlock(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000169 DeleteDeadBlock(BB);
170 Changed = true;
Chris Lattnerf3183f62009-11-10 21:40:01 +0000171 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
172 // Can't thread an unconditional jump, but if the block is "almost
173 // empty", we can replace uses of it with uses of the successor and make
174 // this dead.
175 if (BI->isUnconditional() &&
176 BB != &BB->getParent()->getEntryBlock()) {
177 BasicBlock::iterator BBI = BB->getFirstNonPHI();
178 // Ignore dbg intrinsics.
179 while (isa<DbgInfoIntrinsic>(BBI))
180 ++BBI;
181 // If the terminator is the only non-phi instruction, try to nuke it.
182 if (BBI->isTerminator()) {
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000183 // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
184 // block, we have to make sure it isn't in the LoopHeaders set. We
Chris Lattner46875c02009-12-01 06:04:43 +0000185 // reinsert afterward if needed.
Chris Lattner6f84a5f2009-11-10 21:45:09 +0000186 bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000187 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerf3183f62009-11-10 21:40:01 +0000188
Owen Anderson00ac77e2010-08-18 18:39:01 +0000189 // FIXME: It is always conservatively correct to drop the info
190 // for a block even if it doesn't get erased. This isn't totally
191 // awesome, but it allows us to use AssertingVH to prevent nasty
192 // dangling pointer issues within LazyValueInfo.
193 if (LVI) LVI->eraseBlock(BB);
Chris Lattner46875c02009-12-01 06:04:43 +0000194 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
Chris Lattnerf3183f62009-11-10 21:40:01 +0000195 Changed = true;
Chris Lattner46875c02009-12-01 06:04:43 +0000196 // If we deleted BB and BB was the header of a loop, then the
197 // successor is now the header of the loop.
198 BB = Succ;
199 }
200
201 if (ErasedFromLoopHeaders)
Chris Lattnerf3183f62009-11-10 21:40:01 +0000202 LoopHeaders.insert(BB);
203 }
204 }
Chris Lattner421fa9e2008-12-03 07:48:08 +0000205 }
206 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000207 EverChanged |= Changed;
Benjamin Kramer66b581e2010-01-07 13:50:07 +0000208 } while (Changed);
Mike Stumpfe095f32009-05-04 18:40:41 +0000209
210 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000211 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000212}
Chris Lattner177480b2008-04-20 21:13:06 +0000213
Chris Lattner78c552e2009-10-11 07:24:57 +0000214/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
215/// thread across it.
216static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
217 /// Ignore PHI nodes, these will be flattened when duplication happens.
218 BasicBlock::const_iterator I = BB->getFirstNonPHI();
219
Chris Lattnerb14b88a2009-11-11 00:21:58 +0000220 // FIXME: THREADING will delete values that are just used to compute the
221 // branch, so they shouldn't count against the duplication cost.
222
223
Chris Lattner78c552e2009-10-11 07:24:57 +0000224 // Sum up the cost of each instruction until we get to the terminator. Don't
225 // include the terminator because the copy won't include it.
226 unsigned Size = 0;
227 for (; !isa<TerminatorInst>(I); ++I) {
228 // Debugger intrinsics don't incur code size.
229 if (isa<DbgInfoIntrinsic>(I)) continue;
230
231 // If this is a pointer->pointer bitcast, it is free.
Duncan Sands1df98592010-02-16 11:11:14 +0000232 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000233 continue;
234
235 // All other instructions count for at least one unit.
236 ++Size;
237
238 // Calls are more expensive. If they are non-intrinsic calls, we model them
239 // as having cost of 4. If they are a non-vector intrinsic, we model them
240 // as having cost of 2 total, and if they are a vector intrinsic, we model
241 // them as having cost 1.
242 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
243 if (!isa<IntrinsicInst>(CI))
244 Size += 3;
Duncan Sands1df98592010-02-16 11:11:14 +0000245 else if (!CI->getType()->isVectorTy())
Chris Lattner78c552e2009-10-11 07:24:57 +0000246 Size += 1;
247 }
248 }
249
250 // Threading through a switch statement is particularly profitable. If this
251 // block ends in a switch, decrease its cost to make it more likely to happen.
252 if (isa<SwitchInst>(I))
253 Size = Size > 6 ? Size-6 : 0;
254
255 return Size;
256}
257
Mike Stumpfe095f32009-05-04 18:40:41 +0000258/// FindLoopHeaders - We do not want jump threading to turn proper loop
259/// structures into irreducible loops. Doing this breaks up the loop nesting
260/// hierarchy and pessimizes later transformations. To prevent this from
261/// happening, we first have to find the loop headers. Here we approximate this
262/// by finding targets of backedges in the CFG.
263///
264/// Note that there definitely are cases when we want to allow threading of
265/// edges across a loop header. For example, threading a jump from outside the
266/// loop (the preheader) to an exit block of the loop is definitely profitable.
267/// It is also almost always profitable to thread backedges from within the loop
268/// to exit blocks, and is often profitable to thread backedges to other blocks
269/// within the loop (forming a nested loop). This simple analysis is not rich
270/// enough to track all of these properties and keep it up-to-date as the CFG
271/// mutates, so we don't allow any of these transformations.
272///
273void JumpThreading::FindLoopHeaders(Function &F) {
274 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
275 FindFunctionBackedges(F, Edges);
276
277 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
278 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
279}
280
Owen Anderson0eb355a2010-08-31 20:26:04 +0000281// Helper method for ComputeValueKnownInPredecessors. If Value is a
282// ConstantInt, push it. If it's an undef, push 0. Otherwise, do nothing.
283static void PushConstantIntOrUndef(SmallVectorImpl<std::pair<ConstantInt*,
284 BasicBlock*> > &Result,
285 Constant *Value, BasicBlock* BB){
286 if (ConstantInt *FoldedCInt = dyn_cast<ConstantInt>(Value))
287 Result.push_back(std::make_pair(FoldedCInt, BB));
288 else if (isa<UndefValue>(Value))
289 Result.push_back(std::make_pair((ConstantInt*)0, BB));
290}
291
Chris Lattner5729d382009-11-07 08:05:03 +0000292/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
293/// if we can infer that the value is a known ConstantInt in any of our
Chris Lattnere7e63fe2009-11-09 00:41:49 +0000294/// predecessors. If so, return the known list of value and pred BB in the
Chris Lattner5729d382009-11-07 08:05:03 +0000295/// result vector. If a value is known to be undef, it is returned as null.
296///
Chris Lattner5729d382009-11-07 08:05:03 +0000297/// This returns true if there were any known values.
298///
Chris Lattner5729d382009-11-07 08:05:03 +0000299bool JumpThreading::
300ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
Owen Anderson9ba35362010-08-31 19:24:27 +0000301 // This method walks up use-def chains recursively. Because of this, we could
302 // get into an infinite loop going around loops in the use-def chain. To
303 // prevent this, keep track of what (value, block) pairs we've already visited
304 // and terminate the search if we loop back to them
Owen Andersoncb211902010-08-31 07:36:34 +0000305 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
306 return false;
307
Owen Anderson9ba35362010-08-31 19:24:27 +0000308 // An RAII help to remove this pair from the recursion set once the recursion
309 // stack pops back out again.
310 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
311
Chris Lattner5729d382009-11-07 08:05:03 +0000312 // If V is a constantint, then it is known in all predecessors.
313 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
314 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000315
316 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
317 Result.push_back(std::make_pair(CI, *PI));
Owen Andersoncb211902010-08-31 07:36:34 +0000318
Chris Lattner5729d382009-11-07 08:05:03 +0000319 return true;
320 }
321
322 // If V is a non-instruction value, or an instruction in a different block,
323 // then it can't be derived from a PHI.
324 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000325 if (I == 0 || I->getParent() != BB) {
326
327 // Okay, if this is a live-in value, see if it has a known value at the end
328 // of any of our predecessors.
329 //
330 // FIXME: This should be an edge property, not a block end property.
331 /// TODO: Per PR2563, we could infer value range information about a
332 /// predecessor based on its terminator.
333 //
334 if (LVI) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000335 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
336 // "I" is a non-local compare-with-a-constant instruction. This would be
337 // able to handle value inequalities better, for example if the compare is
338 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
339 // Perhaps getConstantOnEdge should be smart enough to do this?
340
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000341 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +0000342 BasicBlock *P = *PI;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000343 // If the value is known by LazyValueInfo to be a constant in a
344 // predecessor, use that information to try to thread this block.
Gabor Greifee1f44f2010-07-12 14:10:24 +0000345 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000346 if (PredCst == 0 ||
347 (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
348 continue;
349
Gabor Greifee1f44f2010-07-12 14:10:24 +0000350 Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), P));
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000351 }
352
353 return !Result.empty();
354 }
355
Chris Lattner5729d382009-11-07 08:05:03 +0000356 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000357 }
Chris Lattner5729d382009-11-07 08:05:03 +0000358
359 /// If I is a PHI node, then we know the incoming values for any constants.
360 if (PHINode *PN = dyn_cast<PHINode>(I)) {
361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
362 Value *InVal = PN->getIncomingValue(i);
363 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) {
364 ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
365 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
Owen Anderson62efd3b2010-08-26 17:40:24 +0000366 } else if (LVI) {
367 Constant *CI = LVI->getConstantOnEdge(InVal,
368 PN->getIncomingBlock(i), BB);
Owen Anderson327ca7b2010-08-30 23:22:36 +0000369 // LVI returns null is no value could be determined.
370 if (!CI) continue;
Owen Anderson0eb355a2010-08-31 20:26:04 +0000371 PushConstantIntOrUndef(Result, CI, PN->getIncomingBlock(i));
Chris Lattner5729d382009-11-07 08:05:03 +0000372 }
373 }
Owen Andersoncb211902010-08-31 07:36:34 +0000374
Chris Lattner5729d382009-11-07 08:05:03 +0000375 return !Result.empty();
376 }
377
378 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals;
379
380 // Handle some boolean conditions.
381 if (I->getType()->getPrimitiveSizeInBits() == 1) {
382 // X | true -> true
383 // X & false -> false
384 if (I->getOpcode() == Instruction::Or ||
385 I->getOpcode() == Instruction::And) {
386 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
387 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals);
388
Owen Anderson9ba35362010-08-31 19:24:27 +0000389 if (LHSVals.empty() && RHSVals.empty())
Chris Lattner5729d382009-11-07 08:05:03 +0000390 return false;
391
392 ConstantInt *InterestingVal;
393 if (I->getOpcode() == Instruction::Or)
394 InterestingVal = ConstantInt::getTrue(I->getContext());
395 else
396 InterestingVal = ConstantInt::getFalse(I->getContext());
397
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000398 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
399
Chris Lattner1e452652010-02-11 04:40:44 +0000400 // Scan for the sentinel. If we find an undef, force it to the
401 // interesting value: x|undef -> true and x&undef -> false.
Chris Lattner5729d382009-11-07 08:05:03 +0000402 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000403 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) {
Chris Lattner5729d382009-11-07 08:05:03 +0000404 Result.push_back(LHSVals[i]);
Chris Lattner1e452652010-02-11 04:40:44 +0000405 Result.back().first = InterestingVal;
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000406 LHSKnownBBs.insert(LHSVals[i].second);
Chris Lattner1e452652010-02-11 04:40:44 +0000407 }
Chris Lattner5729d382009-11-07 08:05:03 +0000408 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
Chris Lattner1e452652010-02-11 04:40:44 +0000409 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) {
Chris Lattner0a961442010-07-12 00:47:34 +0000410 // If we already inferred a value for this block on the LHS, don't
411 // re-add it.
Chris Lattner2fa7b48e2010-08-18 03:14:36 +0000412 if (!LHSKnownBBs.count(RHSVals[i].second)) {
Chris Lattner0a961442010-07-12 00:47:34 +0000413 Result.push_back(RHSVals[i]);
414 Result.back().first = InterestingVal;
415 }
Chris Lattner1e452652010-02-11 04:40:44 +0000416 }
Owen Andersoncb211902010-08-31 07:36:34 +0000417
Chris Lattner5729d382009-11-07 08:05:03 +0000418 return !Result.empty();
419 }
420
Chris Lattner055d0462009-11-10 22:39:16 +0000421 // Handle the NOT form of XOR.
422 if (I->getOpcode() == Instruction::Xor &&
423 isa<ConstantInt>(I->getOperand(1)) &&
424 cast<ConstantInt>(I->getOperand(1))->isOne()) {
425 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result);
Owen Anderson9ba35362010-08-31 19:24:27 +0000426 if (Result.empty())
Chris Lattner055d0462009-11-10 22:39:16 +0000427 return false;
428
429 // Invert the known values.
430 for (unsigned i = 0, e = Result.size(); i != e; ++i)
Chris Lattner1fb56302009-11-15 19:57:43 +0000431 if (Result[i].first)
432 Result[i].first =
433 cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
Owen Andersoncb211902010-08-31 07:36:34 +0000434
Chris Lattner055d0462009-11-10 22:39:16 +0000435 return true;
436 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000437
438 // Try to simplify some other binary operator values.
439 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Owen Anderson0eb355a2010-08-31 20:26:04 +0000440 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000441 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
442 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals);
Owen Andersoncb211902010-08-31 07:36:34 +0000443
444 // Try to use constant folding to simplify the binary operator.
445 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Owen Anderson0eb355a2010-08-31 20:26:04 +0000446 Constant *V = LHSVals[i].first ? LHSVals[i].first :
447 cast<Constant>(UndefValue::get(BO->getType()));
448 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
Owen Andersoncb211902010-08-31 07:36:34 +0000449
Owen Anderson0eb355a2010-08-31 20:26:04 +0000450 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Andersoncb211902010-08-31 07:36:34 +0000451 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000452 }
Owen Andersoncb211902010-08-31 07:36:34 +0000453
Owen Andersoncb211902010-08-31 07:36:34 +0000454 return !Result.empty();
Chris Lattner5729d382009-11-07 08:05:03 +0000455 }
456
457 // Handle compare with phi operand, where the PHI is defined in this block.
458 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
459 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
460 if (PN && PN->getParent() == BB) {
461 // We can do this simplification if any comparisons fold to true or false.
462 // See if any do.
463 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
464 BasicBlock *PredBB = PN->getIncomingBlock(i);
465 Value *LHS = PN->getIncomingValue(i);
466 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
467
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000468 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
Chris Lattner66c04c42009-11-12 05:24:05 +0000469 if (Res == 0) {
470 if (!LVI || !isa<Constant>(RHS))
471 continue;
472
473 LazyValueInfo::Tristate
474 ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
475 cast<Constant>(RHS), PredBB, BB);
476 if (ResT == LazyValueInfo::Unknown)
477 continue;
478 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
479 }
Chris Lattner5729d382009-11-07 08:05:03 +0000480
Owen Anderson0eb355a2010-08-31 20:26:04 +0000481 if (Constant *ConstRes = dyn_cast<Constant>(Res))
482 PushConstantIntOrUndef(Result, ConstRes, PredBB);
Chris Lattner5729d382009-11-07 08:05:03 +0000483 }
484
485 return !Result.empty();
486 }
487
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000488
489 // If comparing a live-in value against a constant, see if we know the
490 // live-in value on any predecessors.
491 if (LVI && isa<Constant>(Cmp->getOperand(1)) &&
Owen Anderson62efd3b2010-08-26 17:40:24 +0000492 Cmp->getType()->isIntegerTy()) {
493 if (!isa<Instruction>(Cmp->getOperand(0)) ||
Owen Anderson327ca7b2010-08-30 23:22:36 +0000494 cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000495 Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
Gabor Greifee1f44f2010-07-12 14:10:24 +0000496
Owen Anderson62efd3b2010-08-26 17:40:24 +0000497 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
498 BasicBlock *P = *PI;
499 // If the value is known by LazyValueInfo to be a constant in a
500 // predecessor, use that information to try to thread this block.
501 LazyValueInfo::Tristate Res =
502 LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
503 RHSCst, P, BB);
504 if (Res == LazyValueInfo::Unknown)
505 continue;
Chris Lattner0e0ff292009-11-12 04:37:50 +0000506
Owen Anderson62efd3b2010-08-26 17:40:24 +0000507 Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
508 Result.push_back(std::make_pair(cast<ConstantInt>(ResC), P));
509 }
510
511 return !Result.empty();
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000512 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000513
Owen Andersoncb211902010-08-31 07:36:34 +0000514 // Try to find a constant value for the LHS of a comparison,
Owen Anderson62efd3b2010-08-26 17:40:24 +0000515 // and evaluate it statically if we can.
Owen Anderson327ca7b2010-08-30 23:22:36 +0000516 if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
Owen Anderson62efd3b2010-08-26 17:40:24 +0000517 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
518 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
519
Owen Anderson62efd3b2010-08-26 17:40:24 +0000520 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
Owen Anderson0eb355a2010-08-31 20:26:04 +0000521 Constant *V = LHSVals[i].first ? LHSVals[i].first :
522 cast<Constant>(UndefValue::get(CmpConst->getType()));
523 Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
524 V, CmpConst);
525 PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
Owen Anderson62efd3b2010-08-26 17:40:24 +0000526 }
527
528 return !Result.empty();
529 }
Chris Lattner2ad00bf2009-11-11 22:31:38 +0000530 }
Chris Lattner5729d382009-11-07 08:05:03 +0000531 }
Owen Anderson62efd3b2010-08-26 17:40:24 +0000532
533 if (LVI) {
534 // If all else fails, see if LVI can figure out a constant value for us.
535 Constant *CI = LVI->getConstant(V, BB);
536 ConstantInt *CInt = dyn_cast_or_null<ConstantInt>(CI);
537 if (CInt) {
538 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
539 Result.push_back(std::make_pair(CInt, *PI));
540 }
541
542 return !Result.empty();
543 }
544
Chris Lattner5729d382009-11-07 08:05:03 +0000545 return false;
546}
547
548
Chris Lattner6bf77502008-04-22 07:05:46 +0000549
Chris Lattnere33583b2009-10-11 04:18:15 +0000550/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
551/// in an undefined jump, decide which block is best to revector to.
552///
553/// Since we can pick an arbitrary destination, we pick the successor with the
554/// fewest predecessors. This should reduce the in-degree of the others.
555///
556static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
557 TerminatorInst *BBTerm = BB->getTerminator();
558 unsigned MinSucc = 0;
559 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
560 // Compute the successor with the minimum number of predecessors.
561 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
562 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
563 TestBB = BBTerm->getSuccessor(i);
564 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
565 if (NumPreds < MinNumPreds)
566 MinSucc = i;
567 }
568
569 return MinSucc;
570}
571
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000572/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000573/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000574bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner8231fd12010-01-23 18:56:07 +0000575 // If the block is trivially dead, just return and let the caller nuke it.
576 // This simplifies other transformations.
577 if (pred_begin(BB) == pred_end(BB) &&
578 BB != &BB->getParent()->getEntryBlock())
579 return false;
580
Chris Lattner69e067f2008-11-27 05:07:53 +0000581 // If this block has a single predecessor, and if that pred has a single
582 // successor, merge the blocks. This encourages recursive jump threading
583 // because now the condition in this block can be threaded through
584 // predecessors of our predecessor block.
Chris Lattner5729d382009-11-07 08:05:03 +0000585 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000586 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
587 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000588 // If SinglePred was a loop header, BB becomes one.
589 if (LoopHeaders.erase(SinglePred))
590 LoopHeaders.insert(BB);
591
Chris Lattner3d86d242008-11-27 19:25:19 +0000592 // Remember if SinglePred was the entry block of the function. If so, we
593 // will need to move BB back to the entry position.
594 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Owen Anderson00ac77e2010-08-18 18:39:01 +0000595 if (LVI) LVI->eraseBlock(SinglePred);
Chris Lattner69e067f2008-11-27 05:07:53 +0000596 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000597
598 if (isEntry && BB != &BB->getParent()->getEntryBlock())
599 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000600 return true;
601 }
Chris Lattner5729d382009-11-07 08:05:03 +0000602 }
603
604 // Look to see if the terminator is a branch of switch, if not we can't thread
605 // it.
Chris Lattner177480b2008-04-20 21:13:06 +0000606 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000607 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
608 // Can't thread an unconditional jump.
609 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000610 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000611 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000612 Condition = SI->getCondition();
613 else
614 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000615
616 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000617 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000618 // other blocks.
619 if (isa<ConstantInt>(Condition)) {
David Greenefe7fe662010-01-05 01:27:19 +0000620 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000621 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000622 ++NumFolds;
623 ConstantFoldTerminator(BB);
624 return true;
625 }
626
Chris Lattner421fa9e2008-12-03 07:48:08 +0000627 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000628 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000629 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000630 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000631
632 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000633 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000634 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000635 if (i == BestSucc) continue;
Chris Lattnerc2c23d02009-11-09 22:32:36 +0000636 RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000637 }
638
David Greenefe7fe662010-01-05 01:27:19 +0000639 DEBUG(dbgs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000640 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000641 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000642 BBTerm->eraseFromParent();
643 return true;
644 }
645
646 Instruction *CondInst = dyn_cast<Instruction>(Condition);
647
648 // If the condition is an instruction defined in another block, see if a
649 // predecessor has the same condition:
650 // br COND, BBX, BBY
651 // BBX:
652 // br COND, BBZ, BBW
Chris Lattner0e0ff292009-11-12 04:37:50 +0000653 if (!LVI &&
654 !Condition->hasOneUse() && // Multiple uses.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000655 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
656 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
657 if (isa<BranchInst>(BB->getTerminator())) {
Gabor Greifee1f44f2010-07-12 14:10:24 +0000658 for (; PI != E; ++PI) {
659 BasicBlock *P = *PI;
660 if (BranchInst *PBI = dyn_cast<BranchInst>(P->getTerminator()))
Chris Lattner421fa9e2008-12-03 07:48:08 +0000661 if (PBI->isConditional() && PBI->getCondition() == Condition &&
Gabor Greifee1f44f2010-07-12 14:10:24 +0000662 ProcessBranchOnDuplicateCond(P, BB))
Chris Lattner421fa9e2008-12-03 07:48:08 +0000663 return true;
Gabor Greifee1f44f2010-07-12 14:10:24 +0000664 }
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000665 } else {
666 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
Gabor Greifee1f44f2010-07-12 14:10:24 +0000667 for (; PI != E; ++PI) {
668 BasicBlock *P = *PI;
669 if (SwitchInst *PSI = dyn_cast<SwitchInst>(P->getTerminator()))
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000670 if (PSI->getCondition() == Condition &&
Gabor Greifee1f44f2010-07-12 14:10:24 +0000671 ProcessSwitchOnDuplicateCond(P, BB))
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000672 return true;
Gabor Greifee1f44f2010-07-12 14:10:24 +0000673 }
Chris Lattner421fa9e2008-12-03 07:48:08 +0000674 }
675 }
676
Chris Lattner421fa9e2008-12-03 07:48:08 +0000677 // All the rest of our checks depend on the condition being an instruction.
Chris Lattner87e9f592009-11-12 01:41:34 +0000678 if (CondInst == 0) {
679 // FIXME: Unify this with code below.
680 if (LVI && ProcessThreadableEdges(Condition, BB))
681 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000682 return false;
Chris Lattner87e9f592009-11-12 01:41:34 +0000683 }
684
Chris Lattner421fa9e2008-12-03 07:48:08 +0000685
Nick Lewycky9683f182009-06-19 04:56:29 +0000686 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
Chris Lattner0e0ff292009-11-12 04:37:50 +0000687 if (!LVI &&
688 (!isa<PHINode>(CondCmp->getOperand(0)) ||
689 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB)) {
Chris Lattner5729d382009-11-07 08:05:03 +0000690 // If we have a comparison, loop over the predecessors to see if there is
691 // a condition with a lexically identical value.
692 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
Gabor Greifee1f44f2010-07-12 14:10:24 +0000693 for (; PI != E; ++PI) {
694 BasicBlock *P = *PI;
695 if (BranchInst *PBI = dyn_cast<BranchInst>(P->getTerminator()))
696 if (PBI->isConditional() && P != BB) {
Chris Lattner5729d382009-11-07 08:05:03 +0000697 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
698 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
699 CI->getOperand(1) == CondCmp->getOperand(1) &&
700 CI->getPredicate() == CondCmp->getPredicate()) {
701 // TODO: Could handle things like (x != 4) --> (x == 17)
Gabor Greifee1f44f2010-07-12 14:10:24 +0000702 if (ProcessBranchOnDuplicateCond(P, BB))
Chris Lattner5729d382009-11-07 08:05:03 +0000703 return true;
704 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000705 }
706 }
Gabor Greifee1f44f2010-07-12 14:10:24 +0000707 }
Chris Lattner5729d382009-11-07 08:05:03 +0000708 }
Owen Anderson660cab32010-08-27 17:12:29 +0000709
710 // For a comparison where the LHS is outside this block, it's possible
Owen Andersonfc2fb172010-08-27 20:32:56 +0000711 // that we've branched on it before. Used LVI to see if we can simplify
Owen Anderson660cab32010-08-27 17:12:29 +0000712 // the branch based on that.
713 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
714 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
Owen Andersonc1bdac62010-08-31 18:48:48 +0000715 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
716 if (LVI && CondBr && CondConst && CondBr->isConditional() && PI != PE &&
Owen Anderson660cab32010-08-27 17:12:29 +0000717 (!isa<Instruction>(CondCmp->getOperand(0)) ||
718 cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
719 // For predecessor edge, determine if the comparison is true or false
720 // on that edge. If they're all true or all false, we can simplify the
721 // branch.
722 // FIXME: We could handle mixed true/false by duplicating code.
Owen Andersonc1bdac62010-08-31 18:48:48 +0000723 LazyValueInfo::Tristate Baseline =
724 LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
725 CondConst, *PI, BB);
726 if (Baseline != LazyValueInfo::Unknown) {
727 // Check that all remaining incoming values match the first one.
728 while (++PI != PE) {
729 LazyValueInfo::Tristate Ret = LVI->getPredicateOnEdge(
730 CondCmp->getPredicate(),
731 CondCmp->getOperand(0),
732 CondConst, *PI, BB);
733 if (Ret != Baseline) break;
734 }
735
736 // If we terminated early, then one of the values didn't match.
737 if (PI == PE) {
738 unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
739 unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
740 RemovePredecessorAndSimplify(CondBr->getSuccessor(ToRemove), BB, TD);
741 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
742 CondBr->eraseFromParent();
743 return true;
744 }
Owen Anderson660cab32010-08-27 17:12:29 +0000745 }
746 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000747 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000748
749 // Check for some cases that are worth simplifying. Right now we want to look
750 // for loads that are used by a switch or by the condition for the branch. If
751 // we see one, check to see if it's partially redundant. If so, insert a PHI
752 // which can then be used to thread the values.
753 //
Chris Lattner421fa9e2008-12-03 07:48:08 +0000754 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000755 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
756 if (isa<Constant>(CondCmp->getOperand(1)))
757 SimplifyValue = CondCmp->getOperand(0);
758
Chris Lattner4e447eb2009-11-15 19:58:31 +0000759 // TODO: There are other places where load PRE would be profitable, such as
760 // more complex comparisons.
Chris Lattner69e067f2008-11-27 05:07:53 +0000761 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
762 if (SimplifyPartiallyRedundantLoad(LI))
763 return true;
764
Chris Lattner5729d382009-11-07 08:05:03 +0000765
766 // Handle a variety of cases where we are branching on something derived from
767 // a PHI node in the current block. If we can prove that any predecessors
768 // compute a predictable value based on a PHI node, thread those predecessors.
769 //
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000770 if (ProcessThreadableEdges(CondInst, BB))
771 return true;
Chris Lattner5729d382009-11-07 08:05:03 +0000772
Chris Lattner77beb472010-01-11 23:41:09 +0000773 // If this is an otherwise-unfoldable branch on a phi node in the current
774 // block, see if we can simplify.
775 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
776 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
777 return ProcessBranchOnPHI(PN);
Chris Lattner5729d382009-11-07 08:05:03 +0000778
Chris Lattner2249a0b2010-01-12 02:07:17 +0000779
780 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
781 if (CondInst->getOpcode() == Instruction::Xor &&
782 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
783 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
784
785
Chris Lattner69e067f2008-11-27 05:07:53 +0000786 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
Chris Lattner77beb472010-01-11 23:41:09 +0000787 // "(X == 4)", thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000788
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000789 return false;
790}
791
Chris Lattner421fa9e2008-12-03 07:48:08 +0000792/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
793/// block that jump on exactly the same condition. This means that we almost
794/// always know the direction of the edge in the DESTBB:
795/// PREDBB:
796/// br COND, DESTBB, BBY
797/// DESTBB:
798/// br COND, BBZ, BBW
799///
800/// If DESTBB has multiple predecessors, we can't just constant fold the branch
801/// in DESTBB, we have to thread over it.
802bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
803 BasicBlock *BB) {
804 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
805
806 // If both successors of PredBB go to DESTBB, we don't know anything. We can
807 // fold the branch to an unconditional one, which allows other recursive
808 // simplifications.
809 bool BranchDir;
810 if (PredBI->getSuccessor(1) != BB)
811 BranchDir = true;
812 else if (PredBI->getSuccessor(0) != BB)
813 BranchDir = false;
814 else {
David Greenefe7fe662010-01-05 01:27:19 +0000815 DEBUG(dbgs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000816 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000817 ++NumFolds;
818 ConstantFoldTerminator(PredBB);
819 return true;
820 }
821
822 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
823
824 // If the dest block has one predecessor, just fix the branch condition to a
825 // constant and fold it.
826 if (BB->getSinglePredecessor()) {
David Greenefe7fe662010-01-05 01:27:19 +0000827 DEBUG(dbgs() << " In block '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000828 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000829 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000830 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000831 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000832 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
833 BranchDir));
Chris Lattner6f285d22010-04-10 18:26:57 +0000834 // Delete dead instructions before we fold the branch. Folding the branch
835 // can eliminate edges from the CFG which can end up deleting OldCond.
Chris Lattner5a06cf62009-10-11 18:39:58 +0000836 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner6f285d22010-04-10 18:26:57 +0000837 ConstantFoldTerminator(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000838 return true;
839 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000840
Chris Lattner421fa9e2008-12-03 07:48:08 +0000841
842 // Next, figure out which successor we are threading to.
843 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
844
Chris Lattner5729d382009-11-07 08:05:03 +0000845 SmallVector<BasicBlock*, 2> Preds;
846 Preds.push_back(PredBB);
847
Mike Stumpfe095f32009-05-04 18:40:41 +0000848 // Ok, try to thread it!
Chris Lattner5729d382009-11-07 08:05:03 +0000849 return ThreadEdge(BB, Preds, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000850}
851
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000852/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
853/// block that switch on exactly the same condition. This means that we almost
854/// always know the direction of the edge in the DESTBB:
855/// PREDBB:
856/// switch COND [... DESTBB, BBY ... ]
857/// DESTBB:
858/// switch COND [... BBZ, BBW ]
859///
860/// Optimizing switches like this is very important, because simplifycfg builds
861/// switches out of repeated 'if' conditions.
862bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
863 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000864 // Can't thread edge to self.
865 if (PredBB == DestBB)
866 return false;
867
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000868 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
869 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
870
871 // There are a variety of optimizations that we can potentially do on these
872 // blocks: we order them from most to least preferable.
873
874 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
875 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000876 // growth. Skip debug info first.
877 BasicBlock::iterator BBI = DestBB->begin();
878 while (isa<DbgInfoIntrinsic>(BBI))
879 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000880
881 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000882 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000883 bool MadeChange = false;
884 // Ignore the default edge for now.
885 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
886 ConstantInt *DestVal = DestSI->getCaseValue(i);
887 BasicBlock *DestSucc = DestSI->getSuccessor(i);
888
889 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
890 // PredSI has an explicit case for it. If so, forward. If it is covered
891 // by the default case, we can't update PredSI.
892 unsigned PredCase = PredSI->findCaseValue(DestVal);
893 if (PredCase == 0) continue;
894
895 // If PredSI doesn't go to DestBB on this value, then it won't reach the
896 // case on this condition.
897 if (PredSI->getSuccessor(PredCase) != DestBB &&
898 DestSI->getSuccessor(i) != DestBB)
899 continue;
Chris Lattner08bc2702009-12-06 17:17:23 +0000900
901 // Do not forward this if it already goes to this destination, this would
902 // be an infinite loop.
903 if (PredSI->getSuccessor(PredCase) == DestSucc)
904 continue;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000905
906 // Otherwise, we're safe to make the change. Make sure that the edge from
907 // DestSI to DestSucc is not critical and has no PHI nodes.
David Greenefe7fe662010-01-05 01:27:19 +0000908 DEBUG(dbgs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
909 DEBUG(dbgs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000910
911 // If the destination has PHI nodes, just split the edge for updating
912 // simplicity.
913 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
914 SplitCriticalEdge(DestSI, i, this);
915 DestSucc = DestSI->getSuccessor(i);
916 }
917 FoldSingleEntryPHINodes(DestSucc);
918 PredSI->setSuccessor(PredCase, DestSucc);
919 MadeChange = true;
920 }
921
922 if (MadeChange)
923 return true;
924 }
925
926 return false;
927}
928
929
Chris Lattner69e067f2008-11-27 05:07:53 +0000930/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
931/// load instruction, eliminate it by replacing it with a PHI node. This is an
932/// important optimization that encourages jump threading, and needs to be run
933/// interlaced with other jump threading tasks.
934bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
935 // Don't hack volatile loads.
936 if (LI->isVolatile()) return false;
937
938 // If the load is defined in a block with exactly one predecessor, it can't be
939 // partially redundant.
940 BasicBlock *LoadBB = LI->getParent();
941 if (LoadBB->getSinglePredecessor())
942 return false;
943
944 Value *LoadedPtr = LI->getOperand(0);
945
946 // If the loaded operand is defined in the LoadBB, it can't be available.
Chris Lattner4e447eb2009-11-15 19:58:31 +0000947 // TODO: Could do simple PHI translation, that would be fun :)
Chris Lattner69e067f2008-11-27 05:07:53 +0000948 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
949 if (PtrOp->getParent() == LoadBB)
950 return false;
951
952 // Scan a few instructions up from the load, to see if it is obviously live at
953 // the entry to its block.
954 BasicBlock::iterator BBIt = LI;
955
Chris Lattner4e447eb2009-11-15 19:58:31 +0000956 if (Value *AvailableVal =
957 FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000958 // If the value if the load is locally available within the block, just use
959 // it. This frequently occurs for reg2mem'd allocas.
960 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000961
962 // If the returned value is the load itself, replace with an undef. This can
963 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000964 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000965 LI->replaceAllUsesWith(AvailableVal);
966 LI->eraseFromParent();
967 return true;
968 }
969
970 // Otherwise, if we scanned the whole block and got to the top of the block,
971 // we know the block is locally transparent to the load. If not, something
972 // might clobber its value.
973 if (BBIt != LoadBB->begin())
974 return false;
975
976
977 SmallPtrSet<BasicBlock*, 8> PredsScanned;
978 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
979 AvailablePredsTy AvailablePreds;
980 BasicBlock *OneUnavailablePred = 0;
981
982 // If we got here, the loaded value is transparent through to the start of the
983 // block. Check to see if it is available in any of the predecessor blocks.
984 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
985 PI != PE; ++PI) {
986 BasicBlock *PredBB = *PI;
987
988 // If we already scanned this predecessor, skip it.
989 if (!PredsScanned.insert(PredBB))
990 continue;
991
992 // Scan the predecessor to see if the value is available in the pred.
993 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000994 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000995 if (!PredAvailable) {
996 OneUnavailablePred = PredBB;
997 continue;
998 }
999
1000 // If so, this load is partially redundant. Remember this info so that we
1001 // can create a PHI node.
1002 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1003 }
1004
1005 // If the loaded value isn't available in any predecessor, it isn't partially
1006 // redundant.
1007 if (AvailablePreds.empty()) return false;
1008
1009 // Okay, the loaded value is available in at least one (and maybe all!)
1010 // predecessors. If the value is unavailable in more than one unique
1011 // predecessor, we want to insert a merge block for those common predecessors.
1012 // This ensures that we only have to insert one reload, thus not increasing
1013 // code size.
1014 BasicBlock *UnavailablePred = 0;
1015
1016 // If there is exactly one predecessor where the value is unavailable, the
1017 // already computed 'OneUnavailablePred' block is it. If it ends in an
1018 // unconditional branch, we know that it isn't a critical edge.
1019 if (PredsScanned.size() == AvailablePreds.size()+1 &&
1020 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1021 UnavailablePred = OneUnavailablePred;
1022 } else if (PredsScanned.size() != AvailablePreds.size()) {
1023 // Otherwise, we had multiple unavailable predecessors or we had a critical
1024 // edge from the one.
1025 SmallVector<BasicBlock*, 8> PredsToSplit;
1026 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1027
1028 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
1029 AvailablePredSet.insert(AvailablePreds[i].first);
1030
1031 // Add all the unavailable predecessors to the PredsToSplit list.
1032 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
Chris Lattnere58867e2010-06-14 19:45:43 +00001033 PI != PE; ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +00001034 BasicBlock *P = *PI;
Chris Lattnere58867e2010-06-14 19:45:43 +00001035 // If the predecessor is an indirect goto, we can't split the edge.
Gabor Greifee1f44f2010-07-12 14:10:24 +00001036 if (isa<IndirectBrInst>(P->getTerminator()))
Chris Lattnere58867e2010-06-14 19:45:43 +00001037 return false;
1038
Gabor Greifee1f44f2010-07-12 14:10:24 +00001039 if (!AvailablePredSet.count(P))
1040 PredsToSplit.push_back(P);
Chris Lattnere58867e2010-06-14 19:45:43 +00001041 }
Chris Lattner69e067f2008-11-27 05:07:53 +00001042
1043 // Split them out to their own block.
1044 UnavailablePred =
1045 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
Chris Lattner4e447eb2009-11-15 19:58:31 +00001046 "thread-pre-split", this);
Chris Lattner69e067f2008-11-27 05:07:53 +00001047 }
1048
1049 // If the value isn't available in all predecessors, then there will be
1050 // exactly one where it isn't available. Insert a load on that edge and add
1051 // it to the AvailablePreds list.
1052 if (UnavailablePred) {
1053 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1054 "Can't handle critical edge here!");
Chris Lattner4e447eb2009-11-15 19:58:31 +00001055 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
1056 LI->getAlignment(),
Chris Lattner69e067f2008-11-27 05:07:53 +00001057 UnavailablePred->getTerminator());
1058 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1059 }
1060
1061 // Now we know that each predecessor of this block has a value in
1062 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +00001063 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +00001064
1065 // Create a PHI node at the start of the block for the PRE'd load value.
1066 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
1067 PN->takeName(LI);
1068
1069 // Insert new entries into the PHI for each predecessor. A single block may
1070 // have multiple entries here.
1071 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
1072 ++PI) {
Gabor Greifee1f44f2010-07-12 14:10:24 +00001073 BasicBlock *P = *PI;
Chris Lattner69e067f2008-11-27 05:07:53 +00001074 AvailablePredsTy::iterator I =
1075 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
Gabor Greifee1f44f2010-07-12 14:10:24 +00001076 std::make_pair(P, (Value*)0));
Chris Lattner69e067f2008-11-27 05:07:53 +00001077
Gabor Greifee1f44f2010-07-12 14:10:24 +00001078 assert(I != AvailablePreds.end() && I->first == P &&
Chris Lattner69e067f2008-11-27 05:07:53 +00001079 "Didn't find entry for predecessor!");
1080
1081 PN->addIncoming(I->second, I->first);
1082 }
1083
1084 //cerr << "PRE: " << *LI << *PN << "\n";
1085
1086 LI->replaceAllUsesWith(PN);
1087 LI->eraseFromParent();
1088
1089 return true;
1090}
1091
Chris Lattner5729d382009-11-07 08:05:03 +00001092/// FindMostPopularDest - The specified list contains multiple possible
1093/// threadable destinations. Pick the one that occurs the most frequently in
1094/// the list.
1095static BasicBlock *
1096FindMostPopularDest(BasicBlock *BB,
1097 const SmallVectorImpl<std::pair<BasicBlock*,
1098 BasicBlock*> > &PredToDestList) {
1099 assert(!PredToDestList.empty());
1100
1101 // Determine popularity. If there are multiple possible destinations, we
1102 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1103 // blocks with known and real destinations to threading undef. We'll handle
1104 // them later if interesting.
1105 DenseMap<BasicBlock*, unsigned> DestPopularity;
1106 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1107 if (PredToDestList[i].second)
1108 DestPopularity[PredToDestList[i].second]++;
1109
1110 // Find the most popular dest.
1111 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1112 BasicBlock *MostPopularDest = DPI->first;
1113 unsigned Popularity = DPI->second;
1114 SmallVector<BasicBlock*, 4> SamePopularity;
1115
1116 for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1117 // If the popularity of this entry isn't higher than the popularity we've
1118 // seen so far, ignore it.
1119 if (DPI->second < Popularity)
1120 ; // ignore.
1121 else if (DPI->second == Popularity) {
1122 // If it is the same as what we've seen so far, keep track of it.
1123 SamePopularity.push_back(DPI->first);
1124 } else {
1125 // If it is more popular, remember it.
1126 SamePopularity.clear();
1127 MostPopularDest = DPI->first;
1128 Popularity = DPI->second;
1129 }
1130 }
1131
1132 // Okay, now we know the most popular destination. If there is more than
1133 // destination, we need to determine one. This is arbitrary, but we need
1134 // to make a deterministic decision. Pick the first one that appears in the
1135 // successor list.
1136 if (!SamePopularity.empty()) {
1137 SamePopularity.push_back(MostPopularDest);
1138 TerminatorInst *TI = BB->getTerminator();
1139 for (unsigned i = 0; ; ++i) {
1140 assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1141
1142 if (std::find(SamePopularity.begin(), SamePopularity.end(),
1143 TI->getSuccessor(i)) == SamePopularity.end())
1144 continue;
1145
1146 MostPopularDest = TI->getSuccessor(i);
1147 break;
1148 }
1149 }
1150
1151 // Okay, we have finally picked the most popular destination.
1152 return MostPopularDest;
1153}
1154
Chris Lattner1c96b412009-11-12 01:37:43 +00001155bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB) {
Chris Lattner5729d382009-11-07 08:05:03 +00001156 // If threading this would thread across a loop header, don't even try to
1157 // thread the edge.
1158 if (LoopHeaders.count(BB))
1159 return false;
1160
Chris Lattner5729d382009-11-07 08:05:03 +00001161 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001162 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
Chris Lattner5729d382009-11-07 08:05:03 +00001163 return false;
Owen Anderson0eb355a2010-08-31 20:26:04 +00001164
Chris Lattner5729d382009-11-07 08:05:03 +00001165 assert(!PredValues.empty() &&
1166 "ComputeValueKnownInPredecessors returned true with no values");
1167
David Greenefe7fe662010-01-05 01:27:19 +00001168 DEBUG(dbgs() << "IN BB: " << *BB;
Chris Lattner5729d382009-11-07 08:05:03 +00001169 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
David Greenefe7fe662010-01-05 01:27:19 +00001170 dbgs() << " BB '" << BB->getName() << "': FOUND condition = ";
Chris Lattner5729d382009-11-07 08:05:03 +00001171 if (PredValues[i].first)
David Greenefe7fe662010-01-05 01:27:19 +00001172 dbgs() << *PredValues[i].first;
Chris Lattner5729d382009-11-07 08:05:03 +00001173 else
David Greenefe7fe662010-01-05 01:27:19 +00001174 dbgs() << "UNDEF";
1175 dbgs() << " for pred '" << PredValues[i].second->getName()
Chris Lattner5729d382009-11-07 08:05:03 +00001176 << "'.\n";
1177 });
1178
1179 // Decide what we want to thread through. Convert our list of known values to
1180 // a list of known destinations for each pred. This also discards duplicate
1181 // predecessors and keeps track of the undefined inputs (which are represented
Chris Lattnere7e63fe2009-11-09 00:41:49 +00001182 // as a null dest in the PredToDestList).
Chris Lattner5729d382009-11-07 08:05:03 +00001183 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1184 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1185
1186 BasicBlock *OnlyDest = 0;
1187 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1188
1189 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
1190 BasicBlock *Pred = PredValues[i].second;
1191 if (!SeenPreds.insert(Pred))
1192 continue; // Duplicate predecessor entry.
1193
1194 // If the predecessor ends with an indirect goto, we can't change its
1195 // destination.
1196 if (isa<IndirectBrInst>(Pred->getTerminator()))
1197 continue;
1198
1199 ConstantInt *Val = PredValues[i].first;
1200
1201 BasicBlock *DestBB;
1202 if (Val == 0) // Undef.
1203 DestBB = 0;
1204 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1205 DestBB = BI->getSuccessor(Val->isZero());
1206 else {
1207 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
1208 DestBB = SI->getSuccessor(SI->findCaseValue(Val));
1209 }
1210
1211 // If we have exactly one destination, remember it for efficiency below.
1212 if (i == 0)
1213 OnlyDest = DestBB;
1214 else if (OnlyDest != DestBB)
1215 OnlyDest = MultipleDestSentinel;
1216
1217 PredToDestList.push_back(std::make_pair(Pred, DestBB));
1218 }
1219
1220 // If all edges were unthreadable, we fail.
1221 if (PredToDestList.empty())
1222 return false;
1223
1224 // Determine which is the most common successor. If we have many inputs and
1225 // this block is a switch, we want to start by threading the batch that goes
1226 // to the most popular destination first. If we only know about one
1227 // threadable destination (the common case) we can avoid this.
1228 BasicBlock *MostPopularDest = OnlyDest;
1229
1230 if (MostPopularDest == MultipleDestSentinel)
1231 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1232
1233 // Now that we know what the most popular destination is, factor all
1234 // predecessors that will jump to it into a single predecessor.
1235 SmallVector<BasicBlock*, 16> PredsToFactor;
1236 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
1237 if (PredToDestList[i].second == MostPopularDest) {
1238 BasicBlock *Pred = PredToDestList[i].first;
1239
1240 // This predecessor may be a switch or something else that has multiple
1241 // edges to the block. Factor each of these edges by listing them
1242 // according to # occurrences in PredsToFactor.
1243 TerminatorInst *PredTI = Pred->getTerminator();
1244 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
1245 if (PredTI->getSuccessor(i) == BB)
1246 PredsToFactor.push_back(Pred);
1247 }
1248
1249 // If the threadable edges are branching on an undefined value, we get to pick
1250 // the destination that these predecessors should get to.
1251 if (MostPopularDest == 0)
1252 MostPopularDest = BB->getTerminator()->
1253 getSuccessor(GetBestDestForJumpOnUndef(BB));
1254
1255 // Ok, try to thread it!
1256 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1257}
Chris Lattner69e067f2008-11-27 05:07:53 +00001258
Chris Lattner77beb472010-01-11 23:41:09 +00001259/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1260/// a PHI node in the current block. See if there are any simplifications we
1261/// can do based on inputs to the phi node.
Chris Lattnerd38c14e2008-04-22 06:36:15 +00001262///
Chris Lattner77beb472010-01-11 23:41:09 +00001263bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +00001264 BasicBlock *BB = PN->getParent();
1265
Chris Lattner2249a0b2010-01-12 02:07:17 +00001266 // TODO: We could make use of this to do it once for blocks with common PHI
1267 // values.
1268 SmallVector<BasicBlock*, 1> PredBBs;
1269 PredBBs.resize(1);
1270
Chris Lattner5729d382009-11-07 08:05:03 +00001271 // If any of the predecessor blocks end in an unconditional branch, we can
Chris Lattner77beb472010-01-11 23:41:09 +00001272 // *duplicate* the conditional branch into that block in order to further
1273 // encourage jump threading and to eliminate cases where we have branch on a
1274 // phi of an icmp (branch on icmp is much better).
Chris Lattner78c552e2009-10-11 07:24:57 +00001275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1276 BasicBlock *PredBB = PN->getIncomingBlock(i);
1277 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
Chris Lattner2249a0b2010-01-12 02:07:17 +00001278 if (PredBr->isUnconditional()) {
1279 PredBBs[0] = PredBB;
1280 // Try to duplicate BB into PredBB.
1281 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1282 return true;
1283 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001284 }
1285
Chris Lattner6b65f472009-10-11 04:40:21 +00001286 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001287}
1288
Chris Lattner2249a0b2010-01-12 02:07:17 +00001289/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1290/// a xor instruction in the current block. See if there are any
1291/// simplifications we can do based on inputs to the xor.
1292///
1293bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
1294 BasicBlock *BB = BO->getParent();
1295
1296 // If either the LHS or RHS of the xor is a constant, don't do this
1297 // optimization.
1298 if (isa<ConstantInt>(BO->getOperand(0)) ||
1299 isa<ConstantInt>(BO->getOperand(1)))
1300 return false;
1301
Chris Lattner2dd76572010-01-23 19:16:25 +00001302 // If the first instruction in BB isn't a phi, we won't be able to infer
1303 // anything special about any particular predecessor.
1304 if (!isa<PHINode>(BB->front()))
1305 return false;
1306
Chris Lattner2249a0b2010-01-12 02:07:17 +00001307 // If we have a xor as the branch input to this block, and we know that the
1308 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1309 // the condition into the predecessor and fix that value to true, saving some
1310 // logical ops on that path and encouraging other paths to simplify.
1311 //
1312 // This copies something like this:
1313 //
1314 // BB:
1315 // %X = phi i1 [1], [%X']
1316 // %Y = icmp eq i32 %A, %B
1317 // %Z = xor i1 %X, %Y
1318 // br i1 %Z, ...
1319 //
1320 // Into:
1321 // BB':
1322 // %Y = icmp ne i32 %A, %B
1323 // br i1 %Z, ...
1324
1325 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> XorOpValues;
1326 bool isLHS = true;
1327 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues)) {
1328 assert(XorOpValues.empty());
1329 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues))
1330 return false;
1331 isLHS = false;
1332 }
1333
1334 assert(!XorOpValues.empty() &&
1335 "ComputeValueKnownInPredecessors returned true with no values");
1336
1337 // Scan the information to see which is most popular: true or false. The
1338 // predecessors can be of the set true, false, or undef.
1339 unsigned NumTrue = 0, NumFalse = 0;
1340 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1341 if (!XorOpValues[i].first) continue; // Ignore undefs for the count.
1342 if (XorOpValues[i].first->isZero())
1343 ++NumFalse;
1344 else
1345 ++NumTrue;
1346 }
1347
1348 // Determine which value to split on, true, false, or undef if neither.
1349 ConstantInt *SplitVal = 0;
1350 if (NumTrue > NumFalse)
1351 SplitVal = ConstantInt::getTrue(BB->getContext());
1352 else if (NumTrue != 0 || NumFalse != 0)
1353 SplitVal = ConstantInt::getFalse(BB->getContext());
1354
1355 // Collect all of the blocks that this can be folded into so that we can
1356 // factor this once and clone it once.
1357 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1358 for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
1359 if (XorOpValues[i].first != SplitVal && XorOpValues[i].first != 0) continue;
1360
1361 BlocksToFoldInto.push_back(XorOpValues[i].second);
1362 }
1363
Chris Lattner2dd76572010-01-23 19:16:25 +00001364 // If we inferred a value for all of the predecessors, then duplication won't
1365 // help us. However, we can just replace the LHS or RHS with the constant.
1366 if (BlocksToFoldInto.size() ==
1367 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1368 if (SplitVal == 0) {
1369 // If all preds provide undef, just nuke the xor, because it is undef too.
1370 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1371 BO->eraseFromParent();
1372 } else if (SplitVal->isZero()) {
1373 // If all preds provide 0, replace the xor with the other input.
1374 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1375 BO->eraseFromParent();
1376 } else {
1377 // If all preds provide 1, set the computed value to 1.
1378 BO->setOperand(!isLHS, SplitVal);
1379 }
1380
1381 return true;
1382 }
1383
Chris Lattner2249a0b2010-01-12 02:07:17 +00001384 // Try to duplicate BB into PredBB.
Chris Lattner797c4402010-01-12 02:07:50 +00001385 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
Chris Lattner2249a0b2010-01-12 02:07:17 +00001386}
1387
1388
Chris Lattner78c552e2009-10-11 07:24:57 +00001389/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1390/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1391/// NewPred using the entries from OldPred (suitably mapped).
1392static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1393 BasicBlock *OldPred,
1394 BasicBlock *NewPred,
1395 DenseMap<Instruction*, Value*> &ValueMap) {
1396 for (BasicBlock::iterator PNI = PHIBB->begin();
1397 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1398 // Ok, we have a PHI node. Figure out what the incoming value was for the
1399 // DestBlock.
1400 Value *IV = PN->getIncomingValueForBlock(OldPred);
1401
1402 // Remap the value if necessary.
1403 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1404 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1405 if (I != ValueMap.end())
1406 IV = I->second;
1407 }
1408
1409 PN->addIncoming(IV, NewPred);
1410 }
1411}
Chris Lattner6bf77502008-04-22 07:05:46 +00001412
Chris Lattner5729d382009-11-07 08:05:03 +00001413/// ThreadEdge - We have decided that it is safe and profitable to factor the
1414/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1415/// across BB. Transform the IR to reflect this change.
1416bool JumpThreading::ThreadEdge(BasicBlock *BB,
1417 const SmallVectorImpl<BasicBlock*> &PredBBs,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +00001418 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +00001419 // If threading to the same block as we come from, we would infinite loop.
1420 if (SuccBB == BB) {
David Greenefe7fe662010-01-05 01:27:19 +00001421 DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001422 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001423 return false;
1424 }
1425
1426 // If threading this would thread across a loop header, don't thread the edge.
1427 // See the comments above FindLoopHeaders for justifications and caveats.
1428 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001429 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001430 << "' to dest BB '" << SuccBB->getName()
1431 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001432 return false;
1433 }
1434
Chris Lattner78c552e2009-10-11 07:24:57 +00001435 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
1436 if (JumpThreadCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001437 DEBUG(dbgs() << " Not threading BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001438 << "' - Cost is too high: " << JumpThreadCost << "\n");
1439 return false;
1440 }
1441
Chris Lattner5729d382009-11-07 08:05:03 +00001442 // And finally, do it! Start by factoring the predecessors is needed.
1443 BasicBlock *PredBB;
1444 if (PredBBs.size() == 1)
1445 PredBB = PredBBs[0];
1446 else {
David Greenefe7fe662010-01-05 01:27:19 +00001447 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
Chris Lattner5729d382009-11-07 08:05:03 +00001448 << " common predecessors.\n");
1449 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1450 ".thr_comm", this);
1451 }
1452
Mike Stumpfe095f32009-05-04 18:40:41 +00001453 // And finally, do it!
David Greenefe7fe662010-01-05 01:27:19 +00001454 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +00001455 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001456 << ", across block:\n "
1457 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +00001458
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001459 if (LVI)
1460 LVI->threadEdge(PredBB, BB, SuccBB);
1461
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001462 // We are going to have to map operands from the original BB block to the new
1463 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
1464 // account for entry from PredBB.
1465 DenseMap<Instruction*, Value*> ValueMapping;
1466
Owen Anderson1d0be152009-08-13 21:58:54 +00001467 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1468 BB->getName()+".thread",
1469 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001470 NewBB->moveAfter(PredBB);
1471
1472 BasicBlock::iterator BI = BB->begin();
1473 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1474 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1475
1476 // Clone the non-phi instructions of BB into NewBB, keeping track of the
1477 // mapping and using it to remap operands in the cloned instructions.
1478 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +00001479 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001480 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001481 NewBB->getInstList().push_back(New);
1482 ValueMapping[BI] = New;
1483
1484 // Remap operands to patch up intra-block references.
1485 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +00001486 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1487 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1488 if (I != ValueMapping.end())
1489 New->setOperand(i, I->second);
1490 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001491 }
1492
1493 // We didn't copy the terminator from BB over to NewBB, because there is now
1494 // an unconditional jump to SuccBB. Insert the unconditional jump.
1495 BranchInst::Create(SuccBB, NewBB);
1496
1497 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1498 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +00001499 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001500
Chris Lattner433a0db2009-10-10 09:05:58 +00001501 // If there were values defined in BB that are used outside the block, then we
1502 // now have to update all uses of the value to use either the original value,
1503 // the cloned value, or some PHI derived value. This can require arbitrary
1504 // PHI insertion, of which we are prepared to do, clean these up now.
1505 SSAUpdater SSAUpdate;
1506 SmallVector<Use*, 16> UsesToRename;
1507 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1508 // Scan all uses of this instruction to see if it is used outside of its
1509 // block, and if so, record them in UsesToRename.
1510 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1511 ++UI) {
1512 Instruction *User = cast<Instruction>(*UI);
1513 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1514 if (UserPN->getIncomingBlock(UI) == BB)
1515 continue;
1516 } else if (User->getParent() == BB)
1517 continue;
1518
1519 UsesToRename.push_back(&UI.getUse());
1520 }
1521
1522 // If there are no uses outside the block, we're done with this instruction.
1523 if (UsesToRename.empty())
1524 continue;
1525
David Greenefe7fe662010-01-05 01:27:19 +00001526 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001527
1528 // We found a use of I outside of BB. Rename all uses of I that are outside
1529 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1530 // with the two values we know.
Eric Christopheradc581f2010-09-01 17:29:10 +00001531 SSAUpdate.Initialize(I);
Chris Lattner433a0db2009-10-10 09:05:58 +00001532 SSAUpdate.AddAvailableValue(BB, I);
1533 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1534
1535 while (!UsesToRename.empty())
1536 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001537 DEBUG(dbgs() << "\n");
Chris Lattner433a0db2009-10-10 09:05:58 +00001538 }
1539
1540
Chris Lattneref0c6742008-12-01 04:48:07 +00001541 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001542 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1543 // us to simplify any PHI nodes in BB.
1544 TerminatorInst *PredTerm = PredBB->getTerminator();
1545 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1546 if (PredTerm->getSuccessor(i) == BB) {
Chris Lattnerc2c23d02009-11-09 22:32:36 +00001547 RemovePredecessorAndSimplify(BB, PredBB, TD);
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001548 PredTerm->setSuccessor(i, NewBB);
1549 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001550
1551 // At this point, the IR is fully up to date and consistent. Do a quick scan
1552 // over the new instructions and zap any that are constants or dead. This
1553 // frequently happens because of phi translation.
Chris Lattner972a46c2010-01-12 20:41:47 +00001554 SimplifyInstructionsInBlock(NewBB, TD);
Mike Stumpfe095f32009-05-04 18:40:41 +00001555
1556 // Threaded an edge!
1557 ++NumThreads;
1558 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001559}
Chris Lattner78c552e2009-10-11 07:24:57 +00001560
1561/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1562/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1563/// If we can duplicate the contents of BB up into PredBB do so now, this
1564/// improves the odds that the branch will be on an analyzable instruction like
1565/// a compare.
1566bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
Chris Lattner2249a0b2010-01-12 02:07:17 +00001567 const SmallVectorImpl<BasicBlock *> &PredBBs) {
1568 assert(!PredBBs.empty() && "Can't handle an empty set");
1569
Chris Lattner78c552e2009-10-11 07:24:57 +00001570 // If BB is a loop header, then duplicating this block outside the loop would
1571 // cause us to transform this into an irreducible loop, don't do this.
1572 // See the comments above FindLoopHeaders for justifications and caveats.
1573 if (LoopHeaders.count(BB)) {
David Greenefe7fe662010-01-05 01:27:19 +00001574 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
Chris Lattner2249a0b2010-01-12 02:07:17 +00001575 << "' into predecessor block '" << PredBBs[0]->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001576 << "' - it might create an irreducible loop!\n");
1577 return false;
1578 }
1579
1580 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1581 if (DuplicationCost > Threshold) {
David Greenefe7fe662010-01-05 01:27:19 +00001582 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +00001583 << "' - Cost is too high: " << DuplicationCost << "\n");
1584 return false;
1585 }
1586
Chris Lattner2249a0b2010-01-12 02:07:17 +00001587 // And finally, do it! Start by factoring the predecessors is needed.
1588 BasicBlock *PredBB;
1589 if (PredBBs.size() == 1)
1590 PredBB = PredBBs[0];
1591 else {
1592 DEBUG(dbgs() << " Factoring out " << PredBBs.size()
1593 << " common predecessors.\n");
1594 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
1595 ".thr_comm", this);
1596 }
1597
Chris Lattner78c552e2009-10-11 07:24:57 +00001598 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1599 // of PredBB.
David Greenefe7fe662010-01-05 01:27:19 +00001600 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
Chris Lattner78c552e2009-10-11 07:24:57 +00001601 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1602 << DuplicationCost << " block is:" << *BB << "\n");
1603
Chris Lattner2249a0b2010-01-12 02:07:17 +00001604 // Unless PredBB ends with an unconditional branch, split the edge so that we
1605 // can just clone the bits from BB into the end of the new PredBB.
Chris Lattnerd6688392010-01-23 19:21:31 +00001606 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
Chris Lattner2249a0b2010-01-12 02:07:17 +00001607
Chris Lattnerd6688392010-01-23 19:21:31 +00001608 if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
Chris Lattner2249a0b2010-01-12 02:07:17 +00001609 PredBB = SplitEdge(PredBB, BB, this);
1610 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1611 }
1612
Chris Lattner78c552e2009-10-11 07:24:57 +00001613 // We are going to have to map operands from the original BB block into the
1614 // PredBB block. Evaluate PHI nodes in BB.
1615 DenseMap<Instruction*, Value*> ValueMapping;
1616
1617 BasicBlock::iterator BI = BB->begin();
1618 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1619 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1620
Chris Lattner78c552e2009-10-11 07:24:57 +00001621 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1622 // mapping and using it to remap operands in the cloned instructions.
1623 for (; BI != BB->end(); ++BI) {
1624 Instruction *New = BI->clone();
Chris Lattner78c552e2009-10-11 07:24:57 +00001625
1626 // Remap operands to patch up intra-block references.
1627 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1628 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1629 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1630 if (I != ValueMapping.end())
1631 New->setOperand(i, I->second);
1632 }
Chris Lattner972a46c2010-01-12 20:41:47 +00001633
1634 // If this instruction can be simplified after the operands are updated,
1635 // just use the simplified value instead. This frequently happens due to
1636 // phi translation.
1637 if (Value *IV = SimplifyInstruction(New, TD)) {
1638 delete New;
1639 ValueMapping[BI] = IV;
1640 } else {
1641 // Otherwise, insert the new instruction into the block.
1642 New->setName(BI->getName());
1643 PredBB->getInstList().insert(OldPredBranch, New);
1644 ValueMapping[BI] = New;
1645 }
Chris Lattner78c552e2009-10-11 07:24:57 +00001646 }
1647
1648 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1649 // add entries to the PHI nodes for branch from PredBB now.
1650 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1651 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1652 ValueMapping);
1653 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1654 ValueMapping);
1655
1656 // If there were values defined in BB that are used outside the block, then we
1657 // now have to update all uses of the value to use either the original value,
1658 // the cloned value, or some PHI derived value. This can require arbitrary
1659 // PHI insertion, of which we are prepared to do, clean these up now.
1660 SSAUpdater SSAUpdate;
1661 SmallVector<Use*, 16> UsesToRename;
1662 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1663 // Scan all uses of this instruction to see if it is used outside of its
1664 // block, and if so, record them in UsesToRename.
1665 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1666 ++UI) {
1667 Instruction *User = cast<Instruction>(*UI);
1668 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1669 if (UserPN->getIncomingBlock(UI) == BB)
1670 continue;
1671 } else if (User->getParent() == BB)
1672 continue;
1673
1674 UsesToRename.push_back(&UI.getUse());
1675 }
1676
1677 // If there are no uses outside the block, we're done with this instruction.
1678 if (UsesToRename.empty())
1679 continue;
1680
David Greenefe7fe662010-01-05 01:27:19 +00001681 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001682
1683 // We found a use of I outside of BB. Rename all uses of I that are outside
1684 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1685 // with the two values we know.
Eric Christopheradc581f2010-09-01 17:29:10 +00001686 SSAUpdate.Initialize(I);
Chris Lattner78c552e2009-10-11 07:24:57 +00001687 SSAUpdate.AddAvailableValue(BB, I);
1688 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1689
1690 while (!UsesToRename.empty())
1691 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
David Greenefe7fe662010-01-05 01:27:19 +00001692 DEBUG(dbgs() << "\n");
Chris Lattner78c552e2009-10-11 07:24:57 +00001693 }
1694
1695 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1696 // that we nuked.
Chris Lattnerc2c23d02009-11-09 22:32:36 +00001697 RemovePredecessorAndSimplify(BB, PredBB, TD);
Chris Lattner78c552e2009-10-11 07:24:57 +00001698
1699 // Remove the unconditional branch at the end of the PredBB block.
1700 OldPredBranch->eraseFromParent();
1701
1702 ++NumDupes;
1703 return true;
1704}
1705
1706