blob: 8b11edd891fd57f6e22cfc1518e1ab7141fad105 [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
Chris Lattneref0c6742008-12-01 04:48:07 +000071 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneref0c6742008-12-01 04:48:07 +000072 }
73
Chris Lattner8383a7b2008-04-20 20:35:01 +000074 bool runOnFunction(Function &F);
Mike Stumpfe095f32009-05-04 18:40:41 +000075 void FindLoopHeaders(Function &F);
76
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000077 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbdbf1a12009-10-11 04:33:43 +000078 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner78c552e2009-10-11 07:24:57 +000079 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
80 BasicBlock *PredBB);
81
Nick Lewycky9683f182009-06-19 04:56:29 +000082 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Value *Val);
Chris Lattner421fa9e2008-12-03 07:48:08 +000083 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner3cda3cd2008-12-04 06:31:07 +000084 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000085
Chris Lattnerd38c14e2008-04-22 06:36:15 +000086 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000087 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000088 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000089
90 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000091 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000092}
93
Dan Gohman844731a2008-05-13 00:00:25 +000094char JumpThreading::ID = 0;
95static RegisterPass<JumpThreading>
96X("jump-threading", "Jump Threading");
97
Chris Lattner8383a7b2008-04-20 20:35:01 +000098// Public interface to the Jump Threading pass
99FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
100
101/// runOnFunction - Top level algorithm.
102///
103bool JumpThreading::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000104 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n");
Dan Gohman02a436c2009-07-24 18:13:53 +0000105 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000106
Mike Stumpfe095f32009-05-04 18:40:41 +0000107 FindLoopHeaders(F);
108
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000109 bool AnotherIteration = true, EverChanged = false;
110 while (AnotherIteration) {
111 AnotherIteration = false;
112 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000113 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
114 BasicBlock *BB = I;
115 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000116 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000117
118 ++I;
119
120 // If the block is trivially dead, zap it. This eliminates the successor
121 // edges which simplifies the CFG.
122 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner20fa76e2008-12-08 22:44:07 +0000123 BB != &BB->getParent()->getEntryBlock()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000124 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000125 << "' with terminator: " << *BB->getTerminator() << '\n');
Mike Stumpfe095f32009-05-04 18:40:41 +0000126 LoopHeaders.erase(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000127 DeleteDeadBlock(BB);
128 Changed = true;
129 }
130 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000131 AnotherIteration = Changed;
132 EverChanged |= Changed;
133 }
Mike Stumpfe095f32009-05-04 18:40:41 +0000134
135 LoopHeaders.clear();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000136 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000137}
Chris Lattner177480b2008-04-20 21:13:06 +0000138
Chris Lattner78c552e2009-10-11 07:24:57 +0000139/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
140/// thread across it.
141static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
142 /// Ignore PHI nodes, these will be flattened when duplication happens.
143 BasicBlock::const_iterator I = BB->getFirstNonPHI();
144
145 // Sum up the cost of each instruction until we get to the terminator. Don't
146 // include the terminator because the copy won't include it.
147 unsigned Size = 0;
148 for (; !isa<TerminatorInst>(I); ++I) {
149 // Debugger intrinsics don't incur code size.
150 if (isa<DbgInfoIntrinsic>(I)) continue;
151
152 // If this is a pointer->pointer bitcast, it is free.
153 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
154 continue;
155
156 // All other instructions count for at least one unit.
157 ++Size;
158
159 // Calls are more expensive. If they are non-intrinsic calls, we model them
160 // as having cost of 4. If they are a non-vector intrinsic, we model them
161 // as having cost of 2 total, and if they are a vector intrinsic, we model
162 // them as having cost 1.
163 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
164 if (!isa<IntrinsicInst>(CI))
165 Size += 3;
166 else if (!isa<VectorType>(CI->getType()))
167 Size += 1;
168 }
169 }
170
171 // Threading through a switch statement is particularly profitable. If this
172 // block ends in a switch, decrease its cost to make it more likely to happen.
173 if (isa<SwitchInst>(I))
174 Size = Size > 6 ? Size-6 : 0;
175
176 return Size;
177}
178
179
180
Mike Stumpfe095f32009-05-04 18:40:41 +0000181/// FindLoopHeaders - We do not want jump threading to turn proper loop
182/// structures into irreducible loops. Doing this breaks up the loop nesting
183/// hierarchy and pessimizes later transformations. To prevent this from
184/// happening, we first have to find the loop headers. Here we approximate this
185/// by finding targets of backedges in the CFG.
186///
187/// Note that there definitely are cases when we want to allow threading of
188/// edges across a loop header. For example, threading a jump from outside the
189/// loop (the preheader) to an exit block of the loop is definitely profitable.
190/// It is also almost always profitable to thread backedges from within the loop
191/// to exit blocks, and is often profitable to thread backedges to other blocks
192/// within the loop (forming a nested loop). This simple analysis is not rich
193/// enough to track all of these properties and keep it up-to-date as the CFG
194/// mutates, so we don't allow any of these transformations.
195///
196void JumpThreading::FindLoopHeaders(Function &F) {
197 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
198 FindFunctionBackedges(F, Edges);
199
200 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
201 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
202}
203
204
Chris Lattner6bf77502008-04-22 07:05:46 +0000205/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
206/// value for the PHI, factor them together so we get one block to thread for
207/// the whole group.
208/// This is important for things like "phi i1 [true, true, false, true, x]"
209/// where we only need to clone the block for the true blocks once.
210///
Nick Lewycky9683f182009-06-19 04:56:29 +0000211BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Value *Val) {
Chris Lattner6bf77502008-04-22 07:05:46 +0000212 SmallVector<BasicBlock*, 16> CommonPreds;
213 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Nick Lewycky9683f182009-06-19 04:56:29 +0000214 if (PN->getIncomingValue(i) == Val)
Chris Lattner6bf77502008-04-22 07:05:46 +0000215 CommonPreds.push_back(PN->getIncomingBlock(i));
216
217 if (CommonPreds.size() == 1)
218 return CommonPreds[0];
219
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000220 DEBUG(errs() << " Factoring out " << CommonPreds.size()
221 << " common predecessors.\n");
Chris Lattner6bf77502008-04-22 07:05:46 +0000222 return SplitBlockPredecessors(PN->getParent(),
223 &CommonPreds[0], CommonPreds.size(),
224 ".thr_comm", this);
225}
226
227
Chris Lattnere33583b2009-10-11 04:18:15 +0000228/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
229/// in an undefined jump, decide which block is best to revector to.
230///
231/// Since we can pick an arbitrary destination, we pick the successor with the
232/// fewest predecessors. This should reduce the in-degree of the others.
233///
234static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
235 TerminatorInst *BBTerm = BB->getTerminator();
236 unsigned MinSucc = 0;
237 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
238 // Compute the successor with the minimum number of predecessors.
239 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
240 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
241 TestBB = BBTerm->getSuccessor(i);
242 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
243 if (NumPreds < MinNumPreds)
244 MinSucc = i;
245 }
246
247 return MinSucc;
248}
249
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000250/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000251/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000252bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000253 // If this block has a single predecessor, and if that pred has a single
254 // successor, merge the blocks. This encourages recursive jump threading
255 // because now the condition in this block can be threaded through
256 // predecessors of our predecessor block.
257 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000258 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
259 SinglePred != BB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000260 // If SinglePred was a loop header, BB becomes one.
261 if (LoopHeaders.erase(SinglePred))
262 LoopHeaders.insert(BB);
263
Chris Lattner3d86d242008-11-27 19:25:19 +0000264 // Remember if SinglePred was the entry block of the function. If so, we
265 // will need to move BB back to the entry position.
266 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000267 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000268
269 if (isEntry && BB != &BB->getParent()->getEntryBlock())
270 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000271 return true;
272 }
273
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000274 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000275 // condition is a phi node. If so, and if an entry of the phi node is a
276 // constant, we can thread the block.
277 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000278 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
279 // Can't thread an unconditional jump.
280 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000281 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000282 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000283 Condition = SI->getCondition();
284 else
285 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000286
287 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000288 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000289 // other blocks.
290 if (isa<ConstantInt>(Condition)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000291 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000292 << "' folding terminator: " << *BB->getTerminator() << '\n');
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000293 ++NumFolds;
294 ConstantFoldTerminator(BB);
295 return true;
296 }
297
Chris Lattner421fa9e2008-12-03 07:48:08 +0000298 // If the terminator is branching on an undef, we can pick any of the
Chris Lattnere33583b2009-10-11 04:18:15 +0000299 // successors to branch to. Let GetBestDestForJumpOnUndef decide.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000300 if (isa<UndefValue>(Condition)) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000301 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000302
303 // Fold the branch/switch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000304 TerminatorInst *BBTerm = BB->getTerminator();
Chris Lattner421fa9e2008-12-03 07:48:08 +0000305 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
Chris Lattnere33583b2009-10-11 04:18:15 +0000306 if (i == BestSucc) continue;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000307 BBTerm->getSuccessor(i)->removePredecessor(BB);
308 }
309
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000310 DEBUG(errs() << " In block '" << BB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000311 << "' folding undef terminator: " << *BBTerm << '\n');
Chris Lattnere33583b2009-10-11 04:18:15 +0000312 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000313 BBTerm->eraseFromParent();
314 return true;
315 }
316
317 Instruction *CondInst = dyn_cast<Instruction>(Condition);
318
319 // If the condition is an instruction defined in another block, see if a
320 // predecessor has the same condition:
321 // br COND, BBX, BBY
322 // BBX:
323 // br COND, BBZ, BBW
324 if (!Condition->hasOneUse() && // Multiple uses.
325 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
326 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
327 if (isa<BranchInst>(BB->getTerminator())) {
328 for (; PI != E; ++PI)
329 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
330 if (PBI->isConditional() && PBI->getCondition() == Condition &&
331 ProcessBranchOnDuplicateCond(*PI, BB))
332 return true;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000333 } else {
334 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
335 for (; PI != E; ++PI)
336 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
337 if (PSI->getCondition() == Condition &&
338 ProcessSwitchOnDuplicateCond(*PI, BB))
339 return true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000340 }
341 }
342
Chris Lattner421fa9e2008-12-03 07:48:08 +0000343 // All the rest of our checks depend on the condition being an instruction.
344 if (CondInst == 0)
345 return false;
346
Chris Lattner177480b2008-04-20 21:13:06 +0000347 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000348 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
349 if (PN->getParent() == BB)
350 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000351
Chris Lattner6bf77502008-04-22 07:05:46 +0000352 // If this is a conditional branch whose condition is and/or of a phi, try to
353 // simplify it.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000354 if ((CondInst->getOpcode() == Instruction::And ||
355 CondInst->getOpcode() == Instruction::Or) &&
356 isa<BranchInst>(BB->getTerminator()) &&
357 ProcessBranchOnLogical(CondInst, BB,
358 CondInst->getOpcode() == Instruction::And))
359 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000360
Nick Lewycky9683f182009-06-19 04:56:29 +0000361 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
362 if (isa<PHINode>(CondCmp->getOperand(0))) {
363 // If we have "br (phi != 42)" and the phi node has any constant values
364 // as operands, we can thread through this block.
365 //
366 // If we have "br (cmp phi, x)" and the phi node contains x such that the
367 // comparison uniquely identifies the branch target, we can thread
368 // through this block.
369
370 if (ProcessBranchOnCompare(CondCmp, BB))
371 return true;
372 }
Chris Lattner79c740f2009-06-19 16:27:56 +0000373
374 // If we have a comparison, loop over the predecessors to see if there is
375 // a condition with the same value.
376 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
377 for (; PI != E; ++PI)
378 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
379 if (PBI->isConditional() && *PI != BB) {
380 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
381 if (CI->getOperand(0) == CondCmp->getOperand(0) &&
382 CI->getOperand(1) == CondCmp->getOperand(1) &&
383 CI->getPredicate() == CondCmp->getPredicate()) {
384 // TODO: Could handle things like (x != 4) --> (x == 17)
385 if (ProcessBranchOnDuplicateCond(*PI, BB))
386 return true;
387 }
388 }
389 }
Nick Lewycky9683f182009-06-19 04:56:29 +0000390 }
Chris Lattner69e067f2008-11-27 05:07:53 +0000391
392 // Check for some cases that are worth simplifying. Right now we want to look
393 // for loads that are used by a switch or by the condition for the branch. If
394 // we see one, check to see if it's partially redundant. If so, insert a PHI
395 // which can then be used to thread the values.
396 //
397 // This is particularly important because reg2mem inserts loads and stores all
398 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000399 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000400 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
401 if (isa<Constant>(CondCmp->getOperand(1)))
402 SimplifyValue = CondCmp->getOperand(0);
403
404 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
405 if (SimplifyPartiallyRedundantLoad(LI))
406 return true;
407
408 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
409 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000410
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000411 return false;
412}
413
Chris Lattner421fa9e2008-12-03 07:48:08 +0000414/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
415/// block that jump on exactly the same condition. This means that we almost
416/// always know the direction of the edge in the DESTBB:
417/// PREDBB:
418/// br COND, DESTBB, BBY
419/// DESTBB:
420/// br COND, BBZ, BBW
421///
422/// If DESTBB has multiple predecessors, we can't just constant fold the branch
423/// in DESTBB, we have to thread over it.
424bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
425 BasicBlock *BB) {
426 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
427
428 // If both successors of PredBB go to DESTBB, we don't know anything. We can
429 // fold the branch to an unconditional one, which allows other recursive
430 // simplifications.
431 bool BranchDir;
432 if (PredBI->getSuccessor(1) != BB)
433 BranchDir = true;
434 else if (PredBI->getSuccessor(0) != BB)
435 BranchDir = false;
436 else {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000437 DEBUG(errs() << " In block '" << PredBB->getName()
Chris Lattner78c552e2009-10-11 07:24:57 +0000438 << "' folding terminator: " << *PredBB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000439 ++NumFolds;
440 ConstantFoldTerminator(PredBB);
441 return true;
442 }
443
444 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
445
446 // If the dest block has one predecessor, just fix the branch condition to a
447 // constant and fold it.
448 if (BB->getSinglePredecessor()) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000449 DEBUG(errs() << " In block '" << BB->getName()
450 << "' folding condition to '" << BranchDir << "': "
Chris Lattner78c552e2009-10-11 07:24:57 +0000451 << *BB->getTerminator() << '\n');
Chris Lattner421fa9e2008-12-03 07:48:08 +0000452 ++NumFolds;
Chris Lattner5a06cf62009-10-11 18:39:58 +0000453 Value *OldCond = DestBI->getCondition();
Owen Anderson1d0be152009-08-13 21:58:54 +0000454 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
455 BranchDir));
Chris Lattner421fa9e2008-12-03 07:48:08 +0000456 ConstantFoldTerminator(BB);
Chris Lattner5a06cf62009-10-11 18:39:58 +0000457 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000458 return true;
459 }
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000460
Chris Lattner421fa9e2008-12-03 07:48:08 +0000461
462 // Next, figure out which successor we are threading to.
463 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
464
Mike Stumpfe095f32009-05-04 18:40:41 +0000465 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000466 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner421fa9e2008-12-03 07:48:08 +0000467}
468
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000469/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
470/// block that switch on exactly the same condition. This means that we almost
471/// always know the direction of the edge in the DESTBB:
472/// PREDBB:
473/// switch COND [... DESTBB, BBY ... ]
474/// DESTBB:
475/// switch COND [... BBZ, BBW ]
476///
477/// Optimizing switches like this is very important, because simplifycfg builds
478/// switches out of repeated 'if' conditions.
479bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
480 BasicBlock *DestBB) {
Chris Lattner2c7ed112009-01-19 21:20:34 +0000481 // Can't thread edge to self.
482 if (PredBB == DestBB)
483 return false;
484
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000485 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
486 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
487
488 // There are a variety of optimizations that we can potentially do on these
489 // blocks: we order them from most to least preferable.
490
491 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
492 // directly to their destination. This does not introduce *any* code size
Dale Johannesen6b233392009-03-17 00:38:24 +0000493 // growth. Skip debug info first.
494 BasicBlock::iterator BBI = DestBB->begin();
495 while (isa<DbgInfoIntrinsic>(BBI))
496 BBI++;
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000497
498 // FIXME: Thread if it just contains a PHI.
Dale Johannesen6b233392009-03-17 00:38:24 +0000499 if (isa<SwitchInst>(BBI)) {
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000500 bool MadeChange = false;
501 // Ignore the default edge for now.
502 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
503 ConstantInt *DestVal = DestSI->getCaseValue(i);
504 BasicBlock *DestSucc = DestSI->getSuccessor(i);
505
506 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
507 // PredSI has an explicit case for it. If so, forward. If it is covered
508 // by the default case, we can't update PredSI.
509 unsigned PredCase = PredSI->findCaseValue(DestVal);
510 if (PredCase == 0) continue;
511
512 // If PredSI doesn't go to DestBB on this value, then it won't reach the
513 // case on this condition.
514 if (PredSI->getSuccessor(PredCase) != DestBB &&
515 DestSI->getSuccessor(i) != DestBB)
516 continue;
517
518 // Otherwise, we're safe to make the change. Make sure that the edge from
519 // DestSI to DestSucc is not critical and has no PHI nodes.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000520 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI);
521 DEBUG(errs() << "THROUGH: " << *DestSI);
Chris Lattner3cda3cd2008-12-04 06:31:07 +0000522
523 // If the destination has PHI nodes, just split the edge for updating
524 // simplicity.
525 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
526 SplitCriticalEdge(DestSI, i, this);
527 DestSucc = DestSI->getSuccessor(i);
528 }
529 FoldSingleEntryPHINodes(DestSucc);
530 PredSI->setSuccessor(PredCase, DestSucc);
531 MadeChange = true;
532 }
533
534 if (MadeChange)
535 return true;
536 }
537
538 return false;
539}
540
541
Chris Lattner69e067f2008-11-27 05:07:53 +0000542/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
543/// load instruction, eliminate it by replacing it with a PHI node. This is an
544/// important optimization that encourages jump threading, and needs to be run
545/// interlaced with other jump threading tasks.
546bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
547 // Don't hack volatile loads.
548 if (LI->isVolatile()) return false;
549
550 // If the load is defined in a block with exactly one predecessor, it can't be
551 // partially redundant.
552 BasicBlock *LoadBB = LI->getParent();
553 if (LoadBB->getSinglePredecessor())
554 return false;
555
556 Value *LoadedPtr = LI->getOperand(0);
557
558 // If the loaded operand is defined in the LoadBB, it can't be available.
559 // FIXME: Could do PHI translation, that would be fun :)
560 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
561 if (PtrOp->getParent() == LoadBB)
562 return false;
563
564 // Scan a few instructions up from the load, to see if it is obviously live at
565 // the entry to its block.
566 BasicBlock::iterator BBIt = LI;
567
Chris Lattner52c95852008-11-27 08:10:05 +0000568 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
569 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000570 // If the value if the load is locally available within the block, just use
571 // it. This frequently occurs for reg2mem'd allocas.
572 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
Chris Lattner2a99b482009-01-09 06:08:12 +0000573
574 // If the returned value is the load itself, replace with an undef. This can
575 // only happen in dead loops.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000576 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
Chris Lattner69e067f2008-11-27 05:07:53 +0000577 LI->replaceAllUsesWith(AvailableVal);
578 LI->eraseFromParent();
579 return true;
580 }
581
582 // Otherwise, if we scanned the whole block and got to the top of the block,
583 // we know the block is locally transparent to the load. If not, something
584 // might clobber its value.
585 if (BBIt != LoadBB->begin())
586 return false;
587
588
589 SmallPtrSet<BasicBlock*, 8> PredsScanned;
590 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
591 AvailablePredsTy AvailablePreds;
592 BasicBlock *OneUnavailablePred = 0;
593
594 // If we got here, the loaded value is transparent through to the start of the
595 // block. Check to see if it is available in any of the predecessor blocks.
596 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
597 PI != PE; ++PI) {
598 BasicBlock *PredBB = *PI;
599
600 // If we already scanned this predecessor, skip it.
601 if (!PredsScanned.insert(PredBB))
602 continue;
603
604 // Scan the predecessor to see if the value is available in the pred.
605 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000606 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000607 if (!PredAvailable) {
608 OneUnavailablePred = PredBB;
609 continue;
610 }
611
612 // If so, this load is partially redundant. Remember this info so that we
613 // can create a PHI node.
614 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
615 }
616
617 // If the loaded value isn't available in any predecessor, it isn't partially
618 // redundant.
619 if (AvailablePreds.empty()) return false;
620
621 // Okay, the loaded value is available in at least one (and maybe all!)
622 // predecessors. If the value is unavailable in more than one unique
623 // predecessor, we want to insert a merge block for those common predecessors.
624 // This ensures that we only have to insert one reload, thus not increasing
625 // code size.
626 BasicBlock *UnavailablePred = 0;
627
628 // If there is exactly one predecessor where the value is unavailable, the
629 // already computed 'OneUnavailablePred' block is it. If it ends in an
630 // unconditional branch, we know that it isn't a critical edge.
631 if (PredsScanned.size() == AvailablePreds.size()+1 &&
632 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
633 UnavailablePred = OneUnavailablePred;
634 } else if (PredsScanned.size() != AvailablePreds.size()) {
635 // Otherwise, we had multiple unavailable predecessors or we had a critical
636 // edge from the one.
637 SmallVector<BasicBlock*, 8> PredsToSplit;
638 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
639
640 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
641 AvailablePredSet.insert(AvailablePreds[i].first);
642
643 // Add all the unavailable predecessors to the PredsToSplit list.
644 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
645 PI != PE; ++PI)
646 if (!AvailablePredSet.count(*PI))
647 PredsToSplit.push_back(*PI);
648
649 // Split them out to their own block.
650 UnavailablePred =
651 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
652 "thread-split", this);
653 }
654
655 // If the value isn't available in all predecessors, then there will be
656 // exactly one where it isn't available. Insert a load on that edge and add
657 // it to the AvailablePreds list.
658 if (UnavailablePred) {
659 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
660 "Can't handle critical edge here!");
661 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
662 UnavailablePred->getTerminator());
663 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
664 }
665
666 // Now we know that each predecessor of this block has a value in
667 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000668 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000669
670 // Create a PHI node at the start of the block for the PRE'd load value.
671 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
672 PN->takeName(LI);
673
674 // Insert new entries into the PHI for each predecessor. A single block may
675 // have multiple entries here.
676 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
677 ++PI) {
678 AvailablePredsTy::iterator I =
679 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
680 std::make_pair(*PI, (Value*)0));
681
682 assert(I != AvailablePreds.end() && I->first == *PI &&
683 "Didn't find entry for predecessor!");
684
685 PN->addIncoming(I->second, I->first);
686 }
687
688 //cerr << "PRE: " << *LI << *PN << "\n";
689
690 LI->replaceAllUsesWith(PN);
691 LI->eraseFromParent();
692
693 return true;
694}
695
696
Chris Lattnere33583b2009-10-11 04:18:15 +0000697/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000698/// the current block. See if there are any simplifications we can do based on
699/// inputs to the phi node.
700///
701bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000702 BasicBlock *BB = PN->getParent();
703
Chris Lattnere33583b2009-10-11 04:18:15 +0000704 // See if the phi node has any constant integer or undef values. If so, we
705 // can determine where the corresponding predecessor will branch.
Chris Lattnere33583b2009-10-11 04:18:15 +0000706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
707 Value *PredVal = PN->getIncomingValue(i);
Chris Lattner6b65f472009-10-11 04:40:21 +0000708
709 // Check to see if this input is a constant integer. If so, the direction
710 // of the branch is predictable.
Chris Lattnere33583b2009-10-11 04:18:15 +0000711 if (ConstantInt *CI = dyn_cast<ConstantInt>(PredVal)) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000712 // Merge any common predecessors that will act the same.
713 BasicBlock *PredBB = FactorCommonPHIPreds(PN, CI);
714
715 BasicBlock *SuccBB;
716 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
717 SuccBB = BI->getSuccessor(CI->isZero());
718 else {
719 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
720 SuccBB = SI->getSuccessor(SI->findCaseValue(CI));
721 }
722
723 // Ok, try to thread it!
724 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattnere33583b2009-10-11 04:18:15 +0000725 }
726
Chris Lattner6b65f472009-10-11 04:40:21 +0000727 // If the input is an undef, then it doesn't matter which way it will go.
728 // Pick an arbitrary dest and thread the edge.
Chris Lattnere33583b2009-10-11 04:18:15 +0000729 if (UndefValue *UV = dyn_cast<UndefValue>(PredVal)) {
Chris Lattner6b65f472009-10-11 04:40:21 +0000730 // Merge any common predecessors that will act the same.
731 BasicBlock *PredBB = FactorCommonPHIPreds(PN, UV);
732 BasicBlock *SuccBB =
733 BB->getTerminator()->getSuccessor(GetBestDestForJumpOnUndef(BB));
734
735 // Ok, try to thread it!
736 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattnere33583b2009-10-11 04:18:15 +0000737 }
Chris Lattner6b65f472009-10-11 04:40:21 +0000738 }
Chris Lattnerf9065a92008-04-20 21:18:09 +0000739
Chris Lattner78c552e2009-10-11 07:24:57 +0000740 // If the incoming values are all variables, we don't know the destination of
741 // any predecessors. However, if any of the predecessor blocks end in an
742 // unconditional branch, we can *duplicate* the jump into that block in order
743 // to further encourage jump threading and to eliminate cases where we have
744 // branch on a phi of an icmp (branch on icmp is much better).
745
746 // We don't want to do this tranformation for switches, because we don't
747 // really want to duplicate a switch.
748 if (isa<SwitchInst>(BB->getTerminator()))
749 return false;
750
751 // Look for unconditional branch predecessors.
752 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
753 BasicBlock *PredBB = PN->getIncomingBlock(i);
754 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
755 if (PredBr->isUnconditional() &&
756 // Try to duplicate BB into PredBB.
757 DuplicateCondBranchOnPHIIntoPred(BB, PredBB))
758 return true;
759 }
760
Chris Lattner6b65f472009-10-11 04:40:21 +0000761 return false;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000762}
763
Chris Lattner78c552e2009-10-11 07:24:57 +0000764
Chris Lattner6bf77502008-04-22 07:05:46 +0000765/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
766/// whose condition is an AND/OR where one side is PN. If PN has constant
767/// operands that permit us to evaluate the condition for some operand, thread
768/// through the block. For example with:
769/// br (and X, phi(Y, Z, false))
770/// the predecessor corresponding to the 'false' will always jump to the false
771/// destination of the branch.
772///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000773bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
774 bool isAnd) {
775 // If this is a binary operator tree of the same AND/OR opcode, check the
776 // LHS/RHS.
777 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000778 if ((isAnd && BO->getOpcode() == Instruction::And) ||
779 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000780 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
781 return true;
782 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
783 return true;
784 }
785
786 // If this isn't a PHI node, we can't handle it.
787 PHINode *PN = dyn_cast<PHINode>(V);
788 if (!PN || PN->getParent() != BB) return false;
789
Chris Lattner6bf77502008-04-22 07:05:46 +0000790 // We can only do the simplification for phi nodes of 'false' with AND or
791 // 'true' with OR. See if we have any entries in the phi for this.
792 unsigned PredNo = ~0U;
Owen Anderson1d0be152009-08-13 21:58:54 +0000793 ConstantInt *PredCst = ConstantInt::get(Type::getInt1Ty(BB->getContext()),
794 !isAnd);
Chris Lattner6bf77502008-04-22 07:05:46 +0000795 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
796 if (PN->getIncomingValue(i) == PredCst) {
797 PredNo = i;
798 break;
799 }
800 }
801
802 // If no match, bail out.
803 if (PredNo == ~0U)
804 return false;
805
Chris Lattner6bf77502008-04-22 07:05:46 +0000806 // If so, we can actually do this threading. Merge any common predecessors
807 // that will act the same.
808 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
809
810 // Next, figure out which successor we are threading to. If this was an AND,
811 // the constant must be FALSE, and we must be targeting the 'false' block.
812 // If this is an OR, the constant must be TRUE, and we must be targeting the
813 // 'true' block.
814 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
815
Mike Stumpfe095f32009-05-04 18:40:41 +0000816 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000817 return ThreadEdge(BB, PredBB, SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +0000818}
819
Nick Lewycky9683f182009-06-19 04:56:29 +0000820/// GetResultOfComparison - Given an icmp/fcmp predicate and the left and right
821/// hand sides of the compare instruction, try to determine the result. If the
822/// result can not be determined, a null pointer is returned.
823static Constant *GetResultOfComparison(CmpInst::Predicate pred,
Owen Anderson1ff50b32009-07-03 00:54:20 +0000824 Value *LHS, Value *RHS,
Owen Andersone922c022009-07-22 00:24:57 +0000825 LLVMContext &Context) {
Nick Lewycky9683f182009-06-19 04:56:29 +0000826 if (Constant *CLHS = dyn_cast<Constant>(LHS))
827 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000828 return ConstantExpr::getCompare(pred, CLHS, CRHS);
Nick Lewycky9683f182009-06-19 04:56:29 +0000829
830 if (LHS == RHS)
831 if (isa<IntegerType>(LHS->getType()) || isa<PointerType>(LHS->getType()))
832 return ICmpInst::isTrueWhenEqual(pred) ?
Owen Anderson5defacc2009-07-31 17:39:07 +0000833 ConstantInt::getTrue(Context) : ConstantInt::getFalse(Context);
Nick Lewycky9683f182009-06-19 04:56:29 +0000834
835 return 0;
836}
837
Chris Lattnera5ddb592008-04-22 21:40:39 +0000838/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
Nick Lewycky9683f182009-06-19 04:56:29 +0000839/// node and a value. If we can identify when the comparison is true between
840/// the phi inputs and the value, we can fold the compare for that edge and
841/// thread through it.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000842bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
843 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
Nick Lewycky9683f182009-06-19 04:56:29 +0000844 Value *RHS = Cmp->getOperand(1);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000845
846 // If the phi isn't in the current block, an incoming edge to this block
847 // doesn't control the destination.
848 if (PN->getParent() != BB)
849 return false;
850
851 // We can do this simplification if any comparisons fold to true or false.
852 // See if any do.
Nick Lewycky9683f182009-06-19 04:56:29 +0000853 Value *PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000854 bool TrueDirection = false;
855 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Nick Lewycky9683f182009-06-19 04:56:29 +0000856 PredVal = PN->getIncomingValue(i);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000857
Owen Anderson1ff50b32009-07-03 00:54:20 +0000858 Constant *Res = GetResultOfComparison(Cmp->getPredicate(), PredVal,
Owen Andersone922c022009-07-22 00:24:57 +0000859 RHS, Cmp->getContext());
Nick Lewycky9683f182009-06-19 04:56:29 +0000860 if (!Res) {
861 PredVal = 0;
862 continue;
863 }
864
Chris Lattnera5ddb592008-04-22 21:40:39 +0000865 // If this folded to a constant expr, we can't do anything.
866 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
867 TrueDirection = ResC->getZExtValue();
868 break;
869 }
870 // If this folded to undef, just go the false way.
871 if (isa<UndefValue>(Res)) {
872 TrueDirection = false;
873 break;
874 }
875
876 // Otherwise, we can't fold this input.
Nick Lewycky9683f182009-06-19 04:56:29 +0000877 PredVal = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000878 }
879
880 // If no match, bail out.
Nick Lewycky9683f182009-06-19 04:56:29 +0000881 if (PredVal == 0)
Chris Lattnera5ddb592008-04-22 21:40:39 +0000882 return false;
883
Chris Lattnera5ddb592008-04-22 21:40:39 +0000884 // If so, we can actually do this threading. Merge any common predecessors
885 // that will act the same.
Nick Lewycky9683f182009-06-19 04:56:29 +0000886 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredVal);
Chris Lattnera5ddb592008-04-22 21:40:39 +0000887
888 // Next, get our successor.
889 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
890
Mike Stumpfe095f32009-05-04 18:40:41 +0000891 // Ok, try to thread it!
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000892 return ThreadEdge(BB, PredBB, SuccBB);
893}
894
Chris Lattnera5ddb592008-04-22 21:40:39 +0000895
Chris Lattner78c552e2009-10-11 07:24:57 +0000896/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
897/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
898/// NewPred using the entries from OldPred (suitably mapped).
899static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
900 BasicBlock *OldPred,
901 BasicBlock *NewPred,
902 DenseMap<Instruction*, Value*> &ValueMap) {
903 for (BasicBlock::iterator PNI = PHIBB->begin();
904 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
905 // Ok, we have a PHI node. Figure out what the incoming value was for the
906 // DestBlock.
907 Value *IV = PN->getIncomingValueForBlock(OldPred);
908
909 // Remap the value if necessary.
910 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
911 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
912 if (I != ValueMap.end())
913 IV = I->second;
914 }
915
916 PN->addIncoming(IV, NewPred);
917 }
918}
Chris Lattner6bf77502008-04-22 07:05:46 +0000919
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000920/// ThreadEdge - We have decided that it is safe and profitable to thread an
921/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
922/// change.
Mike Stumpfe095f32009-05-04 18:40:41 +0000923bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
Chris Lattnerbdbf1a12009-10-11 04:33:43 +0000924 BasicBlock *SuccBB) {
Mike Stumpfe095f32009-05-04 18:40:41 +0000925 // If threading to the same block as we come from, we would infinite loop.
926 if (SuccBB == BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000927 DEBUG(errs() << " Not threading across BB '" << BB->getName()
928 << "' - would thread to self!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000929 return false;
930 }
931
932 // If threading this would thread across a loop header, don't thread the edge.
933 // See the comments above FindLoopHeaders for justifications and caveats.
934 if (LoopHeaders.count(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000935 DEBUG(errs() << " Not threading from '" << PredBB->getName()
936 << "' across loop header BB '" << BB->getName()
937 << "' to dest BB '" << SuccBB->getName()
938 << "' - it might create an irreducible loop!\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000939 return false;
940 }
941
Chris Lattner78c552e2009-10-11 07:24:57 +0000942 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
943 if (JumpThreadCost > Threshold) {
944 DEBUG(errs() << " Not threading BB '" << BB->getName()
945 << "' - Cost is too high: " << JumpThreadCost << "\n");
946 return false;
947 }
948
Mike Stumpfe095f32009-05-04 18:40:41 +0000949 // And finally, do it!
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000950 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '"
Daniel Dunbar460f6562009-07-26 09:48:23 +0000951 << SuccBB->getName() << "' with cost: " << JumpThreadCost
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000952 << ", across block:\n "
953 << *BB << "\n");
Mike Stumpfe095f32009-05-04 18:40:41 +0000954
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000955 // We are going to have to map operands from the original BB block to the new
956 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
957 // account for entry from PredBB.
958 DenseMap<Instruction*, Value*> ValueMapping;
959
Owen Anderson1d0be152009-08-13 21:58:54 +0000960 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
961 BB->getName()+".thread",
962 BB->getParent(), BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000963 NewBB->moveAfter(PredBB);
964
965 BasicBlock::iterator BI = BB->begin();
966 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
967 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
968
969 // Clone the non-phi instructions of BB into NewBB, keeping track of the
970 // mapping and using it to remap operands in the cloned instructions.
971 for (; !isa<TerminatorInst>(BI); ++BI) {
Nick Lewycky67760642009-09-27 07:38:41 +0000972 Instruction *New = BI->clone();
Daniel Dunbar460f6562009-07-26 09:48:23 +0000973 New->setName(BI->getName());
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000974 NewBB->getInstList().push_back(New);
975 ValueMapping[BI] = New;
976
977 // Remap operands to patch up intra-block references.
978 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
Dan Gohmanf530c922009-07-02 00:17:47 +0000979 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
980 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
981 if (I != ValueMapping.end())
982 New->setOperand(i, I->second);
983 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000984 }
985
986 // We didn't copy the terminator from BB over to NewBB, because there is now
987 // an unconditional jump to SuccBB. Insert the unconditional jump.
988 BranchInst::Create(SuccBB, NewBB);
989
990 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
991 // PHI nodes for NewBB now.
Chris Lattner78c552e2009-10-11 07:24:57 +0000992 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000993
Chris Lattner433a0db2009-10-10 09:05:58 +0000994 // If there were values defined in BB that are used outside the block, then we
995 // now have to update all uses of the value to use either the original value,
996 // the cloned value, or some PHI derived value. This can require arbitrary
997 // PHI insertion, of which we are prepared to do, clean these up now.
998 SSAUpdater SSAUpdate;
999 SmallVector<Use*, 16> UsesToRename;
1000 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1001 // Scan all uses of this instruction to see if it is used outside of its
1002 // block, and if so, record them in UsesToRename.
1003 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1004 ++UI) {
1005 Instruction *User = cast<Instruction>(*UI);
1006 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1007 if (UserPN->getIncomingBlock(UI) == BB)
1008 continue;
1009 } else if (User->getParent() == BB)
1010 continue;
1011
1012 UsesToRename.push_back(&UI.getUse());
1013 }
1014
1015 // If there are no uses outside the block, we're done with this instruction.
1016 if (UsesToRename.empty())
1017 continue;
1018
1019 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1020
1021 // We found a use of I outside of BB. Rename all uses of I that are outside
1022 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1023 // with the two values we know.
1024 SSAUpdate.Initialize(I);
1025 SSAUpdate.AddAvailableValue(BB, I);
1026 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
1027
1028 while (!UsesToRename.empty())
1029 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1030 DEBUG(errs() << "\n");
1031 }
1032
1033
Chris Lattneref0c6742008-12-01 04:48:07 +00001034 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +00001035 // NewBB instead of BB. This eliminates predecessors from BB, which requires
1036 // us to simplify any PHI nodes in BB.
1037 TerminatorInst *PredTerm = PredBB->getTerminator();
1038 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1039 if (PredTerm->getSuccessor(i) == BB) {
1040 BB->removePredecessor(PredBB);
1041 PredTerm->setSuccessor(i, NewBB);
1042 }
Chris Lattneref0c6742008-12-01 04:48:07 +00001043
1044 // At this point, the IR is fully up to date and consistent. Do a quick scan
1045 // over the new instructions and zap any that are constants or dead. This
1046 // frequently happens because of phi translation.
1047 BI = NewBB->begin();
1048 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
1049 Instruction *Inst = BI++;
Owen Anderson50895512009-07-06 18:42:36 +00001050 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattneref0c6742008-12-01 04:48:07 +00001051 Inst->replaceAllUsesWith(C);
1052 Inst->eraseFromParent();
1053 continue;
1054 }
1055
1056 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1057 }
Mike Stumpfe095f32009-05-04 18:40:41 +00001058
1059 // Threaded an edge!
1060 ++NumThreads;
1061 return true;
Chris Lattner177480b2008-04-20 21:13:06 +00001062}
Chris Lattner78c552e2009-10-11 07:24:57 +00001063
1064/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1065/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1066/// If we can duplicate the contents of BB up into PredBB do so now, this
1067/// improves the odds that the branch will be on an analyzable instruction like
1068/// a compare.
1069bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
1070 BasicBlock *PredBB) {
1071 // If BB is a loop header, then duplicating this block outside the loop would
1072 // cause us to transform this into an irreducible loop, don't do this.
1073 // See the comments above FindLoopHeaders for justifications and caveats.
1074 if (LoopHeaders.count(BB)) {
1075 DEBUG(errs() << " Not duplicating loop header '" << BB->getName()
1076 << "' into predecessor block '" << PredBB->getName()
1077 << "' - it might create an irreducible loop!\n");
1078 return false;
1079 }
1080
1081 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB);
1082 if (DuplicationCost > Threshold) {
1083 DEBUG(errs() << " Not duplicating BB '" << BB->getName()
1084 << "' - Cost is too high: " << DuplicationCost << "\n");
1085 return false;
1086 }
1087
1088 // Okay, we decided to do this! Clone all the instructions in BB onto the end
1089 // of PredBB.
1090 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '"
1091 << PredBB->getName() << "' to eliminate branch on phi. Cost: "
1092 << DuplicationCost << " block is:" << *BB << "\n");
1093
1094 // We are going to have to map operands from the original BB block into the
1095 // PredBB block. Evaluate PHI nodes in BB.
1096 DenseMap<Instruction*, Value*> ValueMapping;
1097
1098 BasicBlock::iterator BI = BB->begin();
1099 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1100 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1101
1102 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1103
1104 // Clone the non-phi instructions of BB into PredBB, keeping track of the
1105 // mapping and using it to remap operands in the cloned instructions.
1106 for (; BI != BB->end(); ++BI) {
1107 Instruction *New = BI->clone();
1108 New->setName(BI->getName());
1109 PredBB->getInstList().insert(OldPredBranch, New);
1110 ValueMapping[BI] = New;
1111
1112 // Remap operands to patch up intra-block references.
1113 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1114 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1115 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1116 if (I != ValueMapping.end())
1117 New->setOperand(i, I->second);
1118 }
1119 }
1120
1121 // Check to see if the targets of the branch had PHI nodes. If so, we need to
1122 // add entries to the PHI nodes for branch from PredBB now.
1123 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1124 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1125 ValueMapping);
1126 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1127 ValueMapping);
1128
1129 // If there were values defined in BB that are used outside the block, then we
1130 // now have to update all uses of the value to use either the original value,
1131 // the cloned value, or some PHI derived value. This can require arbitrary
1132 // PHI insertion, of which we are prepared to do, clean these up now.
1133 SSAUpdater SSAUpdate;
1134 SmallVector<Use*, 16> UsesToRename;
1135 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
1136 // Scan all uses of this instruction to see if it is used outside of its
1137 // block, and if so, record them in UsesToRename.
1138 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
1139 ++UI) {
1140 Instruction *User = cast<Instruction>(*UI);
1141 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1142 if (UserPN->getIncomingBlock(UI) == BB)
1143 continue;
1144 } else if (User->getParent() == BB)
1145 continue;
1146
1147 UsesToRename.push_back(&UI.getUse());
1148 }
1149
1150 // If there are no uses outside the block, we're done with this instruction.
1151 if (UsesToRename.empty())
1152 continue;
1153
1154 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n");
1155
1156 // We found a use of I outside of BB. Rename all uses of I that are outside
1157 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1158 // with the two values we know.
1159 SSAUpdate.Initialize(I);
1160 SSAUpdate.AddAvailableValue(BB, I);
1161 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
1162
1163 while (!UsesToRename.empty())
1164 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1165 DEBUG(errs() << "\n");
1166 }
1167
1168 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1169 // that we nuked.
1170 BB->removePredecessor(PredBB);
1171
1172 // Remove the unconditional branch at the end of the PredBB block.
1173 OldPredBranch->eraseFromParent();
1174
1175 ++NumDupes;
1176 return true;
1177}
1178
1179