Merge branch 'master' into msp430
[llvm/msp430.git] / lib / Transforms / Scalar / JumpThreading.cpp
blobc0ca2df1ce11daa7259854e3df712fbc6cc5cd7c
1 //===- 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 //
10 // This file implements the Jump Threading pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jump-threading"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ValueHandle.h"
31 using namespace llvm;
33 STATISTIC(NumThreads, "Number of jumps threaded");
34 STATISTIC(NumFolds, "Number of terminators folded");
36 static cl::opt<unsigned>
37 Threshold("jump-threading-threshold",
38 cl::desc("Max block size to duplicate for jump threading"),
39 cl::init(6), cl::Hidden);
41 namespace {
42 /// This pass performs 'jump threading', which looks at blocks that have
43 /// multiple predecessors and multiple successors. If one or more of the
44 /// predecessors of the block can be proven to always jump to one of the
45 /// successors, we forward the edge from the predecessor to the successor by
46 /// duplicating the contents of this block.
47 ///
48 /// An example of when this can occur is code like this:
49 ///
50 /// if () { ...
51 /// X = 4;
52 /// }
53 /// if (X < 3) {
54 ///
55 /// In this case, the unconditional branch at the end of the first if can be
56 /// revectored to the false side of the second if.
57 ///
58 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
59 TargetData *TD;
60 #ifdef NDEBUG
61 SmallPtrSet<BasicBlock*, 16> LoopHeaders;
62 #else
63 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
64 #endif
65 public:
66 static char ID; // Pass identification
67 JumpThreading() : FunctionPass(&ID) {}
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetData>();
73 bool runOnFunction(Function &F);
74 void FindLoopHeaders(Function &F);
76 bool ProcessBlock(BasicBlock *BB);
77 bool ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB,
78 unsigned JumpThreadCost);
79 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
80 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
81 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB);
83 bool ProcessJumpOnPHI(PHINode *PN);
84 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
85 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
87 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
91 char JumpThreading::ID = 0;
92 static RegisterPass<JumpThreading>
93 X("jump-threading", "Jump Threading");
95 // Public interface to the Jump Threading pass
96 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
98 /// runOnFunction - Top level algorithm.
99 ///
100 bool JumpThreading::runOnFunction(Function &F) {
101 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
102 TD = &getAnalysis<TargetData>();
104 FindLoopHeaders(F);
106 bool AnotherIteration = true, EverChanged = false;
107 while (AnotherIteration) {
108 AnotherIteration = false;
109 bool Changed = false;
110 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
111 BasicBlock *BB = I;
112 while (ProcessBlock(BB))
113 Changed = true;
115 ++I;
117 // If the block is trivially dead, zap it. This eliminates the successor
118 // edges which simplifies the CFG.
119 if (pred_begin(BB) == pred_end(BB) &&
120 BB != &BB->getParent()->getEntryBlock()) {
121 DOUT << " JT: Deleting dead block '" << BB->getNameStart()
122 << "' with terminator: " << *BB->getTerminator();
123 LoopHeaders.erase(BB);
124 DeleteDeadBlock(BB);
125 Changed = true;
128 AnotherIteration = Changed;
129 EverChanged |= Changed;
132 LoopHeaders.clear();
133 return EverChanged;
136 /// FindLoopHeaders - We do not want jump threading to turn proper loop
137 /// structures into irreducible loops. Doing this breaks up the loop nesting
138 /// hierarchy and pessimizes later transformations. To prevent this from
139 /// happening, we first have to find the loop headers. Here we approximate this
140 /// by finding targets of backedges in the CFG.
142 /// Note that there definitely are cases when we want to allow threading of
143 /// edges across a loop header. For example, threading a jump from outside the
144 /// loop (the preheader) to an exit block of the loop is definitely profitable.
145 /// It is also almost always profitable to thread backedges from within the loop
146 /// to exit blocks, and is often profitable to thread backedges to other blocks
147 /// within the loop (forming a nested loop). This simple analysis is not rich
148 /// enough to track all of these properties and keep it up-to-date as the CFG
149 /// mutates, so we don't allow any of these transformations.
151 void JumpThreading::FindLoopHeaders(Function &F) {
152 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
153 FindFunctionBackedges(F, Edges);
155 for (unsigned i = 0, e = Edges.size(); i != e; ++i)
156 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
160 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
161 /// value for the PHI, factor them together so we get one block to thread for
162 /// the whole group.
163 /// This is important for things like "phi i1 [true, true, false, true, x]"
164 /// where we only need to clone the block for the true blocks once.
166 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
167 SmallVector<BasicBlock*, 16> CommonPreds;
168 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
169 if (PN->getIncomingValue(i) == CstVal)
170 CommonPreds.push_back(PN->getIncomingBlock(i));
172 if (CommonPreds.size() == 1)
173 return CommonPreds[0];
175 DOUT << " Factoring out " << CommonPreds.size()
176 << " common predecessors.\n";
177 return SplitBlockPredecessors(PN->getParent(),
178 &CommonPreds[0], CommonPreds.size(),
179 ".thr_comm", this);
183 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
184 /// thread across it.
185 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
186 /// Ignore PHI nodes, these will be flattened when duplication happens.
187 BasicBlock::const_iterator I = BB->getFirstNonPHI();
189 // Sum up the cost of each instruction until we get to the terminator. Don't
190 // include the terminator because the copy won't include it.
191 unsigned Size = 0;
192 for (; !isa<TerminatorInst>(I); ++I) {
193 // Debugger intrinsics don't incur code size.
194 if (isa<DbgInfoIntrinsic>(I)) continue;
196 // If this is a pointer->pointer bitcast, it is free.
197 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
198 continue;
200 // All other instructions count for at least one unit.
201 ++Size;
203 // Calls are more expensive. If they are non-intrinsic calls, we model them
204 // as having cost of 4. If they are a non-vector intrinsic, we model them
205 // as having cost of 2 total, and if they are a vector intrinsic, we model
206 // them as having cost 1.
207 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
208 if (!isa<IntrinsicInst>(CI))
209 Size += 3;
210 else if (isa<VectorType>(CI->getType()))
211 Size += 1;
215 // Threading through a switch statement is particularly profitable. If this
216 // block ends in a switch, decrease its cost to make it more likely to happen.
217 if (isa<SwitchInst>(I))
218 Size = Size > 6 ? Size-6 : 0;
220 return Size;
223 /// ProcessBlock - If there are any predecessors whose control can be threaded
224 /// through to a successor, transform them now.
225 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
226 // If this block has a single predecessor, and if that pred has a single
227 // successor, merge the blocks. This encourages recursive jump threading
228 // because now the condition in this block can be threaded through
229 // predecessors of our predecessor block.
230 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
231 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
232 SinglePred != BB) {
233 // If SinglePred was a loop header, BB becomes one.
234 if (LoopHeaders.erase(SinglePred))
235 LoopHeaders.insert(BB);
237 // Remember if SinglePred was the entry block of the function. If so, we
238 // will need to move BB back to the entry position.
239 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
240 MergeBasicBlockIntoOnlyPred(BB);
242 if (isEntry && BB != &BB->getParent()->getEntryBlock())
243 BB->moveBefore(&BB->getParent()->getEntryBlock());
244 return true;
247 // See if this block ends with a branch or switch. If so, see if the
248 // condition is a phi node. If so, and if an entry of the phi node is a
249 // constant, we can thread the block.
250 Value *Condition;
251 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
252 // Can't thread an unconditional jump.
253 if (BI->isUnconditional()) return false;
254 Condition = BI->getCondition();
255 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
256 Condition = SI->getCondition();
257 else
258 return false; // Must be an invoke.
260 // If the terminator of this block is branching on a constant, simplify the
261 // terminator to an unconditional branch. This can occur due to threading in
262 // other blocks.
263 if (isa<ConstantInt>(Condition)) {
264 DOUT << " In block '" << BB->getNameStart()
265 << "' folding terminator: " << *BB->getTerminator();
266 ++NumFolds;
267 ConstantFoldTerminator(BB);
268 return true;
271 // If the terminator is branching on an undef, we can pick any of the
272 // successors to branch to. Since this is arbitrary, we pick the successor
273 // with the fewest predecessors. This should reduce the in-degree of the
274 // others.
275 if (isa<UndefValue>(Condition)) {
276 TerminatorInst *BBTerm = BB->getTerminator();
277 unsigned MinSucc = 0;
278 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
279 // Compute the successor with the minimum number of predecessors.
280 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
281 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
282 TestBB = BBTerm->getSuccessor(i);
283 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
284 if (NumPreds < MinNumPreds)
285 MinSucc = i;
288 // Fold the branch/switch.
289 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
290 if (i == MinSucc) continue;
291 BBTerm->getSuccessor(i)->removePredecessor(BB);
294 DOUT << " In block '" << BB->getNameStart()
295 << "' folding undef terminator: " << *BBTerm;
296 BranchInst::Create(BBTerm->getSuccessor(MinSucc), BBTerm);
297 BBTerm->eraseFromParent();
298 return true;
301 Instruction *CondInst = dyn_cast<Instruction>(Condition);
303 // If the condition is an instruction defined in another block, see if a
304 // predecessor has the same condition:
305 // br COND, BBX, BBY
306 // BBX:
307 // br COND, BBZ, BBW
308 if (!Condition->hasOneUse() && // Multiple uses.
309 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition.
310 pred_iterator PI = pred_begin(BB), E = pred_end(BB);
311 if (isa<BranchInst>(BB->getTerminator())) {
312 for (; PI != E; ++PI)
313 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
314 if (PBI->isConditional() && PBI->getCondition() == Condition &&
315 ProcessBranchOnDuplicateCond(*PI, BB))
316 return true;
317 } else {
318 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
319 for (; PI != E; ++PI)
320 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
321 if (PSI->getCondition() == Condition &&
322 ProcessSwitchOnDuplicateCond(*PI, BB))
323 return true;
327 // If there is only a single predecessor of this block, nothing to fold.
328 if (BB->getSinglePredecessor())
329 return false;
331 // All the rest of our checks depend on the condition being an instruction.
332 if (CondInst == 0)
333 return false;
335 // See if this is a phi node in the current block.
336 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
337 if (PN->getParent() == BB)
338 return ProcessJumpOnPHI(PN);
340 // If this is a conditional branch whose condition is and/or of a phi, try to
341 // simplify it.
342 if ((CondInst->getOpcode() == Instruction::And ||
343 CondInst->getOpcode() == Instruction::Or) &&
344 isa<BranchInst>(BB->getTerminator()) &&
345 ProcessBranchOnLogical(CondInst, BB,
346 CondInst->getOpcode() == Instruction::And))
347 return true;
349 // If we have "br (phi != 42)" and the phi node has any constant values as
350 // operands, we can thread through this block.
351 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst))
352 if (isa<PHINode>(CondCmp->getOperand(0)) &&
353 isa<Constant>(CondCmp->getOperand(1)) &&
354 ProcessBranchOnCompare(CondCmp, BB))
355 return true;
357 // Check for some cases that are worth simplifying. Right now we want to look
358 // for loads that are used by a switch or by the condition for the branch. If
359 // we see one, check to see if it's partially redundant. If so, insert a PHI
360 // which can then be used to thread the values.
362 // This is particularly important because reg2mem inserts loads and stores all
363 // over the place, and this blocks jump threading if we don't zap them.
364 Value *SimplifyValue = CondInst;
365 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
366 if (isa<Constant>(CondCmp->getOperand(1)))
367 SimplifyValue = CondCmp->getOperand(0);
369 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
370 if (SimplifyPartiallyRedundantLoad(LI))
371 return true;
373 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
374 // "(X == 4)" thread through this block.
376 return false;
379 /// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that
380 /// block that jump on exactly the same condition. This means that we almost
381 /// always know the direction of the edge in the DESTBB:
382 /// PREDBB:
383 /// br COND, DESTBB, BBY
384 /// DESTBB:
385 /// br COND, BBZ, BBW
387 /// If DESTBB has multiple predecessors, we can't just constant fold the branch
388 /// in DESTBB, we have to thread over it.
389 bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB,
390 BasicBlock *BB) {
391 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator());
393 // If both successors of PredBB go to DESTBB, we don't know anything. We can
394 // fold the branch to an unconditional one, which allows other recursive
395 // simplifications.
396 bool BranchDir;
397 if (PredBI->getSuccessor(1) != BB)
398 BranchDir = true;
399 else if (PredBI->getSuccessor(0) != BB)
400 BranchDir = false;
401 else {
402 DOUT << " In block '" << PredBB->getNameStart()
403 << "' folding terminator: " << *PredBB->getTerminator();
404 ++NumFolds;
405 ConstantFoldTerminator(PredBB);
406 return true;
409 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator());
411 // If the dest block has one predecessor, just fix the branch condition to a
412 // constant and fold it.
413 if (BB->getSinglePredecessor()) {
414 DOUT << " In block '" << BB->getNameStart()
415 << "' folding condition to '" << BranchDir << "': "
416 << *BB->getTerminator();
417 ++NumFolds;
418 DestBI->setCondition(ConstantInt::get(Type::Int1Ty, BranchDir));
419 ConstantFoldTerminator(BB);
420 return true;
423 // Otherwise we need to thread from PredBB to DestBB's successor which
424 // involves code duplication. Check to see if it is worth it.
425 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
426 if (JumpThreadCost > Threshold) {
427 DOUT << " Not threading BB '" << BB->getNameStart()
428 << "' - Cost is too high: " << JumpThreadCost << "\n";
429 return false;
432 // Next, figure out which successor we are threading to.
433 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir);
435 // Ok, try to thread it!
436 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
439 /// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that
440 /// block that switch on exactly the same condition. This means that we almost
441 /// always know the direction of the edge in the DESTBB:
442 /// PREDBB:
443 /// switch COND [... DESTBB, BBY ... ]
444 /// DESTBB:
445 /// switch COND [... BBZ, BBW ]
447 /// Optimizing switches like this is very important, because simplifycfg builds
448 /// switches out of repeated 'if' conditions.
449 bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB,
450 BasicBlock *DestBB) {
451 // Can't thread edge to self.
452 if (PredBB == DestBB)
453 return false;
456 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator());
457 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator());
459 // There are a variety of optimizations that we can potentially do on these
460 // blocks: we order them from most to least preferable.
462 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB
463 // directly to their destination. This does not introduce *any* code size
464 // growth. Skip debug info first.
465 BasicBlock::iterator BBI = DestBB->begin();
466 while (isa<DbgInfoIntrinsic>(BBI))
467 BBI++;
469 // FIXME: Thread if it just contains a PHI.
470 if (isa<SwitchInst>(BBI)) {
471 bool MadeChange = false;
472 // Ignore the default edge for now.
473 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) {
474 ConstantInt *DestVal = DestSI->getCaseValue(i);
475 BasicBlock *DestSucc = DestSI->getSuccessor(i);
477 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if
478 // PredSI has an explicit case for it. If so, forward. If it is covered
479 // by the default case, we can't update PredSI.
480 unsigned PredCase = PredSI->findCaseValue(DestVal);
481 if (PredCase == 0) continue;
483 // If PredSI doesn't go to DestBB on this value, then it won't reach the
484 // case on this condition.
485 if (PredSI->getSuccessor(PredCase) != DestBB &&
486 DestSI->getSuccessor(i) != DestBB)
487 continue;
489 // Otherwise, we're safe to make the change. Make sure that the edge from
490 // DestSI to DestSucc is not critical and has no PHI nodes.
491 DOUT << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI;
492 DOUT << "THROUGH: " << *DestSI;
494 // If the destination has PHI nodes, just split the edge for updating
495 // simplicity.
496 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){
497 SplitCriticalEdge(DestSI, i, this);
498 DestSucc = DestSI->getSuccessor(i);
500 FoldSingleEntryPHINodes(DestSucc);
501 PredSI->setSuccessor(PredCase, DestSucc);
502 MadeChange = true;
505 if (MadeChange)
506 return true;
509 return false;
513 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
514 /// load instruction, eliminate it by replacing it with a PHI node. This is an
515 /// important optimization that encourages jump threading, and needs to be run
516 /// interlaced with other jump threading tasks.
517 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
518 // Don't hack volatile loads.
519 if (LI->isVolatile()) return false;
521 // If the load is defined in a block with exactly one predecessor, it can't be
522 // partially redundant.
523 BasicBlock *LoadBB = LI->getParent();
524 if (LoadBB->getSinglePredecessor())
525 return false;
527 Value *LoadedPtr = LI->getOperand(0);
529 // If the loaded operand is defined in the LoadBB, it can't be available.
530 // FIXME: Could do PHI translation, that would be fun :)
531 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
532 if (PtrOp->getParent() == LoadBB)
533 return false;
535 // Scan a few instructions up from the load, to see if it is obviously live at
536 // the entry to its block.
537 BasicBlock::iterator BBIt = LI;
539 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
540 BBIt, 6)) {
541 // If the value if the load is locally available within the block, just use
542 // it. This frequently occurs for reg2mem'd allocas.
543 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
545 // If the returned value is the load itself, replace with an undef. This can
546 // only happen in dead loops.
547 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
548 LI->replaceAllUsesWith(AvailableVal);
549 LI->eraseFromParent();
550 return true;
553 // Otherwise, if we scanned the whole block and got to the top of the block,
554 // we know the block is locally transparent to the load. If not, something
555 // might clobber its value.
556 if (BBIt != LoadBB->begin())
557 return false;
560 SmallPtrSet<BasicBlock*, 8> PredsScanned;
561 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
562 AvailablePredsTy AvailablePreds;
563 BasicBlock *OneUnavailablePred = 0;
565 // If we got here, the loaded value is transparent through to the start of the
566 // block. Check to see if it is available in any of the predecessor blocks.
567 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
568 PI != PE; ++PI) {
569 BasicBlock *PredBB = *PI;
571 // If we already scanned this predecessor, skip it.
572 if (!PredsScanned.insert(PredBB))
573 continue;
575 // Scan the predecessor to see if the value is available in the pred.
576 BBIt = PredBB->end();
577 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
578 if (!PredAvailable) {
579 OneUnavailablePred = PredBB;
580 continue;
583 // If so, this load is partially redundant. Remember this info so that we
584 // can create a PHI node.
585 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
588 // If the loaded value isn't available in any predecessor, it isn't partially
589 // redundant.
590 if (AvailablePreds.empty()) return false;
592 // Okay, the loaded value is available in at least one (and maybe all!)
593 // predecessors. If the value is unavailable in more than one unique
594 // predecessor, we want to insert a merge block for those common predecessors.
595 // This ensures that we only have to insert one reload, thus not increasing
596 // code size.
597 BasicBlock *UnavailablePred = 0;
599 // If there is exactly one predecessor where the value is unavailable, the
600 // already computed 'OneUnavailablePred' block is it. If it ends in an
601 // unconditional branch, we know that it isn't a critical edge.
602 if (PredsScanned.size() == AvailablePreds.size()+1 &&
603 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
604 UnavailablePred = OneUnavailablePred;
605 } else if (PredsScanned.size() != AvailablePreds.size()) {
606 // Otherwise, we had multiple unavailable predecessors or we had a critical
607 // edge from the one.
608 SmallVector<BasicBlock*, 8> PredsToSplit;
609 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
611 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
612 AvailablePredSet.insert(AvailablePreds[i].first);
614 // Add all the unavailable predecessors to the PredsToSplit list.
615 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
616 PI != PE; ++PI)
617 if (!AvailablePredSet.count(*PI))
618 PredsToSplit.push_back(*PI);
620 // Split them out to their own block.
621 UnavailablePred =
622 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
623 "thread-split", this);
626 // If the value isn't available in all predecessors, then there will be
627 // exactly one where it isn't available. Insert a load on that edge and add
628 // it to the AvailablePreds list.
629 if (UnavailablePred) {
630 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
631 "Can't handle critical edge here!");
632 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
633 UnavailablePred->getTerminator());
634 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
637 // Now we know that each predecessor of this block has a value in
638 // AvailablePreds, sort them for efficient access as we're walking the preds.
639 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
641 // Create a PHI node at the start of the block for the PRE'd load value.
642 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
643 PN->takeName(LI);
645 // Insert new entries into the PHI for each predecessor. A single block may
646 // have multiple entries here.
647 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
648 ++PI) {
649 AvailablePredsTy::iterator I =
650 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
651 std::make_pair(*PI, (Value*)0));
653 assert(I != AvailablePreds.end() && I->first == *PI &&
654 "Didn't find entry for predecessor!");
656 PN->addIncoming(I->second, I->first);
659 //cerr << "PRE: " << *LI << *PN << "\n";
661 LI->replaceAllUsesWith(PN);
662 LI->eraseFromParent();
664 return true;
668 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
669 /// the current block. See if there are any simplifications we can do based on
670 /// inputs to the phi node.
671 ///
672 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
673 // See if the phi node has any constant values. If so, we can determine where
674 // the corresponding predecessor will branch.
675 ConstantInt *PredCst = 0;
676 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
677 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
678 break;
680 // If no incoming value has a constant, we don't know the destination of any
681 // predecessors.
682 if (PredCst == 0)
683 return false;
685 // See if the cost of duplicating this block is low enough.
686 BasicBlock *BB = PN->getParent();
687 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
688 if (JumpThreadCost > Threshold) {
689 DOUT << " Not threading BB '" << BB->getNameStart()
690 << "' - Cost is too high: " << JumpThreadCost << "\n";
691 return false;
694 // If so, we can actually do this threading. Merge any common predecessors
695 // that will act the same.
696 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
698 // Next, figure out which successor we are threading to.
699 BasicBlock *SuccBB;
700 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
701 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
702 else {
703 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
704 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
707 // Ok, try to thread it!
708 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
711 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
712 /// whose condition is an AND/OR where one side is PN. If PN has constant
713 /// operands that permit us to evaluate the condition for some operand, thread
714 /// through the block. For example with:
715 /// br (and X, phi(Y, Z, false))
716 /// the predecessor corresponding to the 'false' will always jump to the false
717 /// destination of the branch.
719 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
720 bool isAnd) {
721 // If this is a binary operator tree of the same AND/OR opcode, check the
722 // LHS/RHS.
723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
724 if ((isAnd && BO->getOpcode() == Instruction::And) ||
725 (!isAnd && BO->getOpcode() == Instruction::Or)) {
726 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
727 return true;
728 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
729 return true;
732 // If this isn't a PHI node, we can't handle it.
733 PHINode *PN = dyn_cast<PHINode>(V);
734 if (!PN || PN->getParent() != BB) return false;
736 // We can only do the simplification for phi nodes of 'false' with AND or
737 // 'true' with OR. See if we have any entries in the phi for this.
738 unsigned PredNo = ~0U;
739 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
740 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
741 if (PN->getIncomingValue(i) == PredCst) {
742 PredNo = i;
743 break;
747 // If no match, bail out.
748 if (PredNo == ~0U)
749 return false;
751 // See if the cost of duplicating this block is low enough.
752 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
753 if (JumpThreadCost > Threshold) {
754 DOUT << " Not threading BB '" << BB->getNameStart()
755 << "' - Cost is too high: " << JumpThreadCost << "\n";
756 return false;
759 // If so, we can actually do this threading. Merge any common predecessors
760 // that will act the same.
761 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
763 // Next, figure out which successor we are threading to. If this was an AND,
764 // the constant must be FALSE, and we must be targeting the 'false' block.
765 // If this is an OR, the constant must be TRUE, and we must be targeting the
766 // 'true' block.
767 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
769 // Ok, try to thread it!
770 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
773 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
774 /// node and a constant. If the PHI node contains any constants as inputs, we
775 /// can fold the compare for that edge and thread through it.
776 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
777 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
778 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
780 // If the phi isn't in the current block, an incoming edge to this block
781 // doesn't control the destination.
782 if (PN->getParent() != BB)
783 return false;
785 // We can do this simplification if any comparisons fold to true or false.
786 // See if any do.
787 Constant *PredCst = 0;
788 bool TrueDirection = false;
789 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
790 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
791 if (PredCst == 0) continue;
793 Constant *Res;
794 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
795 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
796 else
797 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
798 PredCst, RHS);
799 // If this folded to a constant expr, we can't do anything.
800 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
801 TrueDirection = ResC->getZExtValue();
802 break;
804 // If this folded to undef, just go the false way.
805 if (isa<UndefValue>(Res)) {
806 TrueDirection = false;
807 break;
810 // Otherwise, we can't fold this input.
811 PredCst = 0;
814 // If no match, bail out.
815 if (PredCst == 0)
816 return false;
818 // See if the cost of duplicating this block is low enough.
819 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
820 if (JumpThreadCost > Threshold) {
821 DOUT << " Not threading BB '" << BB->getNameStart()
822 << "' - Cost is too high: " << JumpThreadCost << "\n";
823 return false;
826 // If so, we can actually do this threading. Merge any common predecessors
827 // that will act the same.
828 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
830 // Next, get our successor.
831 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
833 // Ok, try to thread it!
834 return ThreadEdge(BB, PredBB, SuccBB, JumpThreadCost);
838 /// ThreadEdge - We have decided that it is safe and profitable to thread an
839 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
840 /// change.
841 bool JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
842 BasicBlock *SuccBB, unsigned JumpThreadCost) {
844 // If threading to the same block as we come from, we would infinite loop.
845 if (SuccBB == BB) {
846 DOUT << " Not threading across BB '" << BB->getNameStart()
847 << "' - would thread to self!\n";
848 return false;
851 // If threading this would thread across a loop header, don't thread the edge.
852 // See the comments above FindLoopHeaders for justifications and caveats.
853 if (LoopHeaders.count(BB)) {
854 DOUT << " Not threading from '" << PredBB->getNameStart()
855 << "' across loop header BB '" << BB->getNameStart()
856 << "' to dest BB '" << SuccBB->getNameStart()
857 << "' - it might create an irreducible loop!\n";
858 return false;
861 // And finally, do it!
862 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
863 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
864 << ", across block:\n "
865 << *BB << "\n";
867 // Jump Threading can not update SSA properties correctly if the values
868 // defined in the duplicated block are used outside of the block itself. For
869 // this reason, we spill all values that are used outside of BB to the stack.
870 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
871 if (!I->isUsedOutsideOfBlock(BB))
872 continue;
874 // We found a use of I outside of BB. Create a new stack slot to
875 // break this inter-block usage pattern.
876 DemoteRegToStack(*I);
879 // We are going to have to map operands from the original BB block to the new
880 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
881 // account for entry from PredBB.
882 DenseMap<Instruction*, Value*> ValueMapping;
884 BasicBlock *NewBB =
885 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
886 NewBB->moveAfter(PredBB);
888 BasicBlock::iterator BI = BB->begin();
889 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
890 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
892 // Clone the non-phi instructions of BB into NewBB, keeping track of the
893 // mapping and using it to remap operands in the cloned instructions.
894 for (; !isa<TerminatorInst>(BI); ++BI) {
895 Instruction *New = BI->clone();
896 New->setName(BI->getNameStart());
897 NewBB->getInstList().push_back(New);
898 ValueMapping[BI] = New;
900 // Remap operands to patch up intra-block references.
901 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
902 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
903 if (Value *Remapped = ValueMapping[Inst])
904 New->setOperand(i, Remapped);
907 // We didn't copy the terminator from BB over to NewBB, because there is now
908 // an unconditional jump to SuccBB. Insert the unconditional jump.
909 BranchInst::Create(SuccBB, NewBB);
911 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
912 // PHI nodes for NewBB now.
913 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
914 PHINode *PN = cast<PHINode>(PNI);
915 // Ok, we have a PHI node. Figure out what the incoming value was for the
916 // DestBlock.
917 Value *IV = PN->getIncomingValueForBlock(BB);
919 // Remap the value if necessary.
920 if (Instruction *Inst = dyn_cast<Instruction>(IV))
921 if (Value *MappedIV = ValueMapping[Inst])
922 IV = MappedIV;
923 PN->addIncoming(IV, NewBB);
926 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
927 // NewBB instead of BB. This eliminates predecessors from BB, which requires
928 // us to simplify any PHI nodes in BB.
929 TerminatorInst *PredTerm = PredBB->getTerminator();
930 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
931 if (PredTerm->getSuccessor(i) == BB) {
932 BB->removePredecessor(PredBB);
933 PredTerm->setSuccessor(i, NewBB);
936 // At this point, the IR is fully up to date and consistent. Do a quick scan
937 // over the new instructions and zap any that are constants or dead. This
938 // frequently happens because of phi translation.
939 BI = NewBB->begin();
940 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
941 Instruction *Inst = BI++;
942 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
943 Inst->replaceAllUsesWith(C);
944 Inst->eraseFromParent();
945 continue;
948 RecursivelyDeleteTriviallyDeadInstructions(Inst);
951 // Threaded an edge!
952 ++NumThreads;
953 return true;