blob: ec4bbf9d5b9f1f36711f0d30c15e56b1dc1a7ca9 [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"
Chris Lattner8383a7b2008-04-20 20:35:01 +000017#include "llvm/Pass.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000018#include "llvm/ADT/DenseMap.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000019#include "llvm/ADT/Statistic.h"
Chris Lattnera3522002008-12-01 06:52:57 +000020#include "llvm/ADT/STLExtras.h"
Chris Lattneref0c6742008-12-01 04:48:07 +000021#include "llvm/Analysis/ConstantFolding.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 Lattneref0c6742008-12-01 04:48:07 +000024#include "llvm/Target/TargetData.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000027#include "llvm/Support/Debug.h"
Chris Lattner69e067f2008-11-27 05:07:53 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000029using namespace llvm;
30
Chris Lattnerbd3401f2008-04-20 22:39:42 +000031STATISTIC(NumThreads, "Number of jumps threaded");
32STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000033
Chris Lattner177480b2008-04-20 21:13:06 +000034static cl::opt<unsigned>
35Threshold("jump-threading-threshold",
36 cl::desc("Max block size to duplicate for jump threading"),
37 cl::init(6), cl::Hidden);
38
Chris Lattner77ee9772008-12-04 00:07:59 +000039static cl::opt<int>
40DebugIterations("jump-threading-debug",
41 cl::desc("Stop jump threading after N iterations"),
42 cl::init(-1), cl::Hidden);
43
Chris Lattner8383a7b2008-04-20 20:35:01 +000044namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000045 /// This pass performs 'jump threading', which looks at blocks that have
46 /// multiple predecessors and multiple successors. If one or more of the
47 /// predecessors of the block can be proven to always jump to one of the
48 /// successors, we forward the edge from the predecessor to the successor by
49 /// duplicating the contents of this block.
50 ///
51 /// An example of when this can occur is code like this:
52 ///
53 /// if () { ...
54 /// X = 4;
55 /// }
56 /// if (X < 3) {
57 ///
58 /// In this case, the unconditional branch at the end of the first if can be
59 /// revectored to the false side of the second if.
60 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000061 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000062 TargetData *TD;
Chris Lattner8383a7b2008-04-20 20:35:01 +000063 public:
64 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000065 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000066
Chris Lattneref0c6742008-12-01 04:48:07 +000067 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequired<TargetData>();
69 }
70
Chris Lattner8383a7b2008-04-20 20:35:01 +000071 bool runOnFunction(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000072 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +000073 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000074 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
Chris Lattner421fa9e2008-12-03 07:48:08 +000075 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000076
Chris Lattnerd38c14e2008-04-22 06:36:15 +000077 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000078 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000079 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000080
81 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000082 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000083}
84
Dan Gohman844731a2008-05-13 00:00:25 +000085char JumpThreading::ID = 0;
86static RegisterPass<JumpThreading>
87X("jump-threading", "Jump Threading");
88
Chris Lattner8383a7b2008-04-20 20:35:01 +000089// Public interface to the Jump Threading pass
90FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
91
92/// runOnFunction - Top level algorithm.
93///
94bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000095 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneref0c6742008-12-01 04:48:07 +000096 TD = &getAnalysis<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +000097
98 bool AnotherIteration = true, EverChanged = false;
99 while (AnotherIteration) {
100 AnotherIteration = false;
101 bool Changed = false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000102 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
103 BasicBlock *BB = I;
104 while (ProcessBlock(BB))
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000105 Changed = true;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000106
107 ++I;
108
109 // If the block is trivially dead, zap it. This eliminates the successor
110 // edges which simplifies the CFG.
111 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattner77ee9772008-12-04 00:07:59 +0000112 BB != &BB->getParent()->getEntryBlock() &&
113 DebugIterations != 0) {
Chris Lattner421fa9e2008-12-03 07:48:08 +0000114 DOUT << " JT: Deleting dead block '" << BB->getNameStart()
115 << "' with terminator: " << *BB->getTerminator();
116 DeleteDeadBlock(BB);
117 Changed = true;
Chris Lattner77ee9772008-12-04 00:07:59 +0000118
119 if (DebugIterations != -1)
120 DebugIterations = DebugIterations-1;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000121 }
122 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000123 AnotherIteration = Changed;
124 EverChanged |= Changed;
125 }
126 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000127}
Chris Lattner177480b2008-04-20 21:13:06 +0000128
Chris Lattner6bf77502008-04-22 07:05:46 +0000129/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
130/// value for the PHI, factor them together so we get one block to thread for
131/// the whole group.
132/// This is important for things like "phi i1 [true, true, false, true, x]"
133/// where we only need to clone the block for the true blocks once.
134///
135BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
136 SmallVector<BasicBlock*, 16> CommonPreds;
137 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
138 if (PN->getIncomingValue(i) == CstVal)
139 CommonPreds.push_back(PN->getIncomingBlock(i));
140
141 if (CommonPreds.size() == 1)
142 return CommonPreds[0];
143
144 DOUT << " Factoring out " << CommonPreds.size()
145 << " common predecessors.\n";
146 return SplitBlockPredecessors(PN->getParent(),
147 &CommonPreds[0], CommonPreds.size(),
148 ".thr_comm", this);
149}
150
151
Chris Lattner177480b2008-04-20 21:13:06 +0000152/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
153/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000154static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000155 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000156 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000157
158 // Sum up the cost of each instruction until we get to the terminator. Don't
159 // include the terminator because the copy won't include it.
160 unsigned Size = 0;
161 for (; !isa<TerminatorInst>(I); ++I) {
162 // Debugger intrinsics don't incur code size.
163 if (isa<DbgInfoIntrinsic>(I)) continue;
164
165 // If this is a pointer->pointer bitcast, it is free.
166 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
167 continue;
168
169 // All other instructions count for at least one unit.
170 ++Size;
171
172 // Calls are more expensive. If they are non-intrinsic calls, we model them
173 // as having cost of 4. If they are a non-vector intrinsic, we model them
174 // as having cost of 2 total, and if they are a vector intrinsic, we model
175 // them as having cost 1.
176 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
177 if (!isa<IntrinsicInst>(CI))
178 Size += 3;
179 else if (isa<VectorType>(CI->getType()))
180 Size += 1;
181 }
182 }
183
184 // Threading through a switch statement is particularly profitable. If this
185 // block ends in a switch, decrease its cost to make it more likely to happen.
186 if (isa<SwitchInst>(I))
187 Size = Size > 6 ? Size-6 : 0;
188
189 return Size;
190}
191
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000192/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000193/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000194bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner77ee9772008-12-04 00:07:59 +0000195 if (DebugIterations == 0) return false;
196 if (DebugIterations != -1)
197 DebugIterations = DebugIterations-1;
198
Chris Lattner69e067f2008-11-27 05:07:53 +0000199 // If this block has a single predecessor, and if that pred has a single
200 // successor, merge the blocks. This encourages recursive jump threading
201 // because now the condition in this block can be threaded through
202 // predecessors of our predecessor block.
203 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000204 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
205 SinglePred != BB) {
Chris Lattner3d86d242008-11-27 19:25:19 +0000206 // Remember if SinglePred was the entry block of the function. If so, we
207 // will need to move BB back to the entry position.
208 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000209 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000210
211 if (isEntry && BB != &BB->getParent()->getEntryBlock())
212 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000213 return true;
214 }
215
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000216 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000217 // condition is a phi node. If so, and if an entry of the phi node is a
218 // constant, we can thread the block.
219 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000220 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
221 // Can't thread an unconditional jump.
222 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000223 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000224 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000225 Condition = SI->getCondition();
226 else
227 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000228
229 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000230 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000231 // other blocks.
232 if (isa<ConstantInt>(Condition)) {
233 DOUT << " In block '" << BB->getNameStart()
234 << "' folding terminator: " << *BB->getTerminator();
235 ++NumFolds;
236 ConstantFoldTerminator(BB);
237 return true;
238 }
239
Chris Lattner421fa9e2008-12-03 07:48:08 +0000240 // If the terminator is branching on an undef, we can pick any of the
241 // successors to branch to. Since this is arbitrary, we pick the successor
242 // with the fewest predecessors. This should reduce the in-degree of the
243 // others.
244 if (isa<UndefValue>(Condition)) {
245 TerminatorInst *BBTerm = BB->getTerminator();
246 unsigned MinSucc = 0;
247 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
248 // Compute the successor with the minimum number of predecessors.
249 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
250 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
251 TestBB = BBTerm->getSuccessor(i);
252 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
253 if (NumPreds < MinNumPreds)
254 MinSucc = i;
255 }
256
257 // Fold the branch/switch.
258 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
259 if (i == MinSucc) continue;
260 BBTerm->getSuccessor(i)->removePredecessor(BB);
261 }
262
263 DOUT << " In block '" << BB->getNameStart()
264 << "' folding undef terminator: " << *BBTerm;
265 BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
266 BBTerm->eraseFromParent();
267 return true;
268 }
269
270 Instruction *CondInst = dyn_cast<Instruction>(Condition);
271
272 // If the condition is an instruction defined in another block, see if a
273 // predecessor has the same condition:
274 // br COND, BBX, BBY
275 // BBX:
276 // br COND, BBZ, BBW
277 if (!Condition->hasOneUse() && // Multiple uses.
278 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
279 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
280 if (isa<BranchInst>(BB->getTerminator())) {
281 for (; PI != E; ++PI)
282 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
283 if (PBI->isConditional() && PBI->getCondition() == Condition &&
284 ProcessBranchOnDuplicateCond(*PI, BB))
285 return true;
286 }
287 }
288
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000289 // If there is only a single predecessor of this block, nothing to fold.
290 if (BB->getSinglePredecessor())
291 return false;
Chris Lattner421fa9e2008-12-03 07:48:08 +0000292
293 // All the rest of our checks depend on the condition being an instruction.
294 if (CondInst == 0)
295 return false;
296
Chris Lattner177480b2008-04-20 21:13:06 +0000297 // See if this is a phi node in the current block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000298 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
299 if (PN->getParent() == BB)
300 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000301
Chris Lattner6bf77502008-04-22 07:05:46 +0000302 // If this is a conditional branch whose condition is and/or of a phi, try to
303 // simplify it.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000304 if ((CondInst->getOpcode() == Instruction::And ||
305 CondInst->getOpcode() == Instruction::Or) &&
306 isa<BranchInst>(BB->getTerminator()) &&
307 ProcessBranchOnLogical(CondInst, BB,
308 CondInst->getOpcode() == Instruction::And))
309 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000310
Chris Lattnera5ddb592008-04-22 21:40:39 +0000311 // If we have "br (phi != 42)" and the phi node has any constant values as
312 // operands, we can thread through this block.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000313 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst))
Chris Lattnera5ddb592008-04-22 21:40:39 +0000314 if (isa<PHINode>(CondCmp->getOperand(0)) &&
315 isa<Constant>(CondCmp->getOperand(1)) &&
316 ProcessBranchOnCompare(CondCmp, BB))
317 return true;
Chris Lattner69e067f2008-11-27 05:07:53 +0000318
319 // Check for some cases that are worth simplifying. Right now we want to look
320 // for loads that are used by a switch or by the condition for the branch. If
321 // we see one, check to see if it's partially redundant. If so, insert a PHI
322 // which can then be used to thread the values.
323 //
324 // This is particularly important because reg2mem inserts loads and stores all
325 // over the place, and this blocks jump threading if we don't zap them.
Chris Lattner421fa9e2008-12-03 07:48:08 +0000326 Value *SimplifyValue = CondInst;
Chris Lattner69e067f2008-11-27 05:07:53 +0000327 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
328 if (isa<Constant>(CondCmp->getOperand(1)))
329 SimplifyValue = CondCmp->getOperand(0);
330
331 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
332 if (SimplifyPartiallyRedundantLoad(LI))
333 return true;
334
335 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
336 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000337
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000338 return false;
339}
340
Chris Lattner421fa9e2008-12-03 07:48:08 +0000341/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
342/// block that jump on exactly the same condition. This means that we almost
343/// always know the direction of the edge in the DESTBB:
344/// PREDBB:
345/// br COND, DESTBB, BBY
346/// DESTBB:
347/// br COND, BBZ, BBW
348///
349/// If DESTBB has multiple predecessors, we can't just constant fold the branch
350/// in DESTBB, we have to thread over it.
351bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
352 BasicBlock *BB) {
353 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
354
355 // If both successors of PredBB go to DESTBB, we don't know anything. We can
356 // fold the branch to an unconditional one, which allows other recursive
357 // simplifications.
358 bool BranchDir;
359 if (PredBI->getSuccessor(1) != BB)
360 BranchDir = true;
361 else if (PredBI->getSuccessor(0) != BB)
362 BranchDir = false;
363 else {
364 DOUT << " In block '" << PredBB->getNameStart()
365 << "' folding terminator: " << *PredBB->getTerminator();
366 ++NumFolds;
367 ConstantFoldTerminator(PredBB);
368 return true;
369 }
370
371 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
372
373 // If the dest block has one predecessor, just fix the branch condition to a
374 // constant and fold it.
375 if (BB->getSinglePredecessor()) {
376 DOUT << " In block '" << BB->getNameStart()
377 << "' folding condition to '" << BranchDir << "': "
378 << *BB->getTerminator();
379 ++NumFolds;
380 DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
381 ConstantFoldTerminator(BB);
382 return true;
383 }
384
385 // Otherwise we need to thread from PredBB to DestBB's successor which
386 // involves code duplication. Check to see if it is worth it.
387 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
388 if (JumpThreadCost > Threshold) {
389 DOUT << " Not threading BB '" << BB->getNameStart()
390 << "' - Cost is too high: " << JumpThreadCost << "\n";
391 return false;
392 }
393
394 // Next, figure out which successor we are threading to.
395 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
396
397 // If threading to the same block as we come from, we would infinite loop.
398 if (SuccBB == BB) {
399 DOUT << " Not threading BB '" << BB->getNameStart()
400 << "' - would thread to self!\n";
401 return false;
402 }
403
404 // And finally, do it!
405 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
406 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
407 << ", across block:\n "
408 << *BB << "\n";
409
410 ThreadEdge(BB, PredBB, SuccBB);
411 ++NumThreads;
412 return true;
413}
414
Chris Lattner69e067f2008-11-27 05:07:53 +0000415/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
416/// load instruction, eliminate it by replacing it with a PHI node. This is an
417/// important optimization that encourages jump threading, and needs to be run
418/// interlaced with other jump threading tasks.
419bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
420 // Don't hack volatile loads.
421 if (LI->isVolatile()) return false;
422
423 // If the load is defined in a block with exactly one predecessor, it can't be
424 // partially redundant.
425 BasicBlock *LoadBB = LI->getParent();
426 if (LoadBB->getSinglePredecessor())
427 return false;
428
429 Value *LoadedPtr = LI->getOperand(0);
430
431 // If the loaded operand is defined in the LoadBB, it can't be available.
432 // FIXME: Could do PHI translation, that would be fun :)
433 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
434 if (PtrOp->getParent() == LoadBB)
435 return false;
436
437 // Scan a few instructions up from the load, to see if it is obviously live at
438 // the entry to its block.
439 BasicBlock::iterator BBIt = LI;
440
Chris Lattner52c95852008-11-27 08:10:05 +0000441 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
442 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000443 // If the value if the load is locally available within the block, just use
444 // it. This frequently occurs for reg2mem'd allocas.
445 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
446 LI->replaceAllUsesWith(AvailableVal);
447 LI->eraseFromParent();
448 return true;
449 }
450
451 // Otherwise, if we scanned the whole block and got to the top of the block,
452 // we know the block is locally transparent to the load. If not, something
453 // might clobber its value.
454 if (BBIt != LoadBB->begin())
455 return false;
456
457
458 SmallPtrSet<BasicBlock*, 8> PredsScanned;
459 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
460 AvailablePredsTy AvailablePreds;
461 BasicBlock *OneUnavailablePred = 0;
462
463 // If we got here, the loaded value is transparent through to the start of the
464 // block. Check to see if it is available in any of the predecessor blocks.
465 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
466 PI != PE; ++PI) {
467 BasicBlock *PredBB = *PI;
468
469 // If we already scanned this predecessor, skip it.
470 if (!PredsScanned.insert(PredBB))
471 continue;
472
473 // Scan the predecessor to see if the value is available in the pred.
474 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000475 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000476 if (!PredAvailable) {
477 OneUnavailablePred = PredBB;
478 continue;
479 }
480
481 // If so, this load is partially redundant. Remember this info so that we
482 // can create a PHI node.
483 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
484 }
485
486 // If the loaded value isn't available in any predecessor, it isn't partially
487 // redundant.
488 if (AvailablePreds.empty()) return false;
489
490 // Okay, the loaded value is available in at least one (and maybe all!)
491 // predecessors. If the value is unavailable in more than one unique
492 // predecessor, we want to insert a merge block for those common predecessors.
493 // This ensures that we only have to insert one reload, thus not increasing
494 // code size.
495 BasicBlock *UnavailablePred = 0;
496
497 // If there is exactly one predecessor where the value is unavailable, the
498 // already computed 'OneUnavailablePred' block is it. If it ends in an
499 // unconditional branch, we know that it isn't a critical edge.
500 if (PredsScanned.size() == AvailablePreds.size()+1 &&
501 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
502 UnavailablePred = OneUnavailablePred;
503 } else if (PredsScanned.size() != AvailablePreds.size()) {
504 // Otherwise, we had multiple unavailable predecessors or we had a critical
505 // edge from the one.
506 SmallVector<BasicBlock*, 8> PredsToSplit;
507 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
508
509 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
510 AvailablePredSet.insert(AvailablePreds[i].first);
511
512 // Add all the unavailable predecessors to the PredsToSplit list.
513 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
514 PI != PE; ++PI)
515 if (!AvailablePredSet.count(*PI))
516 PredsToSplit.push_back(*PI);
517
518 // Split them out to their own block.
519 UnavailablePred =
520 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
521 "thread-split", this);
522 }
523
524 // If the value isn't available in all predecessors, then there will be
525 // exactly one where it isn't available. Insert a load on that edge and add
526 // it to the AvailablePreds list.
527 if (UnavailablePred) {
528 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
529 "Can't handle critical edge here!");
530 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
531 UnavailablePred->getTerminator());
532 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
533 }
534
535 // Now we know that each predecessor of this block has a value in
536 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000537 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000538
539 // Create a PHI node at the start of the block for the PRE'd load value.
540 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
541 PN->takeName(LI);
542
543 // Insert new entries into the PHI for each predecessor. A single block may
544 // have multiple entries here.
545 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
546 ++PI) {
547 AvailablePredsTy::iterator I =
548 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
549 std::make_pair(*PI, (Value*)0));
550
551 assert(I != AvailablePreds.end() && I->first == *PI &&
552 "Didn't find entry for predecessor!");
553
554 PN->addIncoming(I->second, I->first);
555 }
556
557 //cerr << "PRE: " << *LI << *PN << "\n";
558
559 LI->replaceAllUsesWith(PN);
560 LI->eraseFromParent();
561
562 return true;
563}
564
565
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000566/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
567/// the current block. See if there are any simplifications we can do based on
568/// inputs to the phi node.
569///
570bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000571 // See if the phi node has any constant values. If so, we can determine where
572 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000573 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000574 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
575 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000576 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000577
578 // If no incoming value has a constant, we don't know the destination of any
579 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000580 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000581 return false;
582
Chris Lattner177480b2008-04-20 21:13:06 +0000583 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000584 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000585 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
586 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000587 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000588 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000589 return false;
590 }
Chris Lattner177480b2008-04-20 21:13:06 +0000591
Chris Lattner6bf77502008-04-22 07:05:46 +0000592 // If so, we can actually do this threading. Merge any common predecessors
593 // that will act the same.
594 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
595
596 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000597 BasicBlock *SuccBB;
598 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
599 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
600 else {
601 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
602 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
603 }
604
Chris Lattnereede65c2008-04-25 04:12:29 +0000605 // If threading to the same block as we come from, we would infinite loop.
606 if (SuccBB == BB) {
607 DOUT << " Not threading BB '" << BB->getNameStart()
608 << "' - would thread to self!\n";
609 return false;
610 }
611
Chris Lattner6bf77502008-04-22 07:05:46 +0000612 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000613 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
614 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
615 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000616 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000617
618 ThreadEdge(BB, PredBB, SuccBB);
619 ++NumThreads;
620 return true;
621}
622
Chris Lattner6bf77502008-04-22 07:05:46 +0000623/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
624/// whose condition is an AND/OR where one side is PN. If PN has constant
625/// operands that permit us to evaluate the condition for some operand, thread
626/// through the block. For example with:
627/// br (and X, phi(Y, Z, false))
628/// the predecessor corresponding to the 'false' will always jump to the false
629/// destination of the branch.
630///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000631bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
632 bool isAnd) {
633 // If this is a binary operator tree of the same AND/OR opcode, check the
634 // LHS/RHS.
635 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000636 if ((isAnd && BO->getOpcode() == Instruction::And) ||
637 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000638 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
639 return true;
640 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
641 return true;
642 }
643
644 // If this isn't a PHI node, we can't handle it.
645 PHINode *PN = dyn_cast<PHINode>(V);
646 if (!PN || PN->getParent() != BB) return false;
647
Chris Lattner6bf77502008-04-22 07:05:46 +0000648 // We can only do the simplification for phi nodes of 'false' with AND or
649 // 'true' with OR. See if we have any entries in the phi for this.
650 unsigned PredNo = ~0U;
651 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
653 if (PN->getIncomingValue(i) == PredCst) {
654 PredNo = i;
655 break;
656 }
657 }
658
659 // If no match, bail out.
660 if (PredNo == ~0U)
661 return false;
662
663 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000664 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
665 if (JumpThreadCost > Threshold) {
666 DOUT << " Not threading BB '" << BB->getNameStart()
667 << "' - Cost is too high: " << JumpThreadCost << "\n";
668 return false;
669 }
670
671 // If so, we can actually do this threading. Merge any common predecessors
672 // that will act the same.
673 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
674
675 // Next, figure out which successor we are threading to. If this was an AND,
676 // the constant must be FALSE, and we must be targeting the 'false' block.
677 // If this is an OR, the constant must be TRUE, and we must be targeting the
678 // 'true' block.
679 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
680
Chris Lattnereede65c2008-04-25 04:12:29 +0000681 // If threading to the same block as we come from, we would infinite loop.
682 if (SuccBB == BB) {
683 DOUT << " Not threading BB '" << BB->getNameStart()
684 << "' - would thread to self!\n";
685 return false;
686 }
687
Chris Lattner6bf77502008-04-22 07:05:46 +0000688 // And finally, do it!
689 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
690 << "' to '" << SuccBB->getNameStart() << "' with cost: "
691 << JumpThreadCost << ", across block:\n "
692 << *BB << "\n";
693
694 ThreadEdge(BB, PredBB, SuccBB);
695 ++NumThreads;
696 return true;
697}
698
Chris Lattnera5ddb592008-04-22 21:40:39 +0000699/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
700/// node and a constant. If the PHI node contains any constants as inputs, we
701/// can fold the compare for that edge and thread through it.
702bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
703 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
704 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
705
706 // If the phi isn't in the current block, an incoming edge to this block
707 // doesn't control the destination.
708 if (PN->getParent() != BB)
709 return false;
710
711 // We can do this simplification if any comparisons fold to true or false.
712 // See if any do.
713 Constant *PredCst = 0;
714 bool TrueDirection = false;
715 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
716 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
717 if (PredCst == 0) continue;
718
719 Constant *Res;
720 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
721 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
722 else
723 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
724 PredCst, RHS);
725 // If this folded to a constant expr, we can't do anything.
726 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
727 TrueDirection = ResC->getZExtValue();
728 break;
729 }
730 // If this folded to undef, just go the false way.
731 if (isa<UndefValue>(Res)) {
732 TrueDirection = false;
733 break;
734 }
735
736 // Otherwise, we can't fold this input.
737 PredCst = 0;
738 }
739
740 // If no match, bail out.
741 if (PredCst == 0)
742 return false;
743
744 // See if the cost of duplicating this block is low enough.
745 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
746 if (JumpThreadCost > Threshold) {
747 DOUT << " Not threading BB '" << BB->getNameStart()
748 << "' - Cost is too high: " << JumpThreadCost << "\n";
749 return false;
750 }
751
752 // If so, we can actually do this threading. Merge any common predecessors
753 // that will act the same.
754 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
755
756 // Next, get our successor.
757 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
758
Chris Lattnereede65c2008-04-25 04:12:29 +0000759 // If threading to the same block as we come from, we would infinite loop.
760 if (SuccBB == BB) {
761 DOUT << " Not threading BB '" << BB->getNameStart()
762 << "' - would thread to self!\n";
763 return false;
764 }
765
766
Chris Lattnera5ddb592008-04-22 21:40:39 +0000767 // And finally, do it!
768 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
769 << "' to '" << SuccBB->getNameStart() << "' with cost: "
770 << JumpThreadCost << ", across block:\n "
771 << *BB << "\n";
772
773 ThreadEdge(BB, PredBB, SuccBB);
774 ++NumThreads;
775 return true;
776}
777
Chris Lattner6bf77502008-04-22 07:05:46 +0000778
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000779/// ThreadEdge - We have decided that it is safe and profitable to thread an
780/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
781/// change.
782void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
783 BasicBlock *SuccBB) {
784
785 // Jump Threading can not update SSA properties correctly if the values
786 // defined in the duplicated block are used outside of the block itself. For
787 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000788 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
789 if (!I->isUsedOutsideOfBlock(BB))
790 continue;
791
792 // We found a use of I outside of BB. Create a new stack slot to
793 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000794 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000795 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000796
797 // We are going to have to map operands from the original BB block to the new
798 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
799 // account for entry from PredBB.
800 DenseMap<Instruction*, Value*> ValueMapping;
801
802 BasicBlock *NewBB =
803 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
804 NewBB->moveAfter(PredBB);
805
806 BasicBlock::iterator BI = BB->begin();
807 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
808 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
809
810 // Clone the non-phi instructions of BB into NewBB, keeping track of the
811 // mapping and using it to remap operands in the cloned instructions.
812 for (; !isa<TerminatorInst>(BI); ++BI) {
813 Instruction *New = BI->clone();
814 New->setName(BI->getNameStart());
815 NewBB->getInstList().push_back(New);
816 ValueMapping[BI] = New;
817
818 // Remap operands to patch up intra-block references.
819 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
820 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
821 if (Value *Remapped = ValueMapping[Inst])
822 New->setOperand(i, Remapped);
823 }
824
825 // We didn't copy the terminator from BB over to NewBB, because there is now
826 // an unconditional jump to SuccBB. Insert the unconditional jump.
827 BranchInst::Create(SuccBB, NewBB);
828
829 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
830 // PHI nodes for NewBB now.
831 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
832 PHINode *PN = cast<PHINode>(PNI);
833 // Ok, we have a PHI node. Figure out what the incoming value was for the
834 // DestBlock.
835 Value *IV = PN->getIncomingValueForBlock(BB);
836
837 // Remap the value if necessary.
838 if (Instruction *Inst = dyn_cast<Instruction>(IV))
839 if (Value *MappedIV = ValueMapping[Inst])
840 IV = MappedIV;
841 PN->addIncoming(IV, NewBB);
842 }
843
Chris Lattneref0c6742008-12-01 04:48:07 +0000844 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000845 // NewBB instead of BB. This eliminates predecessors from BB, which requires
846 // us to simplify any PHI nodes in BB.
847 TerminatorInst *PredTerm = PredBB->getTerminator();
848 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
849 if (PredTerm->getSuccessor(i) == BB) {
850 BB->removePredecessor(PredBB);
851 PredTerm->setSuccessor(i, NewBB);
852 }
Chris Lattneref0c6742008-12-01 04:48:07 +0000853
854 // At this point, the IR is fully up to date and consistent. Do a quick scan
855 // over the new instructions and zap any that are constants or dead. This
856 // frequently happens because of phi translation.
857 BI = NewBB->begin();
858 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
859 Instruction *Inst = BI++;
860 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
861 Inst->replaceAllUsesWith(C);
862 Inst->eraseFromParent();
863 continue;
864 }
865
866 RecursivelyDeleteTriviallyDeadInstructions(Inst);
867 }
Chris Lattner177480b2008-04-20 21:13:06 +0000868}