blob: 0a02351a7b86603ee8bef6ed4e7920a767474325 [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 Lattner8383a7b2008-04-20 20:35:01 +000039namespace {
Chris Lattner94019f82008-05-09 04:43:13 +000040 /// This pass performs 'jump threading', which looks at blocks that have
41 /// multiple predecessors and multiple successors. If one or more of the
42 /// predecessors of the block can be proven to always jump to one of the
43 /// successors, we forward the edge from the predecessor to the successor by
44 /// duplicating the contents of this block.
45 ///
46 /// An example of when this can occur is code like this:
47 ///
48 /// if () { ...
49 /// X = 4;
50 /// }
51 /// if (X < 3) {
52 ///
53 /// In this case, the unconditional branch at the end of the first if can be
54 /// revectored to the false side of the second if.
55 ///
Chris Lattner8383a7b2008-04-20 20:35:01 +000056 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
Chris Lattneref0c6742008-12-01 04:48:07 +000057 TargetData *TD;
Chris Lattner8383a7b2008-04-20 20:35:01 +000058 public:
59 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +000060 JumpThreading() : FunctionPass(&ID) {}
Chris Lattner8383a7b2008-04-20 20:35:01 +000061
Chris Lattneref0c6742008-12-01 04:48:07 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<TargetData>();
64 }
65
Chris Lattner8383a7b2008-04-20 20:35:01 +000066 bool runOnFunction(Function &F);
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000067 bool ProcessBlock(BasicBlock *BB);
Chris Lattnerbd3401f2008-04-20 22:39:42 +000068 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000069 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
70
Chris Lattnerd38c14e2008-04-22 06:36:15 +000071 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000072 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000073 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner69e067f2008-11-27 05:07:53 +000074
75 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
Chris Lattner8383a7b2008-04-20 20:35:01 +000076 };
Chris Lattner8383a7b2008-04-20 20:35:01 +000077}
78
Dan Gohman844731a2008-05-13 00:00:25 +000079char JumpThreading::ID = 0;
80static RegisterPass<JumpThreading>
81X("jump-threading", "Jump Threading");
82
Chris Lattner8383a7b2008-04-20 20:35:01 +000083// Public interface to the Jump Threading pass
84FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
85
86/// runOnFunction - Top level algorithm.
87///
88bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000089 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneref0c6742008-12-01 04:48:07 +000090 TD = &getAnalysis<TargetData>();
Chris Lattnerbd3401f2008-04-20 22:39:42 +000091
92 bool AnotherIteration = true, EverChanged = false;
93 while (AnotherIteration) {
94 AnotherIteration = false;
95 bool Changed = false;
96 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc7bcbf62008-11-27 07:20:04 +000097 while (ProcessBlock(I))
Chris Lattnerbd3401f2008-04-20 22:39:42 +000098 Changed = true;
99 AnotherIteration = Changed;
100 EverChanged |= Changed;
101 }
102 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +0000103}
Chris Lattner177480b2008-04-20 21:13:06 +0000104
Chris Lattner6bf77502008-04-22 07:05:46 +0000105/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
106/// value for the PHI, factor them together so we get one block to thread for
107/// the whole group.
108/// This is important for things like "phi i1 [true, true, false, true, x]"
109/// where we only need to clone the block for the true blocks once.
110///
111BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
112 SmallVector<BasicBlock*, 16> CommonPreds;
113 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
114 if (PN->getIncomingValue(i) == CstVal)
115 CommonPreds.push_back(PN->getIncomingBlock(i));
116
117 if (CommonPreds.size() == 1)
118 return CommonPreds[0];
119
120 DOUT << " Factoring out " << CommonPreds.size()
121 << " common predecessors.\n";
122 return SplitBlockPredecessors(PN->getParent(),
123 &CommonPreds[0], CommonPreds.size(),
124 ".thr_comm", this);
125}
126
127
Chris Lattner177480b2008-04-20 21:13:06 +0000128/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
129/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000130static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000131 /// Ignore PHI nodes, these will be flattened when duplication happens.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000132 BasicBlock::const_iterator I = BB->getFirstNonPHI();
Chris Lattner177480b2008-04-20 21:13:06 +0000133
134 // Sum up the cost of each instruction until we get to the terminator. Don't
135 // include the terminator because the copy won't include it.
136 unsigned Size = 0;
137 for (; !isa<TerminatorInst>(I); ++I) {
138 // Debugger intrinsics don't incur code size.
139 if (isa<DbgInfoIntrinsic>(I)) continue;
140
141 // If this is a pointer->pointer bitcast, it is free.
142 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
143 continue;
144
145 // All other instructions count for at least one unit.
146 ++Size;
147
148 // Calls are more expensive. If they are non-intrinsic calls, we model them
149 // as having cost of 4. If they are a non-vector intrinsic, we model them
150 // as having cost of 2 total, and if they are a vector intrinsic, we model
151 // them as having cost 1.
152 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
153 if (!isa<IntrinsicInst>(CI))
154 Size += 3;
155 else if (isa<VectorType>(CI->getType()))
156 Size += 1;
157 }
158 }
159
160 // Threading through a switch statement is particularly profitable. If this
161 // block ends in a switch, decrease its cost to make it more likely to happen.
162 if (isa<SwitchInst>(I))
163 Size = Size > 6 ? Size-6 : 0;
164
165 return Size;
166}
167
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000168/// ProcessBlock - If there are any predecessors whose control can be threaded
Chris Lattner177480b2008-04-20 21:13:06 +0000169/// through to a successor, transform them now.
Chris Lattnerc7bcbf62008-11-27 07:20:04 +0000170bool JumpThreading::ProcessBlock(BasicBlock *BB) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000171 // If this block has a single predecessor, and if that pred has a single
172 // successor, merge the blocks. This encourages recursive jump threading
173 // because now the condition in this block can be threaded through
174 // predecessors of our predecessor block.
175 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
Chris Lattnerf5102a02008-11-28 19:54:49 +0000176 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
177 SinglePred != BB) {
Chris Lattner3d86d242008-11-27 19:25:19 +0000178 // Remember if SinglePred was the entry block of the function. If so, we
179 // will need to move BB back to the entry position.
180 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner69e067f2008-11-27 05:07:53 +0000181 MergeBasicBlockIntoOnlyPred(BB);
Chris Lattner3d86d242008-11-27 19:25:19 +0000182
183 if (isEntry && BB != &BB->getParent()->getEntryBlock())
184 BB->moveBefore(&BB->getParent()->getEntryBlock());
Chris Lattner69e067f2008-11-27 05:07:53 +0000185 return true;
186 }
187
Matthijs Kooijman6e7b3222008-05-20 07:26:45 +0000188 // See if this block ends with a branch or switch. If so, see if the
Chris Lattner177480b2008-04-20 21:13:06 +0000189 // condition is a phi node. If so, and if an entry of the phi node is a
190 // constant, we can thread the block.
191 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000192 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
193 // Can't thread an unconditional jump.
194 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000195 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000196 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000197 Condition = SI->getCondition();
198 else
199 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000200
201 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000202 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000203 // other blocks.
204 if (isa<ConstantInt>(Condition)) {
205 DOUT << " In block '" << BB->getNameStart()
206 << "' folding terminator: " << *BB->getTerminator();
207 ++NumFolds;
208 ConstantFoldTerminator(BB);
209 return true;
210 }
211
212 // If there is only a single predecessor of this block, nothing to fold.
213 if (BB->getSinglePredecessor())
214 return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000215
216 // See if this is a phi node in the current block.
217 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000218 if (PN && PN->getParent() == BB)
219 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000220
Chris Lattner6bf77502008-04-22 07:05:46 +0000221 // If this is a conditional branch whose condition is and/or of a phi, try to
222 // simplify it.
223 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
224 if ((CondI->getOpcode() == Instruction::And ||
225 CondI->getOpcode() == Instruction::Or) &&
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000226 isa<BranchInst>(BB->getTerminator()) &&
227 ProcessBranchOnLogical(CondI, BB,
228 CondI->getOpcode() == Instruction::And))
229 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000230 }
231
Chris Lattnera5ddb592008-04-22 21:40:39 +0000232 // If we have "br (phi != 42)" and the phi node has any constant values as
233 // operands, we can thread through this block.
234 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
235 if (isa<PHINode>(CondCmp->getOperand(0)) &&
236 isa<Constant>(CondCmp->getOperand(1)) &&
237 ProcessBranchOnCompare(CondCmp, BB))
238 return true;
Chris Lattner69e067f2008-11-27 05:07:53 +0000239
240 // Check for some cases that are worth simplifying. Right now we want to look
241 // for loads that are used by a switch or by the condition for the branch. If
242 // we see one, check to see if it's partially redundant. If so, insert a PHI
243 // which can then be used to thread the values.
244 //
245 // This is particularly important because reg2mem inserts loads and stores all
246 // over the place, and this blocks jump threading if we don't zap them.
247 Value *SimplifyValue = Condition;
248 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
249 if (isa<Constant>(CondCmp->getOperand(1)))
250 SimplifyValue = CondCmp->getOperand(0);
251
252 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
253 if (SimplifyPartiallyRedundantLoad(LI))
254 return true;
255
256 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
257 // "(X == 4)" thread through this block.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000258
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000259 return false;
260}
261
Chris Lattner69e067f2008-11-27 05:07:53 +0000262/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
263/// load instruction, eliminate it by replacing it with a PHI node. This is an
264/// important optimization that encourages jump threading, and needs to be run
265/// interlaced with other jump threading tasks.
266bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
267 // Don't hack volatile loads.
268 if (LI->isVolatile()) return false;
269
270 // If the load is defined in a block with exactly one predecessor, it can't be
271 // partially redundant.
272 BasicBlock *LoadBB = LI->getParent();
273 if (LoadBB->getSinglePredecessor())
274 return false;
275
276 Value *LoadedPtr = LI->getOperand(0);
277
278 // If the loaded operand is defined in the LoadBB, it can't be available.
279 // FIXME: Could do PHI translation, that would be fun :)
280 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
281 if (PtrOp->getParent() == LoadBB)
282 return false;
283
284 // Scan a few instructions up from the load, to see if it is obviously live at
285 // the entry to its block.
286 BasicBlock::iterator BBIt = LI;
287
Chris Lattner52c95852008-11-27 08:10:05 +0000288 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
289 BBIt, 6)) {
Chris Lattner69e067f2008-11-27 05:07:53 +0000290 // If the value if the load is locally available within the block, just use
291 // it. This frequently occurs for reg2mem'd allocas.
292 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
293 LI->replaceAllUsesWith(AvailableVal);
294 LI->eraseFromParent();
295 return true;
296 }
297
298 // Otherwise, if we scanned the whole block and got to the top of the block,
299 // we know the block is locally transparent to the load. If not, something
300 // might clobber its value.
301 if (BBIt != LoadBB->begin())
302 return false;
303
304
305 SmallPtrSet<BasicBlock*, 8> PredsScanned;
306 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
307 AvailablePredsTy AvailablePreds;
308 BasicBlock *OneUnavailablePred = 0;
309
310 // If we got here, the loaded value is transparent through to the start of the
311 // block. Check to see if it is available in any of the predecessor blocks.
312 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
313 PI != PE; ++PI) {
314 BasicBlock *PredBB = *PI;
315
316 // If we already scanned this predecessor, skip it.
317 if (!PredsScanned.insert(PredBB))
318 continue;
319
320 // Scan the predecessor to see if the value is available in the pred.
321 BBIt = PredBB->end();
Chris Lattner52c95852008-11-27 08:10:05 +0000322 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
Chris Lattner69e067f2008-11-27 05:07:53 +0000323 if (!PredAvailable) {
324 OneUnavailablePred = PredBB;
325 continue;
326 }
327
328 // If so, this load is partially redundant. Remember this info so that we
329 // can create a PHI node.
330 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
331 }
332
333 // If the loaded value isn't available in any predecessor, it isn't partially
334 // redundant.
335 if (AvailablePreds.empty()) return false;
336
337 // Okay, the loaded value is available in at least one (and maybe all!)
338 // predecessors. If the value is unavailable in more than one unique
339 // predecessor, we want to insert a merge block for those common predecessors.
340 // This ensures that we only have to insert one reload, thus not increasing
341 // code size.
342 BasicBlock *UnavailablePred = 0;
343
344 // If there is exactly one predecessor where the value is unavailable, the
345 // already computed 'OneUnavailablePred' block is it. If it ends in an
346 // unconditional branch, we know that it isn't a critical edge.
347 if (PredsScanned.size() == AvailablePreds.size()+1 &&
348 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
349 UnavailablePred = OneUnavailablePred;
350 } else if (PredsScanned.size() != AvailablePreds.size()) {
351 // Otherwise, we had multiple unavailable predecessors or we had a critical
352 // edge from the one.
353 SmallVector<BasicBlock*, 8> PredsToSplit;
354 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
355
356 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
357 AvailablePredSet.insert(AvailablePreds[i].first);
358
359 // Add all the unavailable predecessors to the PredsToSplit list.
360 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
361 PI != PE; ++PI)
362 if (!AvailablePredSet.count(*PI))
363 PredsToSplit.push_back(*PI);
364
365 // Split them out to their own block.
366 UnavailablePred =
367 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
368 "thread-split", this);
369 }
370
371 // If the value isn't available in all predecessors, then there will be
372 // exactly one where it isn't available. Insert a load on that edge and add
373 // it to the AvailablePreds list.
374 if (UnavailablePred) {
375 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
376 "Can't handle critical edge here!");
377 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
378 UnavailablePred->getTerminator());
379 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
380 }
381
382 // Now we know that each predecessor of this block has a value in
383 // AvailablePreds, sort them for efficient access as we're walking the preds.
Chris Lattnera3522002008-12-01 06:52:57 +0000384 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
Chris Lattner69e067f2008-11-27 05:07:53 +0000385
386 // Create a PHI node at the start of the block for the PRE'd load value.
387 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
388 PN->takeName(LI);
389
390 // Insert new entries into the PHI for each predecessor. A single block may
391 // have multiple entries here.
392 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
393 ++PI) {
394 AvailablePredsTy::iterator I =
395 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
396 std::make_pair(*PI, (Value*)0));
397
398 assert(I != AvailablePreds.end() && I->first == *PI &&
399 "Didn't find entry for predecessor!");
400
401 PN->addIncoming(I->second, I->first);
402 }
403
404 //cerr << "PRE: " << *LI << *PN << "\n";
405
406 LI->replaceAllUsesWith(PN);
407 LI->eraseFromParent();
408
409 return true;
410}
411
412
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000413/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
414/// the current block. See if there are any simplifications we can do based on
415/// inputs to the phi node.
416///
417bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000418 // See if the phi node has any constant values. If so, we can determine where
419 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000420 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
422 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000423 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000424
425 // If no incoming value has a constant, we don't know the destination of any
426 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000427 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000428 return false;
429
Chris Lattner177480b2008-04-20 21:13:06 +0000430 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000431 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000432 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
433 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000434 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000435 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000436 return false;
437 }
Chris Lattner177480b2008-04-20 21:13:06 +0000438
Chris Lattner6bf77502008-04-22 07:05:46 +0000439 // If so, we can actually do this threading. Merge any common predecessors
440 // that will act the same.
441 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
442
443 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000444 BasicBlock *SuccBB;
445 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
446 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
447 else {
448 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
449 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
450 }
451
Chris Lattnereede65c2008-04-25 04:12:29 +0000452 // If threading to the same block as we come from, we would infinite loop.
453 if (SuccBB == BB) {
454 DOUT << " Not threading BB '" << BB->getNameStart()
455 << "' - would thread to self!\n";
456 return false;
457 }
458
Chris Lattner6bf77502008-04-22 07:05:46 +0000459 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000460 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
461 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
462 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000463 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000464
465 ThreadEdge(BB, PredBB, SuccBB);
466 ++NumThreads;
467 return true;
468}
469
Chris Lattner6bf77502008-04-22 07:05:46 +0000470/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
471/// whose condition is an AND/OR where one side is PN. If PN has constant
472/// operands that permit us to evaluate the condition for some operand, thread
473/// through the block. For example with:
474/// br (and X, phi(Y, Z, false))
475/// the predecessor corresponding to the 'false' will always jump to the false
476/// destination of the branch.
477///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000478bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
479 bool isAnd) {
480 // If this is a binary operator tree of the same AND/OR opcode, check the
481 // LHS/RHS.
482 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
Duncan Sands43e2a032008-05-27 11:50:51 +0000483 if ((isAnd && BO->getOpcode() == Instruction::And) ||
484 (!isAnd && BO->getOpcode() == Instruction::Or)) {
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000485 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
486 return true;
487 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
488 return true;
489 }
490
491 // If this isn't a PHI node, we can't handle it.
492 PHINode *PN = dyn_cast<PHINode>(V);
493 if (!PN || PN->getParent() != BB) return false;
494
Chris Lattner6bf77502008-04-22 07:05:46 +0000495 // We can only do the simplification for phi nodes of 'false' with AND or
496 // 'true' with OR. See if we have any entries in the phi for this.
497 unsigned PredNo = ~0U;
498 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
499 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
500 if (PN->getIncomingValue(i) == PredCst) {
501 PredNo = i;
502 break;
503 }
504 }
505
506 // If no match, bail out.
507 if (PredNo == ~0U)
508 return false;
509
510 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000511 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
512 if (JumpThreadCost > Threshold) {
513 DOUT << " Not threading BB '" << BB->getNameStart()
514 << "' - Cost is too high: " << JumpThreadCost << "\n";
515 return false;
516 }
517
518 // If so, we can actually do this threading. Merge any common predecessors
519 // that will act the same.
520 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
521
522 // Next, figure out which successor we are threading to. If this was an AND,
523 // the constant must be FALSE, and we must be targeting the 'false' block.
524 // If this is an OR, the constant must be TRUE, and we must be targeting the
525 // 'true' block.
526 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
527
Chris Lattnereede65c2008-04-25 04:12:29 +0000528 // If threading to the same block as we come from, we would infinite loop.
529 if (SuccBB == BB) {
530 DOUT << " Not threading BB '" << BB->getNameStart()
531 << "' - would thread to self!\n";
532 return false;
533 }
534
Chris Lattner6bf77502008-04-22 07:05:46 +0000535 // And finally, do it!
536 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
537 << "' to '" << SuccBB->getNameStart() << "' with cost: "
538 << JumpThreadCost << ", across block:\n "
539 << *BB << "\n";
540
541 ThreadEdge(BB, PredBB, SuccBB);
542 ++NumThreads;
543 return true;
544}
545
Chris Lattnera5ddb592008-04-22 21:40:39 +0000546/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
547/// node and a constant. If the PHI node contains any constants as inputs, we
548/// can fold the compare for that edge and thread through it.
549bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
550 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
551 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
552
553 // If the phi isn't in the current block, an incoming edge to this block
554 // doesn't control the destination.
555 if (PN->getParent() != BB)
556 return false;
557
558 // We can do this simplification if any comparisons fold to true or false.
559 // See if any do.
560 Constant *PredCst = 0;
561 bool TrueDirection = false;
562 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
563 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
564 if (PredCst == 0) continue;
565
566 Constant *Res;
567 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
568 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
569 else
570 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
571 PredCst, RHS);
572 // If this folded to a constant expr, we can't do anything.
573 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
574 TrueDirection = ResC->getZExtValue();
575 break;
576 }
577 // If this folded to undef, just go the false way.
578 if (isa<UndefValue>(Res)) {
579 TrueDirection = false;
580 break;
581 }
582
583 // Otherwise, we can't fold this input.
584 PredCst = 0;
585 }
586
587 // If no match, bail out.
588 if (PredCst == 0)
589 return false;
590
591 // See if the cost of duplicating this block is low enough.
592 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
593 if (JumpThreadCost > Threshold) {
594 DOUT << " Not threading BB '" << BB->getNameStart()
595 << "' - Cost is too high: " << JumpThreadCost << "\n";
596 return false;
597 }
598
599 // If so, we can actually do this threading. Merge any common predecessors
600 // that will act the same.
601 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
602
603 // Next, get our successor.
604 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
605
Chris Lattnereede65c2008-04-25 04:12:29 +0000606 // If threading to the same block as we come from, we would infinite loop.
607 if (SuccBB == BB) {
608 DOUT << " Not threading BB '" << BB->getNameStart()
609 << "' - would thread to self!\n";
610 return false;
611 }
612
613
Chris Lattnera5ddb592008-04-22 21:40:39 +0000614 // And finally, do it!
615 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
616 << "' to '" << SuccBB->getNameStart() << "' with cost: "
617 << JumpThreadCost << ", across block:\n "
618 << *BB << "\n";
619
620 ThreadEdge(BB, PredBB, SuccBB);
621 ++NumThreads;
622 return true;
623}
624
Chris Lattner6bf77502008-04-22 07:05:46 +0000625
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000626/// ThreadEdge - We have decided that it is safe and profitable to thread an
627/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
628/// change.
629void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
630 BasicBlock *SuccBB) {
631
632 // Jump Threading can not update SSA properties correctly if the values
633 // defined in the duplicated block are used outside of the block itself. For
634 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000635 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
636 if (!I->isUsedOutsideOfBlock(BB))
637 continue;
638
639 // We found a use of I outside of BB. Create a new stack slot to
640 // break this inter-block usage pattern.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000641 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000642 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000643
644 // We are going to have to map operands from the original BB block to the new
645 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
646 // account for entry from PredBB.
647 DenseMap<Instruction*, Value*> ValueMapping;
648
649 BasicBlock *NewBB =
650 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
651 NewBB->moveAfter(PredBB);
652
653 BasicBlock::iterator BI = BB->begin();
654 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
655 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
656
657 // Clone the non-phi instructions of BB into NewBB, keeping track of the
658 // mapping and using it to remap operands in the cloned instructions.
659 for (; !isa<TerminatorInst>(BI); ++BI) {
660 Instruction *New = BI->clone();
661 New->setName(BI->getNameStart());
662 NewBB->getInstList().push_back(New);
663 ValueMapping[BI] = New;
664
665 // Remap operands to patch up intra-block references.
666 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
667 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
668 if (Value *Remapped = ValueMapping[Inst])
669 New->setOperand(i, Remapped);
670 }
671
672 // We didn't copy the terminator from BB over to NewBB, because there is now
673 // an unconditional jump to SuccBB. Insert the unconditional jump.
674 BranchInst::Create(SuccBB, NewBB);
675
676 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
677 // PHI nodes for NewBB now.
678 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
679 PHINode *PN = cast<PHINode>(PNI);
680 // Ok, we have a PHI node. Figure out what the incoming value was for the
681 // DestBlock.
682 Value *IV = PN->getIncomingValueForBlock(BB);
683
684 // Remap the value if necessary.
685 if (Instruction *Inst = dyn_cast<Instruction>(IV))
686 if (Value *MappedIV = ValueMapping[Inst])
687 IV = MappedIV;
688 PN->addIncoming(IV, NewBB);
689 }
690
Chris Lattneref0c6742008-12-01 04:48:07 +0000691 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000692 // NewBB instead of BB. This eliminates predecessors from BB, which requires
693 // us to simplify any PHI nodes in BB.
694 TerminatorInst *PredTerm = PredBB->getTerminator();
695 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
696 if (PredTerm->getSuccessor(i) == BB) {
697 BB->removePredecessor(PredBB);
698 PredTerm->setSuccessor(i, NewBB);
699 }
Chris Lattneref0c6742008-12-01 04:48:07 +0000700
701 // At this point, the IR is fully up to date and consistent. Do a quick scan
702 // over the new instructions and zap any that are constants or dead. This
703 // frequently happens because of phi translation.
704 BI = NewBB->begin();
705 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
706 Instruction *Inst = BI++;
707 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
708 Inst->replaceAllUsesWith(C);
709 Inst->eraseFromParent();
710 continue;
711 }
712
713 RecursivelyDeleteTriviallyDeadInstructions(Inst);
714 }
Chris Lattner177480b2008-04-20 21:13:06 +0000715}